xref: /linux/include/linux/fortify-string.h (revision 85f24b0ace9aa79142f632fc3ccc730a8d2a4a28)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_FORTIFY_STRING_H_
3 #define _LINUX_FORTIFY_STRING_H_
4 
5 #include <linux/bug.h>
6 #include <linux/const.h>
7 #include <linux/limits.h>
8 
9 #define __FORTIFY_INLINE extern __always_inline __gnu_inline __overloadable
10 #define __RENAME(x) __asm__(#x)
11 
12 #define FORTIFY_REASON_DIR(r)		((r) & 1)
13 #define FORTIFY_REASON_FUNC(r)		((r) >> 1)
14 #define FORTIFY_REASON(func, write)	((func) << 1 | (write))
15 
16 /* Overridden by KUnit tests. */
17 #ifndef fortify_panic
18 # define fortify_panic(func, write, avail, size, retfail)	\
19 	 __fortify_panic(FORTIFY_REASON(func, write), avail, size)
20 #endif
21 #ifndef fortify_warn_once
22 # define fortify_warn_once(x...)	WARN_ONCE(x)
23 #endif
24 
25 #define FORTIFY_READ		 0
26 #define FORTIFY_WRITE		 1
27 
28 #define EACH_FORTIFY_FUNC(macro)	\
29 	macro(strncpy),			\
30 	macro(strnlen),			\
31 	macro(strlen),			\
32 	macro(strscpy),			\
33 	macro(strlcat),			\
34 	macro(strcat),			\
35 	macro(strncat),			\
36 	macro(memset),			\
37 	macro(memcpy),			\
38 	macro(memmove),			\
39 	macro(memscan),			\
40 	macro(memcmp),			\
41 	macro(memchr),			\
42 	macro(memchr_inv),		\
43 	macro(kmemdup),			\
44 	macro(strcpy),			\
45 	macro(UNKNOWN),
46 
47 #define MAKE_FORTIFY_FUNC(func)	FORTIFY_FUNC_##func
48 
49 enum fortify_func {
50 	EACH_FORTIFY_FUNC(MAKE_FORTIFY_FUNC)
51 };
52 
53 void __fortify_report(const u8 reason, const size_t avail, const size_t size);
54 void __fortify_panic(const u8 reason, const size_t avail, const size_t size) __cold __noreturn;
55 void __read_overflow(void) __compiletime_error("detected read beyond size of object (1st parameter)");
56 void __read_overflow2(void) __compiletime_error("detected read beyond size of object (2nd parameter)");
57 void __read_overflow2_field(size_t avail, size_t wanted) __compiletime_warning("detected read beyond size of field (2nd parameter); maybe use struct_group()?");
58 void __write_overflow(void) __compiletime_error("detected write beyond size of object (1st parameter)");
59 void __write_overflow_field(size_t avail, size_t wanted) __compiletime_warning("detected write beyond size of field (1st parameter); maybe use struct_group()?");
60 
61 #define __compiletime_strlen(p)					\
62 ({								\
63 	char *__p = (char *)(p);				\
64 	size_t __ret = SIZE_MAX;				\
65 	const size_t __p_size = __member_size(p);		\
66 	if (__p_size != SIZE_MAX &&				\
67 	    __builtin_constant_p(*__p)) {			\
68 		size_t __p_len = __p_size - 1;			\
69 		if (__builtin_constant_p(__p[__p_len]) &&	\
70 		    __p[__p_len] == '\0')			\
71 			__ret = __builtin_strlen(__p);		\
72 	}							\
73 	__ret;							\
74 })
75 
76 #if defined(__SANITIZE_ADDRESS__)
77 
78 #if !defined(CONFIG_CC_HAS_KASAN_MEMINTRINSIC_PREFIX) && !defined(CONFIG_GENERIC_ENTRY)
79 extern void *__underlying_memset(void *p, int c, __kernel_size_t size) __RENAME(memset);
80 extern void *__underlying_memmove(void *p, const void *q, __kernel_size_t size) __RENAME(memmove);
81 extern void *__underlying_memcpy(void *p, const void *q, __kernel_size_t size) __RENAME(memcpy);
82 #elif defined(CONFIG_KASAN_GENERIC)
83 extern void *__underlying_memset(void *p, int c, __kernel_size_t size) __RENAME(__asan_memset);
84 extern void *__underlying_memmove(void *p, const void *q, __kernel_size_t size) __RENAME(__asan_memmove);
85 extern void *__underlying_memcpy(void *p, const void *q, __kernel_size_t size) __RENAME(__asan_memcpy);
86 #else /* CONFIG_KASAN_SW_TAGS */
87 extern void *__underlying_memset(void *p, int c, __kernel_size_t size) __RENAME(__hwasan_memset);
88 extern void *__underlying_memmove(void *p, const void *q, __kernel_size_t size) __RENAME(__hwasan_memmove);
89 extern void *__underlying_memcpy(void *p, const void *q, __kernel_size_t size) __RENAME(__hwasan_memcpy);
90 #endif
91 
92 extern void *__underlying_memchr(const void *p, int c, __kernel_size_t size) __RENAME(memchr);
93 extern int __underlying_memcmp(const void *p, const void *q, __kernel_size_t size) __RENAME(memcmp);
94 extern char *__underlying_strcat(char *p, const char *q) __RENAME(strcat);
95 extern char *__underlying_strcpy(char *p, const char *q) __RENAME(strcpy);
96 extern __kernel_size_t __underlying_strlen(const char *p) __RENAME(strlen);
97 extern char *__underlying_strncat(char *p, const char *q, __kernel_size_t count) __RENAME(strncat);
98 extern char *__underlying_strncpy(char *p, const char *q, __kernel_size_t size) __RENAME(strncpy);
99 
100 #else
101 
102 #if defined(__SANITIZE_MEMORY__)
103 /*
104  * For KMSAN builds all memcpy/memset/memmove calls should be replaced by the
105  * corresponding __msan_XXX functions.
106  */
107 #include <linux/kmsan_string.h>
108 #define __underlying_memcpy	__msan_memcpy
109 #define __underlying_memmove	__msan_memmove
110 #define __underlying_memset	__msan_memset
111 #else
112 #define __underlying_memcpy	__builtin_memcpy
113 #define __underlying_memmove	__builtin_memmove
114 #define __underlying_memset	__builtin_memset
115 #endif
116 
117 #define __underlying_memchr	__builtin_memchr
118 #define __underlying_memcmp	__builtin_memcmp
119 #define __underlying_strcat	__builtin_strcat
120 #define __underlying_strcpy	__builtin_strcpy
121 #define __underlying_strlen	__builtin_strlen
122 #define __underlying_strncat	__builtin_strncat
123 #define __underlying_strncpy	__builtin_strncpy
124 
125 #endif
126 
127 /**
128  * unsafe_memcpy - memcpy implementation with no FORTIFY bounds checking
129  *
130  * @dst: Destination memory address to write to
131  * @src: Source memory address to read from
132  * @bytes: How many bytes to write to @dst from @src
133  * @justification: Free-form text or comment describing why the use is needed
134  *
135  * This should be used for corner cases where the compiler cannot do the
136  * right thing, or during transitions between APIs, etc. It should be used
137  * very rarely, and includes a place for justification detailing where bounds
138  * checking has happened, and why existing solutions cannot be employed.
139  */
140 #define unsafe_memcpy(dst, src, bytes, justification)		\
141 	__underlying_memcpy(dst, src, bytes)
142 
143 /*
144  * Clang's use of __builtin_*object_size() within inlines needs hinting via
145  * __pass_*object_size(). The preference is to only ever use type 1 (member
146  * size, rather than struct size), but there remain some stragglers using
147  * type 0 that will be converted in the future.
148  */
149 #if __has_builtin(__builtin_dynamic_object_size)
150 #define POS			__pass_dynamic_object_size(1)
151 #define POS0			__pass_dynamic_object_size(0)
152 #else
153 #define POS			__pass_object_size(1)
154 #define POS0			__pass_object_size(0)
155 #endif
156 
157 #define __compiletime_lessthan(bounds, length)	(	\
158 	__builtin_constant_p((bounds) < (length)) &&	\
159 	(bounds) < (length)				\
160 )
161 
162 /**
163  * strncpy - Copy a string to memory with non-guaranteed NUL padding
164  *
165  * @p: pointer to destination of copy
166  * @q: pointer to NUL-terminated source string to copy
167  * @size: bytes to write at @p
168  *
169  * If strlen(@q) >= @size, the copy of @q will stop after @size bytes,
170  * and @p will NOT be NUL-terminated
171  *
172  * If strlen(@q) < @size, following the copy of @q, trailing NUL bytes
173  * will be written to @p until @size total bytes have been written.
174  *
175  * Do not use this function. While FORTIFY_SOURCE tries to avoid
176  * over-reads of @q, it cannot defend against writing unterminated
177  * results to @p. Using strncpy() remains ambiguous and fragile.
178  * Instead, please choose an alternative, so that the expectation
179  * of @p's contents is unambiguous:
180  *
181  * +--------------------+--------------------+------------+
182  * | **p** needs to be: | padded to **size** | not padded |
183  * +====================+====================+============+
184  * |     NUL-terminated | strscpy_pad()      | strscpy()  |
185  * +--------------------+--------------------+------------+
186  * | not NUL-terminated | strtomem_pad()     | strtomem() |
187  * +--------------------+--------------------+------------+
188  *
189  * Note strscpy*()'s differing return values for detecting truncation,
190  * and strtomem*()'s expectation that the destination is marked with
191  * __nonstring when it is a character array.
192  *
193  */
194 __FORTIFY_INLINE __diagnose_as(__builtin_strncpy, 1, 2, 3)
strncpy(char * const POS p,const char * q,__kernel_size_t size)195 char *strncpy(char * const POS p, const char *q, __kernel_size_t size)
196 {
197 	const size_t p_size = __member_size(p);
198 
199 	if (__compiletime_lessthan(p_size, size))
200 		__write_overflow();
201 	if (p_size < size)
202 		fortify_panic(FORTIFY_FUNC_strncpy, FORTIFY_WRITE, p_size, size, p);
203 	return __underlying_strncpy(p, q, size);
204 }
205 
206 extern __kernel_size_t __real_strnlen(const char *, __kernel_size_t) __RENAME(strnlen);
207 /**
208  * strnlen - Return bounded count of characters in a NUL-terminated string
209  *
210  * @p: pointer to NUL-terminated string to count.
211  * @maxlen: maximum number of characters to count.
212  *
213  * Returns number of characters in @p (NOT including the final NUL), or
214  * @maxlen, if no NUL has been found up to there.
215  *
216  */
strnlen(const char * const POS p,__kernel_size_t maxlen)217 __FORTIFY_INLINE __kernel_size_t strnlen(const char * const POS p, __kernel_size_t maxlen)
218 {
219 	const size_t p_size = __member_size(p);
220 	const size_t p_len = __compiletime_strlen(p);
221 	size_t ret;
222 
223 	/* We can take compile-time actions when maxlen is const. */
224 	if (__builtin_constant_p(maxlen) && p_len != SIZE_MAX) {
225 		/* If p is const, we can use its compile-time-known len. */
226 		if (maxlen >= p_size)
227 			return p_len;
228 	}
229 
230 	/* Do not check characters beyond the end of p. */
231 	ret = __real_strnlen(p, maxlen < p_size ? maxlen : p_size);
232 	if (p_size <= ret && maxlen != ret)
233 		fortify_panic(FORTIFY_FUNC_strnlen, FORTIFY_READ, p_size, ret + 1, ret);
234 	return ret;
235 }
236 
237 /*
238  * Defined after fortified strnlen to reuse it. However, it must still be
239  * possible for strlen() to be used on compile-time strings for use in
240  * static initializers (i.e. as a constant expression).
241  */
242 /**
243  * strlen - Return count of characters in a NUL-terminated string
244  *
245  * @p: pointer to NUL-terminated string to count.
246  *
247  * Do not use this function unless the string length is known at
248  * compile-time. When @p is unterminated, this function may crash
249  * or return unexpected counts that could lead to memory content
250  * exposures. Prefer strnlen().
251  *
252  * Returns number of characters in @p (NOT including the final NUL).
253  *
254  */
255 #define strlen(p)							\
256 	__builtin_choose_expr(__is_constexpr(__builtin_strlen(p)),	\
257 		__builtin_strlen(p), __fortify_strlen(p))
258 __FORTIFY_INLINE __diagnose_as(__builtin_strlen, 1)
__fortify_strlen(const char * const POS p)259 __kernel_size_t __fortify_strlen(const char * const POS p)
260 {
261 	const size_t p_size = __member_size(p);
262 	__kernel_size_t ret;
263 
264 	/* Give up if we don't know how large p is. */
265 	if (p_size == SIZE_MAX)
266 		return __underlying_strlen(p);
267 	ret = strnlen(p, p_size);
268 	if (p_size <= ret)
269 		fortify_panic(FORTIFY_FUNC_strlen, FORTIFY_READ, p_size, ret + 1, ret);
270 	return ret;
271 }
272 
273 /* Defined after fortified strnlen() to reuse it. */
274 extern ssize_t __real_strscpy(char *, const char *, size_t) __RENAME(sized_strscpy);
sized_strscpy(char * const POS p,const char * const POS q,size_t size)275 __FORTIFY_INLINE ssize_t sized_strscpy(char * const POS p, const char * const POS q, size_t size)
276 {
277 	/* Use string size rather than possible enclosing struct size. */
278 	const size_t p_size = __member_size(p);
279 	const size_t q_size = __member_size(q);
280 	size_t len;
281 
282 	/* If we cannot get size of p and q default to call strscpy. */
283 	if (p_size == SIZE_MAX && q_size == SIZE_MAX)
284 		return __real_strscpy(p, q, size);
285 
286 	/*
287 	 * If size can be known at compile time and is greater than
288 	 * p_size, generate a compile time write overflow error.
289 	 */
290 	if (__compiletime_lessthan(p_size, size))
291 		__write_overflow();
292 
293 	/* Short-circuit for compile-time known-safe lengths. */
294 	if (__compiletime_lessthan(p_size, SIZE_MAX)) {
295 		len = __compiletime_strlen(q);
296 
297 		if (len < SIZE_MAX && __compiletime_lessthan(len, size)) {
298 			__underlying_memcpy(p, q, len + 1);
299 			return len;
300 		}
301 	}
302 
303 	/*
304 	 * This call protects from read overflow, because len will default to q
305 	 * length if it smaller than size.
306 	 */
307 	len = strnlen(q, size);
308 	/*
309 	 * If len equals size, we will copy only size bytes which leads to
310 	 * -E2BIG being returned.
311 	 * Otherwise we will copy len + 1 because of the final '\O'.
312 	 */
313 	len = len == size ? size : len + 1;
314 
315 	/*
316 	 * Generate a runtime write overflow error if len is greater than
317 	 * p_size.
318 	 */
319 	if (p_size < len)
320 		fortify_panic(FORTIFY_FUNC_strscpy, FORTIFY_WRITE, p_size, len, -E2BIG);
321 
322 	/*
323 	 * We can now safely call vanilla strscpy because we are protected from:
324 	 * 1. Read overflow thanks to call to strnlen().
325 	 * 2. Write overflow thanks to above ifs.
326 	 */
327 	return __real_strscpy(p, q, len);
328 }
329 
330 /* Defined after fortified strlen() to reuse it. */
331 extern size_t __real_strlcat(char *p, const char *q, size_t avail) __RENAME(strlcat);
332 /**
333  * strlcat - Append a string to an existing string
334  *
335  * @p: pointer to %NUL-terminated string to append to
336  * @q: pointer to %NUL-terminated string to append from
337  * @avail: Maximum bytes available in @p
338  *
339  * Appends %NUL-terminated string @q after the %NUL-terminated
340  * string at @p, but will not write beyond @avail bytes total,
341  * potentially truncating the copy from @q. @p will stay
342  * %NUL-terminated only if a %NUL already existed within
343  * the @avail bytes of @p. If so, the resulting number of
344  * bytes copied from @q will be at most "@avail - strlen(@p) - 1".
345  *
346  * Do not use this function. While FORTIFY_SOURCE tries to avoid
347  * read and write overflows, this is only possible when the sizes
348  * of @p and @q are known to the compiler. Prefer building the
349  * string with formatting, via scnprintf(), seq_buf, or similar.
350  *
351  * Returns total bytes that _would_ have been contained by @p
352  * regardless of truncation, similar to snprintf(). If return
353  * value is >= @avail, the string has been truncated.
354  *
355  */
356 __FORTIFY_INLINE
strlcat(char * const POS p,const char * const POS q,size_t avail)357 size_t strlcat(char * const POS p, const char * const POS q, size_t avail)
358 {
359 	const size_t p_size = __member_size(p);
360 	const size_t q_size = __member_size(q);
361 	size_t p_len, copy_len;
362 	size_t actual, wanted;
363 
364 	/* Give up immediately if both buffer sizes are unknown. */
365 	if (p_size == SIZE_MAX && q_size == SIZE_MAX)
366 		return __real_strlcat(p, q, avail);
367 
368 	p_len = strnlen(p, avail);
369 	copy_len = strlen(q);
370 	wanted = actual = p_len + copy_len;
371 
372 	/* Cannot append any more: report truncation. */
373 	if (avail <= p_len)
374 		return wanted;
375 
376 	/* Give up if string is already overflowed. */
377 	if (p_size <= p_len)
378 		fortify_panic(FORTIFY_FUNC_strlcat, FORTIFY_READ, p_size, p_len + 1, wanted);
379 
380 	if (actual >= avail) {
381 		copy_len = avail - p_len - 1;
382 		actual = p_len + copy_len;
383 	}
384 
385 	/* Give up if copy will overflow. */
386 	if (p_size <= actual)
387 		fortify_panic(FORTIFY_FUNC_strlcat, FORTIFY_WRITE, p_size, actual + 1, wanted);
388 	__underlying_memcpy(p + p_len, q, copy_len);
389 	p[actual] = '\0';
390 
391 	return wanted;
392 }
393 
394 /* Defined after fortified strlcat() to reuse it. */
395 /**
396  * strcat - Append a string to an existing string
397  *
398  * @p: pointer to NUL-terminated string to append to
399  * @q: pointer to NUL-terminated source string to append from
400  *
401  * Do not use this function. While FORTIFY_SOURCE tries to avoid
402  * read and write overflows, this is only possible when the
403  * destination buffer size is known to the compiler. Prefer
404  * building the string with formatting, via scnprintf() or similar.
405  * At the very least, use strncat().
406  *
407  * Returns @p.
408  *
409  */
410 __FORTIFY_INLINE __diagnose_as(__builtin_strcat, 1, 2)
strcat(char * const POS p,const char * q)411 char *strcat(char * const POS p, const char *q)
412 {
413 	const size_t p_size = __member_size(p);
414 	const size_t wanted = strlcat(p, q, p_size);
415 
416 	if (p_size <= wanted)
417 		fortify_panic(FORTIFY_FUNC_strcat, FORTIFY_WRITE, p_size, wanted + 1, p);
418 	return p;
419 }
420 
421 /**
422  * strncat - Append a string to an existing string
423  *
424  * @p: pointer to NUL-terminated string to append to
425  * @q: pointer to source string to append from
426  * @count: Maximum bytes to read from @q
427  *
428  * Appends at most @count bytes from @q (stopping at the first
429  * NUL byte) after the NUL-terminated string at @p. @p will be
430  * NUL-terminated.
431  *
432  * Do not use this function. While FORTIFY_SOURCE tries to avoid
433  * read and write overflows, this is only possible when the sizes
434  * of @p and @q are known to the compiler. Prefer building the
435  * string with formatting, via scnprintf() or similar.
436  *
437  * Returns @p.
438  *
439  */
440 /* Defined after fortified strlen() and strnlen() to reuse them. */
441 __FORTIFY_INLINE __diagnose_as(__builtin_strncat, 1, 2, 3)
strncat(char * const POS p,const char * const POS q,__kernel_size_t count)442 char *strncat(char * const POS p, const char * const POS q, __kernel_size_t count)
443 {
444 	const size_t p_size = __member_size(p);
445 	const size_t q_size = __member_size(q);
446 	size_t p_len, copy_len, total;
447 
448 	if (p_size == SIZE_MAX && q_size == SIZE_MAX)
449 		return __underlying_strncat(p, q, count);
450 	p_len = strlen(p);
451 	copy_len = strnlen(q, count);
452 	total = p_len + copy_len + 1;
453 	if (p_size < total)
454 		fortify_panic(FORTIFY_FUNC_strncat, FORTIFY_WRITE, p_size, total, p);
455 	__underlying_memcpy(p + p_len, q, copy_len);
456 	p[p_len + copy_len] = '\0';
457 	return p;
458 }
459 
fortify_memset_chk(__kernel_size_t size,const size_t p_size,const size_t p_size_field)460 __FORTIFY_INLINE bool fortify_memset_chk(__kernel_size_t size,
461 					 const size_t p_size,
462 					 const size_t p_size_field)
463 {
464 	if (__builtin_constant_p(size)) {
465 		/*
466 		 * Length argument is a constant expression, so we
467 		 * can perform compile-time bounds checking where
468 		 * buffer sizes are also known at compile time.
469 		 */
470 
471 		/* Error when size is larger than enclosing struct. */
472 		if (__compiletime_lessthan(p_size_field, p_size) &&
473 		    __compiletime_lessthan(p_size, size))
474 			__write_overflow();
475 
476 		/* Warn when write size is larger than dest field. */
477 		if (__compiletime_lessthan(p_size_field, size))
478 			__write_overflow_field(p_size_field, size);
479 	}
480 	/*
481 	 * At this point, length argument may not be a constant expression,
482 	 * so run-time bounds checking can be done where buffer sizes are
483 	 * known. (This is not an "else" because the above checks may only
484 	 * be compile-time warnings, and we want to still warn for run-time
485 	 * overflows.)
486 	 */
487 
488 	/*
489 	 * Always stop accesses beyond the struct that contains the
490 	 * field, when the buffer's remaining size is known.
491 	 * (The SIZE_MAX test is to optimize away checks where the buffer
492 	 * lengths are unknown.)
493 	 */
494 	if (p_size != SIZE_MAX && p_size < size)
495 		fortify_panic(FORTIFY_FUNC_memset, FORTIFY_WRITE, p_size, size, true);
496 	return false;
497 }
498 
499 #define __fortify_memset_chk(p, c, size, p_size, p_size_field) ({	\
500 	size_t __fortify_size = (size_t)(size);				\
501 	fortify_memset_chk(__fortify_size, p_size, p_size_field),	\
502 	__underlying_memset(p, c, __fortify_size);			\
503 })
504 
505 /*
506  * __struct_size() vs __member_size() must be captured here to avoid
507  * evaluating argument side-effects further into the macro layers.
508  */
509 #ifndef CONFIG_KMSAN
510 #define memset(p, c, s) __fortify_memset_chk(p, c, s,			\
511 		__struct_size(p), __member_size(p))
512 #endif
513 
514 /*
515  * To make sure the compiler can enforce protection against buffer overflows,
516  * memcpy(), memmove(), and memset() must not be used beyond individual
517  * struct members. If you need to copy across multiple members, please use
518  * struct_group() to create a named mirror of an anonymous struct union.
519  * (e.g. see struct sk_buff.) Read overflow checking is currently only
520  * done when a write overflow is also present, or when building with W=1.
521  *
522  * Mitigation coverage matrix
523  *					Bounds checking at:
524  *					+-------+-------+-------+-------+
525  *					| Compile time  |   Run time    |
526  * memcpy() argument sizes:		| write | read  | write | read  |
527  *        dest     source   length      +-------+-------+-------+-------+
528  * memcpy(known,   known,   constant)	|   y   |   y   |  n/a  |  n/a  |
529  * memcpy(known,   unknown, constant)	|   y   |   n   |  n/a  |   V   |
530  * memcpy(known,   known,   dynamic)	|   n   |   n   |   B   |   B   |
531  * memcpy(known,   unknown, dynamic)	|   n   |   n   |   B   |   V   |
532  * memcpy(unknown, known,   constant)	|   n   |   y   |   V   |  n/a  |
533  * memcpy(unknown, unknown, constant)	|   n   |   n   |   V   |   V   |
534  * memcpy(unknown, known,   dynamic)	|   n   |   n   |   V   |   B   |
535  * memcpy(unknown, unknown, dynamic)	|   n   |   n   |   V   |   V   |
536  *					+-------+-------+-------+-------+
537  *
538  * y = perform deterministic compile-time bounds checking
539  * n = cannot perform deterministic compile-time bounds checking
540  * n/a = no run-time bounds checking needed since compile-time deterministic
541  * B = can perform run-time bounds checking (currently unimplemented)
542  * V = vulnerable to run-time overflow (will need refactoring to solve)
543  *
544  */
fortify_memcpy_chk(__kernel_size_t size,const size_t p_size,const size_t q_size,const size_t p_size_field,const size_t q_size_field,const u8 func)545 __FORTIFY_INLINE bool fortify_memcpy_chk(__kernel_size_t size,
546 					 const size_t p_size,
547 					 const size_t q_size,
548 					 const size_t p_size_field,
549 					 const size_t q_size_field,
550 					 const u8 func)
551 {
552 	if (__builtin_constant_p(size)) {
553 		/*
554 		 * Length argument is a constant expression, so we
555 		 * can perform compile-time bounds checking where
556 		 * buffer sizes are also known at compile time.
557 		 */
558 
559 		/* Error when size is larger than enclosing struct. */
560 		if (__compiletime_lessthan(p_size_field, p_size) &&
561 		    __compiletime_lessthan(p_size, size))
562 			__write_overflow();
563 		if (__compiletime_lessthan(q_size_field, q_size) &&
564 		    __compiletime_lessthan(q_size, size))
565 			__read_overflow2();
566 
567 		/* Warn when write size argument larger than dest field. */
568 		if (__compiletime_lessthan(p_size_field, size))
569 			__write_overflow_field(p_size_field, size);
570 		/*
571 		 * Warn for source field over-read when building with W=1
572 		 * or when an over-write happened, so both can be fixed at
573 		 * the same time.
574 		 */
575 		if ((IS_ENABLED(KBUILD_EXTRA_WARN1) ||
576 		     __compiletime_lessthan(p_size_field, size)) &&
577 		    __compiletime_lessthan(q_size_field, size))
578 			__read_overflow2_field(q_size_field, size);
579 	}
580 	/*
581 	 * At this point, length argument may not be a constant expression,
582 	 * so run-time bounds checking can be done where buffer sizes are
583 	 * known. (This is not an "else" because the above checks may only
584 	 * be compile-time warnings, and we want to still warn for run-time
585 	 * overflows.)
586 	 */
587 
588 	/*
589 	 * Always stop accesses beyond the struct that contains the
590 	 * field, when the buffer's remaining size is known.
591 	 * (The SIZE_MAX test is to optimize away checks where the buffer
592 	 * lengths are unknown.)
593 	 */
594 	if (p_size != SIZE_MAX && p_size < size)
595 		fortify_panic(func, FORTIFY_WRITE, p_size, size, true);
596 	else if (q_size != SIZE_MAX && q_size < size)
597 		fortify_panic(func, FORTIFY_READ, q_size, size, true);
598 
599 	/*
600 	 * Warn when writing beyond destination field size.
601 	 *
602 	 * Note the implementation of __builtin_*object_size() behaves
603 	 * like sizeof() when not directly referencing a flexible
604 	 * array member, which means there will be many bounds checks
605 	 * that will appear at run-time, without a way for them to be
606 	 * detected at compile-time (as can be done when the destination
607 	 * is specifically the flexible array member).
608 	 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101832
609 	 */
610 	if (p_size_field != SIZE_MAX &&
611 	    p_size != p_size_field && p_size_field < size)
612 		return true;
613 
614 	return false;
615 }
616 
617 /*
618  * To work around what seems to be an optimizer bug, the macro arguments
619  * need to have const copies or the values end up changed by the time they
620  * reach fortify_warn_once(). See commit 6f7630b1b5bc ("fortify: Capture
621  * __bos() results in const temp vars") for more details.
622  */
623 #define __fortify_memcpy_chk(p, q, size, p_size, q_size,		\
624 			     p_size_field, q_size_field, op) ({		\
625 	const size_t __fortify_size = (size_t)(size);			\
626 	const size_t __p_size = (p_size);				\
627 	const size_t __q_size = (q_size);				\
628 	const size_t __p_size_field = (p_size_field);			\
629 	const size_t __q_size_field = (q_size_field);			\
630 	/* Keep a mutable version of the size for the final copy. */	\
631 	size_t __copy_size = __fortify_size;				\
632 	fortify_warn_once(fortify_memcpy_chk(__fortify_size, __p_size,	\
633 				     __q_size, __p_size_field,		\
634 				     __q_size_field, FORTIFY_FUNC_ ##op), \
635 		  #op ": detected field-spanning write (size %zu) of single %s (size %zu)\n", \
636 		  __fortify_size,					\
637 		  "field \"" #p "\" at " FILE_LINE,			\
638 		  __p_size_field);					\
639 	/* Hide only the run-time size from value range tracking to */	\
640 	/* silence compile-time false positive bounds warnings. */	\
641 	if (!__builtin_constant_p(__copy_size))				\
642 		OPTIMIZER_HIDE_VAR(__copy_size);			\
643 	__underlying_##op(p, q, __copy_size);				\
644 })
645 
646 /*
647  * Notes about compile-time buffer size detection:
648  *
649  * With these types...
650  *
651  *	struct middle {
652  *		u16 a;
653  *		u8 middle_buf[16];
654  *		int b;
655  *	};
656  *	struct end {
657  *		u16 a;
658  *		u8 end_buf[16];
659  *	};
660  *	struct flex {
661  *		int a;
662  *		u8 flex_buf[];
663  *	};
664  *
665  *	void func(TYPE *ptr) { ... }
666  *
667  * Cases where destination size cannot be currently detected:
668  * - the size of ptr's object (seemingly by design, gcc & clang fail):
669  *	__builtin_object_size(ptr, 1) == SIZE_MAX
670  * - the size of flexible arrays in ptr's obj (by design, dynamic size):
671  *	__builtin_object_size(ptr->flex_buf, 1) == SIZE_MAX
672  * - the size of ANY array at the end of ptr's obj (gcc and clang bug):
673  *	__builtin_object_size(ptr->end_buf, 1) == SIZE_MAX
674  *	https://gcc.gnu.org/bugzilla/show_bug.cgi?id=101836
675  *
676  * Cases where destination size is currently detected:
677  * - the size of non-array members within ptr's object:
678  *	__builtin_object_size(ptr->a, 1) == 2
679  * - the size of non-flexible-array in the middle of ptr's obj:
680  *	__builtin_object_size(ptr->middle_buf, 1) == 16
681  *
682  */
683 
684 /*
685  * __struct_size() vs __member_size() must be captured here to avoid
686  * evaluating argument side-effects further into the macro layers.
687  */
688 #define memcpy(p, q, s)  __fortify_memcpy_chk(p, q, s,			\
689 		__struct_size(p), __struct_size(q),			\
690 		__member_size(p), __member_size(q),			\
691 		memcpy)
692 #define memmove(p, q, s)  __fortify_memcpy_chk(p, q, s,			\
693 		__struct_size(p), __struct_size(q),			\
694 		__member_size(p), __member_size(q),			\
695 		memmove)
696 
697 extern void *__real_memscan(void *, int, __kernel_size_t) __RENAME(memscan);
memscan(void * const POS0 p,int c,__kernel_size_t size)698 __FORTIFY_INLINE void *memscan(void * const POS0 p, int c, __kernel_size_t size)
699 {
700 	const size_t p_size = __struct_size(p);
701 
702 	if (__compiletime_lessthan(p_size, size))
703 		__read_overflow();
704 	if (p_size < size)
705 		fortify_panic(FORTIFY_FUNC_memscan, FORTIFY_READ, p_size, size, NULL);
706 	return __real_memscan(p, c, size);
707 }
708 
709 __FORTIFY_INLINE __diagnose_as(__builtin_memcmp, 1, 2, 3)
memcmp(const void * const POS0 p,const void * const POS0 q,__kernel_size_t size)710 int memcmp(const void * const POS0 p, const void * const POS0 q, __kernel_size_t size)
711 {
712 	const size_t p_size = __struct_size(p);
713 	const size_t q_size = __struct_size(q);
714 
715 	if (__builtin_constant_p(size)) {
716 		if (__compiletime_lessthan(p_size, size))
717 			__read_overflow();
718 		if (__compiletime_lessthan(q_size, size))
719 			__read_overflow2();
720 	}
721 	if (p_size < size)
722 		fortify_panic(FORTIFY_FUNC_memcmp, FORTIFY_READ, p_size, size, INT_MIN);
723 	else if (q_size < size)
724 		fortify_panic(FORTIFY_FUNC_memcmp, FORTIFY_READ, q_size, size, INT_MIN);
725 	return __underlying_memcmp(p, q, size);
726 }
727 
728 __FORTIFY_INLINE __diagnose_as(__builtin_memchr, 1, 2, 3)
memchr(const void * const POS0 p,int c,__kernel_size_t size)729 void *memchr(const void * const POS0 p, int c, __kernel_size_t size)
730 {
731 	const size_t p_size = __struct_size(p);
732 
733 	if (__compiletime_lessthan(p_size, size))
734 		__read_overflow();
735 	if (p_size < size)
736 		fortify_panic(FORTIFY_FUNC_memchr, FORTIFY_READ, p_size, size, NULL);
737 	return __underlying_memchr(p, c, size);
738 }
739 
740 void *__real_memchr_inv(const void *s, int c, size_t n) __RENAME(memchr_inv);
memchr_inv(const void * const POS0 p,int c,size_t size)741 __FORTIFY_INLINE void *memchr_inv(const void * const POS0 p, int c, size_t size)
742 {
743 	const size_t p_size = __struct_size(p);
744 
745 	if (__compiletime_lessthan(p_size, size))
746 		__read_overflow();
747 	if (p_size < size)
748 		fortify_panic(FORTIFY_FUNC_memchr_inv, FORTIFY_READ, p_size, size, NULL);
749 	return __real_memchr_inv(p, c, size);
750 }
751 
752 extern void *__real_kmemdup(const void *src, size_t len, gfp_t gfp) __RENAME(kmemdup_noprof)
753 								    __realloc_size(2);
kmemdup_noprof(const void * const POS0 p,size_t size,gfp_t gfp)754 __FORTIFY_INLINE void *kmemdup_noprof(const void * const POS0 p, size_t size, gfp_t gfp)
755 {
756 	const size_t p_size = __struct_size(p);
757 
758 	if (__compiletime_lessthan(p_size, size))
759 		__read_overflow();
760 	if (p_size < size)
761 		fortify_panic(FORTIFY_FUNC_kmemdup, FORTIFY_READ, p_size, size,
762 			      __real_kmemdup(p, 0, gfp));
763 	return __real_kmemdup(p, size, gfp);
764 }
765 #define kmemdup(...)	alloc_hooks(kmemdup_noprof(__VA_ARGS__))
766 
767 /**
768  * strcpy - Copy a string into another string buffer
769  *
770  * @p: pointer to destination of copy
771  * @q: pointer to NUL-terminated source string to copy
772  *
773  * Do not use this function. While FORTIFY_SOURCE tries to avoid
774  * overflows, this is only possible when the sizes of @q and @p are
775  * known to the compiler. Prefer strscpy(), though note its different
776  * return values for detecting truncation.
777  *
778  * Returns @p.
779  *
780  */
781 /* Defined after fortified strlen to reuse it. */
782 __FORTIFY_INLINE __diagnose_as(__builtin_strcpy, 1, 2)
strcpy(char * const POS p,const char * const POS q)783 char *strcpy(char * const POS p, const char * const POS q)
784 {
785 	const size_t p_size = __member_size(p);
786 	const size_t q_size = __member_size(q);
787 	size_t size;
788 
789 	/* If neither buffer size is known, immediately give up. */
790 	if (__builtin_constant_p(p_size) &&
791 	    __builtin_constant_p(q_size) &&
792 	    p_size == SIZE_MAX && q_size == SIZE_MAX)
793 		return __underlying_strcpy(p, q);
794 	size = strlen(q) + 1;
795 	/* Compile-time check for const size overflow. */
796 	if (__compiletime_lessthan(p_size, size))
797 		__write_overflow();
798 	/* Run-time check for dynamic size overflow. */
799 	if (p_size < size)
800 		fortify_panic(FORTIFY_FUNC_strcpy, FORTIFY_WRITE, p_size, size, p);
801 	__underlying_memcpy(p, q, size);
802 	return p;
803 }
804 
805 /* Don't use these outside the FORITFY_SOURCE implementation */
806 #undef __underlying_memchr
807 #undef __underlying_memcmp
808 #undef __underlying_strcat
809 #undef __underlying_strcpy
810 #undef __underlying_strlen
811 #undef __underlying_strncat
812 #undef __underlying_strncpy
813 
814 #undef POS
815 #undef POS0
816 
817 #endif /* _LINUX_FORTIFY_STRING_H_ */
818