3 # Build log hardening check, checks build logs for missing hardening flags.
5 # Copyright (C) 2012 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.03';
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: (.+?) \[(.+?)\]$/;
52 # List of source file extensions which require preprocessing.
53 my @source_preprocess_compile_cpp = (
55 qw( cc cp cxx cpp CPP c++ C ),
59 my @source_preprocess_compile = (
65 @source_preprocess_compile_cpp,
67 qw( F FOR fpp FPP FTN F90 F95 F03 F08 ),
69 my @source_preprocess_no_compile = (
73 my @source_preprocess = (
74 @source_preprocess_compile,
75 @source_preprocess_no_compile,
77 # List of source file extensions which don't require preprocessing.
78 my @source_no_preprocess_compile_cpp = (
84 my @source_no_preprocess_compile = (
88 @source_no_preprocess_compile_cpp,
92 qw( f for ftn f90 f95 f03 f08 ),
94 my @source_no_preprocess_no_compile = (
98 my @source_no_preprocess = (
99 @source_no_preprocess_compile,
100 @source_no_preprocess_no_compile,
102 # List of header file extensions which require preprocessing.
103 my @header_preprocess = (
104 # C, C++, Objective-C, Objective-C++
107 qw( hh H hp hxx hpp HPP h++ tcc ),
111 # Normal object files.
113 # Libtool object files.
115 # Dynamic libraries. bzip2 uses .sho.
121 # Hashes for fast extensions lookup to check if a file falls in one of these
123 my %extensions_no_preprocess = map { $_ => 1 } (
124 # There's no @header_no_preprocess.
125 @source_no_preprocess,
127 my %extensions_preprocess = map { $_ => 1 } (
131 my %extensions_compile_link = map { $_ => 1 } (
133 @source_no_preprocess,
135 my %extensions_compile = map { $_ => 1 } (
136 @source_preprocess_compile,
137 @source_no_preprocess_compile,
139 my %extensions_no_compile = map { $_ => 1 } (
140 @source_preprocess_no_compile,
141 @source_no_preprocess_no_compile,
143 my %extensions_compile_cpp = map { $_ => 1 } (
144 @source_preprocess_compile_cpp,
145 @source_no_preprocess_compile_cpp,
147 my %extensions_object = map { $_ => 1 } (
150 my %extension = map { $_ => 1 } (
151 @source_no_preprocess,
157 # Regexp to match file extensions.
158 my $file_extension_regex = qr/
160 \S+ # Filename without extension.
162 ([^\/\\.,;:\s]+)# File extension.
163 (?=\s|\\) # At end of word. Can't use \b because some files have non
164 # word characters at the end and because \b matches double
165 # extensions (like .cpp.o). Works always as all lines are
166 # terminated with "\n".
169 # Expected (hardening) flags. All flags are used as regexps.
174 my @def_cflags_format = (
176 '-Werror=format-security', # implies -Wformat-security
178 my @def_cflags_fortify = (
179 # fortify needs at least -O1, but -O2 is recommended anyway
181 my @def_cflags_stack = (
183 '--param=ssp-buffer-size=4',
185 my @def_cflags_pie = (
191 # @def_cxxflags_* is the same as @def_cflags_*.
192 my @def_cppflags = ();
193 my @def_cppflags_fortify = (
194 '-D_FORTIFY_SOURCE=2', # must be first, see cppflags_fortify_broken()
195 # If you add another flag fix hack below (search for "Hack to fix").
197 my @def_cppflags_fortify_bad = (
198 # These flags may overwrite -D_FORTIFY_SOURCE=2.
200 '-D_FORTIFY_SOURCE=0',
201 '-D_FORTIFY_SOURCE=1',
203 my @def_ldflags = ();
204 my @def_ldflags_relro = (
207 my @def_ldflags_bindnow = (
210 my @def_ldflags_pie = (
214 my @def_ldflags_pic = (
219 # References to all flags checked by the flag checker.
223 \@def_cflags_fortify,
228 \@def_cppflags_fortify,
231 \@def_ldflags_bindnow,
234 # References to all used flags.
235 my @flag_refs_all = (
237 \@def_cppflags_fortify_bad,
240 # Renaming rules for the output so the regex parts are not visible. Also
241 # stores string values of flag regexps above, see compile_flag_regexp().
243 '-O(?:2|3)' => '-O2',
244 '-Wl,(?:-z,)?relro' => '-Wl,-z,relro',
245 '-Wl,(?:-z,)?now' => '-Wl,-z,now',
249 no_compiler_commands => 1 << 0,
250 # used by POD::Usage => 1 << 1,
251 non_verbose_build => 1 << 2,
252 flags_missing => 1 << 3,
253 hardening_wrapper => 1 << 4,
254 invalid_cmake => 1 << 5,
258 no_compiler_commands => 'I-no-compiler-commands',
259 non_verbose_build => 'W-compiler-flags-hidden',
260 flags_missing => 'W-dpkg-buildflags-missing',
261 hardening_wrapper => 'I-hardening-wrapper-used',
262 invalid_cmake => 'I-invalid-cmake-used',
265 # Statistics of missing flags and non-verbose build commands. Used for
269 preprocess_missing => 0,
271 compile_missing => 0,
273 compile_cpp_missing => 0,
277 commands_nonverbose => 0,
280 # Use colored (ANSI) output?
287 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
289 # Get string value of qr//-escaped regexps and if requested rename them.
290 my @missing_flags = map {
291 $flag_renames_ref->{$_}
292 } @{$missing_flags_ref};
294 my $flags = join ' ', @missing_flags;
295 printf '%s (%s)%s %s',
296 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
299 sub error_non_verbose_build {
303 error_color('NONVERBOSE BUILD', 'red'),
304 error_color(':', 'yellow'),
307 sub error_invalid_cmake {
311 error_color('INVALID CMAKE', 'red'),
312 error_color(':', 'yellow'),
315 sub error_hardening_wrapper {
317 error_color('HARDENING WRAPPER', 'red'),
318 error_color(':', 'yellow'),
319 'no checks possible, aborting';
322 my ($message, $color) = @_;
325 return Term::ANSIColor::colored($message, $color);
332 my ($line, @flags) = @_;
334 foreach my $flag (@flags) {
335 return 1 if $line =~ /$flag/;
341 my ($line, $missing_flags_ref, @flags) = @_;
343 my @missing_flags = ();
344 foreach my $flag (@flags) {
345 if (not $line =~ /$flag/) {
346 push @missing_flags, $flag;
350 return 1 if scalar @missing_flags == 0;
352 @{$missing_flags_ref} = @missing_flags;
356 sub cppflags_fortify_broken {
357 my ($line, $missing_flags) = @_;
359 # This doesn't take the position into account, but is a simple solution.
360 # And if the build system tries to force -D_FORTIFY_SOURCE=0/1, something
363 if (any_flags_used($line, @def_cppflags_fortify_bad)) {
364 # $def_cppflags_fortify[0] must be -D_FORTIFY_SOURCE=2!
365 push @{$missing_flags}, $def_cppflags_fortify[0];
372 # Modifies $missing_flags_ref array.
373 sub pic_pie_conflict {
374 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
376 return 0 if not $pie;
377 return 0 if not any_flags_used($line, @def_ldflags_pic);
379 my %flags = map { $_ => 1 } @flags_pie;
381 # Remove all PIE flags from @missing_flags as they are not required with
384 not exists $flags{$_}
385 } @{$missing_flags_ref};
386 @{$missing_flags_ref} = @result;
388 # We got a conflict when no flags are left, thus only PIE flags were
389 # missing. If other flags were missing abort because the conflict is not
391 return scalar @result == 0;
394 sub is_non_verbose_build {
395 my ($line, $next_line, $skip_ref) = @_;
397 if (not (index($line, 'checking if you want to see long compiling messages... no') == 0
398 or $line =~ /^\s*\[?(?:CC|CCLD|C\+\+|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
399 or $line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/
400 or $line =~ /^\s*[Bb]uilding (?:program|shared library)\s+(.+?)$/
401 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
407 # C++ compiler setting.
408 return 0 if $line =~ /^\s*C\+\+.+?:\s+(?:yes|no)\s*$/;
409 # "Compiling" with no file name.
410 if ($line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/) {
411 # $file_extension_regex may need spaces around the filename.
412 return 0 if not " $1 " =~ /$file_extension_regex/o;
417 # On the first pass we only check if this line is verbose or not.
418 return 1 if not defined $next_line;
420 # Second pass, we have access to the next line.
423 # CMake and other build systems print the non-verbose messages also when
424 # building verbose. If a compiler and the file name occurs in the next
425 # line, treat it as verbose build.
427 # Get filename, we can't use the complete path as only parts of it are
428 # used in the real compiler command.
429 $file =~ m{/([^/\s]+)$};
432 if (index($next_line, $file) != -1 and $next_line =~ /$cc_regex/o) {
433 # We still have to skip the current line as it doesn't contain any
444 my ($flag_refs_ref, $flag_renames_ref, @flags) = @_;
446 my %removes = map { $_ => 1 } @flags;
447 foreach my $flags (@{$flag_refs_ref}) {
449 # Flag found as string.
450 not exists $removes{$_}
451 # Flag found as string representation of regexp.
452 and (not defined $flag_renames_ref->{$_}
453 or not exists $removes{$flag_renames_ref->{$_}})
458 sub compile_flag_regexp {
459 my ($flag_renames_ref, @flags) = @_;
462 foreach my $flag (@flags) {
463 # Store flag name in replacement string for correct flags in messages
464 # with qr//ed flag regexps.
465 $flag_renames_ref->{qr/\s$flag(?:\s|\\)/}
466 = (exists $flag_renames_ref->{$flag})
467 ? $flag_renames_ref->{$flag}
470 # Compile flag regexp for faster execution.
471 push @result, qr/\s$flag(?:\s|\\)/;
476 sub extension_found {
477 my ($extensions_ref, @extensions) = @_;
480 foreach my $extension (@extensions) {
481 if (exists $extensions_ref->{$extension}) {
492 # Parse command line arguments.
494 my $option_version = 0;
496 my $option_bindnow = 0;
497 my @option_ignore_arch = ();
498 my @option_ignore_flag = ();
499 my @option_ignore_arch_flag = ();
500 my @option_ignore_line = ();
501 my @option_ignore_arch_line = ();
503 my $option_arch = undef;
504 my $option_buildd = 0;
506 if (not Getopt::Long::GetOptions(
507 'help|h|?' => \$option_help,
508 'version' => \$option_version,
510 'pie' => \$option_pie,
511 'bindnow' => \$option_bindnow,
512 'all' => \$option_all,
514 'ignore-arch=s' => \@option_ignore_arch,
515 'ignore-flag=s' => \@option_ignore_flag,
516 'ignore-arch-flag=s' => \@option_ignore_arch_flag,
517 'ignore-line=s' => \@option_ignore_line,
518 'ignore-arch-line=s' => \@option_ignore_arch_line,
520 'color' => \$option_color,
521 'arch=s' => \$option_arch,
522 'buildd' => \$option_buildd,
525 Pod::Usage::pod2usage(2);
529 Pod::Usage::pod2usage(1);
531 if ($option_version) {
532 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
534 This program is free software: you can redistribute it and/or modify
535 it under the terms of the GNU General Public License as published by
536 the Free Software Foundation, either version 3 of the License, or
537 (at your option) any later version.
539 This program is distributed in the hope that it will be useful,
540 but WITHOUT ANY WARRANTY; without even the implied warranty of
541 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
542 GNU General Public License for more details.
544 You should have received a copy of the GNU General Public License
545 along with this program. If not, see <http://www.gnu.org/licenses/>.
551 if (scalar @ARGV == 0) {
553 Pod::Usage::pod2usage(2);
556 # Don't load Term::ANSIColor in buildd mode because Term::ANSIColor is not
557 # installed on Debian's buildds.
558 if (not $option_buildd) {
559 require Term::ANSIColor;
567 # Precompiled ignores for faster lookup.
568 my %option_ignore_arch_flag = ();
569 my %option_ignore_arch_line = ();
571 # Strip flags which should be ignored.
572 if (scalar @option_ignore_flag > 0) {
573 remove_flags(\@flag_refs, \%flag_renames, @option_ignore_flag);
575 # Same for arch specific ignore flags, but only prepare here.
576 if (scalar @option_ignore_arch_flag > 0) {
577 foreach my $ignore (@option_ignore_arch_flag) {
578 my ($ignore_arch, $ignore_flag) = split ':', $ignore, 2;
580 if (not $ignore_arch or not $ignore_flag) {
581 printf STDERR 'Value "%s" invalid for option ignore-arch-flag '
582 . '("arch:flag" expected)' . "\n", $ignore;
584 Pod::Usage::pod2usage(2);
587 push @{$option_ignore_arch_flag{$ignore_arch}}, $ignore_flag;
591 # Precompile all flag regexps. any_flags_used(), all_flags_used() get a lot
593 foreach my $flags (@flag_refs_all) {
594 @{$flags} = compile_flag_regexp(\%flag_renames, @{$flags});
597 # Precompile ignore line regexps, also anchor at beginning and end of line.
598 foreach my $ignore (@option_ignore_line) {
599 $ignore = qr/^$ignore$/;
601 # Same for arch specific ignore lines.
602 if (scalar @option_ignore_arch_line > 0) {
603 foreach my $ignore (@option_ignore_arch_line) {
604 my ($ignore_arch, $ignore_line) = split ':', $ignore, 2;
606 if (not $ignore_arch or not $ignore_line) {
607 printf STDERR 'Value "%s" invalid for option ignore-arch-line '
608 . '("arch:line" expected)' . "\n", $ignore;
610 Pod::Usage::pod2usage(2);
613 push @{$option_ignore_arch_line{$ignore_arch}}, qr/^$ignore_line$/;
621 foreach my $file (@ARGV) {
622 print "checking '$file'...\n" if scalar @ARGV > 1;
624 -f $file or die "No such file: $file";
626 open my $fh, '<', $file or die $!;
628 # Architecture of this file.
629 my $arch = $option_arch;
631 # Hardening options. Not all architectures support all hardening options.
632 my $harden_format = 1;
633 my $harden_fortify = 1;
634 my $harden_stack = 1;
635 my $harden_relro = 1;
636 my $harden_bindnow = $option_bindnow; # defaults to 0
637 my $harden_pie = $option_pie; # defaults to 0
639 while (my $line = <$fh>) {
640 # Detect architecture automatically unless overridden. For buildd logs
641 # only, doesn't use the dpkg-buildpackage header. Necessary to ignore
642 # build logs which aren't built (wrong architecture, build error,
645 and $line =~ /^Architecture: (.+)$/) {
649 # dpkg-buildflags only provides hardening flags since 1.16.1, don't
650 # check for hardening flags in buildd mode if an older dpkg-dev is
651 # used. Default flags (-g -O2) are still checked.
653 # Packages which were built before 1.16.1 but used their own hardening
654 # flags are not checked.
656 and index($line, 'Toolchain package versions: ') == 0) {
657 require Dpkg::Version;
658 if (not $line =~ /\bdpkg-dev_(\S+)/
659 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
669 # The following two versions of CMake in Debian obeyed CPPFLAGS, but
670 # this was later dropped because upstream rejected the patch. Thus
671 # build logs with these versions will have fortify hardening flags
672 # enabled, even though they may be not correctly set and are missing
673 # when build with later CMake versions. Thanks to Aron Xu for letting
675 if (index($line, 'Package versions: ') == 0
676 and $line =~ /\bcmake_(\S+)/
677 and ($1 eq '2.8.7-1' or $1 eq '2.8.7-2')) {
678 if (not $option_buildd) {
679 error_invalid_cmake($1);
680 $exit |= $exit_code{invalid_cmake};
682 print "$buildd_tag{invalid_cmake}|$1|\n";
686 # If hardening wrapper is used (wraps calls to gcc and adds hardening
687 # flags automatically) we can't perform any checks, abort.
688 if (index($line, 'Build-Depends: ') == 0
689 and $line =~ /\bhardening-wrapper\b/) {
690 if (not $option_buildd) {
691 error_hardening_wrapper();
692 $exit |= $exit_code{hardening_wrapper};
694 print "$buildd_tag{hardening_wrapper}||\n";
699 # We skip over unimportant lines at the beginning of the log to
700 # prevent false positives.
701 last if index($line, 'dpkg-buildpackage: ') == 0;
704 # Input lines, contain only the lines with compiler commands.
707 my $continuation = 0;
708 my $complete_line = undef;
709 while (my $line = <$fh>) {
710 # And stop at the end of the build log. Package details (reported by
711 # the buildd logs) are not important for us. This also prevents false
713 last if $line =~ /^Build finished at \d{8}-\d{4}$/;
715 # Detect architecture automatically unless overridden.
717 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
721 # Ignore compiler warnings for now.
722 next if $line =~ /$warning_regex/o;
724 if (not $option_buildd and index($line, "\033") != -1) { # \033 = esc
725 # Remove all ANSI color sequences which are sometimes used in
726 # non-verbose builds.
727 $line = Term::ANSIColor::colorstrip($line);
728 # Also strip '\0xf' (delete previous character), used by Elinks'
731 # And "ESC(B" which seems to be used on armhf and hurd (not sure
733 $line =~ s/\033\(B//g;
736 # Check if this line indicates a non verbose build.
737 my $non_verbose = is_non_verbose_build($line);
739 # One line may contain multiple commands (";"). Treat each one as
740 # single line. parse_line() is slow, only use it when necessary.
741 my @line = (index($line, ';') == -1)
744 # Ensure newline at the line end - necessary for
745 # correct parsing later.
748 } Text::ParseWords::parse_line(';', 1, $line);
749 foreach my $line (@line) {
753 # Join lines, but leave the "\" in place so it's clear where
754 # the original line break was.
755 chomp $complete_line;
756 $complete_line .= ' ' . $line;
758 # Line continuation, line ends with "\".
759 if ($line =~ /\\$/) {
761 # Start line continuation.
762 if (not defined $complete_line) {
763 $complete_line = $line;
768 # Use the complete line if a line continuation occurred.
769 if (defined $complete_line) {
770 $line = $complete_line;
771 $complete_line = undef;
774 # Ignore lines with no compiler commands.
775 next if not $non_verbose
776 and not $line =~ /$cc_regex_normal/o;
777 # Ignore lines with no filenames with extensions. May miss some
778 # non-verbose builds (e.g. "gcc -o test" [sic!]), but shouldn't be
779 # a problem as the log will most likely contain other non-verbose
780 # commands which are detected.
781 next if not $non_verbose
782 and not $line =~ /$file_extension_regex/o;
784 # Ignore false positives.
786 # `./configure` output.
787 next if not $non_verbose
788 and $line =~ /^(?:checking|[Cc]onfigure:) /;
789 next if $line =~ /^\s*(?:Host\s+)?(?:C(?:\+\+)?\s+)?
790 [Cc]ompiler[\s.]*:?\s+
792 next if $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex_full\s*$/o;
793 # `moc-qt4`, contains '-I/usr/share/qt4/mkspecs/linux-g++' (or
794 # similar for other architectures) which gets recognized as a
795 # compiler line. Ignore it.
796 next if $line =~ m{^/usr/bin/moc-qt4
798 -I/usr/share/qt4/mkspecs/[a-z]+-g\++(?:-64)?
800 # Ignore false positives when the line contains only CC=gcc but no
802 if ($line =~ /(.*)CC=$cc_regex_full(.*)/o) {
805 next if not $before =~ /$cc_regex_normal/o
806 and not $after =~ /$cc_regex_normal/o;
809 # Check if additional hardening options were used. Used to ensure
810 # they are used for the complete build.
811 $harden_pie = 1 if any_flags_used($line, @def_cflags_pie,
813 $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);
821 # Ignore arch if requested.
822 if (scalar @option_ignore_arch > 0 and $arch) {
823 foreach my $ignore (@option_ignore_arch) {
824 if ($arch eq $ignore) {
825 print "ignoring architecture '$arch'\n";
831 if (scalar @input == 0) {
832 if (not $option_buildd) {
833 print "No compiler commands!\n";
834 $exit |= $exit_code{no_compiler_commands};
836 print "$buildd_tag{no_compiler_commands}||\n";
841 if ($option_buildd) {
842 $statistics{commands} += scalar @input;
845 # Option or auto detected.
847 # The following was partially copied from dpkg-dev 1.16.4.3
848 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
849 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
850 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
851 # later. Keep it in sync.
854 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($arch);
856 # Disable unsupported hardening options.
857 if ($cpu =~ /^(?:ia64|alpha|mips|mipsel|hppa)$/ or $arch eq 'arm') {
860 if ($cpu =~ /^(?:ia64|hppa|avr32)$/) {
867 my @cflags = @def_cflags;
868 my @cxxflags = @def_cxxflags;
869 my @cppflags = @def_cppflags;
870 my @ldflags = @def_ldflags;
871 # Check the specified hardening options, same order as dpkg-buildflags.
873 @cflags = (@cflags, @def_cflags_pie);
874 @cxxflags = (@cxxflags, @def_cflags_pie);
875 @ldflags = (@ldflags, @def_ldflags_pie);
878 @cflags = (@cflags, @def_cflags_stack);
879 @cxxflags = (@cxxflags, @def_cflags_stack);
881 if ($harden_fortify) {
882 @cflags = (@cflags, @def_cflags_fortify);
883 @cxxflags = (@cxxflags, @def_cflags_fortify);
884 @cppflags = (@cppflags, @def_cppflags_fortify);
886 if ($harden_format) {
887 @cflags = (@cflags, @def_cflags_format);
888 @cxxflags = (@cxxflags, @def_cflags_format);
891 @ldflags = (@ldflags, @def_ldflags_relro);
893 if ($harden_bindnow) {
894 @ldflags = (@ldflags, @def_ldflags_bindnow);
897 # Hack to fix cppflags_fortify_broken() if --ignore-flag
898 # -D_FORTIFY_SOURCE=2 is used to ignore missing fortification. Only works
899 # as long as @def_cppflags_fortify contains only one variable.
900 if (scalar @def_cppflags_fortify == 0) {
904 # Ignore flags for this arch if requested.
905 if ($arch and exists $option_ignore_arch_flag{$arch}) {
906 my @flag_refs = (\@cflags, \@cxxflags, \@cppflags, \@ldflags);
908 remove_flags(\@flag_refs,
910 @{$option_ignore_arch_flag{$arch}});
913 my @ignore_line = @option_ignore_line;
914 # Ignore lines for this arch if requested.
915 if ($arch and exists $option_ignore_arch_line{$arch}) {
916 @ignore_line = (@ignore_line, @{$option_ignore_arch_line{$arch}});
920 for (my $i = 0; $i < scalar @input; $i++) {
921 my $line = $input[$i];
923 # Ignore line if requested.
924 foreach my $ignore (@ignore_line) {
925 next LINE if $line =~ /$ignore/;
929 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
930 if (not $option_buildd) {
931 error_non_verbose_build($line);
932 $exit |= $exit_code{non_verbose_build};
934 $statistics{commands_nonverbose}++;
938 # Even if it's a verbose build, we might have to skip this line.
941 # Remove everything until and including the compiler command. Makes
942 # checks easier and faster.
943 $line =~ s/^.*?$cc_regex//o;
944 # "([...] test.c)" is not detected as 'test.c' - fix this by removing
945 # the brace and similar characters at the line end.
946 $line =~ s/['")]+$//;
948 # Skip unnecessary tests when only preprocessing.
949 my $flag_preprocess = 0;
956 # Preprocess, compile, assemble.
957 if ($line =~ /\s(-E|-S|-c)\b/) {
959 $flag_preprocess = 1 if $1 eq '-E';
960 $compile = 1 if $1 eq '-S' or $1 eq '-c';
961 # Dependency generation for Makefiles. The other flags (-MF -MG -MP
962 # -MT -MQ) are always used with -M/-MM.
963 } elsif ($line =~ /\s(?:-M|-MM)\b/) {
965 # Otherwise assume we are linking.
970 # -MD/-MMD also cause dependency generation, but they don't imply -E!
971 if ($line =~ /\s(?:-MD|-MMD)\b/) {
973 $flag_preprocess = 0;
976 # Dependency generation for Makefiles, no preprocessing or other flags
980 # Get all file extensions on this line.
981 my @extensions = $line =~ /$file_extension_regex/go;
982 # Ignore all unknown extensions to speedup the search below.
983 @extensions = grep { exists $extension{$_} } @extensions;
985 # These file types don't require preprocessing.
986 if (extension_found(\%extensions_no_preprocess, @extensions)) {
989 # These file types require preprocessing.
990 if (extension_found(\%extensions_preprocess, @extensions)) {
994 if (not $flag_preprocess) {
995 # If there are source files then it's compiling/linking in one
996 # step and we must check both. We only check for source files
997 # here, because header files cause too many false positives.
998 if (extension_found(\%extensions_compile_link, @extensions)) {
999 # Assembly files don't need CFLAGS.
1000 if (not extension_found(\%extensions_compile, @extensions)
1001 and extension_found(\%extensions_no_compile, @extensions)) {
1003 # But the rest does.
1007 # No compilable extensions found, either linking or compiling
1010 # If there are also no object files we are just compiling headers
1011 # (.h -> .h.gch). Don't check for linker flags in this case. Due
1012 # to our liberal checks for compiler lines, this also reduces the
1013 # number of false positives considerably.
1015 and not extension_found(\%extensions_object, @extensions)) {
1020 # Assume CXXFLAGS are required when a C++ file is specified in the
1022 my $compile_cpp = 0;
1024 and extension_found(\%extensions_compile_cpp, @extensions)) {
1029 if ($option_buildd) {
1030 $statistics{preprocess}++ if $preprocess;
1031 $statistics{compile}++ if $compile;
1032 $statistics{compile_cpp}++ if $compile_cpp;
1033 $statistics{link}++ if $link;
1036 # Check hardening flags.
1038 if ($compile and not all_flags_used($line, \@missing, @cflags)
1039 # Libraries linked with -fPIC don't have to (and can't) be
1040 # linked with -fPIE as well. It's no error if only PIE flags
1042 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1043 # Assume dpkg-buildflags returns the correct flags.
1044 and index($line, '`dpkg-buildflags --get CFLAGS`') == -1) {
1045 if (not $option_buildd) {
1046 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1047 $exit |= $exit_code{flags_missing};
1049 $statistics{compile_missing}++;
1051 } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
1052 # Libraries linked with -fPIC don't have to (and can't) be
1053 # linked with -fPIE as well. It's no error if only PIE flags
1055 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1056 # Assume dpkg-buildflags returns the correct flags.
1057 and index($line, '`dpkg-buildflags --get CXXFLAGS`') == -1) {
1058 if (not $option_buildd) {
1059 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1060 $exit |= $exit_code{flags_missing};
1062 $statistics{compile_cpp_missing}++;
1066 and (not all_flags_used($line, \@missing, @cppflags)
1067 # The fortify flag might be overwritten, detect that.
1069 and cppflags_fortify_broken($line, \@missing)))
1070 # Assume dpkg-buildflags returns the correct flags.
1071 and index($line, '`dpkg-buildflags --get CPPFLAGS`') == -1) {
1072 if (not $option_buildd) {
1073 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1074 $exit |= $exit_code{flags_missing};
1076 $statistics{preprocess_missing}++;
1079 if ($link and not all_flags_used($line, \@missing, @ldflags)
1080 # Same here, -fPIC conflicts with -fPIE.
1081 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
1082 # Assume dpkg-buildflags returns the correct flags.
1083 and index($line, '`dpkg-buildflags --get LDFLAGS`') == -1) {
1084 if (not $option_buildd) {
1085 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1086 $exit |= $exit_code{flags_missing};
1088 $statistics{link_missing}++;
1094 # Print statistics for buildd mode, only output in this mode.
1095 if ($option_buildd) {
1098 if ($statistics{preprocess_missing}) {
1099 push @warning, sprintf 'CPPFLAGS %d (of %d)',
1100 $statistics{preprocess_missing},
1101 $statistics{preprocess};
1103 if ($statistics{compile_missing}) {
1104 push @warning, sprintf 'CFLAGS %d (of %d)',
1105 $statistics{compile_missing},
1106 $statistics{compile};
1108 if ($statistics{compile_cpp_missing}) {
1109 push @warning, sprintf 'CXXFLAGS %d (of %d)',
1110 $statistics{compile_cpp_missing},
1111 $statistics{compile_cpp};
1113 if ($statistics{link_missing}) {
1114 push @warning, sprintf 'LDFLAGS %d (of %d)',
1115 $statistics{link_missing},
1118 if (scalar @warning) {
1119 local $" = ', '; # array join string
1120 print "$buildd_tag{flags_missing}|@warning missing|\n";
1123 if ($statistics{commands_nonverbose}) {
1124 printf "$buildd_tag{non_verbose_build}|%d (of %d) hidden|\n",
1125 $statistics{commands_nonverbose},
1126 $statistics{commands},
1138 blhc - build log hardening check, checks build logs for missing hardening flags
1142 B<blhc> [I<options>] I<< <dpkg-buildpackage build log file>.. >>
1146 blhc is a small tool which checks build logs for missing hardening flags. It's
1147 licensed under the GPL 3 or later.
1149 It's designed to check build logs generated by Debian's dpkg-buildpackage (or
1150 tools using dpkg-buildpackage like pbuilder or the official buildd build logs)
1151 to help maintainers detect missing hardening flags in their packages.
1153 Only gcc is detected as compiler at the moment. If other compilers support
1154 hardening flags as well, please report them.
1156 If there's no output, no flags are missing and the build log is fine.
1164 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
1167 =item B<--arch> I<architecture>
1169 Set the specific architecture (e.g. amd64, armel, etc.), automatically
1170 disables hardening flags not available on this architecture. Is detected
1171 automatically if dpkg-buildpackage is used.
1175 Force check for all +bindnow hardening flags. By default it's auto detected.
1179 Special mode for buildds when automatically parsing log files. The following
1180 changes are in effect:
1186 Print tags instead of normal warnings, see L</"BUILDD TAGS"> for a list of
1191 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
1196 Don't require Term::ANSIColor.
1200 Return exit code 0, unless there was a error (-I, -W messages don't count as
1207 Use colored (ANSI) output for warning messages.
1209 =item B<--ignore-arch> I<arch>
1211 Ignore build logs from architectures matching I<arch>. I<arch> is a string.
1213 Used to prevent false positives. This option can be specified multiple times.
1215 =item B<--ignore-arch-flag> I<arch>:I<flag>
1217 Like B<--ignore-flag>, but only ignore flag on I<arch>.
1219 =item B<--ignore-arch-line> I<arch>:I<line>
1221 Like B<--ignore-line>, but only ignore line on I<arch>.
1223 =item B<--ignore-flag> I<flag>
1225 Don't print an error when the specific flag is missing in a compiler line.
1226 I<flag> is a string.
1228 Used to prevent false positives. This option can be specified multiple times.
1230 =item B<--ignore-line> I<regex>
1232 Ignore lines matching the given Perl regex. I<regex> is automatically anchored
1233 at the beginning and end of the line to prevent false negatives.
1235 B<NOTE>: Not the input lines are checked, but the lines which are displayed in
1236 warnings (which have line continuation resolved).
1238 Used to prevent false positives. This option can be specified multiple times.
1242 Force check for all +pie hardening flags. By default it's auto detected.
1244 =item B<-h -? --help>
1246 Print available options.
1250 Print version number and license.
1254 Auto detection for B<--pie> and B<--bindnow> only works if at least one
1255 command uses the required hardening flag (e.g. -fPIE). Then it's required for
1256 all other commands as well.
1260 Normal usage, parse a single log file.
1262 blhc path/to/log/file
1264 If there's no output, no flags are missing and the build log is fine.
1266 Parse multiple log files. The exit code is ORed over all files.
1268 blhc path/to/directory/with/log/files/*
1270 Don't treat missing C<-g> as error:
1272 blhc --ignore-flag -g path/to/log/file
1274 Don't treat missing C<-pie> on kfreebsd-amd64 as error:
1276 blhc --ignore-arch-flag kfreebsd-amd64:-pie path/to/log/file
1278 Ignore lines consisting exactly of C<./script gcc file> which would cause a
1281 blhc --ignore-line '\./script gcc file' path/to/log/file
1283 Ignore lines matching C<./script gcc file> somewhere in the line.
1285 blhc --ignore-line '.*\./script gcc file.*' path/to/log/file
1287 Use blhc with pbuilder.
1289 pbuilder path/to/package.dsc | tee path/log/file
1290 blhc path/to/file || echo flags missing
1294 The following tags are used in I<--buildd> mode. In braces the additional data
1299 =item B<I-hardening-wrapper-used>
1301 The package uses hardening-wrapper which intercepts calls to gcc and adds
1302 hardening flags. The build log doesn't contain any hardening flags and thus
1303 can't be checked by blhc.
1305 =item B<W-compiler-flags-hidden> (summary of hidden lines)
1307 Build log contains lines which hide the real compiler flags. For example:
1314 Most of the time either C<export V=1> or C<export verbose=1> in
1315 F<debian/rules> fixes builds with hidden compiler flags. Sometimes C<.SILENT>
1316 in a F<Makefile> must be removed. And as last resort the F<Makefile> must be
1317 patched to remove the C<@>s hiding the real compiler commands.
1319 =item B<W-dpkg-buildflags-missing> (summary of missing flags)
1321 CPPFLAGS, CFLAGS, CXXFLAGS, LDFLAGS missing.
1323 =item B<I-invalid-cmake-used> (version)
1325 By default CMake ignores CPPFLAGS thus missing those hardening flags. Debian
1326 patched CMake in versions 2.8.7-1 and 2.8.7-2 to respect CPPFLAGS, but this
1327 patch was rejected by upstream and later reverted in Debian. Thus those two
1328 versions show correct usage of CPPFLAGS even if the package doesn't correctly
1329 handle them (for example by passing them to CFLAGS). To prevent false
1330 negatives just blacklist those two versions.
1332 =item B<I-no-compiler-commands>
1334 No compiler commands were detected. Either the log contains none or they were
1335 not correctly detected by blhc (please report the bug in this case).
1341 The exit status is a "bit mask", each listed status is ORed when the error
1342 condition occurs to get the result.
1352 No compiler commands were found.
1356 Invalid arguments/options given to blhc.
1364 Missing hardening flags.
1368 Hardening wrapper detected, no tests performed.
1372 Invalid CMake version used. See B<I-invalid-cmake-used> under L</"BUILDD
1373 TAGS"> for a detailed explanation.
1379 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
1381 Thanks to to Bernhard R. Link E<lt>brlink@debian.orgE<gt> and Jaria Alto
1382 E<lt>jari.aalto@cante.netE<gt> for their valuable input and suggestions.
1384 =head1 COPYRIGHT AND LICENSE
1386 Copyright (C) 2012 by Simon Ruderich
1388 This program is free software: you can redistribute it and/or modify
1389 it under the terms of the GNU General Public License as published by
1390 the Free Software Foundation, either version 3 of the License, or
1391 (at your option) any later version.
1393 This program is distributed in the hope that it will be useful,
1394 but WITHOUT ANY WARRANTY; without even the implied warranty of
1395 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1396 GNU General Public License for more details.
1398 You should have received a copy of the GNU General Public License
1399 along with this program. If not, see <http://www.gnu.org/licenses/>.
1403 L<hardening-check(1)>, L<dpkg-buildflags(1)>