summary refs log tree commit diff
path: root/pkgs/build-support/cc-wrapper/add-hardening.sh
blob: b98833b3513b5cab1fcd5dee3e1c1aec8f64f13c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
hardeningFlags=(fortify stackprotector pic strictoverflow format relro bindnow)
hardeningFlags+=("${hardeningEnable[@]}")
hardeningCFlags=()
hardeningLDFlags=()
hardeningDisable=${hardeningDisable:-""}

hardeningDisable+=" @hardening_unsupported_flags@"

if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: Value of '$hardeningDisable': $hardeningDisable >&2; fi

if [[ ! $hardeningDisable =~ "all" ]]; then
  if [[ -n "$NIX_DEBUG" ]]; then echo 'HARDENING: Is active (not completely disabled with "all" flag)' >&2; fi
  for flag in "${hardeningFlags[@]}"
  do
    if [[ ! "${hardeningDisable}" =~ "$flag" ]]; then
      case $flag in
        fortify)
          if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: enabling fortify >&2; fi
          hardeningCFlags+=('-O2' '-D_FORTIFY_SOURCE=2')
          ;;
        stackprotector)
          if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: enabling stackprotector >&2; fi
          hardeningCFlags+=('-fstack-protector-strong' '--param ssp-buffer-size=4')
          ;;
        pie)
          if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: enabling CFlags -fPIE >&2; fi
          hardeningCFlags+=('-fPIE')
          if [[ ! ("$*" =~ " -shared " || "$*" =~ " -static ") ]]; then
            if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: enabling LDFlags -pie >&2; fi
            hardeningLDFlags+=('-pie')
          fi
          ;;
        pic)
          if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: enabling pic >&2; fi
          hardeningCFlags+=('-fPIC')
          ;;
        strictoverflow)
          if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: enabling strictoverflow >&2; fi
          hardeningCFlags+=('-fno-strict-overflow')
          ;;
        format)
          if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: enabling format >&2; fi
          hardeningCFlags+=('-Wformat' '-Wformat-security' '-Werror=format-security')
          ;;
        relro)
          if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: enabling relro >&2; fi
          hardeningLDFlags+=('-z' 'relro')
          ;;
        bindnow)
          if [[ -n "$NIX_DEBUG" ]]; then echo HARDENING: enabling bindnow >&2; fi
          hardeningLDFlags+=('-z' 'now')
          ;;
        *)
          echo "Hardening flag unknown: $flag" >&2
          ;;
      esac
    fi
  done
fi