Skip to content

Commit 820d0ca

Browse files
committed
utmp_setid: Make sure we don't read past the end of ut_line
Use strnlen() instead of strlen() since ut_line is not guaranteed to be NUL-terminated. Found by the ZeroPath AI Security Engineer <https://zeropath.com>
1 parent f764980 commit 820d0ca

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

src/utmp.c

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -95,27 +95,28 @@ static void
9595
utmp_setid(sudo_utmp_t *old, sudo_utmp_t *new)
9696
{
9797
const char *line = new->ut_line;
98-
size_t idlen;
98+
size_t linelen = strnlen(new->ut_line, sizeof(new->ut_line);
9999
debug_decl(utmp_setid, SUDO_DEBUG_UTMP);
100100

101101
/* Skip over "tty" in the id if old entry did too. */
102102
if (old != NULL) {
103103
/* cppcheck-suppress uninitdata */
104104
if (strncmp(line, "tty", 3) == 0) {
105-
idlen = MIN(sizeof(old->ut_id), 3);
106-
if (strncmp(old->ut_id, "tty", idlen) != 0)
105+
const size_t idlen = MIN(sizeof(old->ut_id), 3);
106+
if (strncmp(old->ut_id, "tty", idlen) != 0) {
107107
line += 3;
108+
linelen -= 3;
109+
}
108110
}
109111
}
110112

111113
/* Store as much as will fit, skipping parts of the beginning as needed. */
112114
/* cppcheck-suppress uninitdata */
113-
idlen = strlen(line);
114-
if (idlen > sizeof(new->ut_id)) {
115-
line += idlen - sizeof(new->ut_id);
116-
idlen = sizeof(new->ut_id);
115+
if (linelen > sizeof(new->ut_id)) {
116+
line += linelen - sizeof(new->ut_id);
117+
linelen = sizeof(new->ut_id);
117118
}
118-
strncpy(new->ut_id, line, idlen);
119+
strncpy(new->ut_id, line, linelen);
119120

120121
debug_return;
121122
}

0 commit comments

Comments
 (0)