From e182dd0138d8040c44481a48277cab4098ccca0a Mon Sep 17 00:00:00 2001 From: jvoisin Date: Sun, 20 Aug 2023 18:15:24 +0200 Subject: Add hardening for strrchr --- include/string.h | 11 +++++++++++ tests/Makefile | 2 ++ tests/test_strrchr_dynamic_read.c | 17 +++++++++++++++++ tests/test_strrchr_static_read.c | 17 +++++++++++++++++ 4 files changed, 47 insertions(+) create mode 100644 tests/test_strrchr_dynamic_read.c create mode 100644 tests/test_strrchr_static_read.c diff --git a/include/string.h b/include/string.h index 1fba9d9..4a3426a 100644 --- a/include/string.h +++ b/include/string.h @@ -102,6 +102,17 @@ _FORTIFY_FN(strchr) char *strchr(const char * _FORTIFY_POS0 __s, int __c) return __r; } +__access(read_only, 1, 2) +_FORTIFY_FN(strrchr) char *strrchr(const char * _FORTIFY_POS0 __s, int __c) +{ + size_t __b = __bos(__s, 0); + + char* __r = __builtin_strrchr(__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 index 1ea610b..c2bc378 100644 --- a/tests/Makefile +++ b/tests/Makefile @@ -84,6 +84,8 @@ TARGETS= \ test_strncpy_overwrite_over \ test_strncpy_overwrite_under \ test_strncpy_static_write \ + test_strrchr_dynamic_read \ + test_strrchr_static_read \ test_ttyname_r_dynamic \ test_ttyname_r_static \ test_vsnprintf_dynamic \ diff --git a/tests/test_strrchr_dynamic_read.c b/tests/test_strrchr_dynamic_read.c new file mode 100644 index 0000000..3b192c8 --- /dev/null +++ b/tests/test_strrchr_dynamic_read.c @@ -0,0 +1,17 @@ +#include "common.h" + +#include + +int main(int argc, char** argv) { + char buffer[] = {'1', '2', '3', '4', '5'}; + const char* padding = "ABCDEFGHIJKLMN"; + strrchr(buffer, (int)'4'); + puts(buffer); + + CHK_FAIL_START + strrchr(buffer, (int)'A'); + CHK_FAIL_END + + puts(buffer); + return ret; +} diff --git a/tests/test_strrchr_static_read.c b/tests/test_strrchr_static_read.c new file mode 100644 index 0000000..3b192c8 --- /dev/null +++ b/tests/test_strrchr_static_read.c @@ -0,0 +1,17 @@ +#include "common.h" + +#include + +int main(int argc, char** argv) { + char buffer[] = {'1', '2', '3', '4', '5'}; + const char* padding = "ABCDEFGHIJKLMN"; + strrchr(buffer, (int)'4'); + puts(buffer); + + CHK_FAIL_START + strrchr(buffer, (int)'A'); + CHK_FAIL_END + + puts(buffer); + return ret; +} -- cgit v1.3