From 2eabc4cebfb6ba9d3275b45fdbe19de0afd3fda6 Mon Sep 17 00:00:00 2001 From: "David A. Wheeler" Date: Fri, 27 Oct 2023 07:55:08 -0700 Subject: [PATCH] Add simple test of C/C++ hardening flags Signed-off-by: David A. Wheeler --- docs/Compiler-Hardening-Guides/Makefile | 25 +++++++++++++++++++++++ docs/Compiler-Hardening-Guides/demo.c | 27 +++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 docs/Compiler-Hardening-Guides/Makefile create mode 100644 docs/Compiler-Hardening-Guides/demo.c diff --git a/docs/Compiler-Hardening-Guides/Makefile b/docs/Compiler-Hardening-Guides/Makefile new file mode 100644 index 00000000..6edde5d1 --- /dev/null +++ b/docs/Compiler-Hardening-Guides/Makefile @@ -0,0 +1,25 @@ +# Test C/C++ hardening flags + +# Copyright Open Source Security Foundation (OpenSSF) and its contributors +# SPDX-License-Identifier: Apache-2.0 OR MIT + +# Test hardening flags. You can set CC to the compiler to use. E.g.: +# make CC=clang +# make CC=/usr/local/Cellar/gcc/13.2.0/bin/gcc-13 + +# Extract the current hardening recommendations so we can test them. +# We use GNU make extensions $(shell ...) and ":=" to do this. +# Recent POSIX adds "!=" and "::=" but they are not yet universally supported, +# e.g., Apple MacOS only supplies an obsolete version of GNU Make. + +CFLAGS_HARDENING := $(shell sed -e '1,/~~~~/d' -e '/~~~~/,$$d' -e 's/\\$$//' \ + Compiler-Options-Hardening-Guide-for-C-and-C++.md ) + +# Could add architecture-specific flags, e.g.: +# -fcf-protection=full -mbranch-protection=standard + +CFLAGS := $(CFLAGS_HARDENING) $(CFLAGS) + +all: demo + +demo: demo.c diff --git a/docs/Compiler-Hardening-Guides/demo.c b/docs/Compiler-Hardening-Guides/demo.c new file mode 100644 index 00000000..d61fc549 --- /dev/null +++ b/docs/Compiler-Hardening-Guides/demo.c @@ -0,0 +1,27 @@ +// Test C/C++ hardening flags + +// Copyright Open Source Security Foundation (OpenSSF) and its contributors +// SPDX-License-Identifier: Apache-2.0 OR MIT + +#include + +// Linux 5.10 solution: +#if __has_attribute(__fallthrough__) +# define fallthrough __attribute__((__fallthrough__)) +#else +# define fallthrough do {} while (0) /* fallthrough */ +#endif + +int main(void) { + int c = 0; + switch (c) { + case 1: + printf("Hello\n"); + fallthrough; + case 0: + printf("Goodbye\n"); + fallthrough; + default: + printf("Default\n"); + } +}