Skip to content

Commit f348ec9

Browse files
committed
fix bNetStr2Bstr: replace strlen with strnlen, cap digit-loop iterations
strlen(buff) scanned until a null terminator regardless of buffer content, creating an OOB read risk on buffers that are not properly null-terminated (e.g. data read directly from a network socket). Two hardening changes, without breaking the API: 1. Cap the digit-parsing loop at 11 iterations (INT_MAX is 10 decimal digits). Add a post-loop check that ':' was actually found, so a buffer with no ':' in the first 11 bytes returns NULL immediately rather than scanning indefinitely. 2. Replace strlen with strnlen(buff, i + 2 + x), limiting the scan to exactly the number of bytes a valid netstring of the claimed length requires. An unterminated or truncated buffer is still caught by the existing bounds check; the scan is now bounded rather than open-ended. Residual limitation: without a length parameter the caller cannot provide an absolute bound, so strnlen may still scan up to x bytes into the data region for large x. A future bNetStr2BstrN(buff, len) variant would fully eliminate this.
1 parent e7d99e5 commit f348ec9

1 file changed

Lines changed: 6 additions & 2 deletions

File tree

bstring/bstraux.c

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -310,15 +310,19 @@ bNetStr2Bstr(const char * buff)
310310
if (buff == NULL) {
311311
return NULL;
312312
}
313-
size_t blen = strlen(buff);
314313
x = 0;
315-
for (i = 0; buff[i] != ':'; ++i) {
314+
for (i = 0; i < 11 && buff[i] != ':'; ++i) {
316315
unsigned int v = buff[i] - '0';
317316
if (v > 9 || x > ((INT_MAX - (signed int)v) / 10)) {
318317
return NULL;
319318
}
320319
x = (x * 10) + v;
321320
}
321+
if (buff[i] != ':') {
322+
return NULL;
323+
}
324+
/* strnlen with exact bound: only scan as far as needed to verify the netstring */
325+
size_t blen = strnlen(buff, (size_t)i + 2 + (size_t)x);
322326
/* Bounds check: the buffer must contain i+1+x+1 chars (digits, ':', data, ',') */
323327
if ((size_t)i + 1 + (size_t)x >= blen) {
324328
return NULL;

0 commit comments

Comments
 (0)