Fixed potential negative value misinterpretation in load_file()
(cherry picked from commit 42c3ccf36e86972bff3a74c1e74c11311e6a7af0)
Conflicts:
library/x509parse.c
diff --git a/library/x509parse.c b/library/x509parse.c
index 2c65ebb..86a1ab2 100644
--- a/library/x509parse.c
+++ b/library/x509parse.c
@@ -1836,16 +1836,27 @@
int load_file( const char *path, unsigned char **buf, size_t *n )
{
FILE *f;
+ long size;
if( ( f = fopen( path, "rb" ) ) == NULL )
return( POLARSSL_ERR_X509_FILE_IO_ERROR );
fseek( f, 0, SEEK_END );
- *n = (size_t) ftell( f );
+ if( ( size = ftell( f ) ) == -1 )
+ {
+ fclose( f );
+ return( POLARSSL_ERR_X509_FILE_IO_ERROR );
+ }
fseek( f, 0, SEEK_SET );
- if( ( *buf = (unsigned char *) malloc( *n + 1 ) ) == NULL )
+ *n = (size_t) size;
+
+ if( *n + 1 == 0 ||
+ ( *buf = (unsigned char *) malloc( *n + 1 ) ) == NULL )
+ {
+ fclose( f );
return( POLARSSL_ERR_X509_MALLOC_FAILED );
+ }
if( fread( *buf, 1, *n, f ) != *n )
{