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 catch (GCC) compiler warnings.
46 my $warning_regex = qr/^(.+?):(\d+):\d+: warning: (.+?) \[(.+?)\]$/;
48 # List of source file extensions which require preprocessing.
49 my @source_preprocess_compile_cpp = (
51 qw( cc cp cxx cpp CPP c++ C ),
55 my @source_preprocess_compile = (
61 @source_preprocess_compile_cpp,
63 qw( F FOR fpp FPP FTN F90 F95 F03 F08 ),
65 my @source_preprocess_no_compile = (
69 my @source_preprocess = (
70 @source_preprocess_compile,
71 @source_preprocess_no_compile,
73 # List of source file extensions which don't require preprocessing.
74 my @source_no_preprocess_compile_cpp = (
80 my @source_no_preprocess_compile = (
84 @source_no_preprocess_compile_cpp,
88 qw( f for ftn f90 f95 f03 f08 ),
90 my @source_no_preprocess_no_compile = (
94 my @source_no_preprocess = (
95 @source_no_preprocess_compile,
96 @source_no_preprocess_no_compile,
98 # List of header file extensions which require preprocessing.
99 my @header_preprocess = (
100 # C, C++, Objective-C, Objective-C++
103 qw( hh H hp hxx hpp HPP h++ tcc ),
107 # Normal object files.
109 # Libtool object files.
111 # Dynamic libraries. bzip2 uses .sho.
117 # Hashes for fast extensions lookup to check if a file falls in one of these
119 my %extensions_no_preprocess = map { $_ => 1 } (
120 # There's no @header_no_preprocess.
121 @source_no_preprocess,
123 my %extensions_preprocess = map { $_ => 1 } (
127 my %extensions_compile_link = map { $_ => 1 } (
129 @source_no_preprocess,
131 my %extensions_compile = map { $_ => 1 } (
132 @source_preprocess_compile,
133 @source_no_preprocess_compile,
135 my %extensions_no_compile = map { $_ => 1 } (
136 @source_preprocess_no_compile,
137 @source_no_preprocess_no_compile,
139 my %extensions_compile_cpp = map { $_ => 1 } (
140 @source_preprocess_compile_cpp,
141 @source_no_preprocess_compile_cpp,
143 my %extensions_object = map { $_ => 1 } (
146 my %extension = map { $_ => 1 } (
147 @source_no_preprocess,
153 # Regexp to match file extensions.
154 my $file_extension_regex = qr/
156 \S+ # Filename without extension.
158 ([^\/\\.,;:\s]+)# File extension.
159 (?=\s|\\) # At end of word. Can't use \b because some files have non
160 # word characters at the end and because \b matches double
161 # extensions (like .cpp.o). Works always as all lines are
162 # terminated with "\n".
165 # Expected (hardening) flags. All flags are used as regexps.
170 my @def_cflags_format = (
172 '-Werror=format-security', # implies -Wformat-security
174 my @def_cflags_fortify = (
175 # fortify needs at least -O1, but -O2 is recommended anyway
177 my @def_cflags_stack = (
179 '--param=ssp-buffer-size=4',
181 my @def_cflags_pie = (
187 # @def_cxxflags_* is the same as @def_cflags_*.
188 my @def_cppflags = ();
189 my @def_cppflags_fortify = (
190 '-D_FORTIFY_SOURCE=2', # must be first, see cppflags_fortify_broken()
191 # If you add another flag fix hack below (search for "Hack to fix").
193 my @def_cppflags_fortify_bad = (
194 # These flags may overwrite -D_FORTIFY_SOURCE=2.
196 '-D_FORTIFY_SOURCE=0',
197 '-D_FORTIFY_SOURCE=1',
199 my @def_ldflags = ();
200 my @def_ldflags_relro = (
203 my @def_ldflags_bindnow = (
206 my @def_ldflags_pie = (
210 my @def_ldflags_pic = (
215 # References to all flags checked by the flag checker.
219 \@def_cflags_fortify,
224 \@def_cppflags_fortify,
227 \@def_ldflags_bindnow,
230 # References to all used flags.
231 my @flag_refs_all = (
233 \@def_cppflags_fortify_bad,
236 # Renaming rules for the output so the regex parts are not visible. Also
237 # stores string values of flag regexps above, see compile_flag_regexp().
239 '-O(?:2|3)' => '-O2',
240 '-Wl,(?:-z,)?relro' => '-Wl,-z,relro',
241 '-Wl,(?:-z,)?now' => '-Wl,-z,now',
245 no_compiler_commands => 1 << 0,
246 # used by POD::Usage => 1 << 1,
247 non_verbose_build => 1 << 2,
248 flags_missing => 1 << 3,
249 hardening_wrapper => 1 << 4,
250 invalid_cmake => 1 << 5,
254 no_compiler_commands => 'I-no-compiler-commands',
255 non_verbose_build => 'W-compiler-flags-hidden',
256 flags_missing => 'W-dpkg-buildflags-missing',
257 hardening_wrapper => 'I-hardening-wrapper-used',
258 invalid_cmake => 'I-invalid-cmake-used',
261 # Statistics of missing flags and non-verbose build commands. Used for
265 preprocess_missing => 0,
267 compile_missing => 0,
269 compile_cpp_missing => 0,
273 commands_nonverbose => 0,
276 # Use colored (ANSI) output?
283 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
285 # Get string value of qr//-escaped regexps and if requested rename them.
286 my @missing_flags = map {
287 $flag_renames_ref->{$_}
288 } @{$missing_flags_ref};
290 my $flags = join ' ', @missing_flags;
291 printf '%s (%s)%s %s',
292 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
295 sub error_non_verbose_build {
299 error_color('NONVERBOSE BUILD', 'red'),
300 error_color(':', 'yellow'),
303 sub error_invalid_cmake {
307 error_color('INVALID CMAKE', 'red'),
308 error_color(':', 'yellow'),
311 sub error_hardening_wrapper {
313 error_color('HARDENING WRAPPER', 'red'),
314 error_color(':', 'yellow'),
315 'no checks possible, aborting';
318 my ($message, $color) = @_;
321 return Term::ANSIColor::colored($message, $color);
328 my ($line, @flags) = @_;
330 foreach my $flag (@flags) {
331 return 1 if $line =~ /$flag/;
337 my ($line, $missing_flags_ref, @flags) = @_;
339 my @missing_flags = ();
340 foreach my $flag (@flags) {
341 if (not $line =~ /$flag/) {
342 push @missing_flags, $flag;
346 return 1 if scalar @missing_flags == 0;
348 @{$missing_flags_ref} = @missing_flags;
352 sub cppflags_fortify_broken {
353 my ($line, $missing_flags) = @_;
355 # This doesn't take the position into account, but is a simple solution.
356 # And if the build system tries to force -D_FORTIFY_SOURCE=0/1, something
359 if (any_flags_used($line, @def_cppflags_fortify_bad)) {
360 # $def_cppflags_fortify[0] must be -D_FORTIFY_SOURCE=2!
361 push @{$missing_flags}, $def_cppflags_fortify[0];
368 # Modifies $missing_flags_ref array.
369 sub pic_pie_conflict {
370 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
372 return 0 if not $pie;
373 return 0 if not any_flags_used($line, @def_ldflags_pic);
375 my %flags = map { $_ => 1 } @flags_pie;
377 # Remove all PIE flags from @missing_flags as they are not required with
380 not exists $flags{$_}
381 } @{$missing_flags_ref};
382 @{$missing_flags_ref} = @result;
384 # We got a conflict when no flags are left, thus only PIE flags were
385 # missing. If other flags were missing abort because the conflict is not
387 return scalar @result == 0;
390 sub is_non_verbose_build {
391 my ($line, $next_line, $skip_ref) = @_;
393 if (not (index($line, 'checking if you want to see long compiling messages... no') == 0
394 or $line =~ /^\s*\[?(?:CC|CCLD|C\+\+|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
395 or $line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/
396 or $line =~ /^\s*[Bb]uilding (?:program|shared library)\s+(.+?)$/
397 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
403 # C++ compiler setting.
404 return 0 if $line =~ /^\s*C\+\+.+?:\s+(?:yes|no)\s*$/;
405 # "Compiling" with no file name.
406 if ($line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/) {
407 # $file_extension_regex may need spaces around the filename.
408 return 0 if not " $1 " =~ /$file_extension_regex/o;
413 # On the first pass we only check if this line is verbose or not.
414 return 1 if not defined $next_line;
416 # Second pass, we have access to the next line.
419 # CMake and other build systems print the non-verbose messages also when
420 # building verbose. If a compiler and the file name occurs in the next
421 # line, treat it as verbose build.
423 # Get filename, we can't use the complete path as only parts of it are
424 # used in the real compiler command.
425 $file =~ m{/([^/\s]+)$};
428 if (index($next_line, $file) != -1 and $next_line =~ /$cc_regex/o) {
429 # We still have to skip the current line as it doesn't contain any
440 my ($flag_refs_ref, $flag_renames_ref, @flags) = @_;
442 my %removes = map { $_ => 1 } @flags;
443 foreach my $flags (@{$flag_refs_ref}) {
445 # Flag found as string.
446 not exists $removes{$_}
447 # Flag found as string representation of regexp.
448 and (not defined $flag_renames_ref->{$_}
449 or not exists $removes{$flag_renames_ref->{$_}})
454 sub compile_flag_regexp {
455 my ($flag_renames_ref, @flags) = @_;
458 foreach my $flag (@flags) {
459 # Store flag name in replacement string for correct flags in messages
460 # with qr//ed flag regexps.
461 $flag_renames_ref->{qr/\s$flag(?:\s|\\)/}
462 = (exists $flag_renames_ref->{$flag})
463 ? $flag_renames_ref->{$flag}
466 # Compile flag regexp for faster execution.
467 push @result, qr/\s$flag(?:\s|\\)/;
472 sub extension_found {
473 my ($extensions_ref, @extensions) = @_;
476 foreach my $extension (@extensions) {
477 if (exists $extensions_ref->{$extension}) {
488 # Parse command line arguments.
490 my $option_version = 0;
492 my $option_bindnow = 0;
493 my @option_ignore_arch = ();
494 my @option_ignore_flag = ();
495 my @option_ignore_arch_flag = ();
496 my @option_ignore_line = ();
497 my @option_ignore_arch_line = ();
499 my $option_arch = undef;
500 my $option_buildd = 0;
502 if (not Getopt::Long::GetOptions(
503 'help|h|?' => \$option_help,
504 'version' => \$option_version,
506 'pie' => \$option_pie,
507 'bindnow' => \$option_bindnow,
508 'all' => \$option_all,
510 'ignore-arch=s' => \@option_ignore_arch,
511 'ignore-flag=s' => \@option_ignore_flag,
512 'ignore-arch-flag=s' => \@option_ignore_arch_flag,
513 'ignore-line=s' => \@option_ignore_line,
514 'ignore-arch-line=s' => \@option_ignore_arch_line,
516 'color' => \$option_color,
517 'arch=s' => \$option_arch,
518 'buildd' => \$option_buildd,
521 Pod::Usage::pod2usage(2);
525 Pod::Usage::pod2usage(1);
527 if ($option_version) {
528 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
530 This program is free software: you can redistribute it and/or modify
531 it under the terms of the GNU General Public License as published by
532 the Free Software Foundation, either version 3 of the License, or
533 (at your option) any later version.
535 This program is distributed in the hope that it will be useful,
536 but WITHOUT ANY WARRANTY; without even the implied warranty of
537 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
538 GNU General Public License for more details.
540 You should have received a copy of the GNU General Public License
541 along with this program. If not, see <http://www.gnu.org/licenses/>.
547 if (scalar @ARGV == 0) {
549 Pod::Usage::pod2usage(2);
552 # Don't load Term::ANSIColor in buildd mode because Term::ANSIColor is not
553 # installed on Debian's buildds.
554 if (not $option_buildd) {
555 require Term::ANSIColor;
563 # Precompiled ignores for faster lookup.
564 my %option_ignore_arch_flag = ();
565 my %option_ignore_arch_line = ();
567 # Strip flags which should be ignored.
568 if (scalar @option_ignore_flag > 0) {
569 remove_flags(\@flag_refs, \%flag_renames, @option_ignore_flag);
571 # Same for arch specific ignore flags, but only prepare here.
572 if (scalar @option_ignore_arch_flag > 0) {
573 foreach my $ignore (@option_ignore_arch_flag) {
574 my ($ignore_arch, $ignore_flag) = split ':', $ignore, 2;
576 if (not $ignore_arch or not $ignore_flag) {
577 printf STDERR 'Value "%s" invalid for option ignore-arch-flag '
578 . '("arch:flag" expected)' . "\n", $ignore;
580 Pod::Usage::pod2usage(2);
583 push @{$option_ignore_arch_flag{$ignore_arch}}, $ignore_flag;
587 # Precompile all flag regexps. any_flags_used(), all_flags_used() get a lot
589 foreach my $flags (@flag_refs_all) {
590 @{$flags} = compile_flag_regexp(\%flag_renames, @{$flags});
593 # Precompile ignore line regexps, also anchor at beginning and end of line.
594 foreach my $ignore (@option_ignore_line) {
595 $ignore = qr/^$ignore$/;
597 # Same for arch specific ignore lines.
598 if (scalar @option_ignore_arch_line > 0) {
599 foreach my $ignore (@option_ignore_arch_line) {
600 my ($ignore_arch, $ignore_line) = split ':', $ignore, 2;
602 if (not $ignore_arch or not $ignore_line) {
603 printf STDERR 'Value "%s" invalid for option ignore-arch-line '
604 . '("arch:line" expected)' . "\n", $ignore;
606 Pod::Usage::pod2usage(2);
609 push @{$option_ignore_arch_line{$ignore_arch}}, qr/^$ignore_line$/;
617 foreach my $file (@ARGV) {
618 print "checking '$file'...\n" if scalar @ARGV > 1;
620 -f $file or die "No such file: $file";
622 open my $fh, '<', $file or die $!;
624 # Architecture of this file.
625 my $arch = $option_arch;
627 # Hardening options. Not all architectures support all hardening options.
628 my $harden_format = 1;
629 my $harden_fortify = 1;
630 my $harden_stack = 1;
631 my $harden_relro = 1;
632 my $harden_bindnow = $option_bindnow; # defaults to 0
633 my $harden_pie = $option_pie; # defaults to 0
635 while (my $line = <$fh>) {
636 # Detect architecture automatically unless overridden. For buildd logs
637 # only, doesn't use the dpkg-buildpackage header. Necessary to ignore
638 # build logs which aren't built (wrong architecture, build error,
641 and $line =~ /^Architecture: (.+)$/) {
645 # dpkg-buildflags only provides hardening flags since 1.16.1, don't
646 # check for hardening flags in buildd mode if an older dpkg-dev is
647 # used. Default flags (-g -O2) are still checked.
649 # Packages which were built before 1.16.1 but used their own hardening
650 # flags are not checked.
652 and index($line, 'Toolchain package versions: ') == 0) {
653 require Dpkg::Version;
654 if (not $line =~ /\bdpkg-dev_(\S+)/
655 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
665 # The following two versions of CMake in Debian obeyed CPPFLAGS, but
666 # this was later dropped because upstream rejected the patch. Thus
667 # build logs with these versions will have fortify hardening flags
668 # enabled, even though they may be not correctly set and are missing
669 # when build with later CMake versions. Thanks to Aron Xu for letting
671 if (index($line, 'Package versions: ') == 0
672 and $line =~ /\bcmake_(\S+)/
673 and ($1 eq '2.8.7-1' or $1 eq '2.8.7-2')) {
674 if (not $option_buildd) {
675 error_invalid_cmake($1);
676 $exit |= $exit_code{invalid_cmake};
678 print "$buildd_tag{invalid_cmake}|$1|\n";
682 # If hardening wrapper is used (wraps calls to gcc and adds hardening
683 # flags automatically) we can't perform any checks, abort.
684 if (index($line, 'Build-Depends: ') == 0
685 and $line =~ /\bhardening-wrapper\b/) {
686 if (not $option_buildd) {
687 error_hardening_wrapper();
688 $exit |= $exit_code{hardening_wrapper};
690 print "$buildd_tag{hardening_wrapper}||\n";
695 # We skip over unimportant lines at the beginning of the log to
696 # prevent false positives.
697 last if index($line, 'dpkg-buildpackage: ') == 0;
700 # Input lines, contain only the lines with compiler commands.
703 my $continuation = 0;
704 my $complete_line = undef;
705 while (my $line = <$fh>) {
706 # And stop at the end of the build log. Package details (reported by
707 # the buildd logs) are not important for us. This also prevents false
709 last if $line =~ /^Build finished at \d{8}-\d{4}$/;
711 # Detect architecture automatically unless overridden.
713 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
717 # Ignore compiler warnings for now.
718 next if $line =~ /$warning_regex/o;
720 if (not $option_buildd and index($line, "\033") != -1) { # esc
721 # Remove all ANSI color sequences which are sometimes used in
722 # non-verbose builds.
723 $line = Term::ANSIColor::colorstrip($line);
724 # Also strip '\0xf' (delete previous character), used by Elinks'
727 # And "ESC(B" which seems to be used on armhf and hurd (not sure
729 $line =~ s/\033\(B//g;
732 # Check if this line indicates a non verbose build.
733 my $non_verbose = is_non_verbose_build($line);
735 # One line may contain multiple commands (";"). Treat each one as
736 # single line. parse_line() is slow, only use it when necessary.
737 my @line = (index($line, ';') == -1)
740 # Ensure newline at the line end - necessary for
741 # correct parsing later.
744 } Text::ParseWords::parse_line(';', 1, $line);
745 foreach my $line (@line) {
749 # Join lines, but leave the "\" in place so it's clear where
750 # the original line break was.
751 chomp $complete_line;
752 $complete_line .= ' ' . $line;
754 # Line continuation, line ends with "\".
755 if ($line =~ /\\$/) {
757 # Start line continuation.
758 if (not defined $complete_line) {
759 $complete_line = $line;
764 # Use the complete line if a line continuation occurred.
765 if (defined $complete_line) {
766 $line = $complete_line;
767 $complete_line = undef;
770 # Ignore lines with no compiler commands.
771 next if not $non_verbose
772 and not $line =~ /\b$cc_regex(?:\s|\\)/o;
773 # Ignore lines with no filenames with extensions. May miss some
774 # non-verbose builds (e.g. "gcc -o test" [sic!]), but shouldn't be
775 # a problem as the log will most likely contain other non-verbose
776 # commands which are detected.
777 next if not $non_verbose
778 and not $line =~ /$file_extension_regex/o;
780 # Ignore false positives.
782 # `./configure` output.
783 next if not $non_verbose
784 and $line =~ /^(?:checking|[Cc]onfigure:) /;
785 next if $line =~ /^\s*(?:Host\s+)?(?:C(?:\+\+)?\s+)?
786 [Cc]ompiler[\s.]*:?\s+
788 next if $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex_full\s*$/o;
789 # `moc-qt4`, contains '-I/usr/share/qt4/mkspecs/linux-g++' (or
790 # similar for other architectures) which gets recognized as a
791 # compiler line. Ignore it.
792 next if $line =~ m{^/usr/bin/moc-qt4
794 -I/usr/share/qt4/mkspecs/[a-z]+-g\++(?:-64)?
797 # Check if additional hardening options were used. Used to ensure
798 # they are used for the complete build.
799 $harden_pie = 1 if any_flags_used($line, @def_cflags_pie,
801 $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);
809 # Ignore arch if requested.
810 if (scalar @option_ignore_arch > 0 and $arch) {
811 foreach my $ignore (@option_ignore_arch) {
812 if ($arch eq $ignore) {
813 print "ignoring architecture '$arch'\n";
819 if (scalar @input == 0) {
820 if (not $option_buildd) {
821 print "No compiler commands!\n";
822 $exit |= $exit_code{no_compiler_commands};
824 print "$buildd_tag{no_compiler_commands}||\n";
829 if ($option_buildd) {
830 $statistics{commands} += scalar @input;
833 # Option or auto detected.
835 # The following was partially copied from dpkg-dev 1.16.1.2
836 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
837 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
838 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
839 # later. Keep it in sync.
842 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($arch);
844 # Disable unsupported hardening options.
845 if ($cpu =~ /^(?:ia64|alpha|mips|mipsel|hppa)$/ or $arch eq 'arm') {
848 if ($cpu =~ /^(?:ia64|hppa|avr32)$/) {
855 my @cflags = @def_cflags;
856 my @cxxflags = @def_cxxflags;
857 my @cppflags = @def_cppflags;
858 my @ldflags = @def_ldflags;
859 # Check the specified hardening options, same order as dpkg-buildflags.
861 @cflags = (@cflags, @def_cflags_pie);
862 @cxxflags = (@cxxflags, @def_cflags_pie);
863 @ldflags = (@ldflags, @def_ldflags_pie);
866 @cflags = (@cflags, @def_cflags_stack);
867 @cxxflags = (@cxxflags, @def_cflags_stack);
869 if ($harden_fortify) {
870 @cflags = (@cflags, @def_cflags_fortify);
871 @cxxflags = (@cxxflags, @def_cflags_fortify);
872 @cppflags = (@cppflags, @def_cppflags_fortify);
874 if ($harden_format) {
875 @cflags = (@cflags, @def_cflags_format);
876 @cxxflags = (@cxxflags, @def_cflags_format);
879 @ldflags = (@ldflags, @def_ldflags_relro);
881 if ($harden_bindnow) {
882 @ldflags = (@ldflags, @def_ldflags_bindnow);
885 # Hack to fix cppflags_fortify_broken() if --ignore-flag
886 # -D_FORTIFY_SOURCE=2 is used to ignore missing fortification. Only works
887 # as long as @def_cppflags_fortify contains only one variable.
888 if (scalar @def_cppflags_fortify == 0) {
892 # Ignore flags for this arch if requested.
893 if ($arch and exists $option_ignore_arch_flag{$arch}) {
894 my @flag_refs = (\@cflags, \@cxxflags, \@cppflags, \@ldflags);
896 remove_flags(\@flag_refs,
898 @{$option_ignore_arch_flag{$arch}});
901 my @ignore_line = @option_ignore_line;
902 # Ignore lines for this arch if requested.
903 if ($arch and exists $option_ignore_arch_line{$arch}) {
904 @ignore_line = (@ignore_line, @{$option_ignore_arch_line{$arch}});
908 for (my $i = 0; $i < scalar @input; $i++) {
909 my $line = $input[$i];
911 # Ignore line if requested.
912 foreach my $ignore (@ignore_line) {
913 next LINE if $line =~ /$ignore/;
917 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
918 if (not $option_buildd) {
919 error_non_verbose_build($line);
920 $exit |= $exit_code{non_verbose_build};
922 $statistics{commands_nonverbose}++;
926 # Even if it's a verbose build, we might have to skip this line.
929 # Remove everything until and including the compiler command. Makes
930 # checks easier and faster.
931 $line =~ s/^.*?$cc_regex//o;
932 # "([...] test.c)" is not detected as 'test.c' - fix this by removing
933 # the brace and similar characters.
934 $line =~ s/['")]+$//;
936 # Skip unnecessary tests when only preprocessing.
937 my $flag_preprocess = 0;
944 # Preprocess, compile, assemble.
945 if ($line =~ /\s(-E|-S|-c)\b/) {
947 $flag_preprocess = 1 if $1 eq '-E';
948 $compile = 1 if $1 eq '-S' or $1 eq '-c';
949 # Dependency generation for Makefiles. The other flags (-MF -MG -MP
950 # -MT -MQ) are always used with -M/-MM.
951 } elsif ($line =~ /\s(?:-M|-MM)\b/) {
953 # Otherwise assume we are linking.
958 # -MD/-MMD also cause dependency generation, but they don't imply -E!
959 if ($line =~ /\s(?:-MD|-MMD)\b/) {
961 $flag_preprocess = 0;
964 # Dependency generation for Makefiles, no preprocessing or other flags
968 # Get all file extensions on this line.
969 my @extensions = $line =~ /$file_extension_regex/go;
970 # Ignore all unknown extensions to speedup the search below.
971 @extensions = grep { exists $extension{$_} } @extensions;
973 # These file types don't require preprocessing.
974 if (extension_found(\%extensions_no_preprocess, @extensions)) {
977 # These file types require preprocessing.
978 if (extension_found(\%extensions_preprocess, @extensions)) {
982 if (not $flag_preprocess) {
983 # If there are source files then it's compiling/linking in one
984 # step and we must check both. We only check for source files
985 # here, because header files cause too many false positives.
986 if (extension_found(\%extensions_compile_link, @extensions)) {
987 # Assembly files don't need CFLAGS.
988 if (not extension_found(\%extensions_compile, @extensions)
989 and extension_found(\%extensions_no_compile, @extensions)) {
995 # No compilable extensions found, either linking or compiling
998 # If there are also no object files we are just compiling headers
999 # (.h -> .h.gch). Don't check for linker flags in this case. Due
1000 # to our liberal checks for compiler lines, this also reduces the
1001 # number of false positives considerably.
1003 and not extension_found(\%extensions_object, @extensions)) {
1008 # Assume CXXFLAGS are required when a C++ file is specified in the
1010 my $compile_cpp = 0;
1012 and extension_found(\%extensions_compile_cpp, @extensions)) {
1017 if ($option_buildd) {
1018 $statistics{preprocess}++ if $preprocess;
1019 $statistics{compile}++ if $compile;
1020 $statistics{compile_cpp}++ if $compile_cpp;
1021 $statistics{link}++ if $link;
1024 # Check hardening flags.
1026 if ($compile and not all_flags_used($line, \@missing, @cflags)
1027 # Libraries linked with -fPIC don't have to (and can't) be
1028 # linked with -fPIE as well. It's no error if only PIE flags
1030 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1031 # Assume dpkg-buildflags returns the correct flags.
1032 and index($line, '`dpkg-buildflags --get CFLAGS`') == -1) {
1033 if (not $option_buildd) {
1034 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1035 $exit |= $exit_code{flags_missing};
1037 $statistics{compile_missing}++;
1039 } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
1040 # Libraries linked with -fPIC don't have to (and can't) be
1041 # linked with -fPIE as well. It's no error if only PIE flags
1043 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1044 # Assume dpkg-buildflags returns the correct flags.
1045 and index($line, '`dpkg-buildflags --get CXXFLAGS`') == -1) {
1046 if (not $option_buildd) {
1047 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1048 $exit |= $exit_code{flags_missing};
1050 $statistics{compile_cpp_missing}++;
1054 and (not all_flags_used($line, \@missing, @cppflags)
1055 # The fortify flag might be overwritten, detect that.
1057 and cppflags_fortify_broken($line, \@missing)))
1058 # Assume dpkg-buildflags returns the correct flags.
1059 and index($line, '`dpkg-buildflags --get CPPFLAGS`') == -1) {
1060 if (not $option_buildd) {
1061 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1062 $exit |= $exit_code{flags_missing};
1064 $statistics{preprocess_missing}++;
1067 if ($link and not all_flags_used($line, \@missing, @ldflags)
1068 # Same here, -fPIC conflicts with -fPIE.
1069 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
1070 # Assume dpkg-buildflags returns the correct flags.
1071 and index($line, '`dpkg-buildflags --get LDFLAGS`') == -1) {
1072 if (not $option_buildd) {
1073 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1074 $exit |= $exit_code{flags_missing};
1076 $statistics{link_missing}++;
1082 # Print statistics for buildd mode, only output in this mode.
1083 if ($option_buildd) {
1086 if ($statistics{preprocess_missing}) {
1087 push @warning, sprintf 'CPPFLAGS %d (of %d)',
1088 $statistics{preprocess_missing},
1089 $statistics{preprocess};
1091 if ($statistics{compile_missing}) {
1092 push @warning, sprintf 'CFLAGS %d (of %d)',
1093 $statistics{compile_missing},
1094 $statistics{compile};
1096 if ($statistics{compile_cpp_missing}) {
1097 push @warning, sprintf 'CXXFLAGS %d (of %d)',
1098 $statistics{compile_cpp_missing},
1099 $statistics{compile_cpp};
1101 if ($statistics{link_missing}) {
1102 push @warning, sprintf 'LDFLAGS %d (of %d)',
1103 $statistics{link_missing},
1106 if (scalar @warning) {
1107 local $" = ', '; # array join string
1108 print "$buildd_tag{flags_missing}|@warning missing|\n";
1111 if ($statistics{commands_nonverbose}) {
1112 printf "$buildd_tag{non_verbose_build}|%d (of %d) hidden|\n",
1113 $statistics{commands_nonverbose},
1114 $statistics{commands},
1126 blhc - build log hardening check, checks build logs for missing hardening flags
1130 B<blhc> [I<options>] I<< <dpkg-buildpackage build log file>.. >>
1134 blhc is a small tool which checks build logs for missing hardening flags. It's
1135 licensed under the GPL 3 or later.
1137 It's designed to check build logs generated by Debian's dpkg-buildpackage (or
1138 tools using dpkg-buildpackage like pbuilder or the official buildd build logs)
1139 to help maintainers detect missing hardening flags in their packages.
1141 Only gcc is detected as compiler at the moment. If other compilers support
1142 hardening flags as well, please report them.
1144 If there's no output, no flags are missing and the build log is fine.
1152 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
1155 =item B<--arch> I<architecture>
1157 Set the specific architecture (e.g. amd64, armel, etc.), automatically
1158 disables hardening flags not available on this architecture. Is detected
1159 automatically if dpkg-buildpackage is used.
1163 Force check for all +bindnow hardening flags. By default it's auto detected.
1167 Special mode for buildds when automatically parsing log files. The following
1168 changes are in effect:
1174 Print tags instead of normal warnings, see L</"BUILDD TAGS"> for a list of
1179 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
1184 Don't require Term::ANSIColor.
1188 Return exit code 0, unless there was a error (-I, -W messages don't count as
1195 Use colored (ANSI) output for warning messages.
1197 =item B<--ignore-arch> I<arch>
1199 Ignore build logs from architectures matching I<arch>. I<arch> is a string.
1201 Used to prevent false positives. This option can be specified multiple times.
1203 =item B<--ignore-arch-flag> I<arch>:I<flag>
1205 Like B<--ignore-flag>, but only ignore flag on I<arch>.
1207 =item B<--ignore-arch-line> I<arch>:I<line>
1209 Like B<--ignore-line>, but only ignore line on I<arch>.
1211 =item B<--ignore-flag> I<flag>
1213 Don't print an error when the specific flag is missing in a compiler line.
1214 I<flag> is a string.
1216 Used to prevent false positives. This option can be specified multiple times.
1218 =item B<--ignore-line> I<regex>
1220 Ignore lines matching the given Perl regex. I<regex> is automatically anchored
1221 at the beginning and end of the line to prevent false negatives.
1223 B<NOTE>: Not the input lines are checked, but the lines which are displayed in
1224 warnings (which have line continuation resolved).
1226 Used to prevent false positives. This option can be specified multiple times.
1230 Force check for all +pie hardening flags. By default it's auto detected.
1232 =item B<-h -? --help>
1234 Print available options.
1238 Print version number and license.
1242 Auto detection for B<--pie> and B<--bindnow> only works if at least one
1243 command uses the required hardening flag (e.g. -fPIE). Then it's required for
1244 all other commands as well.
1248 Normal usage, parse a single log file.
1250 blhc path/to/log/file
1252 If there's no output, no flags are missing and the build log is fine.
1254 Parse multiple log files. The exit code is ORed over all files.
1256 blhc path/to/directory/with/log/files/*
1258 Don't treat missing C<-g> as error:
1260 blhc --ignore-flag -g path/to/log/file
1262 Don't treat missing C<-pie> on kfreebsd-amd64 as error:
1264 blhc --ignore-arch-flag kfreebsd-amd64:-pie path/to/log/file
1266 Ignore lines consisting exactly of C<./script gcc file> which would cause a
1269 blhc --ignore-line '\./script gcc file' path/to/log/file
1271 Ignore lines matching C<./script gcc file> somewhere in the line.
1273 blhc --ignore-line '.*\./script gcc file.*' path/to/log/file
1275 Use blhc with pbuilder.
1277 pbuilder path/to/package.dsc | tee path/log/file
1278 blhc path/to/file || echo flags missing
1282 The following tags are used in I<--buildd> mode. In braces the additional data
1287 =item B<I-hardening-wrapper-used>
1289 The package uses hardening-wrapper which intercepts calls to gcc and adds
1290 hardening flags. The build log doesn't contain any hardening flags and thus
1291 can't be checked by blhc.
1293 =item B<W-compiler-flags-hidden> (summary of hidden lines)
1295 Build log contains lines which hide the real compiler flags. For example:
1302 Most of the time either C<export V=1> or C<export verbose=1> in
1303 F<debian/rules> fixes builds with hidden compiler flags. Sometimes C<.SILENT>
1304 in a F<Makefile> must be removed. And as last resort the F<Makefile> must be
1305 patched to remove the C<@>s hiding the real compiler commands.
1307 =item B<W-dpkg-buildflags-missing> (summary of missing flags)
1309 CPPFLAGS, CFLAGS, CXXFLAGS, LDFLAGS missing.
1311 =item B<I-invalid-cmake-used> (version)
1313 By default CMake ignores CPPFLAGS thus missing those hardening flags. Debian
1314 patched CMake in versions 2.8.7-1 and 2.8.7-2 to respect CPPFLAGS, but this
1315 patch was rejected by upstream and later reverted in Debian. Thus those two
1316 versions show correct usage of CPPFLAGS even if the package doesn't correctly
1317 handle them (for example by passing them to CFLAGS). To prevent false
1318 negatives just blacklist those two versions.
1320 =item B<I-no-compiler-commands>
1322 No compiler commands were detected. Either the log contains none or they were
1323 not correctly detected by blhc (please report the bug in this case).
1329 The exit status is a "bit mask", each listed status is ORed when the error
1330 condition occurs to get the result.
1340 No compiler commands were found.
1344 Invalid arguments/options given to blhc.
1352 Missing hardening flags.
1356 Hardening wrapper detected, no tests performed.
1360 Invalid CMake version used. See B<I-invalid-cmake-used> under L</"BUILDD
1361 TAGS"> for a detailed explanation.
1367 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
1369 Thanks to to Bernhard R. Link E<lt>brlink@debian.orgE<gt> and Jaria Alto
1370 E<lt>jari.aalto@cante.netE<gt> for their valuable input and suggestions.
1372 =head1 COPYRIGHT AND LICENSE
1374 Copyright (C) 2012 by Simon Ruderich
1376 This program is free software: you can redistribute it and/or modify
1377 it under the terms of the GNU General Public License as published by
1378 the Free Software Foundation, either version 3 of the License, or
1379 (at your option) any later version.
1381 This program is distributed in the hope that it will be useful,
1382 but WITHOUT ANY WARRANTY; without even the implied warranty of
1383 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1384 GNU General Public License for more details.
1386 You should have received a copy of the GNU General Public License
1387 along with this program. If not, see <http://www.gnu.org/licenses/>.
1391 L<hardening-check(1)>, L<dpkg-buildflags(1)>