From 9c1887c4c7baaa388cf561c11ed32ed07935aa77 Mon Sep 17 00:00:00 2001 From: David Horstmann Date: Wed, 15 Feb 2023 11:48:13 +0000 Subject: [PATCH] Disallow overlong encoding when parsing OIDs OID subidentifiers are encoded as follow. For every byte: * The top bit is 1 if there is another byte to come, 0 if this is the last byte. * The other 7 bits form 7 bits of the number. These groups of 7 are concatenated together in big-endian order. Overlong encodings are explicitly disallowed by the BER/DER/X690 specification. For example, the number 1 cannot be encoded as: 0x80 0x80 0x01 It must be encoded as: 0x01 Enforce this in Mbed TLS' OID DER-to-string parser. Signed-off-by: David Horstmann --- library/oid.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/library/oid.c b/library/oid.c index 5668e2aa56..17d3e093a4 100644 --- a/library/oid.c +++ b/library/oid.c @@ -837,6 +837,11 @@ int mbedtls_oid_get_numeric_string(char *buf, size_t size, /* First subidentifier contains first two OID components */ i = 0; value = 0; + if ((oid->p[0]) == 0x80) { + /* Overlong encoding is not allowed */ + return MBEDTLS_ERR_OID_BUF_TOO_SMALL; + } + while (i < oid->len && ((oid->p[i] & 0x80) != 0)) { /* Prevent overflow in value. */ if (((value << 7) >> 7) != value) { @@ -871,6 +876,10 @@ int mbedtls_oid_get_numeric_string(char *buf, size_t size, if (((value << 7) >> 7) != value) { return MBEDTLS_ERR_OID_BUF_TOO_SMALL; } + if ((value == 0) && ((oid->p[i]) == 0x80)) { + /* Overlong encoding is not allowed */ + return MBEDTLS_ERR_OID_BUF_TOO_SMALL; + } value <<= 7; value += oid->p[i] & 0x7F;