xref: /linux-6.15/include/linux/fortify-string.h (revision ed5edd5a)
1 /* SPDX-License-Identifier: GPL-2.0 */
2 #ifndef _LINUX_FORTIFY_STRING_H_
3 #define _LINUX_FORTIFY_STRING_H_
4 
5 #include <linux/const.h>
6 
7 #define __FORTIFY_INLINE extern __always_inline __gnu_inline __overloadable
8 #define __RENAME(x) __asm__(#x)
9 
10 void fortify_panic(const char *name) __noreturn __cold;
11 void __read_overflow(void) __compiletime_error("detected read beyond size of object (1st parameter)");
12 void __read_overflow2(void) __compiletime_error("detected read beyond size of object (2nd parameter)");
13 void __read_overflow2_field(size_t avail, size_t wanted) __compiletime_warning("detected read beyond size of field (2nd parameter); maybe use struct_group()?");
14 void __write_overflow(void) __compiletime_error("detected write beyond size of object (1st parameter)");
15 void __write_overflow_field(size_t avail, size_t wanted) __compiletime_warning("detected write beyond size of field (1st parameter); maybe use struct_group()?");
16 
17 #define __compiletime_strlen(p)					\
18 ({								\
19 	unsigned char *__p = (unsigned char *)(p);		\
20 	size_t __ret = (size_t)-1;				\
21 	size_t __p_size = __builtin_object_size(p, 1);		\
22 	if (__p_size != (size_t)-1) {				\
23 		size_t __p_len = __p_size - 1;			\
24 		if (__builtin_constant_p(__p[__p_len]) &&	\
25 		    __p[__p_len] == '\0')			\
26 			__ret = __builtin_strlen(__p);		\
27 	}							\
28 	__ret;							\
29 })
30 
31 #if defined(CONFIG_KASAN_GENERIC) || defined(CONFIG_KASAN_SW_TAGS)
32 extern void *__underlying_memchr(const void *p, int c, __kernel_size_t size) __RENAME(memchr);
33 extern int __underlying_memcmp(const void *p, const void *q, __kernel_size_t size) __RENAME(memcmp);
34 extern void *__underlying_memcpy(void *p, const void *q, __kernel_size_t size) __RENAME(memcpy);
35 extern void *__underlying_memmove(void *p, const void *q, __kernel_size_t size) __RENAME(memmove);
36 extern void *__underlying_memset(void *p, int c, __kernel_size_t size) __RENAME(memset);
37 extern char *__underlying_strcat(char *p, const char *q) __RENAME(strcat);
38 extern char *__underlying_strcpy(char *p, const char *q) __RENAME(strcpy);
39 extern __kernel_size_t __underlying_strlen(const char *p) __RENAME(strlen);
40 extern char *__underlying_strncat(char *p, const char *q, __kernel_size_t count) __RENAME(strncat);
41 extern char *__underlying_strncpy(char *p, const char *q, __kernel_size_t size) __RENAME(strncpy);
42 #else
43 #define __underlying_memchr	__builtin_memchr
44 #define __underlying_memcmp	__builtin_memcmp
45 #define __underlying_memcpy	__builtin_memcpy
46 #define __underlying_memmove	__builtin_memmove
47 #define __underlying_memset	__builtin_memset
48 #define __underlying_strcat	__builtin_strcat
49 #define __underlying_strcpy	__builtin_strcpy
50 #define __underlying_strlen	__builtin_strlen
51 #define __underlying_strncat	__builtin_strncat
52 #define __underlying_strncpy	__builtin_strncpy
53 #endif
54 
55 /*
56  * Clang's use of __builtin_object_size() within inlines needs hinting via
57  * __pass_object_size(). The preference is to only ever use type 1 (member
58  * size, rather than struct size), but there remain some stragglers using
59  * type 0 that will be converted in the future.
60  */
61 #define POS	__pass_object_size(1)
62 #define POS0	__pass_object_size(0)
63 
64 __FORTIFY_INLINE __diagnose_as(__builtin_strncpy, 1, 2, 3)
65 char *strncpy(char * const POS p, const char *q, __kernel_size_t size)
66 {
67 	size_t p_size = __builtin_object_size(p, 1);
68 
69 	if (__builtin_constant_p(size) && p_size < size)
70 		__write_overflow();
71 	if (p_size < size)
72 		fortify_panic(__func__);
73 	return __underlying_strncpy(p, q, size);
74 }
75 
76 __FORTIFY_INLINE __diagnose_as(__builtin_strcat, 1, 2)
77 char *strcat(char * const POS p, const char *q)
78 {
79 	size_t p_size = __builtin_object_size(p, 1);
80 
81 	if (p_size == (size_t)-1)
82 		return __underlying_strcat(p, q);
83 	if (strlcat(p, q, p_size) >= p_size)
84 		fortify_panic(__func__);
85 	return p;
86 }
87 
88 extern __kernel_size_t __real_strnlen(const char *, __kernel_size_t) __RENAME(strnlen);
89 __FORTIFY_INLINE __kernel_size_t strnlen(const char * const POS p, __kernel_size_t maxlen)
90 {
91 	size_t p_size = __builtin_object_size(p, 1);
92 	size_t p_len = __compiletime_strlen(p);
93 	size_t ret;
94 
95 	/* We can take compile-time actions when maxlen is const. */
96 	if (__builtin_constant_p(maxlen) && p_len != (size_t)-1) {
97 		/* If p is const, we can use its compile-time-known len. */
98 		if (maxlen >= p_size)
99 			return p_len;
100 	}
101 
102 	/* Do not check characters beyond the end of p. */
103 	ret = __real_strnlen(p, maxlen < p_size ? maxlen : p_size);
104 	if (p_size <= ret && maxlen != ret)
105 		fortify_panic(__func__);
106 	return ret;
107 }
108 
109 /*
110  * Defined after fortified strnlen to reuse it. However, it must still be
111  * possible for strlen() to be used on compile-time strings for use in
112  * static initializers (i.e. as a constant expression).
113  */
114 #define strlen(p)							\
115 	__builtin_choose_expr(__is_constexpr(__builtin_strlen(p)),	\
116 		__builtin_strlen(p), __fortify_strlen(p))
117 __FORTIFY_INLINE __diagnose_as(__builtin_strlen, 1)
118 __kernel_size_t __fortify_strlen(const char * const POS p)
119 {
120 	__kernel_size_t ret;
121 	size_t p_size = __builtin_object_size(p, 1);
122 
123 	/* Give up if we don't know how large p is. */
124 	if (p_size == (size_t)-1)
125 		return __underlying_strlen(p);
126 	ret = strnlen(p, p_size);
127 	if (p_size <= ret)
128 		fortify_panic(__func__);
129 	return ret;
130 }
131 
132 /* defined after fortified strlen to reuse it */
133 extern size_t __real_strlcpy(char *, const char *, size_t) __RENAME(strlcpy);
134 __FORTIFY_INLINE size_t strlcpy(char * const POS p, const char * const POS q, size_t size)
135 {
136 	size_t p_size = __builtin_object_size(p, 1);
137 	size_t q_size = __builtin_object_size(q, 1);
138 	size_t q_len;	/* Full count of source string length. */
139 	size_t len;	/* Count of characters going into destination. */
140 
141 	if (p_size == (size_t)-1 && q_size == (size_t)-1)
142 		return __real_strlcpy(p, q, size);
143 	q_len = strlen(q);
144 	len = (q_len >= size) ? size - 1 : q_len;
145 	if (__builtin_constant_p(size) && __builtin_constant_p(q_len) && size) {
146 		/* Write size is always larger than destination. */
147 		if (len >= p_size)
148 			__write_overflow();
149 	}
150 	if (size) {
151 		if (len >= p_size)
152 			fortify_panic(__func__);
153 		__underlying_memcpy(p, q, len);
154 		p[len] = '\0';
155 	}
156 	return q_len;
157 }
158 
159 /* defined after fortified strnlen to reuse it */
160 extern ssize_t __real_strscpy(char *, const char *, size_t) __RENAME(strscpy);
161 __FORTIFY_INLINE ssize_t strscpy(char * const POS p, const char * const POS q, size_t size)
162 {
163 	size_t len;
164 	/* Use string size rather than possible enclosing struct size. */
165 	size_t p_size = __builtin_object_size(p, 1);
166 	size_t q_size = __builtin_object_size(q, 1);
167 
168 	/* If we cannot get size of p and q default to call strscpy. */
169 	if (p_size == (size_t) -1 && q_size == (size_t) -1)
170 		return __real_strscpy(p, q, size);
171 
172 	/*
173 	 * If size can be known at compile time and is greater than
174 	 * p_size, generate a compile time write overflow error.
175 	 */
176 	if (__builtin_constant_p(size) && size > p_size)
177 		__write_overflow();
178 
179 	/*
180 	 * This call protects from read overflow, because len will default to q
181 	 * length if it smaller than size.
182 	 */
183 	len = strnlen(q, size);
184 	/*
185 	 * If len equals size, we will copy only size bytes which leads to
186 	 * -E2BIG being returned.
187 	 * Otherwise we will copy len + 1 because of the final '\O'.
188 	 */
189 	len = len == size ? size : len + 1;
190 
191 	/*
192 	 * Generate a runtime write overflow error if len is greater than
193 	 * p_size.
194 	 */
195 	if (len > p_size)
196 		fortify_panic(__func__);
197 
198 	/*
199 	 * We can now safely call vanilla strscpy because we are protected from:
200 	 * 1. Read overflow thanks to call to strnlen().
201 	 * 2. Write overflow thanks to above ifs.
202 	 */
203 	return __real_strscpy(p, q, len);
204 }
205 
206 /* defined after fortified strlen and strnlen to reuse them */
207 __FORTIFY_INLINE __diagnose_as(__builtin_strncat, 1, 2, 3)
208 char *strncat(char * const POS p, const char * const POS q, __kernel_size_t count)
209 {
210 	size_t p_len, copy_len;
211 	size_t p_size = __builtin_object_size(p, 1);
212 	size_t q_size = __builtin_object_size(q, 1);
213 
214 	if (p_size == (size_t)-1 && q_size == (size_t)-1)
215 		return __underlying_strncat(p, q, count);
216 	p_len = strlen(p);
217 	copy_len = strnlen(q, count);
218 	if (p_size < p_len + copy_len + 1)
219 		fortify_panic(__func__);
220 	__underlying_memcpy(p + p_len, q, copy_len);
221 	p[p_len + copy_len] = '\0';
222 	return p;
223 }
224 
225 __FORTIFY_INLINE void fortify_memset_chk(__kernel_size_t size,
226 					 const size_t p_size,
227 					 const size_t p_size_field)
228 {
229 	if (__builtin_constant_p(size)) {
230 		/*
231 		 * Length argument is a constant expression, so we
232 		 * can perform compile-time bounds checking where
233 		 * buffer sizes are known.
234 		 */
235 
236 		/* Error when size is larger than enclosing struct. */
237 		if (p_size > p_size_field && p_size < size)
238 			__write_overflow();
239 
240 		/* Warn when write size is larger than dest field. */
241 		if (p_size_field < size)
242 			__write_overflow_field(p_size_field, size);
243 	}
244 	/*
245 	 * At this point, length argument may not be a constant expression,
246 	 * so run-time bounds checking can be done where buffer sizes are
247 	 * known. (This is not an "else" because the above checks may only
248 	 * be compile-time warnings, and we want to still warn for run-time
249 	 * overflows.)
250 	 */
251 
252 	/*
253 	 * Always stop accesses beyond the struct that contains the
254 	 * field, when the buffer's remaining size is known.
255 	 * (The -1 test is to optimize away checks where the buffer
256 	 * lengths are unknown.)
257 	 */
258 	if (p_size != (size_t)(-1) && p_size < size)
259 		fortify_panic("memset");
260 }
261 
262 #define __fortify_memset_chk(p, c, size, p_size, p_size_field) ({	\
263 	size_t __fortify_size = (size_t)(size);				\
264 	fortify_memset_chk(__fortify_size, p_size, p_size_field),	\
265 	__underlying_memset(p, c, __fortify_size);			\
266 })
267 
268 /*
269  * __builtin_object_size() must be captured here to avoid evaluating argument
270  * side-effects further into the macro layers.
271  */
272 #define memset(p, c, s) __fortify_memset_chk(p, c, s,			\
273 		__builtin_object_size(p, 0), __builtin_object_size(p, 1))
274 
275 /*
276  * To make sure the compiler can enforce protection against buffer overflows,
277  * memcpy(), memmove(), and memset() must not be used beyond individual
278  * struct members. If you need to copy across multiple members, please use
279  * struct_group() to create a named mirror of an anonymous struct union.
280  * (e.g. see struct sk_buff.) Read overflow checking is currently only
281  * done when a write overflow is also present, or when building with W=1.
282  *
283  * Mitigation coverage matrix
284  *					Bounds checking at:
285  *					+-------+-------+-------+-------+
286  *					| Compile time  |   Run time    |
287  * memcpy() argument sizes:		| write | read  | write | read  |
288  *        dest     source   length      +-------+-------+-------+-------+
289  * memcpy(known,   known,   constant)	|   y   |   y   |  n/a  |  n/a  |
290  * memcpy(known,   unknown, constant)	|   y   |   n   |  n/a  |   V   |
291  * memcpy(known,   known,   dynamic)	|   n   |   n   |   B   |   B   |
292  * memcpy(known,   unknown, dynamic)	|   n   |   n   |   B   |   V   |
293  * memcpy(unknown, known,   constant)	|   n   |   y   |   V   |  n/a  |
294  * memcpy(unknown, unknown, constant)	|   n   |   n   |   V   |   V   |
295  * memcpy(unknown, known,   dynamic)	|   n   |   n   |   V   |   B   |
296  * memcpy(unknown, unknown, dynamic)	|   n   |   n   |   V   |   V   |
297  *					+-------+-------+-------+-------+
298  *
299  * y = perform deterministic compile-time bounds checking
300  * n = cannot perform deterministic compile-time bounds checking
301  * n/a = no run-time bounds checking needed since compile-time deterministic
302  * B = can perform run-time bounds checking (currently unimplemented)
303  * V = vulnerable to run-time overflow (will need refactoring to solve)
304  *
305  */
306 __FORTIFY_INLINE void fortify_memcpy_chk(__kernel_size_t size,
307 					 const size_t p_size,
308 					 const size_t q_size,
309 					 const size_t p_size_field,
310 					 const size_t q_size_field,
311 					 const char *func)
312 {
313 	if (__builtin_constant_p(size)) {
314 		/*
315 		 * Length argument is a constant expression, so we
316 		 * can perform compile-time bounds checking where
317 		 * buffer sizes are known.
318 		 */
319 
320 		/* Error when size is larger than enclosing struct. */
321 		if (p_size > p_size_field && p_size < size)
322 			__write_overflow();
323 		if (q_size > q_size_field && q_size < size)
324 			__read_overflow2();
325 
326 		/* Warn when write size argument larger than dest field. */
327 		if (p_size_field < size)
328 			__write_overflow_field(p_size_field, size);
329 		/*
330 		 * Warn for source field over-read when building with W=1
331 		 * or when an over-write happened, so both can be fixed at
332 		 * the same time.
333 		 */
334 		if ((IS_ENABLED(KBUILD_EXTRA_WARN1) || p_size_field < size) &&
335 		    q_size_field < size)
336 			__read_overflow2_field(q_size_field, size);
337 	}
338 	/*
339 	 * At this point, length argument may not be a constant expression,
340 	 * so run-time bounds checking can be done where buffer sizes are
341 	 * known. (This is not an "else" because the above checks may only
342 	 * be compile-time warnings, and we want to still warn for run-time
343 	 * overflows.)
344 	 */
345 
346 	/*
347 	 * Always stop accesses beyond the struct that contains the
348 	 * field, when the buffer's remaining size is known.
349 	 * (The -1 test is to optimize away checks where the buffer
350 	 * lengths are unknown.)
351 	 */
352 	if ((p_size != (size_t)(-1) && p_size < size) ||
353 	    (q_size != (size_t)(-1) && q_size < size))
354 		fortify_panic(func);
355 }
356 
357 #define __fortify_memcpy_chk(p, q, size, p_size, q_size,		\
358 			     p_size_field, q_size_field, op) ({		\
359 	size_t __fortify_size = (size_t)(size);				\
360 	fortify_memcpy_chk(__fortify_size, p_size, q_size,		\
361 			   p_size_field, q_size_field, #op);		\
362 	__underlying_##op(p, q, __fortify_size);			\
363 })
364 
365 /*
366  * __builtin_object_size() must be captured here to avoid evaluating argument
367  * side-effects further into the macro layers.
368  */
369 #define memcpy(p, q, s)  __fortify_memcpy_chk(p, q, s,			\
370 		__builtin_object_size(p, 0), __builtin_object_size(q, 0), \
371 		__builtin_object_size(p, 1), __builtin_object_size(q, 1), \
372 		memcpy)
373 #define memmove(p, q, s)  __fortify_memcpy_chk(p, q, s,			\
374 		__builtin_object_size(p, 0), __builtin_object_size(q, 0), \
375 		__builtin_object_size(p, 1), __builtin_object_size(q, 1), \
376 		memmove)
377 
378 extern void *__real_memscan(void *, int, __kernel_size_t) __RENAME(memscan);
379 __FORTIFY_INLINE void *memscan(void * const POS0 p, int c, __kernel_size_t size)
380 {
381 	size_t p_size = __builtin_object_size(p, 0);
382 
383 	if (__builtin_constant_p(size) && p_size < size)
384 		__read_overflow();
385 	if (p_size < size)
386 		fortify_panic(__func__);
387 	return __real_memscan(p, c, size);
388 }
389 
390 __FORTIFY_INLINE __diagnose_as(__builtin_memcmp, 1, 2, 3)
391 int memcmp(const void * const POS0 p, const void * const POS0 q, __kernel_size_t size)
392 {
393 	size_t p_size = __builtin_object_size(p, 0);
394 	size_t q_size = __builtin_object_size(q, 0);
395 
396 	if (__builtin_constant_p(size)) {
397 		if (p_size < size)
398 			__read_overflow();
399 		if (q_size < size)
400 			__read_overflow2();
401 	}
402 	if (p_size < size || q_size < size)
403 		fortify_panic(__func__);
404 	return __underlying_memcmp(p, q, size);
405 }
406 
407 __FORTIFY_INLINE __diagnose_as(__builtin_memchr, 1, 2, 3)
408 void *memchr(const void * const POS0 p, int c, __kernel_size_t size)
409 {
410 	size_t p_size = __builtin_object_size(p, 0);
411 
412 	if (__builtin_constant_p(size) && p_size < size)
413 		__read_overflow();
414 	if (p_size < size)
415 		fortify_panic(__func__);
416 	return __underlying_memchr(p, c, size);
417 }
418 
419 void *__real_memchr_inv(const void *s, int c, size_t n) __RENAME(memchr_inv);
420 __FORTIFY_INLINE void *memchr_inv(const void * const POS0 p, int c, size_t size)
421 {
422 	size_t p_size = __builtin_object_size(p, 0);
423 
424 	if (__builtin_constant_p(size) && p_size < size)
425 		__read_overflow();
426 	if (p_size < size)
427 		fortify_panic(__func__);
428 	return __real_memchr_inv(p, c, size);
429 }
430 
431 extern void *__real_kmemdup(const void *src, size_t len, gfp_t gfp) __RENAME(kmemdup);
432 __FORTIFY_INLINE void *kmemdup(const void * const POS0 p, size_t size, gfp_t gfp)
433 {
434 	size_t p_size = __builtin_object_size(p, 0);
435 
436 	if (__builtin_constant_p(size) && p_size < size)
437 		__read_overflow();
438 	if (p_size < size)
439 		fortify_panic(__func__);
440 	return __real_kmemdup(p, size, gfp);
441 }
442 
443 /* Defined after fortified strlen to reuse it. */
444 __FORTIFY_INLINE __diagnose_as(__builtin_strcpy, 1, 2)
445 char *strcpy(char * const POS p, const char * const POS q)
446 {
447 	size_t p_size = __builtin_object_size(p, 1);
448 	size_t q_size = __builtin_object_size(q, 1);
449 	size_t size;
450 
451 	/* If neither buffer size is known, immediately give up. */
452 	if (p_size == (size_t)-1 && q_size == (size_t)-1)
453 		return __underlying_strcpy(p, q);
454 	size = strlen(q) + 1;
455 	/* Compile-time check for const size overflow. */
456 	if (__builtin_constant_p(size) && p_size < size)
457 		__write_overflow();
458 	/* Run-time check for dynamic size overflow. */
459 	if (p_size < size)
460 		fortify_panic(__func__);
461 	__underlying_memcpy(p, q, size);
462 	return p;
463 }
464 
465 /* Don't use these outside the FORITFY_SOURCE implementation */
466 #undef __underlying_memchr
467 #undef __underlying_memcmp
468 #undef __underlying_strcat
469 #undef __underlying_strcpy
470 #undef __underlying_strlen
471 #undef __underlying_strncat
472 #undef __underlying_strncpy
473 
474 #undef POS
475 #undef POS0
476 
477 #endif /* _LINUX_FORTIFY_STRING_H_ */
478