From 5ad1728a2d5313e5d9f2490c73b29a63311a58db Mon Sep 17 00:00:00 2001 From: "Robin H. Johnson" Date: Thu, 2 Jan 2025 09:01:05 -0800 Subject: [PATCH] test: increase snprintf safety Detected by CodeQL scanning; only in test harness, not used in main codebase. Signed-off-by: Robin H. Johnson --- test/print_safe_buffer.c | 25 ++++++++++++++++++------- 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/test/print_safe_buffer.c b/test/print_safe_buffer.c index a9d62b7..55b01cb 100644 --- a/test/print_safe_buffer.c +++ b/test/print_safe_buffer.c @@ -15,19 +15,30 @@ void print_safe_buffer(struct safe_buffer const *sb) size_t snprint_safe_buffer(char *s, size_t size, struct safe_buffer const *sb) { size_t count = 0; + int n; - count += snprintf((s + count), (size - count), "unsigned char expected[] = { /* sb.allocated = %ld, sb.used = %ld */", sb->allocated, sb->used); + n = snprintf((s + count), (size - count), "unsigned char expected[] = { /* sb.allocated = %ld, sb.used = %ld */", sb->allocated, sb->used); + if (n < 0 || n >= size - count) { + return count; + } + count += n; + char* nextline = "\n\t"; + char* nextbyte = " "; for (size_t i = 0; i < sb->used; ++i) { - if (i % 8 == 0) { - count += snprintf((s + count), (size - count), "\n\t0x%02x,", sb->buffer[i]); - } else { - count += snprintf((s + count), (size - count), " 0x%02x,", sb->buffer[i]); + char* nextspace = (i % 8 == 0) ? nextline : nextbyte; + n = snprintf((s + count), (size - count), "%s0x%02x,", nextspace, sb->buffer[i]); + if (n < 0 || n >= size - count) { + return count; } + count += n; } /* Do not remove the final byte's comma. Only JSON requires the comma is * removed, and this is not JSON. */ - - count += snprintf((s + count), (size - count), "\n};\n"); + n = snprintf((s + count), (size - count), "\n};\n"); + if (n < 0 || n >= size - count) { + return count; + } + count += n; return count; }