d0480e
From 6d3e97e83a7d61cbb2f5109efb4b519383a55712 Mon Sep 17 00:00:00 2001
d0480e
From: Eugene Syromyatnikov <evgsyr@gmail.com>
d0480e
Date: Tue, 28 Jun 2022 16:55:49 +0200
d0480e
Subject: [PATCH] util: add offs sanity check to print_clock_t
d0480e
d0480e
While it is not strictly needed right now, the code that uses
d0480e
the calculated offs value lacks any checks for possible buf overruns,
d0480e
which is not defensive enough, so let's add them.  Reported by covscan:
d0480e
d0480e
    Error: OVERRUN (CWE-119):
d0480e
    strace-5.18/src/util.c:248: assignment: Assigning:
d0480e
    "offs" = "ilog10(val / clk_tck)". The value of "offs" is now between
d0480e
    16 and 31 (inclusive).
d0480e
    strace-5.18/src/util.c:249: overrun-local: Overrunning array of 30 bytes
d0480e
    at byte offset 31 by dereferencing pointer "buf + offs". [Note: The source
d0480e
    code implementation of the function has been overridden by a builtin model.]
d0480e
d0480e
    Error: OVERRUN (CWE-119):
d0480e
    strace-5.18/src/util.c:248: assignment: Assigning:
d0480e
    "offs" = "ilog10(val / clk_tck)". The value of "offs" is now between
d0480e
    16 and 31 (inclusive).
d0480e
    strace-5.18/src/util.c:253: overrun-buffer-arg: Overrunning array "buf"
d0480e
    of 30 bytes by passing it to a function which accesses it at byte offset
d0480e
    32 using argument "offs + 2UL" (which evaluates to 33). [Note: The source
d0480e
    code implementation of the function has been overridden by a builtin model.]
d0480e
d0480e
    Error: OVERRUN (CWE-119):
d0480e
    strace-5.18/src/util.c:248: assignment: Assigning:
d0480e
    "offs" = "ilog10(val / clk_tck)". The value of "offs" is now between
d0480e
    16 and 31 (inclusive).
d0480e
    strace-5.18/src/util.c:254: overrun-local: Overrunning array "buf"
d0480e
    of 30 bytes at byte offset 32 using index "offs + 1UL" (which evaluates
d0480e
    to 32).
d0480e
d0480e
* src/util.c (print_clock_t): Add check that offs is small enough
d0480e
for it and "offs + 2" not to overrun buf.
d0480e
---
d0480e
 src/util.c | 8 ++++++++
d0480e
 1 file changed, 8 insertions(+)
d0480e
d0480e
diff --git a/src/util.c b/src/util.c
d0480e
index 5f87acb..93aa7b3 100644
d0480e
--- a/src/util.c
d0480e
+++ b/src/util.c
d0480e
@@ -246,6 +246,14 @@ print_clock_t(uint64_t val)
d0480e
 		 */
d0480e
 		char buf[sizeof(uint64_t) * 3 + sizeof("0.0 s")];
d0480e
 		size_t offs = ilog10(val / clk_tck);
d0480e
+		/*
d0480e
+		 * This check is mostly to appease covscan, which thinks
d0480e
+		 * that offs can go as high as 31 (it cannot), but since
d0480e
+		 * there is no proper sanity checks against offs overrunning
d0480e
+		 * buf down the code, it may as well be here.
d0480e
+		 */
d0480e
+		if (offs > (sizeof(buf) - sizeof("0.0 s")))
d0480e
+			return;
d0480e
 		int ret = snprintf(buf + offs, sizeof(buf) - offs, "%.*f s",
d0480e
 				   frac_width,
d0480e
 				   (double) (val % clk_tck) / clk_tck);
d0480e
-- 
d0480e
2.1.4
d0480e