From 62e7fae1090544357bcfaf209b9d87f8f827bfeb Mon Sep 17 00:00:00 2001 From: David Horstmann Date: Fri, 2 Jun 2023 15:32:20 +0100 Subject: [PATCH] Fix bug in calculation of maximum possible bytes Each DER-encoded OID byte can only store 7 bits of actual data, so take account of that. Calculate the number of bytes required as: number_of_bytes = ceil(subidentifier_size * 8 / 7) Signed-off-by: David Horstmann --- library/oid.c | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/library/oid.c b/library/oid.c index b13c76b1e7..88165d3120 100644 --- a/library/oid.c +++ b/library/oid.c @@ -971,7 +971,14 @@ int mbedtls_oid_from_numeric_string(mbedtls_asn1_buf *oid, if (num_dots == 0 || (num_dots > MBEDTLS_OID_MAX_COMPONENTS - 1)) { return MBEDTLS_ERR_ASN1_INVALID_DATA; } - size_t max_possible_bytes = num_dots * sizeof(unsigned int); + /* Each byte can store 7 bits, calculate number of bytes for a + * subidentifier: + * + * bytes = ceil(subidentifer_size * 8 / 7) + */ + size_t bytes_per_subidentifier = (((sizeof(unsigned int) * 8) - 1) / 7) + + 1; + size_t max_possible_bytes = num_dots * bytes_per_subidentifier; oid->p = mbedtls_calloc(max_possible_bytes, 1); if (oid->p == NULL) { return MBEDTLS_ERR_ASN1_ALLOC_FAILED;