Merge of IOTSSL-476 - Random malloc in pem_read()
diff --git a/ChangeLog b/ChangeLog
index 63cedaa..2aa7a21 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -16,6 +16,10 @@
      but might be in other uses. On 32 bit machines, requires reading a string
      of close to or larger than 1GB to exploit; on 64 bit machines, would require
      reading a string of close to or larger than 2^62 bytes.
+   * Fix potential random memory allocation in mbedtls_pem_read_buffer()
+     on crafted PEM input data. Found an fix provided by Guid Vranken.
+     Not triggerable remotely in TLS. Triggerable remotely if you accept PEM
+     data from an untrusted source.
 
 Changes
    * Added checking of hostname length in mbedtls_ssl_set_hostname() to ensure
diff --git a/library/base64.c b/library/base64.c
index 16c254d..e468e2c 100644
--- a/library/base64.c
+++ b/library/base64.c
@@ -184,7 +184,10 @@
     }
 
     if( n == 0 )
+    {
+        *olen = 0;
         return( 0 );
+    }
 
     n = ( ( n * 6 ) + 7 ) >> 3;
     n -= j;
diff --git a/library/pem.c b/library/pem.c
index 541e870..1ee3966 100644
--- a/library/pem.c
+++ b/library/pem.c
@@ -316,6 +316,9 @@
           ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
     }
 
+    if( s1 == s2 )
+        return( MBEDTLS_ERR_PEM_INVALID_DATA );
+
     ret = mbedtls_base64_decode( NULL, 0, &len, s1, s2 - s1 );
 
     if( ret == MBEDTLS_ERR_BASE64_INVALID_CHARACTER )