3 # Build log hardening check, checks build logs for missing hardening flags.
5 # Copyright (C) 2012-2015 Simon Ruderich
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
25 use Text::ParseWords ();
27 our $VERSION = '0.05';
32 # Regex to catch compiler commands.
34 (?<!\s-) # ignore options, e.g. "-c++" [sic!] (used by swig)
35 (?<!\.) # ignore file names, e.g. "test.gcc"
36 (?:cc|gcc|g\+\+|c\+\+)
37 (?:-[\d.]+)? # version suffix, e.g. "gcc-4.6"
39 # Full regex which matches the complete compiler name. Used in a few places to
40 # prevent false negatives.
41 my $cc_regex_full = qr/
42 (?:[a-z0-9_]+-(?:linux-|kfreebsd-)?gnu(?:eabi|eabihf)?-)?
45 # Regex to check if a line contains a compiler command.
46 my $cc_regex_normal = qr/
49 # Regex to catch (GCC) compiler warnings.
50 my $warning_regex = qr/^(.+?):(\d+):\d+: warning: (.+?) \[(.+?)\]$/;
51 # Regex to catch libtool commands and not lines which show commands executed
52 # by libtool (e.g. libtool: link: ...).
53 my $libtool_regex = qr/\blibtool\s.*--mode=/;
54 my $libtool_link_regex = qr/\blibtool: link: /;
56 # List of source file extensions which require preprocessing.
57 my @source_preprocess_compile_cpp = (
59 qw( cc cp cxx cpp CPP c++ C ),
63 my @source_preprocess_compile = (
69 @source_preprocess_compile_cpp,
71 qw( F FOR fpp FPP FTN F90 F95 F03 F08 ),
73 my @source_preprocess_no_compile = (
77 my @source_preprocess = (
78 @source_preprocess_compile,
79 @source_preprocess_no_compile,
81 # List of source file extensions which don't require preprocessing.
82 my @source_no_preprocess_compile_cpp = (
88 my @source_no_preprocess_compile_ada = (
91 # If you add another file, fix use of @source_no_preprocess_compile_ada
92 # below (search for $compile_ada).
94 my @source_no_preprocess_compile = (
98 @source_no_preprocess_compile_cpp,
102 qw( f for ftn f90 f95 f03 f08 ),
104 @source_no_preprocess_compile_ada,
106 my @source_no_preprocess_no_compile = (
112 my @source_no_preprocess = (
113 @source_no_preprocess_compile,
114 @source_no_preprocess_no_compile,
116 # List of header file extensions which require preprocessing.
117 my @header_preprocess = (
118 # C, C++, Objective-C, Objective-C++
121 qw( hh H hp hxx hpp HPP h++ tcc ),
125 # Normal object files.
127 # Libtool object files.
129 # Dynamic libraries. bzip2 uses .sho.
135 # Hashes for fast extensions lookup to check if a file falls in one of these
137 my %extensions_no_preprocess = map { $_ => 1 } (
138 # There's no @header_no_preprocess.
139 @source_no_preprocess,
141 my %extensions_preprocess = map { $_ => 1 } (
145 my %extensions_compile_link = map { $_ => 1 } (
147 @source_no_preprocess,
149 my %extensions_compile = map { $_ => 1 } (
150 @source_preprocess_compile,
151 @source_no_preprocess_compile,
153 my %extensions_no_compile = map { $_ => 1 } (
154 @source_preprocess_no_compile,
155 @source_no_preprocess_no_compile,
157 my %extensions_compile_cpp = map { $_ => 1 } (
158 @source_preprocess_compile_cpp,
159 @source_no_preprocess_compile_cpp,
161 my %extensions_object = map { $_ => 1 } (
164 my %extension = map { $_ => 1 } (
165 @source_no_preprocess,
171 # Regexp to match file extensions.
172 my $file_extension_regex = qr/
174 \S+ # Filename without extension.
176 ([^\/\\.,;:\s]+)# File extension.
177 (?=\s|\\) # At end of word. Can't use \b because some files have non
178 # word characters at the end and because \b matches double
179 # extensions (like .cpp.o). Works always as all lines are
180 # terminated with "\n".
183 # Expected (hardening) flags. All flags are used as regexps (and compiled to
184 # real regexps below for better execution speed).
187 '-O(?:2|3)', # keep at index 1, search for @def_cflags_debug to change it
189 my @def_cflags_debug = (
190 # These flags indicate a debug build which disables checks for -O2.
194 my @def_cflags_format = (
195 '-Wformat(?:=2)?', # -Wformat=2 implies -Wformat, accept it too
196 '-Werror=format-security', # implies -Wformat-security
198 my @def_cflags_fortify = (
199 # fortify needs at least -O1, but -O2 is recommended anyway
201 my @def_cflags_stack = (
203 '--param[= ]ssp-buffer-size=4',
205 my @def_cflags_stack_strong = (
206 '-fstack-protector-strong',
208 my @def_cflags_pie = (
214 # @def_cxxflags_* is the same as @def_cflags_*.
215 my @def_cppflags = ();
216 my @def_cppflags_fortify = (
217 '-D_FORTIFY_SOURCE=2', # must be first, see cppflags_fortify_broken()
218 # If you add another flag fix hack below (search for "Hack to fix") and
219 # $def_cppflags_fortify[0].
221 my @def_cppflags_fortify_bad = (
222 # These flags may overwrite -D_FORTIFY_SOURCE=2.
224 '-D_FORTIFY_SOURCE=0',
225 '-D_FORTIFY_SOURCE=1',
227 my @def_ldflags = ();
228 my @def_ldflags_relro = (
231 my @def_ldflags_bindnow = (
234 my @def_ldflags_pie = (
238 my @def_ldflags_pic = (
243 # References to all flags checked by the flag checker.
247 \@def_cflags_fortify,
249 \@def_cflags_stack_strong,
253 \@def_cppflags_fortify,
256 \@def_ldflags_bindnow,
259 # References to all used flags.
260 my @flag_refs_all = (
263 \@def_cppflags_fortify_bad,
266 # Renaming rules for the output so the regex parts are not visible. Also
267 # stores string values of flag regexps above, see compile_flag_regexp().
269 '-O(?:2|3)' => '-O2',
270 '-Wformat(?:=2)?' => '-Wformat',
271 '--param[= ]ssp-buffer-size=4' => '--param=ssp-buffer-size=4',
272 '-Wl,(?:-z,)?relro' => '-Wl,-z,relro',
273 '-Wl,(?:-z,)?now' => '-Wl,-z,now',
277 no_compiler_commands => 1 << 0,
278 # used by POD::Usage => 1 << 1,
279 non_verbose_build => 1 << 2,
280 flags_missing => 1 << 3,
281 hardening_wrapper => 1 << 4,
282 invalid_cmake => 1 << 5,
286 no_compiler_commands => 'I-no-compiler-commands',
287 non_verbose_build => 'W-compiler-flags-hidden',
288 flags_missing => 'W-dpkg-buildflags-missing',
289 hardening_wrapper => 'I-hardening-wrapper-used',
290 invalid_cmake => 'I-invalid-cmake-used',
293 # Statistics of missing flags and non-verbose build commands. Used for
297 preprocess_missing => 0,
299 compile_missing => 0,
301 compile_cpp_missing => 0,
305 commands_nonverbose => 0,
308 # Use colored (ANSI) output?
314 # Only works for single-level arrays with no undef values. Thanks to perlfaq4.
316 my ($first_ref, $second_ref) = @_;
318 return 0 if scalar @{$first_ref} != scalar @{$second_ref};
320 my $length = scalar @{$first_ref};
321 for (my $i = 0; $i < $length; $i++) {
322 return 0 if $first_ref->[$i] ne $second_ref->[$i];
329 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
331 # Get string value of qr//-escaped regexps and if requested rename them.
332 my @missing_flags = map {
333 $flag_renames_ref->{$_}
334 } @{$missing_flags_ref};
336 my $flags = join ' ', @missing_flags;
337 printf '%s (%s)%s %s',
338 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
343 sub error_non_verbose_build {
347 error_color('NONVERBOSE BUILD', 'red'),
348 error_color(':', 'yellow'),
353 sub error_invalid_cmake {
357 error_color('INVALID CMAKE', 'red'),
358 error_color(':', 'yellow'),
363 sub error_hardening_wrapper {
365 error_color('HARDENING WRAPPER', 'red'),
366 error_color(':', 'yellow'),
367 'no checks possible, aborting';
372 my ($message, $color) = @_;
375 return Term::ANSIColor::colored($message, $color);
382 my ($line, @flags) = @_;
384 foreach my $flag (@flags) {
385 return 1 if $line =~ /$flag/;
391 my ($line, $missing_flags_ref, @flags) = @_;
393 my @missing_flags = ();
394 foreach my $flag (@flags) {
395 if (not $line =~ /$flag/) {
396 push @missing_flags, $flag;
400 return 1 if scalar @missing_flags == 0;
402 @{$missing_flags_ref} = @missing_flags;
406 sub cppflags_fortify_broken {
407 my ($line, $missing_flags) = @_;
409 # This doesn't take the position into account, but is a simple solution.
410 # And if the build system tries to force -D_FORTIFY_SOURCE=0/1, something
413 if (any_flags_used($line, @def_cppflags_fortify_bad)) {
414 # $def_cppflags_fortify[0] must be -D_FORTIFY_SOURCE=2!
415 push @{$missing_flags}, $def_cppflags_fortify[0];
422 # Modifies $missing_flags_ref array.
423 sub pic_pie_conflict {
424 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
426 return 0 if not $pie;
427 return 0 if not any_flags_used($line, @def_ldflags_pic);
429 my %flags = map { $_ => 1 } @flags_pie;
431 # Remove all PIE flags from @missing_flags as they are not required with
434 not exists $flags{$_}
435 } @{$missing_flags_ref};
436 @{$missing_flags_ref} = @result;
438 # We got a conflict when no flags are left, thus only PIE flags were
439 # missing. If other flags were missing abort because the conflict is not
441 return scalar @result == 0;
444 sub is_non_verbose_build {
445 my ($line, $next_line, $skip_ref) = @_;
447 if ($line =~ /$libtool_regex/o) {
448 # libtool's --silent hides the real compiler flags.
449 if ($line =~ /\s--silent/) {
451 # If --silent is not present, skip this line as some compiler flags
452 # might be missing (e.g. -fPIE) which are handled correctly by libtool
453 # internally. libtool displays the real compiler command on the next
454 # line, so the flags are checked as usual.
461 if (not (index($line, 'checking if you want to see long compiling messages... no') == 0
462 or $line =~ /^\s*\[?(?:CC|CCLD|C\+\+|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
463 or $line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/
464 or $line =~ /^\s*[Bb]uilding (?:program|shared library)\s+(.+?)$/
465 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
471 # C++ compiler setting.
472 return 0 if $line =~ /^\s*C\+\+.+?:\s+(?:yes|no)\s*$/;
473 return 0 if $line =~ /^\s*C\+\+ Library: stdc\+\+$/;
474 # "Compiling" non binary files.
475 return 0 if $line =~ /^\s*Compiling \S+\.(?:py|el)['"]?\s*(?:\.\.\.)?$/;
476 # "Compiling" with no file name.
477 if ($line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/) {
478 # $file_extension_regex may need spaces around the filename.
479 return 0 if not " $1 " =~ /$file_extension_regex/o;
484 # On the first pass we only check if this line is verbose or not.
485 return 1 if not defined $next_line;
487 # Second pass, we have access to the next line.
490 # CMake and other build systems print the non-verbose messages also when
491 # building verbose. If a compiler and the file name occurs in the next
492 # line, treat it as verbose build.
494 # Get filename, we can't use the complete path as only parts of it are
495 # used in the real compiler command.
496 $file =~ m{/([^/\s]+)$};
499 if (index($next_line, $file) != -1 and $next_line =~ /$cc_regex/o) {
500 # Not a non-verbose line, but we still have to skip the current line
501 # as it doesn't contain any compiler commands.
510 # Remove @flags from $flag_refs_ref, uses $flag_renames_ref as reference.
512 my ($flag_refs_ref, $flag_renames_ref, @flags) = @_;
514 my %removes = map { $_ => 1 } @flags;
515 foreach my $flags (@{$flag_refs_ref}) {
517 # Flag found as string.
518 not exists $removes{$_}
519 # Flag found as string representation of regexp.
520 and (not defined $flag_renames_ref->{$_}
521 or not exists $removes{$flag_renames_ref->{$_}})
528 # Modifies $flag_renames_ref hash.
529 sub compile_flag_regexp {
530 my ($flag_renames_ref, @flags) = @_;
533 foreach my $flag (@flags) {
534 # Compile flag regexp for faster execution.
535 my $regex = qr/\s$flag(?:\s|\\)/;
537 # Store flag name in replacement string for correct flags in messages
538 # with qr//ed flag regexps.
539 $flag_renames_ref->{$regex}
540 = (exists $flag_renames_ref->{$flag})
541 ? $flag_renames_ref->{$flag}
544 push @result, $regex;
549 # Does any extension in @extensions exist in %{$extensions_ref}?
550 sub extension_found {
551 my ($extensions_ref, @extensions) = @_;
553 foreach my $extension (@extensions) {
554 if (exists $extensions_ref->{$extension}) {
564 # Parse command line arguments.
566 my $option_version = 0;
568 my $option_bindnow = 0;
569 my @option_ignore_arch = ();
570 my @option_ignore_flag = ();
571 my @option_ignore_arch_flag = ();
572 my @option_ignore_line = ();
573 my @option_ignore_arch_line = ();
575 my $option_arch = undef;
576 my $option_buildd = 0;
578 if (not Getopt::Long::GetOptions(
579 'help|h|?' => \$option_help,
580 'version' => \$option_version,
582 'pie' => \$option_pie,
583 'bindnow' => \$option_bindnow,
584 'all' => \$option_all,
586 'ignore-arch=s' => \@option_ignore_arch,
587 'ignore-flag=s' => \@option_ignore_flag,
588 'ignore-arch-flag=s' => \@option_ignore_arch_flag,
589 'ignore-line=s' => \@option_ignore_line,
590 'ignore-arch-line=s' => \@option_ignore_arch_line,
592 'color' => \$option_color,
593 'arch=s' => \$option_arch,
594 'buildd' => \$option_buildd,
597 Pod::Usage::pod2usage(2);
601 Pod::Usage::pod2usage(1);
603 if ($option_version) {
605 blhc $VERSION Copyright (C) 2012-2015 Simon Ruderich
607 This program is free software: you can redistribute it and/or modify
608 it under the terms of the GNU General Public License as published by
609 the Free Software Foundation, either version 3 of the License, or
610 (at your option) any later version.
612 This program is distributed in the hope that it will be useful,
613 but WITHOUT ANY WARRANTY; without even the implied warranty of
614 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
615 GNU General Public License for more details.
617 You should have received a copy of the GNU General Public License
618 along with this program. If not, see <http://www.gnu.org/licenses/>.
624 if (scalar @ARGV == 0) {
626 Pod::Usage::pod2usage(2);
629 # Don't load Term::ANSIColor in buildd mode because Term::ANSIColor is not
630 # installed on Debian's buildds.
631 if (not $option_buildd) {
632 require Term::ANSIColor;
640 # Precompiled ignores for faster lookup.
641 my %option_ignore_arch_flag = ();
642 my %option_ignore_arch_line = ();
644 # Strip flags which should be ignored.
645 if (scalar @option_ignore_flag > 0) {
646 remove_flags(\@flag_refs, \%flag_renames, @option_ignore_flag);
648 # Same for arch specific ignore flags, but only prepare here.
649 if (scalar @option_ignore_arch_flag > 0) {
650 foreach my $ignore (@option_ignore_arch_flag) {
651 my ($ignore_arch, $ignore_flag) = split /:/, $ignore, 2;
653 if (not $ignore_arch or not $ignore_flag) {
654 printf STDERR 'Value "%s" invalid for option ignore-arch-flag '
655 . '("arch:flag" expected)' . "\n", $ignore;
657 Pod::Usage::pod2usage(2);
660 push @{$option_ignore_arch_flag{$ignore_arch}}, $ignore_flag;
664 # Precompile all flag regexps. any_flags_used(), all_flags_used() get a lot
666 foreach my $flags (@flag_refs_all) {
667 @{$flags} = compile_flag_regexp(\%flag_renames, @{$flags});
670 # Precompile ignore line regexps, also anchor at beginning and end of line.
671 foreach my $ignore (@option_ignore_line) {
672 $ignore = qr/^$ignore$/;
674 # Same for arch specific ignore lines.
675 if (scalar @option_ignore_arch_line > 0) {
676 foreach my $ignore (@option_ignore_arch_line) {
677 my ($ignore_arch, $ignore_line) = split /:/, $ignore, 2;
679 if (not $ignore_arch or not $ignore_line) {
680 printf STDERR 'Value "%s" invalid for option ignore-arch-line '
681 . '("arch:line" expected)' . "\n", $ignore;
683 Pod::Usage::pod2usage(2);
686 push @{$option_ignore_arch_line{$ignore_arch}}, qr/^$ignore_line$/;
694 foreach my $file (@ARGV) {
695 print "checking '$file'...\n" if scalar @ARGV > 1;
697 -f $file or die "No such file: $file";
699 open my $fh, '<', $file or die $!;
701 # Architecture of this file.
702 my $arch = $option_arch;
704 # Hardening options. Not all architectures support all hardening options.
705 my $harden_format = 1;
706 my $harden_fortify = 1;
707 my $harden_stack = 1;
708 my $harden_stack_strong = 1;
709 my $harden_relro = 1;
710 my $harden_bindnow = $option_bindnow; # defaults to 0
711 my $harden_pie = $option_pie; # defaults to 0
713 # Does this build log use ada? Ada also uses gcc as compiler but uses
714 # different CFLAGS. But only perform ada checks if an ada compiler is used
715 # for performance reasons.
718 while (my $line = <$fh>) {
719 # Detect architecture automatically unless overridden. For buildd logs
720 # only, doesn't use the dpkg-buildpackage header. Necessary to ignore
721 # build logs which aren't built (wrong architecture, build error,
724 if (index($line, 'Build Architecture: ') == 0) {
725 $arch = substr $line, 20, -1; # -1 to ignore '\n' at the end
726 # For old logs (sbuild << 0.63.0-1).
727 } elsif (index($line, 'Architecture: ') == 0) {
728 $arch = substr $line, 14, -1; # -1 to ignore '\n' at the end
732 # dpkg-buildflags only provides hardening flags since 1.16.1, don't
733 # check for hardening flags in buildd mode if an older dpkg-dev is
734 # used. Default flags (-g -O2) are still checked.
736 # Packages which were built before 1.16.1 but used their own hardening
737 # flags are not checked.
739 # Strong stack protector is used since dpkg 1.17.11.
741 and index($line, 'Toolchain package versions: ') == 0) {
742 require Dpkg::Version;
745 my $disable_strong = 1;
747 if ($line =~ /\bdpkg-dev_(\S+)/) {
748 if (Dpkg::Version::version_compare($1, '1.16.1') >= 0) {
751 if (Dpkg::Version::version_compare($1, '1.17.11') >= 0) {
764 if ($disable_strong) {
765 $harden_stack_strong = 0;
769 # The following two versions of CMake in Debian obeyed CPPFLAGS, but
770 # this was later dropped because upstream rejected the patch. Thus
771 # build logs with these versions will have fortify hardening flags
772 # enabled, even though they may be not correctly set and are missing
773 # when build with later CMake versions. Thanks to Aron Xu for letting
775 if (index($line, 'Package versions: ') == 0
776 and $line =~ /\bcmake_(\S+)/
777 and ($1 eq '2.8.7-1' or $1 eq '2.8.7-2')) {
778 if (not $option_buildd) {
779 error_invalid_cmake($1);
780 $exit |= $exit_code{invalid_cmake};
782 print "$buildd_tag{invalid_cmake}|$1|\n";
786 # Debian's build daemons use "Filtered Build-Depends:" (or just
787 # "Build-Depends:" in older versions) for the build dependencies, but
788 # pbuilder uses "Depends:"; support both.
789 if (index($line, 'Filtered Build-Depends: ') == 0
790 or index($line, 'Build-Depends: ') == 0
791 or index($line, 'Depends: ') == 0) {
792 # If hardening wrapper is used (wraps calls to gcc and adds
793 # hardening flags automatically) we can't perform any checks,
795 if ($line =~ /\bhardening-wrapper\b/) {
796 if (not $option_buildd) {
797 error_hardening_wrapper();
798 $exit |= $exit_code{hardening_wrapper};
800 print "$buildd_tag{hardening_wrapper}||\n";
806 if ($line =~ /\bgnat\b/) {
811 # We skip over unimportant lines at the beginning of the log to
812 # prevent false positives.
813 last if index($line, 'dpkg-buildpackage: ') == 0;
816 # Input lines, contain only the lines with compiler commands.
818 # Non-verbose lines in the input. Used to reduce calls to
819 # is_non_verbose_build() (which is quite slow) in the second loop when
820 # it's already clear if a line is non-verbose or not.
821 my @input_nonverbose = ();
823 my $continuation = 0;
824 my $complete_line = undef;
826 while (my $line = <$fh>) {
827 # And stop at the end of the build log. Package details (reported by
828 # the buildd logs) are not important for us. This also prevents false
830 last if index($line, 'Build finished at ') == 0
831 and $line =~ /^Build finished at \d{8}-\d{4}$/;
833 if (not $continuation) {
837 # Detect architecture automatically unless overridden.
839 and index($line, 'dpkg-buildpackage: host architecture ') == 0) {
840 $arch = substr $line, 37, -1; # -1 to ignore '\n' at the end
842 # Old buildd logs use e.g. "host architecture is alpha", remove
843 # the "is", otherwise debarch_to_debtriplet() will not detect the
845 if (index($arch, 'is ') == 0) {
846 $arch = substr $arch, 3;
850 # Ignore compiler warnings for now.
851 next if $line =~ /$warning_regex/o;
853 if (not $option_buildd and index($line, "\033") != -1) { # \033 = esc
854 # Remove all ANSI color sequences which are sometimes used in
855 # non-verbose builds.
856 $line = Term::ANSIColor::colorstrip($line);
857 # Also strip '\0xf' (delete previous character), used by Elinks'
860 # And "ESC(B" which seems to be used on armhf and hurd (not sure
862 $line =~ s/\033\(B//g;
865 # Check if this line indicates a non verbose build.
867 $non_verbose |= is_non_verbose_build($line, undef, \$skip);
870 # One line may contain multiple commands (";"). Treat each one as
871 # single line. parse_line() is slow, only use it when necessary.
872 my @line = (index($line, ';') == -1)
875 # Ensure newline at the line end - necessary for
876 # correct parsing later.
879 } Text::ParseWords::parse_line(';', 1, $line);
880 foreach my $line (@line) {
884 # Join lines, but leave the "\" in place so it's clear where
885 # the original line break was.
886 chomp $complete_line;
887 $complete_line .= ' ' . $line;
889 # Line continuation, line ends with "\".
890 if ($line =~ /\\$/) {
892 # Start line continuation.
893 if (not defined $complete_line) {
894 $complete_line = $line;
899 # Use the complete line if a line continuation occurred.
900 if (defined $complete_line) {
901 $line = $complete_line;
902 $complete_line = undef;
905 # Ignore lines with no compiler commands.
906 next if not $non_verbose
907 and not $line =~ /$cc_regex_normal/o;
908 # Ignore lines with no filenames with extensions. May miss some
909 # non-verbose builds (e.g. "gcc -o test" [sic!]), but shouldn't be
910 # a problem as the log will most likely contain other non-verbose
911 # commands which are detected.
912 next if not $non_verbose
913 and not $line =~ /$file_extension_regex/o;
915 # Ignore false positives.
917 # `./configure` output.
918 next if not $non_verbose
919 and $line =~ /^(?:checking|[Cc]onfigure:) /;
920 next if $line =~ /^\s*(?:Host\s+)?(?:C(?:\+\+)?\s+)?
921 [Cc]ompiler[\s.]*:?\s+
923 next if $line =~ m{^\s*(?:-\s)?(?:HOST_)?(?:CC|CXX)
924 \s*=\s*$cc_regex_full
925 # optional compiler options, don't allow
926 # "everything" here to prevent false negatives
927 \s*(?:\s-\S+)*\s*$}xo;
928 # `moc-qt4`/`moc-qt5` contain '-I.../linux-g++' in their command
929 # line (or similar for other architectures) which gets recognized
930 # as a compiler line, but `moc-qt*` is only a preprocessor for Qt
931 # C++ files. No hardening flags are relevant during this step,
932 # thus ignore `moc-qt*` lines. The resulting files will be
933 # compiled in a separate step (and therefore checked).
934 next if $line =~ m{^\S+/bin/moc(?:-qt[45])?
936 -I\S+/mkspecs/[a-z]+-g\++(?:-64)?
938 # Ignore false positives when the line contains only CC=gcc but no
940 if ($line =~ /(.*)CC=$cc_regex_full(.*)/o) {
943 next if not $before =~ /$cc_regex_normal/o
944 and not $after =~ /$cc_regex_normal/o;
947 # Check if additional hardening options were used. Used to ensure
948 # they are used for the complete build.
949 $harden_pie = 1 if any_flags_used($line, @def_cflags_pie,
951 $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);
954 push @input_nonverbose, $non_verbose;
960 # Ignore arch if requested.
961 if (scalar @option_ignore_arch > 0 and $arch) {
962 foreach my $ignore (@option_ignore_arch) {
963 if ($arch eq $ignore) {
964 print "ignoring architecture '$arch'\n";
970 if (scalar @input == 0) {
971 if (not $option_buildd) {
972 print "No compiler commands!\n";
973 $exit |= $exit_code{no_compiler_commands};
975 print "$buildd_tag{no_compiler_commands}||\n";
980 if ($option_buildd) {
981 $statistics{commands} += scalar @input;
984 # Option or auto detected.
986 # The following was partially copied from dpkg-dev 1.18.2
987 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
988 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
989 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
990 # later. Keep it in sync.
993 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($arch);
995 # Disable unsupported hardening options.
996 if ($os !~ /^(?:linux|knetbsd|hurd)$/ or $cpu =~ /^(?:hppa|avr32)$/) {
999 if ($cpu =~ /^(?:ia64|alpha|hppa)$/ or $arch eq 'arm') {
1001 $harden_stack_strong = 0;
1003 if ($cpu =~ /^(?:ia64|hppa|avr32)$/) {
1005 $harden_bindnow = 0;
1010 my @cflags = @def_cflags;
1011 my @cxxflags = @def_cxxflags;
1012 my @cppflags = @def_cppflags;
1013 my @ldflags = @def_ldflags;
1014 # Check the specified hardening options, same order as dpkg-buildflags.
1016 @cflags = (@cflags, @def_cflags_pie);
1017 @cxxflags = (@cxxflags, @def_cflags_pie);
1018 @ldflags = (@ldflags, @def_ldflags_pie);
1020 if ($harden_stack_strong) {
1021 @cflags = (@cflags, @def_cflags_stack_strong);
1022 @cxxflags = (@cxxflags, @def_cflags_stack_strong);
1023 } elsif ($harden_stack) {
1024 @cflags = (@cflags, @def_cflags_stack);
1025 @cxxflags = (@cxxflags, @def_cflags_stack);
1027 if ($harden_fortify) {
1028 @cflags = (@cflags, @def_cflags_fortify);
1029 @cxxflags = (@cxxflags, @def_cflags_fortify);
1030 @cppflags = (@cppflags, @def_cppflags_fortify);
1032 if ($harden_format) {
1033 @cflags = (@cflags, @def_cflags_format);
1034 @cxxflags = (@cxxflags, @def_cflags_format);
1036 if ($harden_relro) {
1037 @ldflags = (@ldflags, @def_ldflags_relro);
1039 if ($harden_bindnow) {
1040 @ldflags = (@ldflags, @def_ldflags_bindnow);
1043 # Stores normal CFLAGS when @cflags_ada are temporarily used.
1045 # Ada CFLAGS, only set if ada is used.
1047 # Ada doesn't support format hardening flags, see #680117 for more
1048 # information. Filter them out if ada is used.
1049 if ($ada and $harden_format) {
1050 @cflags_ada = grep {
1052 foreach my $flag (@def_cflags_format) {
1053 $ok = 0 if $_ eq $flag;
1059 # Hack to fix cppflags_fortify_broken() if --ignore-flag
1060 # -D_FORTIFY_SOURCE=2 is used to ignore missing fortification. Only works
1061 # as long as @def_cppflags_fortify contains only one variable.
1062 if (scalar @def_cppflags_fortify == 0) {
1063 $harden_fortify = 0;
1066 # Ignore flags for this arch if requested.
1067 if ($arch and exists $option_ignore_arch_flag{$arch}) {
1068 my @local_flag_refs = (\@cflags, \@cxxflags, \@cppflags, \@ldflags);
1070 remove_flags(\@local_flag_refs,
1072 @{$option_ignore_arch_flag{$arch}});
1075 my @ignore_line = @option_ignore_line;
1076 # Ignore lines for this arch if requested.
1077 if ($arch and exists $option_ignore_arch_line{$arch}) {
1078 @ignore_line = (@ignore_line, @{$option_ignore_arch_line{$arch}});
1082 for (my $i = 0; $i < scalar @input; $i++) {
1083 my $line = $input[$i];
1085 # Ignore line if requested.
1086 foreach my $ignore (@ignore_line) {
1087 next LINE if $line =~ /$ignore/;
1091 if ($input_nonverbose[$i]
1092 and is_non_verbose_build($line, $input[$i + 1], \$skip)) {
1093 if (not $option_buildd) {
1094 error_non_verbose_build($line);
1095 $exit |= $exit_code{non_verbose_build};
1097 $statistics{commands_nonverbose}++;
1101 # Even if it's a verbose build, we might have to skip this line (see
1102 # is_non_verbose_build()).
1105 my $orig_line = $line;
1107 # Remove everything until and including the compiler command. Makes
1108 # checks easier and faster.
1109 $line =~ s/^.*?$cc_regex//o;
1110 # "([...] test.c)" is not detected as 'test.c' - fix this by removing
1111 # the brace and similar characters at the line end.
1112 $line =~ s/['")]+$//;
1114 # Skip unnecessary tests when only preprocessing.
1115 my $flag_preprocess = 0;
1122 # Preprocess, compile, assemble.
1123 if ($line =~ /\s(-E|-S|-c)\b/) {
1125 $flag_preprocess = 1 if $1 eq '-E';
1126 $compile = 1 if $1 eq '-S' or $1 eq '-c';
1127 # Dependency generation for Makefiles. The other flags (-MF -MG -MP
1128 # -MT -MQ) are always used with -M/-MM.
1129 } elsif ($line =~ /\s(?:-M|-MM)\b/) {
1131 # Otherwise assume we are linking.
1136 # -MD/-MMD also cause dependency generation, but they don't imply -E!
1137 if ($line =~ /\s(?:-MD|-MMD)\b/) {
1139 $flag_preprocess = 0;
1142 # Dependency generation for Makefiles, no preprocessing or other flags
1144 next if $dependency;
1146 # Get all file extensions on this line.
1147 my @extensions = $line =~ /$file_extension_regex/go;
1148 # Ignore all unknown extensions to speedup the search below.
1149 @extensions = grep { exists $extension{$_} } @extensions;
1151 # These file types don't require preprocessing.
1152 if (extension_found(\%extensions_no_preprocess, @extensions)) {
1155 # These file types require preprocessing.
1156 if (extension_found(\%extensions_preprocess, @extensions)) {
1157 # Prevent false positives with "libtool: link: g++ -include test.h
1158 # .." compiler lines.
1159 if ($orig_line !~ /$libtool_link_regex/o) {
1164 if (not $flag_preprocess) {
1165 # If there are source files then it's compiling/linking in one
1166 # step and we must check both. We only check for source files
1167 # here, because header files cause too many false positives.
1168 if (extension_found(\%extensions_compile_link, @extensions)) {
1169 # Assembly files don't need CFLAGS.
1170 if (not extension_found(\%extensions_compile, @extensions)
1171 and extension_found(\%extensions_no_compile, @extensions)) {
1173 # But the rest does.
1177 # No compilable extensions found, either linking or compiling
1180 # If there are also no object files we are just compiling headers
1181 # (.h -> .h.gch). Don't check for linker flags in this case. Due
1182 # to our liberal checks for compiler lines, this also reduces the
1183 # number of false positives considerably.
1185 and not extension_found(\%extensions_object, @extensions)) {
1190 my $compile_cpp = 0;
1191 my $compile_ada = 0;
1192 # Assume CXXFLAGS are required when a C++ file is specified in the
1195 and extension_found(\%extensions_compile_cpp, @extensions)) {
1198 # Ada needs special CFLAGS, use them if only ada files are compiled.
1201 and array_equal(\@extensions,
1202 \@source_no_preprocess_compile_ada)) {
1204 @cflags_backup = @cflags;
1205 @cflags = @cflags_ada;
1208 if ($option_buildd) {
1209 $statistics{preprocess}++ if $preprocess;
1210 $statistics{compile}++ if $compile;
1211 $statistics{compile_cpp}++ if $compile_cpp;
1212 $statistics{link}++ if $link;
1215 # Check if there are flags indicating a debug build. If that's true,
1216 # skip the check for -O2. This prevents fortification, but that's fine
1217 # for a debug build.
1218 if (any_flags_used($line, @def_cflags_debug)) {
1219 remove_flags([\@cflags], \%flag_renames, $def_cflags[1]);
1220 remove_flags([\@cppflags], \%flag_renames, $def_cppflags_fortify[0]);
1223 # Check hardening flags.
1225 if ($compile and not all_flags_used($line, \@missing, @cflags)
1226 # Libraries linked with -fPIC don't have to (and can't) be
1227 # linked with -fPIE as well. It's no error if only PIE flags
1229 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1230 # Assume dpkg-buildflags returns the correct flags.
1231 and index($line, '`dpkg-buildflags --get CFLAGS`') == -1) {
1232 if (not $option_buildd) {
1233 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1234 $exit |= $exit_code{flags_missing};
1236 $statistics{compile_missing}++;
1238 } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
1239 # Libraries linked with -fPIC don't have to (and can't) be
1240 # linked with -fPIE as well. It's no error if only PIE flags
1242 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1243 # Assume dpkg-buildflags returns the correct flags.
1244 and index($line, '`dpkg-buildflags --get CXXFLAGS`') == -1) {
1245 if (not $option_buildd) {
1246 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1247 $exit |= $exit_code{flags_missing};
1249 $statistics{compile_cpp_missing}++;
1253 and (not all_flags_used($line, \@missing, @cppflags)
1254 # The fortify flag might be overwritten, detect that.
1256 and cppflags_fortify_broken($line, \@missing)))
1257 # Assume dpkg-buildflags returns the correct flags.
1258 and index($line, '`dpkg-buildflags --get CPPFLAGS`') == -1) {
1259 if (not $option_buildd) {
1260 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1261 $exit |= $exit_code{flags_missing};
1263 $statistics{preprocess_missing}++;
1266 if ($link and not all_flags_used($line, \@missing, @ldflags)
1267 # Same here, -fPIC conflicts with -fPIE.
1268 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
1269 # Assume dpkg-buildflags returns the correct flags.
1270 and index($line, '`dpkg-buildflags --get LDFLAGS`') == -1) {
1271 if (not $option_buildd) {
1272 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1273 $exit |= $exit_code{flags_missing};
1275 $statistics{link_missing}++;
1279 # Restore normal CFLAGS.
1281 @cflags = @cflags_backup;
1286 # Print statistics for buildd mode, only output in this mode.
1287 if ($option_buildd) {
1290 if ($statistics{preprocess_missing}) {
1291 push @warning, sprintf 'CPPFLAGS %d (of %d)',
1292 $statistics{preprocess_missing},
1293 $statistics{preprocess};
1295 if ($statistics{compile_missing}) {
1296 push @warning, sprintf 'CFLAGS %d (of %d)',
1297 $statistics{compile_missing},
1298 $statistics{compile};
1300 if ($statistics{compile_cpp_missing}) {
1301 push @warning, sprintf 'CXXFLAGS %d (of %d)',
1302 $statistics{compile_cpp_missing},
1303 $statistics{compile_cpp};
1305 if ($statistics{link_missing}) {
1306 push @warning, sprintf 'LDFLAGS %d (of %d)',
1307 $statistics{link_missing},
1310 if (scalar @warning) {
1311 local $" = ', '; # array join string
1312 print "$buildd_tag{flags_missing}|@warning missing|\n";
1315 if ($statistics{commands_nonverbose}) {
1316 printf "$buildd_tag{non_verbose_build}|%d (of %d) hidden|\n",
1317 $statistics{commands_nonverbose},
1318 $statistics{commands},
1330 blhc - build log hardening check, checks build logs for missing hardening flags
1334 B<blhc> [I<options>] I<< <dpkg-buildpackage build log file>.. >>
1338 blhc is a small tool which checks build logs for missing hardening flags. It's
1339 licensed under the GPL 3 or later.
1341 It's designed to check build logs generated by Debian's dpkg-buildpackage (or
1342 tools using dpkg-buildpackage like pbuilder or sbuild (which is used for the
1343 official buildd build logs)) to help maintainers detect missing hardening
1344 flags in their packages.
1346 Only gcc is detected as compiler at the moment. If other compilers support
1347 hardening flags as well, please report them.
1349 If there's no output, no flags are missing and the build log is fine.
1351 See F<README> for details about performed checks, auto-detection and
1360 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
1363 =item B<--arch> I<architecture>
1365 Set the specific architecture (e.g. amd64, armel, etc.), automatically
1366 disables hardening flags not available on this architecture. Is detected
1367 automatically if dpkg-buildpackage is used.
1371 Force check for all +bindnow hardening flags. By default it's auto detected.
1375 Special mode for buildds when automatically parsing log files. The following
1376 changes are in effect:
1382 Print tags instead of normal warnings, see L</"BUILDD TAGS"> for a list of
1387 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
1392 Don't require Term::ANSIColor.
1396 Return exit code 0, unless there was a error (-I, -W messages don't count as
1403 Use colored (ANSI) output for warning messages.
1405 =item B<--ignore-arch> I<arch>
1407 Ignore build logs from architectures matching I<arch>. I<arch> is a string.
1409 Used to prevent false positives. This option can be specified multiple times.
1411 =item B<--ignore-arch-flag> I<arch>:I<flag>
1413 Like B<--ignore-flag>, but only ignore flag on I<arch>.
1415 =item B<--ignore-arch-line> I<arch>:I<line>
1417 Like B<--ignore-line>, but only ignore line on I<arch>.
1419 =item B<--ignore-flag> I<flag>
1421 Don't print an error when the specific flag is missing in a compiler line.
1422 I<flag> is a string.
1424 Used to prevent false positives. This option can be specified multiple times.
1426 =item B<--ignore-line> I<regex>
1428 Ignore lines matching the given Perl regex. I<regex> is automatically anchored
1429 at the beginning and end of the line to prevent false negatives.
1431 B<NOTE>: Not the input lines are checked, but the lines which are displayed in
1432 warnings (which have line continuation resolved).
1434 Used to prevent false positives. This option can be specified multiple times.
1438 Force check for all +pie hardening flags. By default it's auto detected.
1440 =item B<-h -? --help>
1442 Print available options.
1446 Print version number and license.
1450 Auto detection for B<--pie> and B<--bindnow> only works if at least one
1451 command uses the required hardening flag (e.g. -fPIE). Then it's required for
1452 all other commands as well.
1456 Normal usage, parse a single log file.
1458 blhc path/to/log/file
1460 If there's no output, no flags are missing and the build log is fine.
1462 Parse multiple log files. The exit code is ORed over all files.
1464 blhc path/to/directory/with/log/files/*
1466 Don't treat missing C<-g> as error:
1468 blhc --ignore-flag -g path/to/log/file
1470 Don't treat missing C<-pie> on kfreebsd-amd64 as error:
1472 blhc --ignore-arch-flag kfreebsd-amd64:-pie path/to/log/file
1474 Ignore lines consisting exactly of C<./script gcc file> which would cause a
1477 blhc --ignore-line '\./script gcc file' path/to/log/file
1479 Ignore lines matching C<./script gcc file> somewhere in the line.
1481 blhc --ignore-line '.*\./script gcc file.*' path/to/log/file
1483 Use blhc with pbuilder.
1485 pbuilder path/to/package.dsc | tee path/log/file
1486 blhc path/to/file || echo flags missing
1490 The following tags are used in I<--buildd> mode. In braces the additional data
1495 =item B<I-hardening-wrapper-used>
1497 The package uses hardening-wrapper which intercepts calls to gcc and adds
1498 hardening flags. The build log doesn't contain any hardening flags and thus
1499 can't be checked by blhc.
1501 =item B<W-compiler-flags-hidden> (summary of hidden lines)
1503 Build log contains lines which hide the real compiler flags. For example:
1510 Most of the time either C<export V=1> or C<export verbose=1> in
1511 F<debian/rules> fixes builds with hidden compiler flags. Sometimes C<.SILENT>
1512 in a F<Makefile> must be removed. And as last resort the F<Makefile> must be
1513 patched to remove the C<@>s hiding the real compiler commands.
1515 =item B<W-dpkg-buildflags-missing> (summary of missing flags)
1517 CPPFLAGS, CFLAGS, CXXFLAGS, LDFLAGS missing.
1519 =item B<I-invalid-cmake-used> (version)
1521 By default CMake ignores CPPFLAGS thus missing those hardening flags. Debian
1522 patched CMake in versions 2.8.7-1 and 2.8.7-2 to respect CPPFLAGS, but this
1523 patch was rejected by upstream and later reverted in Debian. Thus those two
1524 versions show correct usage of CPPFLAGS even if the package doesn't correctly
1525 handle them (for example by passing them to CFLAGS). To prevent false
1526 negatives just blacklist those two versions.
1528 =item B<I-no-compiler-commands>
1530 No compiler commands were detected. Either the log contains none or they were
1531 not correctly detected by blhc (please report the bug in this case).
1537 The exit status is a "bit mask", each listed status is ORed when the error
1538 condition occurs to get the result.
1548 No compiler commands were found.
1552 Invalid arguments/options given to blhc.
1560 Missing hardening flags.
1564 Hardening wrapper detected, no tests performed.
1568 Invalid CMake version used. See B<I-invalid-cmake-used> under L</"BUILDD
1569 TAGS"> for a detailed explanation.
1575 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
1577 Thanks to to Bernhard R. Link E<lt>brlink@debian.orgE<gt> and Jaria Alto
1578 E<lt>jari.aalto@cante.netE<gt> for their valuable input and suggestions.
1580 =head1 LICENSE AND COPYRIGHT
1582 Copyright (C) 2012-2015 by Simon Ruderich
1584 This program is free software: you can redistribute it and/or modify
1585 it under the terms of the GNU General Public License as published by
1586 the Free Software Foundation, either version 3 of the License, or
1587 (at your option) any later version.
1589 This program is distributed in the hope that it will be useful,
1590 but WITHOUT ANY WARRANTY; without even the implied warranty of
1591 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1592 GNU General Public License for more details.
1594 You should have received a copy of the GNU General Public License
1595 along with this program. If not, see <http://www.gnu.org/licenses/>.
1599 L<hardening-check(1)>, L<dpkg-buildflags(1)>