Add setbuf platform function
Add a platform function mbedtls_setbuf(), defaulting to setbuf().
The intent is to allow disabling stdio buffering when reading or writing
files with sensitive data, because this exposes the sensitive data to a
subsequent memory disclosure vulnerability.
Signed-off-by: Gilles Peskine <Gilles.Peskine@arm.com>
diff --git a/library/platform.c b/library/platform.c
index e742fde..f3a1f98 100644
--- a/library/platform.c
+++ b/library/platform.c
@@ -226,6 +226,28 @@
}
#endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */
+#if defined(MBEDTLS_PLATFORM_SETBUF_ALT)
+#if !defined(MBEDTLS_PLATFORM_STD_SETBUF)
+/*
+ * Make dummy function to prevent NULL pointer dereferences
+ */
+static void platform_setbuf_uninit( FILE *stream, char *buf )
+{
+ (( void ) stream);
+ (( void ) buf);
+}
+
+#define MBEDTLS_PLATFORM_STD_SETBUF platform_setbuf_uninit
+#endif /* !MBEDTLS_PLATFORM_STD_SETBUF */
+void (*mbedtls_setbuf)( FILE *stream, char *buf ) = MBEDTLS_PLATFORM_STD_SETBUF;
+
+int mbedtls_platform_set_setbuf( void (*setbuf_func)( FILE *stream, char *buf ) )
+{
+ mbedtls_setbuf = setbuf_func;
+ return( 0 );
+}
+#endif /* MBEDTLS_PLATFORM_SETBUF_ALT */
+
#if defined(MBEDTLS_PLATFORM_EXIT_ALT)
#if !defined(MBEDTLS_PLATFORM_STD_EXIT)
/*
@@ -288,6 +310,9 @@
if( ( file = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "rb" ) ) == NULL )
return( -1 );
+ /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
+ mbedtls_setbuf( file, NULL );
+
if( ( n = fread( buf, 1, buf_len, file ) ) != buf_len )
{
fclose( file );
@@ -307,6 +332,9 @@
if( ( file = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "w" ) ) == NULL )
return -1;
+ /* Ensure no stdio buffering of secrets, as such buffers cannot be wiped. */
+ mbedtls_setbuf( file, NULL );
+
if( ( n = fwrite( buf, 1, buf_len, file ) ) != buf_len )
{
fclose( file );