Better checking for reading over buffer boundaries
(Partial cherry picked from commit 535e97dbab8cf34bb1e487f0f0f169a04eb9921f)
diff --git a/ChangeLog b/ChangeLog
index 587f686..8931237 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -7,6 +7,7 @@
    * mpi_add_abs() now correctly handles adding short numbers to long numbers
      with carry rollover
    * Moved mpi_inv_mod() outside POLARSSL_GENPRIME
+   * Prevent reading over buffer boundaries on X509 certificate parsing
 
 Security
    * Fixed potential memory zeroization on miscrafted RSA key (found by Eloi
diff --git a/library/x509parse.c b/library/x509parse.c
index c9aa738..e91b6f6 100644
--- a/library/x509parse.c
+++ b/library/x509parse.c
@@ -1241,7 +1241,8 @@
         return( ret );
     }
 
-    if( memcmp( crt->sig_oid1.p, crt->sig_oid2.p, crt->sig_oid1.len ) != 0 )
+    if( crt->sig_oid1.len != crt->sig_oid2.len ||
+        memcmp( crt->sig_oid1.p, crt->sig_oid2.p, crt->sig_oid1.len ) != 0 )
     {
         x509_free( crt );
         return( POLARSSL_ERR_X509_CERT_SIG_MISMATCH );
@@ -1662,7 +1663,8 @@
         return( ret );
     }
 
-    if( memcmp( crl->sig_oid1.p, crl->sig_oid2.p, crl->sig_oid1.len ) != 0 )
+    if( crl->sig_oid1.len != crl->sig_oid2.len ||
+        memcmp( crl->sig_oid1.p, crl->sig_oid2.p, crl->sig_oid1.len ) != 0 )
     {
         x509_crl_free( crl );
         return( POLARSSL_ERR_X509_CERT_SIG_MISMATCH );
@@ -2348,7 +2350,8 @@
             SAFE_SNPRINTF();
         }
 
-        if( memcmp( name->oid.p, OID_X520, 2 ) == 0 )
+        if( name->oid.len == 3 &&
+            memcmp( name->oid.p, OID_X520, 2 ) == 0 )
         {
             switch( name->oid.p[2] )
             {
@@ -2377,7 +2380,8 @@
             }
         SAFE_SNPRINTF();
         }
-        else if( memcmp( name->oid.p, OID_PKCS9, 8 ) == 0 )
+        else if( name->oid.len == 9 &&
+                 memcmp( name->oid.p, OID_PKCS9, 8 ) == 0 )
         {
             switch( name->oid.p[8] )
             {
@@ -2898,9 +2902,10 @@
 
         while( name != NULL )
         {
-            if( memcmp( name->oid.p, OID_CN,  3 ) == 0 &&
-                memcmp( name->val.p, cn, cn_len ) == 0 &&
-                name->val.len == cn_len )
+            if( name->oid.len == 3 &&
+                memcmp( name->oid.p, OID_CN,  3 ) == 0 &&
+                name->val.len == cn_len &&
+                memcmp( name->val.p, cn, cn_len ) == 0 )
                 break;
 
             name = name->next;