Make X.509 CRT cache reference counting unconditional
Previously, reference counting for the CRT frames and PK contexts
handed out by mbedtls_x509_crt_{frame|pk}_acquire() was implemented
only in case threading support was enabled, which leaves the door
open for a potential use-after-free should a single-threaded application
use nested calls to mbedtls_x509_crt_acquire().
Since Mbed TLS itself does not use such nested calls, it might be
preferred long-term to forbid nesting of acquire calls on the API
level, and hence get rid of reference counting in the interest of
code-size benefits. However, this can be considered as an optimization
of X.509 on demand parsing, and for now this commit introduces
reference counting unconditionally to have a safe version of
on demand parsing to build further optimizations upon.
diff --git a/library/x509_crt.c b/library/x509_crt.c
index c601686..fa51241 100644
--- a/library/x509_crt.c
+++ b/library/x509_crt.c
@@ -112,10 +112,9 @@
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_lock( &crt->cache->pk_mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
-
+#endif
/* Can only free the PK context if nobody is using it. */
if( crt->cache->pk_readers == 0 )
-#endif
{
#if !defined(MBEDTLS_X509_ON_DEMAND_PARSING)
/* The cache holds a shallow copy of the PK context
@@ -140,10 +139,10 @@
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_lock( &crt->cache->frame_mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
+#endif
/* Can only free the frame if nobody is using it. */
if( crt->cache->frame_readers == 0 )
-#endif
{
mbedtls_free( crt->cache->frame );
crt->cache->frame = NULL;