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