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