2.2.5. Options for hardening code with the GCC
To add security checks during code compilation, you can use GNU Compiler Collection (GCC) compiler options. This helps produce more secure programs and libraries without changing source code.
- Release version options
The following list of options is the recommended minimum for developers targeting Red Hat Enterprise Linux:
$ gcc ... -O2 -g -Wall -Wl,-z,now,-z,relro -fstack-protector-strong -fstack-clash-protection -D_FORTIFY_SOURCE=3 ...-
For programs, add the
-fPIEand-piePosition Independent Executable options. -
For dynamically linked libraries, the mandatory
-fPIC(Position Independent Code) option indirectly increases security.
-
For programs, add the
- Development options
Use the following options to detect security flaws during development. Use these options in conjunction with the options for the release version:
$ gcc ... -Walloc-zero -Walloca-larger-than -Wextra -Wformat-security -Wvla-larger-than ...- -
fhardened -
GCC 14 provides a new flag,
-fhardened, which in turn enables several other flags to improve the security of generated code without impacting the ABI. - -
fanalyzer -
GCC provides a flag,
-fanalyzer, which triggers warnings about potential issues in the source code, including security-related issues. Because-fanalyzerfrequently has false positives and negatives, it should be used to locate potential bugs that should be investigated further and not as a formal analysis tool. This flag greatly increases the time and memory taken during compilation. Use only on C code.