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 Term::ANSIColor ();
26 use Text::ParseWords ();
28 our $VERSION = '0.01';
33 # Regex to catch compiler commands.
35 (?<!\.)(?:cc|gcc|g\+\+|c\+\+)
38 # Full regex which matches the complete compiler name. Used in a few places to
39 # prevent false negatives.
40 my $cc_regex_full = qr/
41 (?:[a-z0-9_]+-(?:linux-|kfreebsd-)?gnu(?:eabi|eabihf)?-)?
44 # Regex to catch (GCC) compiler warnings.
45 my $warning_regex = qr/^(.+?):([0-9]+):[0-9]+: warning: (.+?) \[(.+?)\]$/;
47 # List of source file extensions which require preprocessing.
48 my @source_preprocess_compile_cpp = (
50 qw( cc cp cxx cpp CPP c++ C ),
54 my @source_preprocess_compile = (
60 @source_preprocess_compile_cpp,
62 qw( F FOR fpp FPP FTN F90 F95 F03 F08 ),
64 my @source_preprocess_no_compile = (
68 my @source_preprocess = (
69 @source_preprocess_compile,
70 @source_preprocess_no_compile,
72 # List of source file extensions which don't require preprocessing.
73 my @source_no_preprocess_compile_cpp = (
79 my @source_no_preprocess_compile = (
83 @source_no_preprocess_compile_cpp,
87 qw( f for ftn f90 f95 f03 f08 ),
89 my @source_no_preprocess_no_compile = (
93 my @source_no_preprocess = (
94 @source_no_preprocess_compile,
95 @source_no_preprocess_no_compile,
97 # List of header file extensions which require preprocessing.
98 my @header_preprocess = (
99 # C, C++, Objective-C, Objective-C++
102 qw( hh H hp hxx hpp HPP h++ tcc ),
105 # Hashes for fast extensions lookup to check if a file falls in one of these
107 my %extensions_no_preprocess = map { $_ => 1 } (
108 @source_no_preprocess,
110 my %extensions_preprocess = map { $_ => 1 } (
114 my %extensions_compile_link = map { $_ => 1 } (
116 @source_no_preprocess,
118 my %extensions_compile = map { $_ => 1 } (
119 @source_preprocess_compile,
120 @source_no_preprocess_compile,
122 my %extensions_no_compile = map { $_ => 1 } (
123 @source_preprocess_no_compile,
124 @source_no_preprocess_no_compile,
126 my %extensions_compile_cpp = map { $_ => 1 } (
127 @source_preprocess_compile_cpp,
128 @source_no_preprocess_compile_cpp,
130 my %extension = map { $_ => 1 } (
131 @source_no_preprocess,
132 @source_no_preprocess_compile,
133 @source_no_preprocess_compile_cpp,
134 @source_no_preprocess_no_compile,
137 @source_preprocess_compile,
138 @source_preprocess_compile_cpp,
139 @source_preprocess_no_compile,
142 # Regexp to match file extensions.
143 my $file_extension_regex = qr/
145 \S+ # Filename without extension.
147 ([^\\.\s]+) # File extension.
148 (?=\s|\\) # At end of word. Can't use \b because some files have non
149 # word characters at the end and because \b matches double
150 # extensions (like .cpp.o). Works always as all lines are
151 # terminated with "\n".
154 # Expected (hardening) flags. All flags are used as regexps.
159 my @def_cflags_format = (
162 '-Werror=format-security',
164 my @def_cflags_fortify = (
165 # fortify needs at least -O1, but -O2 is recommended anyway
167 my @def_cflags_stack = (
169 '--param=ssp-buffer-size=4',
171 my @def_cflags_pie = (
177 # @def_cxxflags_* is the same as @def_cflags_*.
178 my @def_cppflags = ();
179 my @def_cppflags_fortify = (
180 '-D_FORTIFY_SOURCE=2',
182 my @def_ldflags = ();
183 my @def_ldflags_relro = (
186 my @def_ldflags_bindnow = (
189 my @def_ldflags_pie = (
193 my @def_ldflags_pic = (
197 # Renaming rules for the output so the regex parts are not visible. Also
198 # stores string values of flag regexps above, see compile_flag_regexp().
200 '-O(?:2|3)' => '-O2',
201 '-Wl,(-z,)?relro' => '-Wl,-z,relro',
202 '-Wl,(-z,)?now' => '-Wl,-z,now',
205 # Use colored (ANSI) output?
212 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
214 # Get string value of qr//-escaped regexps and if requested rename them.
215 my @missing_flags = map {
216 $flag_renames_ref->{$_}
217 } @{$missing_flags_ref};
219 my $flags = join ' ', @missing_flags;
220 printf "%s (%s)%s %s",
221 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
224 sub error_non_verbose_build {
228 error_color('NONVERBOSE BUILD', 'red'),
229 error_color(':', 'yellow'),
232 sub error_hardening_wrapper {
234 error_color('HARDENING WRAPPER', 'red'),
235 error_color(':', 'yellow'),
236 'no checks possible, aborting';
239 my ($message, $color) = @_;
242 return Term::ANSIColor::colored($message, $color);
249 my ($line, @flags) = @_;
251 foreach my $flag (@flags) {
252 return 1 if $line =~ /$flag/;
258 my ($line, $missing_flags_ref, @flags) = @_;
260 my @missing_flags = ();
261 foreach my $flag (@flags) {
262 if (not $line =~ /$flag/) {
263 push @missing_flags, $flag;
267 return 1 if scalar @missing_flags == 0;
269 @{$missing_flags_ref} = @missing_flags;
273 # Modifies $missing_flags_ref array.
274 sub pic_pie_conflict {
275 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
277 return 0 if not $pie;
278 return 0 if not any_flags_used($line, @def_ldflags_pic);
280 my %flags = map { $_ => 1 } @flags_pie;
282 # Remove all PIE flags from @missing_flags as they are not required with
285 not exists $flags{$_}
286 } @{$missing_flags_ref};
287 @{$missing_flags_ref} = @result;
289 # We got a conflict when no flags are left, thus only PIE flags were
290 # missing. If other flags were missing abort because the conflict is not
292 return scalar @result == 0;
295 sub is_non_verbose_build {
296 my ($line, $next_line, $skip_ref) = @_;
298 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
299 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
300 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
301 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
302 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
308 # On the first pass we only check if this line is verbose or not.
309 return 1 if not defined $next_line;
311 # Second pass, we have access to the next line.
314 # CMake and other build systems print the non-verbose messages also when
315 # building verbose. If a compiler and the file name occurs in the next
316 # line, treat it as verbose build.
318 # Get filename, we can't use the complete path as only parts of it are
319 # used in the real compiler command.
320 $file =~ m{/([^/\s]+)$};
323 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/o) {
324 # We still have to skip the current line as it doesn't contain any
334 sub compile_flag_regexp {
335 my ($flag_renames_ref, @flags) = @_;
338 foreach my $flag (@flags) {
339 # Store flag name in replacement string for correct flags in messages
340 # with qr//ed flag regexps.
341 $flag_renames_ref->{qr/\s$flag(?:\s|\\)/}
342 = (exists $flag_renames_ref->{$flag})
343 ? $flag_renames_ref->{$flag}
346 # Compile flag regexp for faster execution.
347 push @result, qr/\s$flag(?:\s|\\)/;
352 sub extension_found {
353 my ($extensions_ref, @extensions) = @_;
356 foreach my $extension (@extensions) {
357 if (exists $extensions_ref->{$extension}) {
368 # Parse command line arguments.
370 my $option_version = 0;
372 my $option_bindnow = 0;
374 my $option_arch = undef;
375 my $option_buildd = 0;
377 if (not Getopt::Long::GetOptions(
378 'help|h|?' => \$option_help,
379 'version' => \$option_version,
381 'pie' => \$option_pie,
382 'bindnow' => \$option_bindnow,
383 'all' => \$option_all,
385 'color' => \$option_color,
386 'arch=s' => \$option_arch,
387 'buildd' => \$option_buildd,
390 Pod::Usage::pod2usage(2);
394 Pod::Usage::pod2usage(1);
396 if ($option_version) {
397 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
399 This program is free software: you can redistribute it and/or modify
400 it under the terms of the GNU General Public License as published by
401 the Free Software Foundation, either version 3 of the License, or
402 (at your option) any later version.
404 This program is distributed in the hope that it will be useful,
405 but WITHOUT ANY WARRANTY; without even the implied warranty of
406 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
407 GNU General Public License for more details.
409 You should have received a copy of the GNU General Public License
410 along with this program. If not, see <http://www.gnu.org/licenses/>.
420 # Precompile all flag regexps. any_flags_used(), all_flags_used() get a lot
422 @def_cflags = compile_flag_regexp(\%flag_renames, @def_cflags);
423 @def_cflags_format = compile_flag_regexp(\%flag_renames, @def_cflags_format);
424 @def_cflags_fortify = compile_flag_regexp(\%flag_renames, @def_cflags_fortify);
425 @def_cflags_stack = compile_flag_regexp(\%flag_renames, @def_cflags_stack);
426 @def_cflags_pie = compile_flag_regexp(\%flag_renames, @def_cflags_pie);
427 @def_cxxflags = compile_flag_regexp(\%flag_renames, @def_cxxflags);
428 @def_cppflags = compile_flag_regexp(\%flag_renames, @def_cppflags);
429 @def_cppflags_fortify = compile_flag_regexp(\%flag_renames, @def_cppflags_fortify);
430 @def_ldflags = compile_flag_regexp(\%flag_renames, @def_ldflags);
431 @def_ldflags_relro = compile_flag_regexp(\%flag_renames, @def_ldflags_relro);
432 @def_ldflags_bindnow = compile_flag_regexp(\%flag_renames, @def_ldflags_bindnow);
433 @def_ldflags_pie = compile_flag_regexp(\%flag_renames, @def_ldflags_pie);
434 @def_ldflags_pic = compile_flag_regexp(\%flag_renames, @def_ldflags_pic);
439 FILE: foreach my $file (@ARGV) {
440 open my $fh, '<', $file or die "$!: $file";
442 # Hardening options. Not all architectures support all hardening options.
443 my $harden_format = 1;
444 my $harden_fortify = 1;
445 my $harden_stack = 1;
446 my $harden_relro = 1;
447 my $harden_bindnow = $option_bindnow; # defaults to 0
448 my $harden_pie = $option_pie; # defaults to 0
450 while (my $line = <$fh>) {
451 # dpkg-buildflags only provides hardening flags since 1.16.1, don't
452 # check for hardening flags in buildd mode if an older dpkg-dev is
453 # used. Default flags (-g -O2) are still checked.
455 # Packages which were built before 1.16.1 but used their own hardening
456 # flags are not checked.
457 if ($option_buildd and $line =~ /^Toolchain package versions: /) {
458 require Dpkg::Version;
459 if ($line !~ /dpkg-dev_(\S+)/
460 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
470 # If hardening wrapper is used (wraps calls to gcc and adds hardening
471 # flags automatically) we can't perform any checks, abort.
472 if ($line =~ /^Build-Depends: .*\bhardening-wrapper\b/) {
473 error_hardening_wrapper();
478 # We skip over unimportant lines at the beginning of the log to
479 # prevent false positives.
480 last if $line =~ /^dpkg-buildpackage:/;
483 # Input lines, contain only the lines with compiler commands.
486 my $continuation = 0;
487 my $complete_line = undef;
488 while (my $line = <$fh>) {
489 # And stop at the end of the build log. Package details (reported by
490 # the buildd logs) are not important for us. This also prevents false
492 last if $line =~ /^Build finished at \d{8}-\d{4}$/;
494 # Detect architecture automatically unless overridden.
496 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
500 # Ignore compiler warnings for now.
501 next if $line =~ /$warning_regex/o;
503 if ($line =~ /\033/) { # esc
504 # Remove all ANSI color sequences which are sometimes used in
505 # non-verbose builds.
506 $line = Term::ANSIColor::colorstrip($line);
507 # Also strip '\0xf' (delete previous character), used by Elinks'
510 # And "ESC(B" which seems to be used on armhf and hurd (not sure
512 $line =~ s/\033\(B//g;
515 # Check if this line indicates a non verbose build.
516 my $non_verbose = is_non_verbose_build($line);
518 # One line may contain multiple commands (";"). Treat each one as
519 # single line. parse_line() is slow, only use it when necessary.
520 my @line = (not $line =~ /;/)
523 # Ensure newline at the line end - necessary for
524 # correct parsing later.
527 } Text::ParseWords::parse_line(';', 1, $line);
528 foreach $line (@line) {
532 # Join lines, but leave the "\" in place so it's clear where
533 # the original line break was.
534 chomp $complete_line;
535 $complete_line .= ' ' . $line;
537 # Line continuation, line ends with "\".
538 if ($line =~ /\\\s*$/) {
540 # Start line continuation.
541 if (not defined $complete_line) {
542 $complete_line = $line;
547 if (not $continuation) {
548 # Use the complete line if a line continuation occurred.
549 if (defined $complete_line) {
550 $line = $complete_line;
551 $complete_line = undef;
554 # Ignore lines with no compiler commands.
555 next if $line !~ /\b$cc_regex(?:\s|\\)/o and not $non_verbose;
557 # Ignore false positives.
559 # `./configure` output.
560 next if not $non_verbose
561 and $line =~ /^(?:checking|(?:C|c)onfigure:) /;
562 next if $line =~ /^\s*(?:Host\s+)?(?:C\s+)?
563 (?:C|c)ompiler[\s.]*:?\s+
565 (?:\s-std=[a-z0-9:+]+)?\s*$
567 or $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex_full\s*$/o
568 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
569 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
571 next if $line =~ /^Making [a-z]+ in \S+/; # e.g. "[...] in c++"
573 # Check if additional hardening options were used. Used to
574 # ensure they are used for the complete build.
575 $harden_pie = 1 if any_flags_used($line, @def_cflags_pie, @def_ldflags_pie);
576 $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);
585 if (scalar @input == 0) {
586 print "No compiler commands!\n";
591 # Option or auto detected.
593 # The following was partially copied from dpkg-dev 1.16.1.2
594 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
595 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
596 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
597 # later. Keep it in sync.
600 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
602 # Disable unsupported hardening options.
603 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
606 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
613 my @cflags = @def_cflags;
614 my @cxxflags = @def_cxxflags;
615 my @cppflags = @def_cppflags;
616 my @ldflags = @def_ldflags;
617 # Check the specified hardening options, same order as dpkg-buildflags.
619 @cflags = (@cflags, @def_cflags_pie);
620 @cxxflags = (@cxxflags, @def_cflags_pie);
621 @ldflags = (@ldflags, @def_ldflags_pie);
624 @cflags = (@cflags, @def_cflags_stack);
625 @cxxflags = (@cxxflags, @def_cflags_stack);
627 if ($harden_fortify) {
628 @cflags = (@cflags, @def_cflags_fortify);
629 @cxxflags = (@cxxflags, @def_cflags_fortify);
630 @cppflags = (@cppflags, @def_cppflags_fortify);
632 if ($harden_format) {
633 @cflags = (@cflags, @def_cflags_format);
634 @cxxflags = (@cxxflags, @def_cflags_format);
637 @ldflags = (@ldflags, @def_ldflags_relro);
639 if ($harden_bindnow) {
640 @ldflags = (@ldflags, @def_ldflags_bindnow);
643 for (my $i = 0; $i < scalar @input; $i++) {
644 my $line = $input[$i];
647 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
648 error_non_verbose_build($line);
652 # Even if it's a verbose build, we might have to skip this line.
655 # Remove everything until and including the compiler command. Makes
656 # checks easier and faster.
657 $line =~ s/^.*?$cc_regex//o;
658 # "([...] test.c)" is not detected as 'test.c' - fix this by removing
659 # the brace and similar characters.
660 $line =~ s/['")]+$//;
662 # Skip unnecessary tests when only preprocessing.
663 my $flag_preprocess = 0;
669 # Preprocess, compile, assemble.
670 if ($line =~ /\s(-E|-S|-c)\b/) {
672 $flag_preprocess = 1 if $1 eq '-E';
673 $compile = 1 if $1 eq '-S' or $1 eq '-c';
674 # Otherwise assume we are linking.
679 # Get all file extensions on this line.
680 my @extensions = $line =~ /$file_extension_regex/go;
681 # Ignore all unknown extensions to speedup the search below.
682 @extensions = grep { exists $extension{$_} } @extensions;
684 # These file types don't require preprocessing.
685 if (extension_found(\%extensions_no_preprocess, @extensions)) {
688 # These file types require preprocessing.
689 if (extension_found(\%extensions_preprocess, @extensions)) {
693 # If there are source files then it's compiling/linking in one step
694 # and we must check both. We only check for source files here, because
695 # header files cause too many false positives.
696 if (not $flag_preprocess
697 and extension_found(\%extensions_compile_link, @extensions)) {
698 # Assembly files don't need CFLAGS.
699 if (not extension_found(\%extensions_compile, @extensions)
700 and extension_found(\%extensions_no_compile, @extensions)) {
708 # Assume CXXFLAGS are required when a C++ file is specified in the
712 and extension_found(\%extensions_compile_cpp, @extensions)) {
717 # Check hardening flags.
719 if ($compile and not all_flags_used($line, \@missing, @cflags)
720 # Libraries linked with -fPIC don't have to (and can't) be
721 # linked with -fPIE as well. It's no error if only PIE flags
723 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
724 # Assume dpkg-buildflags returns the correct flags.
725 and not $line =~ /`dpkg-buildflags --get CFLAGS`/) {
726 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
728 } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
729 # Libraries linked with -fPIC don't have to (and can't) be
730 # linked with -fPIE as well. It's no error if only PIE flags
732 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
733 # Assume dpkg-buildflags returns the correct flags.
734 and not $line =~ /`dpkg-buildflags --get CXXFLAGS`/) {
735 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
738 if ($preprocess and not all_flags_used($line, \@missing, @cppflags)
739 # Assume dpkg-buildflags returns the correct flags.
740 and not $line =~ /`dpkg-buildflags --get CPPFLAGS`/) {
741 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
744 if ($link and not all_flags_used($line, \@missing, @ldflags)
745 # Same here, -fPIC conflicts with -fPIE.
746 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
747 # Assume dpkg-buildflags returns the correct flags.
748 and not $line =~ /`dpkg-buildflags --get LDFLAGS`/) {
749 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
762 blhc - build log hardening check, checks build logs for missing hardening flags
766 B<blhc> [options] <dpkg-buildpackage build log file>..
768 --all force +all (+pie, +bindnow) check
769 --arch set architecture (autodetected)
770 --bindnow force +bindbow check
771 --buildd parser mode for buildds
772 --color use colored output
773 --pie force +pie check
774 --help available options
775 --version version number and license
779 blhc is a small tool which checks build logs for missing hardening flags and
780 other important warnings. It's licensed under the GPL 3 or later.
788 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
793 Set the specific architecture (e.g. amd64, armel, etc.), automatically
794 disables hardening flags not available on this architecture. Is detected
795 automatically if dpkg-buildpackage is used.
799 Force check for all +bindnow hardening flags. By default it's auto detected.
803 Special mode for buildds when automatically parsing log files. The following
804 changes are in effect:
810 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
817 Use colored (ANSI) output for warning messages.
821 Force check for all +pie hardening flags. By default it's auto detected.
823 =item B<-h -? --help>
825 Print available options.
829 Print version number and license.
833 Auto detection for B<--pie> and B<--bindnow> only works if at least one
834 command uses the required hardening flag (e.g. -fPIE). Then it's required for
835 all other commands as well.
839 The exit status is a "bit mask", each listed status is ORed when the error
840 condition occurs to get the result.
850 No compiler commands were found.
854 Invalid arguments/options given to blhc.
862 Missing hardening flags.
866 Hardening wrapper detected, no tests performed.
872 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
874 =head1 COPYRIGHT AND LICENSE
876 Copyright (C) 2012 by Simon Ruderich
878 This program is free software: you can redistribute it and/or modify
879 it under the terms of the GNU General Public License as published by
880 the Free Software Foundation, either version 3 of the License, or
881 (at your option) any later version.
883 This program is distributed in the hope that it will be useful,
884 but WITHOUT ANY WARRANTY; without even the implied warranty of
885 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
886 GNU General Public License for more details.
888 You should have received a copy of the GNU General Public License
889 along with this program. If not, see <http://www.gnu.org/licenses/>.