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=/;
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-2015 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 is 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.18.2
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 $cpu =~ /^(?:hppa|avr32)$/) {
998 if ($cpu =~ /^(?:ia64|alpha|hppa)$/ or $arch eq 'arm') {
1000 $harden_stack_strong = 0;
1002 if ($cpu =~ /^(?:ia64|hppa|avr32)$/) {
1004 $harden_bindnow = 0;
1009 my @cflags = @def_cflags;
1010 my @cxxflags = @def_cxxflags;
1011 my @cppflags = @def_cppflags;
1012 my @ldflags = @def_ldflags;
1013 # Check the specified hardening options, same order as dpkg-buildflags.
1015 @cflags = (@cflags, @def_cflags_pie);
1016 @cxxflags = (@cxxflags, @def_cflags_pie);
1017 @ldflags = (@ldflags, @def_ldflags_pie);
1019 if ($harden_stack_strong) {
1020 @cflags = (@cflags, @def_cflags_stack_strong);
1021 @cxxflags = (@cxxflags, @def_cflags_stack_strong);
1022 } elsif ($harden_stack) {
1023 @cflags = (@cflags, @def_cflags_stack);
1024 @cxxflags = (@cxxflags, @def_cflags_stack);
1026 if ($harden_fortify) {
1027 @cflags = (@cflags, @def_cflags_fortify);
1028 @cxxflags = (@cxxflags, @def_cflags_fortify);
1029 @cppflags = (@cppflags, @def_cppflags_fortify);
1031 if ($harden_format) {
1032 @cflags = (@cflags, @def_cflags_format);
1033 @cxxflags = (@cxxflags, @def_cflags_format);
1035 if ($harden_relro) {
1036 @ldflags = (@ldflags, @def_ldflags_relro);
1038 if ($harden_bindnow) {
1039 @ldflags = (@ldflags, @def_ldflags_bindnow);
1042 # Stores normal CFLAGS when @cflags_ada are temporarily used.
1044 # Ada CFLAGS, only set if ada is used.
1046 # Ada doesn't support format hardening flags, see #680117 for more
1047 # information. Filter them out if ada is used.
1048 if ($ada and $harden_format) {
1049 @cflags_ada = grep {
1051 foreach my $flag (@def_cflags_format) {
1052 $ok = 0 if $_ eq $flag;
1058 # Hack to fix cppflags_fortify_broken() if --ignore-flag
1059 # -D_FORTIFY_SOURCE=2 is used to ignore missing fortification. Only works
1060 # as long as @def_cppflags_fortify contains only one variable.
1061 if (scalar @def_cppflags_fortify == 0) {
1062 $harden_fortify = 0;
1065 # Ignore flags for this arch if requested.
1066 if ($arch and exists $option_ignore_arch_flag{$arch}) {
1067 my @local_flag_refs = (\@cflags, \@cxxflags, \@cppflags, \@ldflags);
1069 remove_flags(\@local_flag_refs,
1071 @{$option_ignore_arch_flag{$arch}});
1074 my @ignore_line = @option_ignore_line;
1075 # Ignore lines for this arch if requested.
1076 if ($arch and exists $option_ignore_arch_line{$arch}) {
1077 @ignore_line = (@ignore_line, @{$option_ignore_arch_line{$arch}});
1081 for (my $i = 0; $i < scalar @input; $i++) {
1082 my $line = $input[$i];
1084 # Ignore line if requested.
1085 foreach my $ignore (@ignore_line) {
1086 next LINE if $line =~ /$ignore/;
1090 if ($input_nonverbose[$i]
1091 and is_non_verbose_build($line, $input[$i + 1], \$skip)) {
1092 if (not $option_buildd) {
1093 error_non_verbose_build($line);
1094 $exit |= $exit_code{non_verbose_build};
1096 $statistics{commands_nonverbose}++;
1100 # Even if it's a verbose build, we might have to skip this line (see
1101 # is_non_verbose_build()).
1104 # Remove everything until and including the compiler command. Makes
1105 # checks easier and faster.
1106 $line =~ s/^.*?$cc_regex//o;
1107 # "([...] test.c)" is not detected as 'test.c' - fix this by removing
1108 # the brace and similar characters at the line end.
1109 $line =~ s/['")]+$//;
1111 # Skip unnecessary tests when only preprocessing.
1112 my $flag_preprocess = 0;
1119 # Preprocess, compile, assemble.
1120 if ($line =~ /\s(-E|-S|-c)\b/) {
1122 $flag_preprocess = 1 if $1 eq '-E';
1123 $compile = 1 if $1 eq '-S' or $1 eq '-c';
1124 # Dependency generation for Makefiles. The other flags (-MF -MG -MP
1125 # -MT -MQ) are always used with -M/-MM.
1126 } elsif ($line =~ /\s(?:-M|-MM)\b/) {
1128 # Otherwise assume we are linking.
1133 # -MD/-MMD also cause dependency generation, but they don't imply -E!
1134 if ($line =~ /\s(?:-MD|-MMD)\b/) {
1136 $flag_preprocess = 0;
1139 # Dependency generation for Makefiles, no preprocessing or other flags
1141 next if $dependency;
1143 # Get all file extensions on this line.
1144 my @extensions = $line =~ /$file_extension_regex/go;
1145 # Ignore all unknown extensions to speedup the search below.
1146 @extensions = grep { exists $extension{$_} } @extensions;
1148 # These file types don't require preprocessing.
1149 if (extension_found(\%extensions_no_preprocess, @extensions)) {
1152 # These file types require preprocessing.
1153 if (extension_found(\%extensions_preprocess, @extensions)) {
1157 if (not $flag_preprocess) {
1158 # If there are source files then it's compiling/linking in one
1159 # step and we must check both. We only check for source files
1160 # here, because header files cause too many false positives.
1161 if (extension_found(\%extensions_compile_link, @extensions)) {
1162 # Assembly files don't need CFLAGS.
1163 if (not extension_found(\%extensions_compile, @extensions)
1164 and extension_found(\%extensions_no_compile, @extensions)) {
1166 # But the rest does.
1170 # No compilable extensions found, either linking or compiling
1173 # If there are also no object files we are just compiling headers
1174 # (.h -> .h.gch). Don't check for linker flags in this case. Due
1175 # to our liberal checks for compiler lines, this also reduces the
1176 # number of false positives considerably.
1178 and not extension_found(\%extensions_object, @extensions)) {
1183 my $compile_cpp = 0;
1184 my $compile_ada = 0;
1185 # Assume CXXFLAGS are required when a C++ file is specified in the
1188 and extension_found(\%extensions_compile_cpp, @extensions)) {
1191 # Ada needs special CFLAGS, use them if only ada files are compiled.
1194 and array_equal(\@extensions,
1195 \@source_no_preprocess_compile_ada)) {
1197 @cflags_backup = @cflags;
1198 @cflags = @cflags_ada;
1201 if ($option_buildd) {
1202 $statistics{preprocess}++ if $preprocess;
1203 $statistics{compile}++ if $compile;
1204 $statistics{compile_cpp}++ if $compile_cpp;
1205 $statistics{link}++ if $link;
1208 # Check if there are flags indicating a debug build. If that's true,
1209 # skip the check for -O2. This prevents fortification, but that's fine
1210 # for a debug build.
1211 if (any_flags_used($line, @def_cflags_debug)) {
1212 remove_flags([\@cflags], \%flag_renames, $def_cflags[1]);
1213 remove_flags([\@cppflags], \%flag_renames, $def_cppflags_fortify[0]);
1216 # Check hardening flags.
1218 if ($compile and not all_flags_used($line, \@missing, @cflags)
1219 # Libraries linked with -fPIC don't have to (and can't) be
1220 # linked with -fPIE as well. It's no error if only PIE flags
1222 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1223 # Assume dpkg-buildflags returns the correct flags.
1224 and index($line, '`dpkg-buildflags --get CFLAGS`') == -1) {
1225 if (not $option_buildd) {
1226 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1227 $exit |= $exit_code{flags_missing};
1229 $statistics{compile_missing}++;
1231 } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
1232 # Libraries linked with -fPIC don't have to (and can't) be
1233 # linked with -fPIE as well. It's no error if only PIE flags
1235 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1236 # Assume dpkg-buildflags returns the correct flags.
1237 and index($line, '`dpkg-buildflags --get CXXFLAGS`') == -1) {
1238 if (not $option_buildd) {
1239 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1240 $exit |= $exit_code{flags_missing};
1242 $statistics{compile_cpp_missing}++;
1246 and (not all_flags_used($line, \@missing, @cppflags)
1247 # The fortify flag might be overwritten, detect that.
1249 and cppflags_fortify_broken($line, \@missing)))
1250 # Assume dpkg-buildflags returns the correct flags.
1251 and index($line, '`dpkg-buildflags --get CPPFLAGS`') == -1) {
1252 if (not $option_buildd) {
1253 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1254 $exit |= $exit_code{flags_missing};
1256 $statistics{preprocess_missing}++;
1259 if ($link and not all_flags_used($line, \@missing, @ldflags)
1260 # Same here, -fPIC conflicts with -fPIE.
1261 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
1262 # Assume dpkg-buildflags returns the correct flags.
1263 and index($line, '`dpkg-buildflags --get LDFLAGS`') == -1) {
1264 if (not $option_buildd) {
1265 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1266 $exit |= $exit_code{flags_missing};
1268 $statistics{link_missing}++;
1272 # Restore normal CFLAGS.
1274 @cflags = @cflags_backup;
1279 # Print statistics for buildd mode, only output in this mode.
1280 if ($option_buildd) {
1283 if ($statistics{preprocess_missing}) {
1284 push @warning, sprintf 'CPPFLAGS %d (of %d)',
1285 $statistics{preprocess_missing},
1286 $statistics{preprocess};
1288 if ($statistics{compile_missing}) {
1289 push @warning, sprintf 'CFLAGS %d (of %d)',
1290 $statistics{compile_missing},
1291 $statistics{compile};
1293 if ($statistics{compile_cpp_missing}) {
1294 push @warning, sprintf 'CXXFLAGS %d (of %d)',
1295 $statistics{compile_cpp_missing},
1296 $statistics{compile_cpp};
1298 if ($statistics{link_missing}) {
1299 push @warning, sprintf 'LDFLAGS %d (of %d)',
1300 $statistics{link_missing},
1303 if (scalar @warning) {
1304 local $" = ', '; # array join string
1305 print "$buildd_tag{flags_missing}|@warning missing|\n";
1308 if ($statistics{commands_nonverbose}) {
1309 printf "$buildd_tag{non_verbose_build}|%d (of %d) hidden|\n",
1310 $statistics{commands_nonverbose},
1311 $statistics{commands},
1323 blhc - build log hardening check, checks build logs for missing hardening flags
1327 B<blhc> [I<options>] I<< <dpkg-buildpackage build log file>.. >>
1331 blhc is a small tool which checks build logs for missing hardening flags. It's
1332 licensed under the GPL 3 or later.
1334 It's designed to check build logs generated by Debian's dpkg-buildpackage (or
1335 tools using dpkg-buildpackage like pbuilder or sbuild (which is used for the
1336 official buildd build logs)) to help maintainers detect missing hardening
1337 flags in their packages.
1339 Only gcc is detected as compiler at the moment. If other compilers support
1340 hardening flags as well, please report them.
1342 If there's no output, no flags are missing and the build log is fine.
1344 See F<README> for details about performed checks, auto-detection and
1353 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
1356 =item B<--arch> I<architecture>
1358 Set the specific architecture (e.g. amd64, armel, etc.), automatically
1359 disables hardening flags not available on this architecture. Is detected
1360 automatically if dpkg-buildpackage is used.
1364 Force check for all +bindnow hardening flags. By default it's auto detected.
1368 Special mode for buildds when automatically parsing log files. The following
1369 changes are in effect:
1375 Print tags instead of normal warnings, see L</"BUILDD TAGS"> for a list of
1380 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
1385 Don't require Term::ANSIColor.
1389 Return exit code 0, unless there was a error (-I, -W messages don't count as
1396 Use colored (ANSI) output for warning messages.
1398 =item B<--ignore-arch> I<arch>
1400 Ignore build logs from architectures matching I<arch>. I<arch> is a string.
1402 Used to prevent false positives. This option can be specified multiple times.
1404 =item B<--ignore-arch-flag> I<arch>:I<flag>
1406 Like B<--ignore-flag>, but only ignore flag on I<arch>.
1408 =item B<--ignore-arch-line> I<arch>:I<line>
1410 Like B<--ignore-line>, but only ignore line on I<arch>.
1412 =item B<--ignore-flag> I<flag>
1414 Don't print an error when the specific flag is missing in a compiler line.
1415 I<flag> is a string.
1417 Used to prevent false positives. This option can be specified multiple times.
1419 =item B<--ignore-line> I<regex>
1421 Ignore lines matching the given Perl regex. I<regex> is automatically anchored
1422 at the beginning and end of the line to prevent false negatives.
1424 B<NOTE>: Not the input lines are checked, but the lines which are displayed in
1425 warnings (which have line continuation resolved).
1427 Used to prevent false positives. This option can be specified multiple times.
1431 Force check for all +pie hardening flags. By default it's auto detected.
1433 =item B<-h -? --help>
1435 Print available options.
1439 Print version number and license.
1443 Auto detection for B<--pie> and B<--bindnow> only works if at least one
1444 command uses the required hardening flag (e.g. -fPIE). Then it's required for
1445 all other commands as well.
1449 Normal usage, parse a single log file.
1451 blhc path/to/log/file
1453 If there's no output, no flags are missing and the build log is fine.
1455 Parse multiple log files. The exit code is ORed over all files.
1457 blhc path/to/directory/with/log/files/*
1459 Don't treat missing C<-g> as error:
1461 blhc --ignore-flag -g path/to/log/file
1463 Don't treat missing C<-pie> on kfreebsd-amd64 as error:
1465 blhc --ignore-arch-flag kfreebsd-amd64:-pie path/to/log/file
1467 Ignore lines consisting exactly of C<./script gcc file> which would cause a
1470 blhc --ignore-line '\./script gcc file' path/to/log/file
1472 Ignore lines matching C<./script gcc file> somewhere in the line.
1474 blhc --ignore-line '.*\./script gcc file.*' path/to/log/file
1476 Use blhc with pbuilder.
1478 pbuilder path/to/package.dsc | tee path/log/file
1479 blhc path/to/file || echo flags missing
1483 The following tags are used in I<--buildd> mode. In braces the additional data
1488 =item B<I-hardening-wrapper-used>
1490 The package uses hardening-wrapper which intercepts calls to gcc and adds
1491 hardening flags. The build log doesn't contain any hardening flags and thus
1492 can't be checked by blhc.
1494 =item B<W-compiler-flags-hidden> (summary of hidden lines)
1496 Build log contains lines which hide the real compiler flags. For example:
1503 Most of the time either C<export V=1> or C<export verbose=1> in
1504 F<debian/rules> fixes builds with hidden compiler flags. Sometimes C<.SILENT>
1505 in a F<Makefile> must be removed. And as last resort the F<Makefile> must be
1506 patched to remove the C<@>s hiding the real compiler commands.
1508 =item B<W-dpkg-buildflags-missing> (summary of missing flags)
1510 CPPFLAGS, CFLAGS, CXXFLAGS, LDFLAGS missing.
1512 =item B<I-invalid-cmake-used> (version)
1514 By default CMake ignores CPPFLAGS thus missing those hardening flags. Debian
1515 patched CMake in versions 2.8.7-1 and 2.8.7-2 to respect CPPFLAGS, but this
1516 patch was rejected by upstream and later reverted in Debian. Thus those two
1517 versions show correct usage of CPPFLAGS even if the package doesn't correctly
1518 handle them (for example by passing them to CFLAGS). To prevent false
1519 negatives just blacklist those two versions.
1521 =item B<I-no-compiler-commands>
1523 No compiler commands were detected. Either the log contains none or they were
1524 not correctly detected by blhc (please report the bug in this case).
1530 The exit status is a "bit mask", each listed status is ORed when the error
1531 condition occurs to get the result.
1541 No compiler commands were found.
1545 Invalid arguments/options given to blhc.
1553 Missing hardening flags.
1557 Hardening wrapper detected, no tests performed.
1561 Invalid CMake version used. See B<I-invalid-cmake-used> under L</"BUILDD
1562 TAGS"> for a detailed explanation.
1568 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
1570 Thanks to to Bernhard R. Link E<lt>brlink@debian.orgE<gt> and Jaria Alto
1571 E<lt>jari.aalto@cante.netE<gt> for their valuable input and suggestions.
1573 =head1 LICENSE AND COPYRIGHT
1575 Copyright (C) 2012-2015 by Simon Ruderich
1577 This program is free software: you can redistribute it and/or modify
1578 it under the terms of the GNU General Public License as published by
1579 the Free Software Foundation, either version 3 of the License, or
1580 (at your option) any later version.
1582 This program is distributed in the hope that it will be useful,
1583 but WITHOUT ANY WARRANTY; without even the implied warranty of
1584 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1585 GNU General Public License for more details.
1587 You should have received a copy of the GNU General Public License
1588 along with this program. If not, see <http://www.gnu.org/licenses/>.
1592 L<hardening-check(1)>, L<dpkg-buildflags(1)>