summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorjvoisin2023-08-20 18:09:14 +0200
committerjvoisin2023-08-20 18:09:14 +0200
commite441ae8c30b35ad7602ab428753afb4a335b34bf (patch)
tree4c993f8817f20058a595c255711c26ef6a108795
parentf0305fb85796cc4dcc537123d6b9b3152cf0c4be (diff)
Add hardening for strchr
-rw-r--r--include/string.h11
-rw-r--r--tests/Makefile2
-rw-r--r--tests/test_strchr_dynamic_read.c17
-rw-r--r--tests/test_strchr_static_read.c17
4 files changed, 47 insertions, 0 deletions
diff --git a/include/string.h b/include/string.h
index 6d4b2d8..1fba9d9 100644
--- a/include/string.h
+++ b/include/string.h
@@ -91,6 +91,17 @@ _FORTIFY_FN(memchr) void *memchr(const void * _FORTIFY_POS0 __d, int __c, size_t
91 return __builtin_memchr(__d, __c, __n); 91 return __builtin_memchr(__d, __c, __n);
92} 92}
93 93
94__access(read_only, 1, 2)
95_FORTIFY_FN(strchr) char *strchr(const char * _FORTIFY_POS0 __s, int __c)
96{
97 size_t __b = __bos(__s, 0);
98
99 char* __r = __builtin_strchr(__s, __c);
100 if (__r - __s > __b)
101 __builtin_trap();
102 return __r;
103}
104
94#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ 105#if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \
95 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ 106 || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \
96 || defined(_BSD_SOURCE) 107 || defined(_BSD_SOURCE)
diff --git a/tests/Makefile b/tests/Makefile
index d5f0a09..1ea610b 100644
--- a/tests/Makefile
+++ b/tests/Makefile
@@ -75,6 +75,8 @@ TARGETS= \
75 test_stpncpy_overwrite_under \ 75 test_stpncpy_overwrite_under \
76 test_stpncpy_static_write \ 76 test_stpncpy_static_write \
77 test_strcat_static_write \ 77 test_strcat_static_write \
78 test_strchr_dynamic_read \
79 test_strchr_static_read \
78 test_strcpy_overwrite_over \ 80 test_strcpy_overwrite_over \
79 test_strcpy_overwrite_under \ 81 test_strcpy_overwrite_under \
80 test_strcpy_static_write \ 82 test_strcpy_static_write \
diff --git a/tests/test_strchr_dynamic_read.c b/tests/test_strchr_dynamic_read.c
new file mode 100644
index 0000000..fdd69df
--- /dev/null
+++ b/tests/test_strchr_dynamic_read.c
@@ -0,0 +1,17 @@
1#include "common.h"
2
3#include <string.h>
4
5int main(int argc, char** argv) {
6 char buffer[] = {'1', '2', '3', '4', '5'};
7 const char* padding = "ABCDEFGHIJKLMN";
8 strchr(buffer, (int)'4');
9 puts(buffer);
10
11 CHK_FAIL_START
12 strchr(buffer, (int)'A');
13 CHK_FAIL_END
14
15 puts(buffer);
16 return ret;
17}
diff --git a/tests/test_strchr_static_read.c b/tests/test_strchr_static_read.c
new file mode 100644
index 0000000..fdd69df
--- /dev/null
+++ b/tests/test_strchr_static_read.c
@@ -0,0 +1,17 @@
1#include "common.h"
2
3#include <string.h>
4
5int main(int argc, char** argv) {
6 char buffer[] = {'1', '2', '3', '4', '5'};
7 const char* padding = "ABCDEFGHIJKLMN";
8 strchr(buffer, (int)'4');
9 puts(buffer);
10
11 CHK_FAIL_START
12 strchr(buffer, (int)'A');
13 CHK_FAIL_END
14
15 puts(buffer);
16 return ret;
17}