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 <david.horstmann@arm.com>
This commit is contained in:
David Horstmann 2023-02-15 11:48:13 +00:00
parent f01de145bd
commit 9c1887c4c7

View file

@ -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;