Skip to contentSkip to conversation

X.509: fix buffer overflow detection in sprint_oid()

PATCH In review Eric Biggers 2 participants 2 messages Nov 27, 2017

Subsystems (3)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 X.509: fix buffer overflow detection in sprint_oid()

From: Eric Biggers <[email protected]>

In sprint_oid(), if the input buffer were to be more than 1 byte too small for the first snprintf(), 'bufsize' would underflow, causing a buffer overflow when printing the remainder of the OID.

Fortunately this cannot actually happen currently, because no users pass in a buffer that can be too small for the first snprintf().

Regardless, fix it by checking the snprintf() return value correctly.

For consistency also tweak the second snprintf() check to look the same.

Fixes 4f73175d0375 ("X.509: Add utility functions to render OIDs as strings")
Cc Takashi Iwai <[email protected]>
---
 lib/oid_registry.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
lib/oid_registry.c +4 -4
index 41b9e50711a7..5a75d127995d 100644
@@ -120,10 +120,10 @@ int sprint_oid(const void *data, size_t datasize, char *buffer, size_t bufsize)
 
 	n = *v++;
 	ret = count = snprintf(buffer, bufsize, "%u.%u", n / 40, n % 40);
+	if (count >= bufsize)
+		return -ENOBUFS;
 	buffer += count;
 	bufsize -= count;
-	if (bufsize = 0)
-		return -ENOBUFS;
 
 	while (v < end) {
 		num = 0;
@@ -141,9 +141,9 @@ int sprint_oid(const void *data, size_t datasize, char *buffer, size_t bufsize)
 			} while (n & 0x80);
 		}
 		ret += count = snprintf(buffer, bufsize, ".%lu", num);
-		buffer += count;
-		if (bufsize <= count)
+		if (count >= bufsize)
 			return -ENOBUFS;
+		buffer += count;
 		bufsize -= count;
 	}
 
Signature · 1 line
2.15.0