diff --git a/ChangeLog.d/pem-integer-underflow.txt b/ChangeLog.d/pem-integer-underflow.txt new file mode 100644 index 0000000000..77274aa279 --- /dev/null +++ b/ChangeLog.d/pem-integer-underflow.txt @@ -0,0 +1,5 @@ +Security + * Fix an integer underflow that could occur when parsing malformed PEM + keys, which could be used by an attacker capable of feeding encrypted + PEM keys to a user. This could cause a crash or information disclosure. + Found and reported by Linh Le and Ngan Nguyen from Calif. diff --git a/library/pem.c b/library/pem.c index 0207601456..119fd59e12 100644 --- a/library/pem.c +++ b/library/pem.c @@ -243,7 +243,10 @@ exit: #if defined(MBEDTLS_DES_C) || defined(MBEDTLS_AES_C) static int pem_check_pkcs_padding(unsigned char *input, size_t input_len, size_t *data_len) { - /* input_len > 0 is guaranteed by mbedtls_pem_read_buffer(). */ + /* input_len > 0 is not guaranteed by mbedtls_pem_read_buffer(). */ + if (input_len < 1) { + return MBEDTLS_ERR_PEM_INVALID_DATA; + } size_t pad_len = input[input_len - 1]; size_t i; diff --git a/tests/suites/test_suite_pem.data b/tests/suites/test_suite_pem.data index 007ba104a9..1df9645650 100644 --- a/tests/suites/test_suite_pem.data +++ b/tests/suites/test_suite_pem.data @@ -53,6 +53,10 @@ PEM read (malformed PEM AES-128-CBC) depends_on:MBEDTLS_MD_CAN_MD5:MBEDTLS_AES_C:MBEDTLS_CIPHER_MODE_CBC mbedtls_pem_read_buffer:"-----BEGIN EC PRIVATE KEY-----":"-----END EC PRIVATE KEY-----":"-----BEGIN EC PRIVATE KEY-----\nProc-Type\: 4,ENCRYPTED\nDEK-Info\: AES-128-CBC,AA94892A169FA426AA94892A169FA426\n\nMAAA\n-----END EC PRIVATE KEY-----":"pwd":MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH:"" +PEM read (malformed PEM AES-128-CBC with fewer than 4 base64 chars) +depends_on:MBEDTLS_MD_CAN_MD5:MBEDTLS_AES_C:MBEDTLS_CIPHER_MODE_CBC +mbedtls_pem_read_buffer:"-----BEGIN EC PRIVATE KEY-----":"-----END EC PRIVATE KEY-----":"-----BEGIN EC PRIVATE KEY-----\nProc-Type\: 4,ENCRYPTED\nDEK-Info\: AES-128-CBC,7BA38DE00F67851E4207216809C3BB15\n\n8Q-----END EC PRIVATE KEY-----":"pwd":MBEDTLS_ERR_PEM_INVALID_DATA:"" + # The output sequence's length is not multiple of block size (16 bytes). This # proves that the pem_context->len value is properly updated based on the SEQUENCE # length read from the decoded ASN.1 data (i.e. extra padding, if any, is ignored).