String functions considered unsafe in kernel

From: Johannes Totz via freebsd-hackers <freebsd-hackers_at_FreeBSD.org>
Date: Thu, 02 Sep 2021 20:57:42 UTC
(looks like gmane swallowed my 1st message, trying again)

Hi folks,

there are a few string (copy, formatting) functions I would consider 
unsafe when used in kernel, in particular when used with untrusted input 
coming from user space.

For example: snprintf.
Yes it has the size of its output buffer given. But its return value is 
problematic. Lets say we have something like

struct ioctl_structure
{
	int blahblah;
	char device_name[64];
}

void ioctl_handler(... caddr_t addr ...)
{
	struct ioctl_structure* inputdata = addr;

	char some_internal_buffer[64];

	snprintf(some_internal_buffer, sizeof(some_internal_buffer), "%s", 
inputdata->device_name);
}

Here, snprintf is supposed to return the number of characters that would 
have been printed. Ie it will scan the input string all the way to the 
end. Unfortunately we can craft input that's not null terminated. So 
snprintf will read well past the end of the buffer, potentially all the 
way into the next page that may or may not be present.

There are more string functions that return similar stuff.
For example strlcpy.

These functions are used *a lot*.
Quite often where the source string is an obvious fixed compile time 
constant, so no problem there.
But also where it's not obvious at first glance.

Have we thought about this as a potential source of problems before?