3 # Build log hardening check, checks build logs for missing hardening flags.
5 # Copyright (C) 2012-2013 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.04';
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=/;
55 # List of source file extensions which require preprocessing.
56 my @source_preprocess_compile_cpp = (
58 qw( cc cp cxx cpp CPP c++ C ),
62 my @source_preprocess_compile = (
68 @source_preprocess_compile_cpp,
70 qw( F FOR fpp FPP FTN F90 F95 F03 F08 ),
72 my @source_preprocess_no_compile = (
76 my @source_preprocess = (
77 @source_preprocess_compile,
78 @source_preprocess_no_compile,
80 # List of source file extensions which don't require preprocessing.
81 my @source_no_preprocess_compile_cpp = (
87 my @source_no_preprocess_compile_ada = (
90 # If you add another file, fix use of @source_no_preprocess_compile_ada
91 # below (search for $compile_ada).
93 my @source_no_preprocess_compile = (
97 @source_no_preprocess_compile_cpp,
101 qw( f for ftn f90 f95 f03 f08 ),
103 @source_no_preprocess_compile_ada,
105 my @source_no_preprocess_no_compile = (
111 my @source_no_preprocess = (
112 @source_no_preprocess_compile,
113 @source_no_preprocess_no_compile,
115 # List of header file extensions which require preprocessing.
116 my @header_preprocess = (
117 # C, C++, Objective-C, Objective-C++
120 qw( hh H hp hxx hpp HPP h++ tcc ),
124 # Normal object files.
126 # Libtool object files.
128 # Dynamic libraries. bzip2 uses .sho.
134 # Hashes for fast extensions lookup to check if a file falls in one of these
136 my %extensions_no_preprocess = map { $_ => 1 } (
137 # There's no @header_no_preprocess.
138 @source_no_preprocess,
140 my %extensions_preprocess = map { $_ => 1 } (
144 my %extensions_compile_link = map { $_ => 1 } (
146 @source_no_preprocess,
148 my %extensions_compile = map { $_ => 1 } (
149 @source_preprocess_compile,
150 @source_no_preprocess_compile,
152 my %extensions_no_compile = map { $_ => 1 } (
153 @source_preprocess_no_compile,
154 @source_no_preprocess_no_compile,
156 my %extensions_compile_cpp = map { $_ => 1 } (
157 @source_preprocess_compile_cpp,
158 @source_no_preprocess_compile_cpp,
160 my %extensions_object = map { $_ => 1 } (
163 my %extension = map { $_ => 1 } (
164 @source_no_preprocess,
170 # Regexp to match file extensions.
171 my $file_extension_regex = qr/
173 \S+ # Filename without extension.
175 ([^\/\\.,;:\s]+)# File extension.
176 (?=\s|\\) # At end of word. Can't use \b because some files have non
177 # word characters at the end and because \b matches double
178 # extensions (like .cpp.o). Works always as all lines are
179 # terminated with "\n".
182 # Expected (hardening) flags. All flags are used as regexps (and compiled to
183 # real regexps below for better execution speed).
186 '-O(?:2|3)', # keep at index 1, search for @def_cflags_debug to change it
188 my @def_cflags_debug = (
189 # These flags indicate a debug build which disables checks for -O2.
193 my @def_cflags_format = (
194 '-Wformat(?:=2)?', # -Wformat=2 implies -Wformat, accept it too
195 '-Werror=format-security', # implies -Wformat-security
197 my @def_cflags_fortify = (
198 # fortify needs at least -O1, but -O2 is recommended anyway
200 my @def_cflags_stack = (
202 '--param[= ]ssp-buffer-size=4',
204 my @def_cflags_stack_strong = (
205 '-fstack-protector-strong',
207 my @def_cflags_pie = (
213 # @def_cxxflags_* is the same as @def_cflags_*.
214 my @def_cppflags = ();
215 my @def_cppflags_fortify = (
216 '-D_FORTIFY_SOURCE=2', # must be first, see cppflags_fortify_broken()
217 # If you add another flag fix hack below (search for "Hack to fix") and
218 # $def_cppflags_fortify[0].
220 my @def_cppflags_fortify_bad = (
221 # These flags may overwrite -D_FORTIFY_SOURCE=2.
223 '-D_FORTIFY_SOURCE=0',
224 '-D_FORTIFY_SOURCE=1',
226 my @def_ldflags = ();
227 my @def_ldflags_relro = (
230 my @def_ldflags_bindnow = (
233 my @def_ldflags_pie = (
237 my @def_ldflags_pic = (
242 # References to all flags checked by the flag checker.
246 \@def_cflags_fortify,
248 \@def_cflags_stack_strong,
252 \@def_cppflags_fortify,
255 \@def_ldflags_bindnow,
258 # References to all used flags.
259 my @flag_refs_all = (
262 \@def_cppflags_fortify_bad,
265 # Renaming rules for the output so the regex parts are not visible. Also
266 # stores string values of flag regexps above, see compile_flag_regexp().
268 '-O(?:2|3)' => '-O2',
269 '-Wformat(?:=2)?' => '-Wformat',
270 '--param[= ]ssp-buffer-size=4' => '--param=ssp-buffer-size=4',
271 '-Wl,(?:-z,)?relro' => '-Wl,-z,relro',
272 '-Wl,(?:-z,)?now' => '-Wl,-z,now',
276 no_compiler_commands => 1 << 0,
277 # used by POD::Usage => 1 << 1,
278 non_verbose_build => 1 << 2,
279 flags_missing => 1 << 3,
280 hardening_wrapper => 1 << 4,
281 invalid_cmake => 1 << 5,
285 no_compiler_commands => 'I-no-compiler-commands',
286 non_verbose_build => 'W-compiler-flags-hidden',
287 flags_missing => 'W-dpkg-buildflags-missing',
288 hardening_wrapper => 'I-hardening-wrapper-used',
289 invalid_cmake => 'I-invalid-cmake-used',
292 # Statistics of missing flags and non-verbose build commands. Used for
296 preprocess_missing => 0,
298 compile_missing => 0,
300 compile_cpp_missing => 0,
304 commands_nonverbose => 0,
307 # Use colored (ANSI) output?
313 # Only works for single-level arrays with no undef values. Thanks to perlfaq4.
315 my ($first_ref, $second_ref) = @_;
317 return 0 if scalar @{$first_ref} != scalar @{$second_ref};
319 my $length = scalar @{$first_ref};
320 for (my $i = 0; $i < $length; $i++) {
321 return 0 if $first_ref->[$i] ne $second_ref->[$i];
328 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
330 # Get string value of qr//-escaped regexps and if requested rename them.
331 my @missing_flags = map {
332 $flag_renames_ref->{$_}
333 } @{$missing_flags_ref};
335 my $flags = join ' ', @missing_flags;
336 printf '%s (%s)%s %s',
337 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
342 sub error_non_verbose_build {
346 error_color('NONVERBOSE BUILD', 'red'),
347 error_color(':', 'yellow'),
352 sub error_invalid_cmake {
356 error_color('INVALID CMAKE', 'red'),
357 error_color(':', 'yellow'),
362 sub error_hardening_wrapper {
364 error_color('HARDENING WRAPPER', 'red'),
365 error_color(':', 'yellow'),
366 'no checks possible, aborting';
371 my ($message, $color) = @_;
374 return Term::ANSIColor::colored($message, $color);
381 my ($line, @flags) = @_;
383 foreach my $flag (@flags) {
384 return 1 if $line =~ /$flag/;
390 my ($line, $missing_flags_ref, @flags) = @_;
392 my @missing_flags = ();
393 foreach my $flag (@flags) {
394 if (not $line =~ /$flag/) {
395 push @missing_flags, $flag;
399 return 1 if scalar @missing_flags == 0;
401 @{$missing_flags_ref} = @missing_flags;
405 sub cppflags_fortify_broken {
406 my ($line, $missing_flags) = @_;
408 # This doesn't take the position into account, but is a simple solution.
409 # And if the build system tries to force -D_FORTIFY_SOURCE=0/1, something
412 if (any_flags_used($line, @def_cppflags_fortify_bad)) {
413 # $def_cppflags_fortify[0] must be -D_FORTIFY_SOURCE=2!
414 push @{$missing_flags}, $def_cppflags_fortify[0];
421 # Modifies $missing_flags_ref array.
422 sub pic_pie_conflict {
423 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
425 return 0 if not $pie;
426 return 0 if not any_flags_used($line, @def_ldflags_pic);
428 my %flags = map { $_ => 1 } @flags_pie;
430 # Remove all PIE flags from @missing_flags as they are not required with
433 not exists $flags{$_}
434 } @{$missing_flags_ref};
435 @{$missing_flags_ref} = @result;
437 # We got a conflict when no flags are left, thus only PIE flags were
438 # missing. If other flags were missing abort because the conflict is not
440 return scalar @result == 0;
443 sub is_non_verbose_build {
444 my ($line, $next_line, $skip_ref) = @_;
446 if ($line =~ /$libtool_regex/o) {
447 # libtool's --silent hides the real compiler flags.
448 if ($line =~ /\s--silent/) {
450 # If --silent is not present, skip this line as some compiler flags
451 # might be missing (e.g. -fPIE) which are handled correctly by libtool
452 # internally. libtool displays the real compiler command on the next
453 # line, so the flags are checked as usual.
460 if (not (index($line, 'checking if you want to see long compiling messages... no') == 0
461 or $line =~ /^\s*\[?(?:CC|CCLD|C\+\+|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
462 or $line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/
463 or $line =~ /^\s*[Bb]uilding (?:program|shared library)\s+(.+?)$/
464 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
470 # C++ compiler setting.
471 return 0 if $line =~ /^\s*C\+\+.+?:\s+(?:yes|no)\s*$/;
472 return 0 if $line =~ /^\s*C\+\+ Library: stdc\+\+$/;
473 # "Compiling" non binary files.
474 return 0 if $line =~ /^\s*Compiling \S+\.(?:py|el)['"]?\s*(?:\.\.\.)?$/;
475 # "Compiling" with no file name.
476 if ($line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/) {
477 # $file_extension_regex may need spaces around the filename.
478 return 0 if not " $1 " =~ /$file_extension_regex/o;
483 # On the first pass we only check if this line is verbose or not.
484 return 1 if not defined $next_line;
486 # Second pass, we have access to the next line.
489 # CMake and other build systems print the non-verbose messages also when
490 # building verbose. If a compiler and the file name occurs in the next
491 # line, treat it as verbose build.
493 # Get filename, we can't use the complete path as only parts of it are
494 # used in the real compiler command.
495 $file =~ m{/([^/\s]+)$};
498 if (index($next_line, $file) != -1 and $next_line =~ /$cc_regex/o) {
499 # Not a non-verbose line, but we still have to skip the current line
500 # as it doesn't contain any compiler commands.
509 # Remove @flags from $flag_refs_ref, uses $flag_renames_ref as reference.
511 my ($flag_refs_ref, $flag_renames_ref, @flags) = @_;
513 my %removes = map { $_ => 1 } @flags;
514 foreach my $flags (@{$flag_refs_ref}) {
516 # Flag found as string.
517 not exists $removes{$_}
518 # Flag found as string representation of regexp.
519 and (not defined $flag_renames_ref->{$_}
520 or not exists $removes{$flag_renames_ref->{$_}})
527 # Modifies $flag_renames_ref hash.
528 sub compile_flag_regexp {
529 my ($flag_renames_ref, @flags) = @_;
532 foreach my $flag (@flags) {
533 # Compile flag regexp for faster execution.
534 my $regex = qr/\s$flag(?:\s|\\)/;
536 # Store flag name in replacement string for correct flags in messages
537 # with qr//ed flag regexps.
538 $flag_renames_ref->{$regex}
539 = (exists $flag_renames_ref->{$flag})
540 ? $flag_renames_ref->{$flag}
543 push @result, $regex;
548 # Does any extension in @extensions exist in %{$extensions_ref}?
549 sub extension_found {
550 my ($extensions_ref, @extensions) = @_;
552 foreach my $extension (@extensions) {
553 if (exists $extensions_ref->{$extension}) {
563 # Parse command line arguments.
565 my $option_version = 0;
567 my $option_bindnow = 0;
568 my @option_ignore_arch = ();
569 my @option_ignore_flag = ();
570 my @option_ignore_arch_flag = ();
571 my @option_ignore_line = ();
572 my @option_ignore_arch_line = ();
574 my $option_arch = undef;
575 my $option_buildd = 0;
577 if (not Getopt::Long::GetOptions(
578 'help|h|?' => \$option_help,
579 'version' => \$option_version,
581 'pie' => \$option_pie,
582 'bindnow' => \$option_bindnow,
583 'all' => \$option_all,
585 'ignore-arch=s' => \@option_ignore_arch,
586 'ignore-flag=s' => \@option_ignore_flag,
587 'ignore-arch-flag=s' => \@option_ignore_arch_flag,
588 'ignore-line=s' => \@option_ignore_line,
589 'ignore-arch-line=s' => \@option_ignore_arch_line,
591 'color' => \$option_color,
592 'arch=s' => \$option_arch,
593 'buildd' => \$option_buildd,
596 Pod::Usage::pod2usage(2);
600 Pod::Usage::pod2usage(1);
602 if ($option_version) {
604 blhc $VERSION Copyright (C) 2012-2013 Simon Ruderich
606 This program is free software: you can redistribute it and/or modify
607 it under the terms of the GNU General Public License as published by
608 the Free Software Foundation, either version 3 of the License, or
609 (at your option) any later version.
611 This program is distributed in the hope that it will be useful,
612 but WITHOUT ANY WARRANTY; without even the implied warranty of
613 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
614 GNU General Public License for more details.
616 You should have received a copy of the GNU General Public License
617 along with this program. If not, see <http://www.gnu.org/licenses/>.
623 if (scalar @ARGV == 0) {
625 Pod::Usage::pod2usage(2);
628 # Don't load Term::ANSIColor in buildd mode because Term::ANSIColor is not
629 # installed on Debian's buildds.
630 if (not $option_buildd) {
631 require Term::ANSIColor;
639 # Precompiled ignores for faster lookup.
640 my %option_ignore_arch_flag = ();
641 my %option_ignore_arch_line = ();
643 # Strip flags which should be ignored.
644 if (scalar @option_ignore_flag > 0) {
645 remove_flags(\@flag_refs, \%flag_renames, @option_ignore_flag);
647 # Same for arch specific ignore flags, but only prepare here.
648 if (scalar @option_ignore_arch_flag > 0) {
649 foreach my $ignore (@option_ignore_arch_flag) {
650 my ($ignore_arch, $ignore_flag) = split /:/, $ignore, 2;
652 if (not $ignore_arch or not $ignore_flag) {
653 printf STDERR 'Value "%s" invalid for option ignore-arch-flag '
654 . '("arch:flag" expected)' . "\n", $ignore;
656 Pod::Usage::pod2usage(2);
659 push @{$option_ignore_arch_flag{$ignore_arch}}, $ignore_flag;
663 # Precompile all flag regexps. any_flags_used(), all_flags_used() get a lot
665 foreach my $flags (@flag_refs_all) {
666 @{$flags} = compile_flag_regexp(\%flag_renames, @{$flags});
669 # Precompile ignore line regexps, also anchor at beginning and end of line.
670 foreach my $ignore (@option_ignore_line) {
671 $ignore = qr/^$ignore$/;
673 # Same for arch specific ignore lines.
674 if (scalar @option_ignore_arch_line > 0) {
675 foreach my $ignore (@option_ignore_arch_line) {
676 my ($ignore_arch, $ignore_line) = split /:/, $ignore, 2;
678 if (not $ignore_arch or not $ignore_line) {
679 printf STDERR 'Value "%s" invalid for option ignore-arch-line '
680 . '("arch:line" expected)' . "\n", $ignore;
682 Pod::Usage::pod2usage(2);
685 push @{$option_ignore_arch_line{$ignore_arch}}, qr/^$ignore_line$/;
693 foreach my $file (@ARGV) {
694 print "checking '$file'...\n" if scalar @ARGV > 1;
696 -f $file or die "No such file: $file";
698 open my $fh, '<', $file or die $!;
700 # Architecture of this file.
701 my $arch = $option_arch;
703 # Hardening options. Not all architectures support all hardening options.
704 my $harden_format = 1;
705 my $harden_fortify = 1;
706 my $harden_stack = 1;
707 my $harden_stack_strong = 1;
708 my $harden_relro = 1;
709 my $harden_bindnow = $option_bindnow; # defaults to 0
710 my $harden_pie = $option_pie; # defaults to 0
712 # Does this build log use ada? Ada also uses gcc as compiler but uses
713 # different CFLAGS. But only perform ada checks if an ada compiler used
714 # for performance reasons.
717 while (my $line = <$fh>) {
718 # Detect architecture automatically unless overridden. For buildd logs
719 # only, doesn't use the dpkg-buildpackage header. Necessary to ignore
720 # build logs which aren't built (wrong architecture, build error,
723 if (index($line, 'Build Architecture: ') == 0) {
724 $arch = substr $line, 20, -1; # -1 to ignore '\n' at the end
725 # For old logs (sbuild << 0.63.0-1).
726 } elsif (index($line, 'Architecture: ') == 0) {
727 $arch = substr $line, 14, -1; # -1 to ignore '\n' at the end
731 # dpkg-buildflags only provides hardening flags since 1.16.1, don't
732 # check for hardening flags in buildd mode if an older dpkg-dev is
733 # used. Default flags (-g -O2) are still checked.
735 # Packages which were built before 1.16.1 but used their own hardening
736 # flags are not checked.
738 # Strong stack protector is used since dpkg 1.17.11.
740 and index($line, 'Toolchain package versions: ') == 0) {
741 require Dpkg::Version;
744 my $disable_strong = 1;
746 if ($line =~ /\bdpkg-dev_(\S+)/) {
747 if (Dpkg::Version::version_compare($1, '1.16.1') >= 0) {
750 if (Dpkg::Version::version_compare($1, '1.17.11') >= 0) {
763 if ($disable_strong) {
764 $harden_stack_strong = 0;
768 # The following two versions of CMake in Debian obeyed CPPFLAGS, but
769 # this was later dropped because upstream rejected the patch. Thus
770 # build logs with these versions will have fortify hardening flags
771 # enabled, even though they may be not correctly set and are missing
772 # when build with later CMake versions. Thanks to Aron Xu for letting
774 if (index($line, 'Package versions: ') == 0
775 and $line =~ /\bcmake_(\S+)/
776 and ($1 eq '2.8.7-1' or $1 eq '2.8.7-2')) {
777 if (not $option_buildd) {
778 error_invalid_cmake($1);
779 $exit |= $exit_code{invalid_cmake};
781 print "$buildd_tag{invalid_cmake}|$1|\n";
785 # Debian's build daemons use "Filtered Build-Depends:" (or just
786 # "Build-Depends:" in older versions) for the build dependencies, but
787 # pbuilder uses "Depends:"; support both.
788 if (index($line, 'Filtered Build-Depends: ') == 0
789 or index($line, 'Build-Depends: ') == 0
790 or index($line, 'Depends: ') == 0) {
791 # If hardening wrapper is used (wraps calls to gcc and adds
792 # hardening flags automatically) we can't perform any checks,
794 if ($line =~ /\bhardening-wrapper\b/) {
795 if (not $option_buildd) {
796 error_hardening_wrapper();
797 $exit |= $exit_code{hardening_wrapper};
799 print "$buildd_tag{hardening_wrapper}||\n";
805 if ($line =~ /\bgnat\b/) {
810 # We skip over unimportant lines at the beginning of the log to
811 # prevent false positives.
812 last if index($line, 'dpkg-buildpackage: ') == 0;
815 # Input lines, contain only the lines with compiler commands.
817 # Non-verbose lines in the input. Used to reduce calls to
818 # is_non_verbose_build() (which is quite slow) in the second loop when
819 # it's already clear if a line is non-verbose or not.
820 my @input_nonverbose = ();
822 my $continuation = 0;
823 my $complete_line = undef;
825 while (my $line = <$fh>) {
826 # And stop at the end of the build log. Package details (reported by
827 # the buildd logs) are not important for us. This also prevents false
829 last if index($line, 'Build finished at ') == 0
830 and $line =~ /^Build finished at \d{8}-\d{4}$/;
832 if (not $continuation) {
836 # Detect architecture automatically unless overridden.
838 and index($line, 'dpkg-buildpackage: host architecture ') == 0) {
839 $arch = substr $line, 37, -1; # -1 to ignore '\n' at the end
841 # Old buildd logs use e.g. "host architecture is alpha", remove
842 # the "is", otherwise debarch_to_debtriplet() will not detect the
844 if (index($arch, 'is ') == 0) {
845 $arch = substr $arch, 3;
849 # Ignore compiler warnings for now.
850 next if $line =~ /$warning_regex/o;
852 if (not $option_buildd and index($line, "\033") != -1) { # \033 = esc
853 # Remove all ANSI color sequences which are sometimes used in
854 # non-verbose builds.
855 $line = Term::ANSIColor::colorstrip($line);
856 # Also strip '\0xf' (delete previous character), used by Elinks'
859 # And "ESC(B" which seems to be used on armhf and hurd (not sure
861 $line =~ s/\033\(B//g;
864 # Check if this line indicates a non verbose build.
866 $non_verbose |= is_non_verbose_build($line, undef, \$skip);
869 # One line may contain multiple commands (";"). Treat each one as
870 # single line. parse_line() is slow, only use it when necessary.
871 my @line = (index($line, ';') == -1)
874 # Ensure newline at the line end - necessary for
875 # correct parsing later.
878 } Text::ParseWords::parse_line(';', 1, $line);
879 foreach my $line (@line) {
883 # Join lines, but leave the "\" in place so it's clear where
884 # the original line break was.
885 chomp $complete_line;
886 $complete_line .= ' ' . $line;
888 # Line continuation, line ends with "\".
889 if ($line =~ /\\$/) {
891 # Start line continuation.
892 if (not defined $complete_line) {
893 $complete_line = $line;
898 # Use the complete line if a line continuation occurred.
899 if (defined $complete_line) {
900 $line = $complete_line;
901 $complete_line = undef;
904 # Ignore lines with no compiler commands.
905 next if not $non_verbose
906 and not $line =~ /$cc_regex_normal/o;
907 # Ignore lines with no filenames with extensions. May miss some
908 # non-verbose builds (e.g. "gcc -o test" [sic!]), but shouldn't be
909 # a problem as the log will most likely contain other non-verbose
910 # commands which are detected.
911 next if not $non_verbose
912 and not $line =~ /$file_extension_regex/o;
914 # Ignore false positives.
916 # `./configure` output.
917 next if not $non_verbose
918 and $line =~ /^(?:checking|[Cc]onfigure:) /;
919 next if $line =~ /^\s*(?:Host\s+)?(?:C(?:\+\+)?\s+)?
920 [Cc]ompiler[\s.]*:?\s+
922 next if $line =~ m{^\s*(?:-\s)?(?:HOST_)?(?:CC|CXX)
923 \s*=\s*$cc_regex_full
924 # optional compiler options, don't allow
925 # "everything" here to prevent false negatives
926 \s*(?:\s-\S+)*\s*$}xo;
927 # `moc-qt4`/`moc-qt5` contain '-I.../linux-g++' in their command
928 # line (or similar for other architectures) which gets recognized
929 # as a compiler line, but `moc-qt*` is only a preprocessor for Qt
930 # C++ files. No hardening flags are relevant during this step,
931 # thus ignore `moc-qt*` lines. The resulting files will be
932 # compiled in a separate step (and therefore checked).
933 next if $line =~ m{^\S+/bin/moc(?:-qt[45])?
935 -I\S+/mkspecs/[a-z]+-g\++(?:-64)?
937 # Ignore false positives when the line contains only CC=gcc but no
939 if ($line =~ /(.*)CC=$cc_regex_full(.*)/o) {
942 next if not $before =~ /$cc_regex_normal/o
943 and not $after =~ /$cc_regex_normal/o;
946 # Check if additional hardening options were used. Used to ensure
947 # they are used for the complete build.
948 $harden_pie = 1 if any_flags_used($line, @def_cflags_pie,
950 $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);
953 push @input_nonverbose, $non_verbose;
959 # Ignore arch if requested.
960 if (scalar @option_ignore_arch > 0 and $arch) {
961 foreach my $ignore (@option_ignore_arch) {
962 if ($arch eq $ignore) {
963 print "ignoring architecture '$arch'\n";
969 if (scalar @input == 0) {
970 if (not $option_buildd) {
971 print "No compiler commands!\n";
972 $exit |= $exit_code{no_compiler_commands};
974 print "$buildd_tag{no_compiler_commands}||\n";
979 if ($option_buildd) {
980 $statistics{commands} += scalar @input;
983 # Option or auto detected.
985 # The following was partially copied from dpkg-dev 1.17.11
986 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
987 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
988 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
989 # later. Keep it in sync.
992 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($arch);
994 # Disable unsupported hardening options.
995 if ($os !~ /^(?:linux|knetbsd|hurd)$/ or
996 $cpu =~ /^(?:hppa|mips|mipsel|avr32)$/) {
999 if ($cpu =~ /^(?:ia64|alpha|mips|mipsel|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 # Remove everything until and including the compiler command. Makes
1106 # checks easier and faster.
1107 $line =~ s/^.*?$cc_regex//o;
1108 # "([...] test.c)" is not detected as 'test.c' - fix this by removing
1109 # the brace and similar characters at the line end.
1110 $line =~ s/['")]+$//;
1112 # Skip unnecessary tests when only preprocessing.
1113 my $flag_preprocess = 0;
1120 # Preprocess, compile, assemble.
1121 if ($line =~ /\s(-E|-S|-c)\b/) {
1123 $flag_preprocess = 1 if $1 eq '-E';
1124 $compile = 1 if $1 eq '-S' or $1 eq '-c';
1125 # Dependency generation for Makefiles. The other flags (-MF -MG -MP
1126 # -MT -MQ) are always used with -M/-MM.
1127 } elsif ($line =~ /\s(?:-M|-MM)\b/) {
1129 # Otherwise assume we are linking.
1134 # -MD/-MMD also cause dependency generation, but they don't imply -E!
1135 if ($line =~ /\s(?:-MD|-MMD)\b/) {
1137 $flag_preprocess = 0;
1140 # Dependency generation for Makefiles, no preprocessing or other flags
1142 next if $dependency;
1144 # Get all file extensions on this line.
1145 my @extensions = $line =~ /$file_extension_regex/go;
1146 # Ignore all unknown extensions to speedup the search below.
1147 @extensions = grep { exists $extension{$_} } @extensions;
1149 # These file types don't require preprocessing.
1150 if (extension_found(\%extensions_no_preprocess, @extensions)) {
1153 # These file types require preprocessing.
1154 if (extension_found(\%extensions_preprocess, @extensions)) {
1158 if (not $flag_preprocess) {
1159 # If there are source files then it's compiling/linking in one
1160 # step and we must check both. We only check for source files
1161 # here, because header files cause too many false positives.
1162 if (extension_found(\%extensions_compile_link, @extensions)) {
1163 # Assembly files don't need CFLAGS.
1164 if (not extension_found(\%extensions_compile, @extensions)
1165 and extension_found(\%extensions_no_compile, @extensions)) {
1167 # But the rest does.
1171 # No compilable extensions found, either linking or compiling
1174 # If there are also no object files we are just compiling headers
1175 # (.h -> .h.gch). Don't check for linker flags in this case. Due
1176 # to our liberal checks for compiler lines, this also reduces the
1177 # number of false positives considerably.
1179 and not extension_found(\%extensions_object, @extensions)) {
1184 my $compile_cpp = 0;
1185 my $compile_ada = 0;
1186 # Assume CXXFLAGS are required when a C++ file is specified in the
1189 and extension_found(\%extensions_compile_cpp, @extensions)) {
1192 # Ada needs special CFLAGS, use them if only ada files are compiled.
1195 and array_equal(\@extensions,
1196 \@source_no_preprocess_compile_ada)) {
1198 @cflags_backup = @cflags;
1199 @cflags = @cflags_ada;
1202 if ($option_buildd) {
1203 $statistics{preprocess}++ if $preprocess;
1204 $statistics{compile}++ if $compile;
1205 $statistics{compile_cpp}++ if $compile_cpp;
1206 $statistics{link}++ if $link;
1209 # Check if there are flags indicating a debug build. If that's true,
1210 # skip the check for -O2. This prevents fortification, but that's fine
1211 # for a debug build.
1212 if (any_flags_used($line, @def_cflags_debug)) {
1213 remove_flags([\@cflags], \%flag_renames, $def_cflags[1]);
1214 remove_flags([\@cppflags], \%flag_renames, $def_cppflags_fortify[0]);
1217 # Check hardening flags.
1219 if ($compile and not all_flags_used($line, \@missing, @cflags)
1220 # Libraries linked with -fPIC don't have to (and can't) be
1221 # linked with -fPIE as well. It's no error if only PIE flags
1223 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1224 # Assume dpkg-buildflags returns the correct flags.
1225 and index($line, '`dpkg-buildflags --get CFLAGS`') == -1) {
1226 if (not $option_buildd) {
1227 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1228 $exit |= $exit_code{flags_missing};
1230 $statistics{compile_missing}++;
1232 } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
1233 # Libraries linked with -fPIC don't have to (and can't) be
1234 # linked with -fPIE as well. It's no error if only PIE flags
1236 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1237 # Assume dpkg-buildflags returns the correct flags.
1238 and index($line, '`dpkg-buildflags --get CXXFLAGS`') == -1) {
1239 if (not $option_buildd) {
1240 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1241 $exit |= $exit_code{flags_missing};
1243 $statistics{compile_cpp_missing}++;
1247 and (not all_flags_used($line, \@missing, @cppflags)
1248 # The fortify flag might be overwritten, detect that.
1250 and cppflags_fortify_broken($line, \@missing)))
1251 # Assume dpkg-buildflags returns the correct flags.
1252 and index($line, '`dpkg-buildflags --get CPPFLAGS`') == -1) {
1253 if (not $option_buildd) {
1254 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1255 $exit |= $exit_code{flags_missing};
1257 $statistics{preprocess_missing}++;
1260 if ($link and not all_flags_used($line, \@missing, @ldflags)
1261 # Same here, -fPIC conflicts with -fPIE.
1262 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
1263 # Assume dpkg-buildflags returns the correct flags.
1264 and index($line, '`dpkg-buildflags --get LDFLAGS`') == -1) {
1265 if (not $option_buildd) {
1266 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1267 $exit |= $exit_code{flags_missing};
1269 $statistics{link_missing}++;
1273 # Restore normal CFLAGS.
1275 @cflags = @cflags_backup;
1280 # Print statistics for buildd mode, only output in this mode.
1281 if ($option_buildd) {
1284 if ($statistics{preprocess_missing}) {
1285 push @warning, sprintf 'CPPFLAGS %d (of %d)',
1286 $statistics{preprocess_missing},
1287 $statistics{preprocess};
1289 if ($statistics{compile_missing}) {
1290 push @warning, sprintf 'CFLAGS %d (of %d)',
1291 $statistics{compile_missing},
1292 $statistics{compile};
1294 if ($statistics{compile_cpp_missing}) {
1295 push @warning, sprintf 'CXXFLAGS %d (of %d)',
1296 $statistics{compile_cpp_missing},
1297 $statistics{compile_cpp};
1299 if ($statistics{link_missing}) {
1300 push @warning, sprintf 'LDFLAGS %d (of %d)',
1301 $statistics{link_missing},
1304 if (scalar @warning) {
1305 local $" = ', '; # array join string
1306 print "$buildd_tag{flags_missing}|@warning missing|\n";
1309 if ($statistics{commands_nonverbose}) {
1310 printf "$buildd_tag{non_verbose_build}|%d (of %d) hidden|\n",
1311 $statistics{commands_nonverbose},
1312 $statistics{commands},
1324 blhc - build log hardening check, checks build logs for missing hardening flags
1328 B<blhc> [I<options>] I<< <dpkg-buildpackage build log file>.. >>
1332 blhc is a small tool which checks build logs for missing hardening flags. It's
1333 licensed under the GPL 3 or later.
1335 It's designed to check build logs generated by Debian's dpkg-buildpackage (or
1336 tools using dpkg-buildpackage like pbuilder or sbuild (which is used for the
1337 official buildd build logs)) to help maintainers detect missing hardening
1338 flags in their packages.
1340 Only gcc is detected as compiler at the moment. If other compilers support
1341 hardening flags as well, please report them.
1343 If there's no output, no flags are missing and the build log is fine.
1345 See F<README> for details about performed checks, auto-detection and
1354 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
1357 =item B<--arch> I<architecture>
1359 Set the specific architecture (e.g. amd64, armel, etc.), automatically
1360 disables hardening flags not available on this architecture. Is detected
1361 automatically if dpkg-buildpackage is used.
1365 Force check for all +bindnow hardening flags. By default it's auto detected.
1369 Special mode for buildds when automatically parsing log files. The following
1370 changes are in effect:
1376 Print tags instead of normal warnings, see L</"BUILDD TAGS"> for a list of
1381 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
1386 Don't require Term::ANSIColor.
1390 Return exit code 0, unless there was a error (-I, -W messages don't count as
1397 Use colored (ANSI) output for warning messages.
1399 =item B<--ignore-arch> I<arch>
1401 Ignore build logs from architectures matching I<arch>. I<arch> is a string.
1403 Used to prevent false positives. This option can be specified multiple times.
1405 =item B<--ignore-arch-flag> I<arch>:I<flag>
1407 Like B<--ignore-flag>, but only ignore flag on I<arch>.
1409 =item B<--ignore-arch-line> I<arch>:I<line>
1411 Like B<--ignore-line>, but only ignore line on I<arch>.
1413 =item B<--ignore-flag> I<flag>
1415 Don't print an error when the specific flag is missing in a compiler line.
1416 I<flag> is a string.
1418 Used to prevent false positives. This option can be specified multiple times.
1420 =item B<--ignore-line> I<regex>
1422 Ignore lines matching the given Perl regex. I<regex> is automatically anchored
1423 at the beginning and end of the line to prevent false negatives.
1425 B<NOTE>: Not the input lines are checked, but the lines which are displayed in
1426 warnings (which have line continuation resolved).
1428 Used to prevent false positives. This option can be specified multiple times.
1432 Force check for all +pie hardening flags. By default it's auto detected.
1434 =item B<-h -? --help>
1436 Print available options.
1440 Print version number and license.
1444 Auto detection for B<--pie> and B<--bindnow> only works if at least one
1445 command uses the required hardening flag (e.g. -fPIE). Then it's required for
1446 all other commands as well.
1450 Normal usage, parse a single log file.
1452 blhc path/to/log/file
1454 If there's no output, no flags are missing and the build log is fine.
1456 Parse multiple log files. The exit code is ORed over all files.
1458 blhc path/to/directory/with/log/files/*
1460 Don't treat missing C<-g> as error:
1462 blhc --ignore-flag -g path/to/log/file
1464 Don't treat missing C<-pie> on kfreebsd-amd64 as error:
1466 blhc --ignore-arch-flag kfreebsd-amd64:-pie path/to/log/file
1468 Ignore lines consisting exactly of C<./script gcc file> which would cause a
1471 blhc --ignore-line '\./script gcc file' path/to/log/file
1473 Ignore lines matching C<./script gcc file> somewhere in the line.
1475 blhc --ignore-line '.*\./script gcc file.*' path/to/log/file
1477 Use blhc with pbuilder.
1479 pbuilder path/to/package.dsc | tee path/log/file
1480 blhc path/to/file || echo flags missing
1484 The following tags are used in I<--buildd> mode. In braces the additional data
1489 =item B<I-hardening-wrapper-used>
1491 The package uses hardening-wrapper which intercepts calls to gcc and adds
1492 hardening flags. The build log doesn't contain any hardening flags and thus
1493 can't be checked by blhc.
1495 =item B<W-compiler-flags-hidden> (summary of hidden lines)
1497 Build log contains lines which hide the real compiler flags. For example:
1504 Most of the time either C<export V=1> or C<export verbose=1> in
1505 F<debian/rules> fixes builds with hidden compiler flags. Sometimes C<.SILENT>
1506 in a F<Makefile> must be removed. And as last resort the F<Makefile> must be
1507 patched to remove the C<@>s hiding the real compiler commands.
1509 =item B<W-dpkg-buildflags-missing> (summary of missing flags)
1511 CPPFLAGS, CFLAGS, CXXFLAGS, LDFLAGS missing.
1513 =item B<I-invalid-cmake-used> (version)
1515 By default CMake ignores CPPFLAGS thus missing those hardening flags. Debian
1516 patched CMake in versions 2.8.7-1 and 2.8.7-2 to respect CPPFLAGS, but this
1517 patch was rejected by upstream and later reverted in Debian. Thus those two
1518 versions show correct usage of CPPFLAGS even if the package doesn't correctly
1519 handle them (for example by passing them to CFLAGS). To prevent false
1520 negatives just blacklist those two versions.
1522 =item B<I-no-compiler-commands>
1524 No compiler commands were detected. Either the log contains none or they were
1525 not correctly detected by blhc (please report the bug in this case).
1531 The exit status is a "bit mask", each listed status is ORed when the error
1532 condition occurs to get the result.
1542 No compiler commands were found.
1546 Invalid arguments/options given to blhc.
1554 Missing hardening flags.
1558 Hardening wrapper detected, no tests performed.
1562 Invalid CMake version used. See B<I-invalid-cmake-used> under L</"BUILDD
1563 TAGS"> for a detailed explanation.
1569 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
1571 Thanks to to Bernhard R. Link E<lt>brlink@debian.orgE<gt> and Jaria Alto
1572 E<lt>jari.aalto@cante.netE<gt> for their valuable input and suggestions.
1574 =head1 LICENSE AND COPYRIGHT
1576 Copyright (C) 2012-2013 by Simon Ruderich
1578 This program is free software: you can redistribute it and/or modify
1579 it under the terms of the GNU General Public License as published by
1580 the Free Software Foundation, either version 3 of the License, or
1581 (at your option) any later version.
1583 This program is distributed in the hope that it will be useful,
1584 but WITHOUT ANY WARRANTY; without even the implied warranty of
1585 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1586 GNU General Public License for more details.
1588 You should have received a copy of the GNU General Public License
1589 along with this program. If not, see <http://www.gnu.org/licenses/>.
1593 L<hardening-check(1)>, L<dpkg-buildflags(1)>