fortify-headers

standalone fortify-source implementation
git clone git://git.2f30.org/fortify-headers
Log | Files | Refs | README | LICENSE

commit e441ae8c30b35ad7602ab428753afb4a335b34bf
parent f0305fb85796cc4dcc537123d6b9b3152cf0c4be
Author: jvoisin <julien.voisin@dustri.org>
Date:   Sun, 20 Aug 2023 18:09:14 +0200

Add hardening for strchr

Diffstat:
Minclude/string.h | 11+++++++++++
Mtests/Makefile | 2++
Atests/test_strchr_dynamic_read.c | 17+++++++++++++++++
Atests/test_strchr_static_read.c | 17+++++++++++++++++
4 files changed, 47 insertions(+), 0 deletions(-)

diff --git 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 return __builtin_memchr(__d, __c, __n); } +__access(read_only, 1, 2) +_FORTIFY_FN(strchr) char *strchr(const char * _FORTIFY_POS0 __s, int __c) +{ + size_t __b = __bos(__s, 0); + + char* __r = __builtin_strchr(__s, __c); + if (__r - __s > __b) + __builtin_trap(); + return __r; +} + #if defined(_POSIX_SOURCE) || defined(_POSIX_C_SOURCE) \ || defined(_XOPEN_SOURCE) || defined(_GNU_SOURCE) \ || defined(_BSD_SOURCE) diff --git a/tests/Makefile b/tests/Makefile @@ -75,6 +75,8 @@ TARGETS= \ test_stpncpy_overwrite_under \ test_stpncpy_static_write \ test_strcat_static_write \ + test_strchr_dynamic_read \ + test_strchr_static_read \ test_strcpy_overwrite_over \ test_strcpy_overwrite_under \ test_strcpy_static_write \ diff --git a/tests/test_strchr_dynamic_read.c b/tests/test_strchr_dynamic_read.c @@ -0,0 +1,17 @@ +#include "common.h" + +#include <string.h> + +int main(int argc, char** argv) { + char buffer[] = {'1', '2', '3', '4', '5'}; + const char* padding = "ABCDEFGHIJKLMN"; + strchr(buffer, (int)'4'); + puts(buffer); + + CHK_FAIL_START + strchr(buffer, (int)'A'); + CHK_FAIL_END + + puts(buffer); + return ret; +} diff --git a/tests/test_strchr_static_read.c b/tests/test_strchr_static_read.c @@ -0,0 +1,17 @@ +#include "common.h" + +#include <string.h> + +int main(int argc, char** argv) { + char buffer[] = {'1', '2', '3', '4', '5'}; + const char* padding = "ABCDEFGHIJKLMN"; + strchr(buffer, (int)'4'); + puts(buffer); + + CHK_FAIL_START + strchr(buffer, (int)'A'); + CHK_FAIL_END + + puts(buffer); + return ret; +}