From 2e65a54d5a2414b8fd3dc36ee1cca3ab9a36586c Mon Sep 17 00:00:00 2001
From: Andres AG <andres.amayagarcia@arm.com>
Date: Fri, 17 Feb 2017 13:54:43 +0000
Subject: [PATCH] Prevent signed integer overflow in CSR parsing

Modify the function mbedtls_x509_csr_parse_der() so that it checks the
parsed CSR version integer before it increments the value. This prevents
a potential signed integer overflow, as these have undefined behaviour
in the C standard.
---
 ChangeLog          | 4 ++++
 library/x509_csr.c | 6 +++---
 2 files changed, 7 insertions(+), 3 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index 567e98883..eea691958 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -46,6 +46,10 @@ Bugfix
      Reported and fix suggested by guidovranken in #740
    * Fix conditional preprocessor directives in bignum.h to enable 64-bit
      compilation when using ARM Compiler 6.
+   * Fix potential integer overflow in the version verification for DER
+     encoded X509 CSRs. The overflow would enable maliciously constructed CSRs
+     to bypass the version verification check. Found by Peng Li/Yueh-Hsun Lin,
+     KNOX Security, Samsung Research America
 
 Security
    * Fix authentication bypass in SSL/TLS: when auth_mode is set to optional,
diff --git a/library/x509_csr.c b/library/x509_csr.c
index f92b66c58..26a06db4f 100644
--- a/library/x509_csr.c
+++ b/library/x509_csr.c
@@ -168,14 +168,14 @@ int mbedtls_x509_csr_parse_der( mbedtls_x509_csr *csr,
         return( ret );
     }
 
-    csr->version++;
-
-    if( csr->version != 1 )
+    if( csr->version != 0 )
     {
         mbedtls_x509_csr_free( csr );
         return( MBEDTLS_ERR_X509_UNKNOWN_VERSION );
     }
 
+    csr->version++;
+
     /*
      *  subject               Name
      */