Index | Thread | Search

From:
Claudio Jeker <cjeker@diehard.n-r-g.com>
Subject:
libutil, use secure idiom from snprintf(3)
To:
tech@openbsd.org
Date:
Mon, 25 Aug 2025 10:44:32 +0200

Download raw body.

Thread
make WARNINGS=yes currently complains about two files that don't do the
error checking as it is shown in snprintf(3).

uucplock.c was just missing the size_t case.
opendev.c did not check for < 0. I adjusted to code to use the idiom from
the man page which inverts the logic of the if else statement.

-- 
:wq Claudio

Index: opendev.c
===================================================================
RCS file: /cvs/src/lib/libutil/opendev.c,v
diff -u -p -r1.17 opendev.c
--- opendev.c	26 Aug 2022 21:47:16 -0000	1.17
+++ opendev.c	25 Aug 2025 08:39:44 -0000
@@ -51,7 +51,7 @@ opendev(const char *path, int oflags, in
 	static char namebuf[PATH_MAX];
 	struct dk_diskmap dm;
 	char *slash, *prefix;
-	int fd;
+	int fd, ret;
 
 	/* Initial state */
 	fd = -1;
@@ -88,19 +88,20 @@ opendev(const char *path, int oflags, in
 			/*
 			 * First try raw partition (for removable drives)
 			 */
-			if (snprintf(namebuf, sizeof(namebuf), "%s%s%s%c",
-			    _PATH_DEV, prefix, path, 'a' + getrawpartition())
-			    < sizeof(namebuf)) {
-				fd = open(namebuf, oflags);
-			} else
+			ret = snprintf(namebuf, sizeof(namebuf), "%s%s%s%c",
+			    _PATH_DEV, prefix, path, 'a' + getrawpartition());
+			if (ret < 0 || (size_t)ret >= sizeof(namebuf))
 				errno = ENAMETOOLONG;
+			else
+				fd = open(namebuf, oflags);
 		}
 		if (fd == -1 && errno == ENOENT) {
-			if (snprintf(namebuf, sizeof(namebuf), "%s%s%s",
-			    _PATH_DEV, prefix, path) < sizeof(namebuf)) {
-				fd = open(namebuf, oflags);
-			} else
+			ret = snprintf(namebuf, sizeof(namebuf), "%s%s%s",
+			    _PATH_DEV, prefix, path);
+			if (ret < 0 || (size_t)ret >= sizeof(namebuf))
 				errno = ENAMETOOLONG;
+			else
+				fd = open(namebuf, oflags);
 		}
 	}
 	if (realpath)
Index: uucplock.c
===================================================================
RCS file: /cvs/src/lib/libutil/uucplock.c,v
diff -u -p -r1.21 uucplock.c
--- uucplock.c	3 Jul 2019 03:24:04 -0000	1.21
+++ uucplock.c	25 Aug 2025 08:40:19 -0000
@@ -197,7 +197,7 @@ put_pid(int fd, pid_t pid)
 	int len;
 
 	len = snprintf(buf, sizeof buf, "%10ld\n", (long)pid);
-	if (len < 0 || len >= sizeof buf)
+	if (len < 0 || (size_t)len >= sizeof buf)
 		return 0;
 
 	if (write(fd, buf, len) != len)