Improve hardening build flags
Wheeeeee!
Currently we use the following build flags to build the freedesktop-sdk:
environment:
CPPFLAGS: "-O2 -D_FORTIFY_SOURCE=2"
CFLAGS: "-O2 -g -fstack-protector-strong"
CXXFLAGS: "-O2 -g -fstack-protector-strong"
LDFLAGS: "-fstack-protector-strong -Wl,-z,relro,-z,now"
It's a good start at hardening, but it's missing a boatload of recommended build flags used by Fedora and RHEL.
References:
- Fedora hardening flags update
- Red Hat's compiler flags recommendations which explains in detail each flag used below
- More Fedora build flags documentation
Probably the only Fedora flags that we don't necessarily want would be the ones for annobin.
The tricky bit will be that separate flags should be used for shared libraries and static libraries and executables. This means that just changing environment variables is no longer enough: GCC spec files will be required. I've been staring at Fedora's /usr/lib/rpm/redhat/macros trying to puzzle out exactly what we do, and after removing annobin flags (if we ever want to add annobin, that will be for another day), it boils down to this for CFLAGS and CXXFLAGS (note -Wp is used to eliminate the need for CPPFLAGS):
-O2 -g -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fexceptions -fstack-protector-strong -grecord-gcc-switches -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1
plus some architecture-specific flags appended at the end, where redhat-hardened-cc1 contains:
*cc1_options:
+ %{!r:%{!fpie:%{!fPIE:%{!fpic:%{!fPIC:%{!fno-pic:-fPIE}}}}}}
And the architecture-specific flags appended at the end are:
armv7hl: -march=armv7-a -mfpu=vfpv3-d16 -mtune=generic-armv7-a -mabi=aapcs-linux -mfloat-abi=hard
armv7hnl: -march=armv7-a -mfpu=neon -mfloat-abi=hard
aarch64: -fasynchronous-unwind-tables -fstack-clash-protection
i586: -m32 -march=i586 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection
x86_64: -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection
(I'm not sure which of those two armv7 architectures best matches ours, so just copied them both here.)
And then for LDFLAGS: -Wl,-z,relro -Wl,-z,now -specs=/usr/lib/rpm/redhat/redhat-hardened-ld
And redhat-hardened-ld contains:
*self_spec:
+ %{!static:%{!shared:%{!r:-pie}}}
Should probably keep those specs unchanged, and just /s/redhat/freedesktop/ for the filenames. The specs files can be installed anywhere. We could use /usr/share/freedesktop-sdk/specs or wherever.
Yes, very simple, I know. :P To double-check my flags reverse-engineering, you can look at the redhat-rpm-config package in the two files macros
and rpmrc
.