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.
34 my $cc_regex = qr/(?:[a-z0-9_]+-(?:linux-|kfreebsd-)?gnu(?:eabi|eabihf)?-)?
35 (?<!\.)(?:cc|gcc|g\+\+|c\+\+)
37 # Regex to catch (GCC) compiler warnings.
38 my $warning_regex = qr/^(.+?):([0-9]+):[0-9]+: warning: (.+?) \[(.+?)\]$/;
40 # List of source file extensions which require preprocessing.
41 my @source_preprocess_compile_cpp = (
43 qw( cc cp cxx cpp CPP c++ C ),
47 my @source_preprocess_compile = (
53 @source_preprocess_compile_cpp,
55 qw( F FOR fpp FPP FTN F90 F95 F03 F08 ),
57 my @source_preprocess_no_compile = (
61 my @source_preprocess = (
62 @source_preprocess_compile,
63 @source_preprocess_no_compile,
65 # List of source file extensions which don't require preprocessing.
66 my @source_no_preprocess_compile_cpp = (
72 my @source_no_preprocess_compile = (
76 @source_no_preprocess_compile_cpp,
80 qw( f for ftn f90 f95 f03 f08 ),
82 my @source_no_preprocess_no_compile = (
86 my @source_no_preprocess = (
87 @source_no_preprocess_compile,
88 @source_no_preprocess_no_compile,
90 # List of header file extensions which require preprocessing.
91 my @header_preprocess = (
92 # C, C++, Objective-C, Objective-C++
95 qw( hh H hp hxx hpp HPP h++ tcc ),
98 # Hashes for fast extensions lookup to check if a file falls in one of these
100 my %extensions_no_preprocess = map { $_ => 1 } (
101 @source_no_preprocess,
103 my %extensions_preprocess = map { $_ => 1 } (
107 my %extensions_compile_link = map { $_ => 1 } (
109 @source_no_preprocess,
111 my %extensions_compile = map { $_ => 1 } (
112 @source_preprocess_compile,
113 @source_no_preprocess_compile,
115 my %extensions_no_compile = map { $_ => 1 } (
116 @source_preprocess_no_compile,
117 @source_no_preprocess_no_compile,
119 my %extensions_compile_cpp = map { $_ => 1 } (
120 @source_preprocess_compile_cpp,
121 @source_no_preprocess_compile_cpp,
123 my %extension = map { $_ => 1 } (
124 @source_no_preprocess,
125 @source_no_preprocess_compile,
126 @source_no_preprocess_compile_cpp,
127 @source_no_preprocess_no_compile,
130 @source_preprocess_compile,
131 @source_preprocess_compile_cpp,
132 @source_preprocess_no_compile,
135 # Regexp to match file extensions.
136 my $file_extension_regex = qr/
138 \S+ # Filename without extension.
140 ([^\\.\s]+) # File extension.
141 (?=\s|\\) # At end of word. Can't use \b because some files have non
142 # word characters at the end and because \b matches double
143 # extensions (like .cpp.o). Works always as all lines are
144 # terminated with "\n".
147 # Expected (hardening) flags. All flags are used as regexps.
152 my @cflags_format = (
155 '-Werror=format-security',
157 my @cflags_fortify = (
158 # fortify needs at least -O1, but -O2 is recommended anyway
162 '--param=ssp-buffer-size=4',
171 # @cxxflags_* is the same as @cflags_*.
173 my @cppflags_fortify = (
174 '-D_FORTIFY_SOURCE=2',
177 my @ldflags_relro = (
180 my @ldflags_bindnow = (
187 # Renaming rules for the output so the regex parts are not visible.
189 '-O(?:2|3)' => '-O2',
190 '-Wl,(-z,)?relro' => '-Wl,-z,relro',
191 '-Wl,(-z,)?now' => '-Wl,-z,now',
194 # Use colored (ANSI) output?
201 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
203 # Rename flags if requested.
204 my @missing_flags = map {
205 (exists $flag_renames_ref->{$_})
206 ? $flag_renames_ref->{$_}
208 } @{$missing_flags_ref};
210 my $flags = join ' ', @missing_flags;
211 printf "%s (%s)%s %s",
212 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
215 sub error_non_verbose_build {
219 error_color('NONVERBOSE BUILD', 'red'),
220 error_color(':', 'yellow'),
223 sub error_hardening_wrapper {
225 error_color('HARDENING WRAPPER', 'red'),
226 error_color(':', 'yellow'),
227 'no checks possible, aborting';
230 my ($message, $color) = @_;
233 return Term::ANSIColor::colored($message, $color);
240 my ($line, @flags) = @_;
242 foreach my $flag (@flags) {
243 return 1 if $line =~ /\s$flag(?:\s|\\)/;
249 my ($line, $missing_flags_ref, @flags) = @_;
251 my @missing_flags = ();
252 foreach my $flag (@flags) {
253 if ($line !~ /\s$flag(?:\s|\\)/) {
254 push @missing_flags, $flag;
258 return 1 if scalar @missing_flags == 0;
260 @{$missing_flags_ref} = @missing_flags;
264 # Modifies $missing_flags_ref array.
265 sub pic_pie_conflict {
266 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
268 return 0 if not $pie;
269 return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
271 my %flags = map { $_ => 1 } @flags_pie;
273 # Remove all PIE flags from @missing_flags as they are not required with
276 not exists $flags{$_}
277 } @{$missing_flags_ref};
278 @{$missing_flags_ref} = @result;
280 # We got a conflict when no flags are left, thus only PIE flags were
281 # missing. If other flags were missing abort because the conflict is not
283 return scalar @result == 0;
286 sub is_non_verbose_build {
287 my ($line, $next_line, $skip_ref) = @_;
289 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
290 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
291 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
292 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
293 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
299 # On the first pass we only check if this line is verbose or not.
300 return 1 if not defined $next_line;
302 # Second pass, we have access to the next line.
305 # CMake and other build systems print the non-verbose messages also when
306 # building verbose. If a compiler and the file name occurs in the next
307 # line, treat it as verbose build.
309 # Get filename, we can't use the complete path as only parts of it are
310 # used in the real compiler command.
311 $file =~ m{/([a-zA-Z0-9._-]+)$};
314 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/o) {
315 # We still have to skip the current line as it doesn't contain any
325 sub extension_found {
326 my ($extensions_ref, @extensions) = @_;
329 foreach my $extension (@extensions) {
330 if (exists $extensions_ref->{$extension}) {
341 # Hardening options. Not all architectures support all hardening options.
342 my $harden_format = 1;
343 my $harden_fortify = 1;
344 my $harden_stack = 1;
345 my $harden_relro = 1;
346 my $harden_bindnow = 0;
349 # Parse command line arguments.
351 my $option_version = 0;
353 my $option_arch = undef;
354 my $option_buildd = 0;
356 if (not Getopt::Long::GetOptions(
357 'help|h|?' => \$option_help,
358 'version' => \$option_version,
360 'pie' => \$harden_pie,
361 'bindnow' => \$harden_bindnow,
362 'all' => \$option_all,
364 'color' => \$option_color,
365 'arch=s' => \$option_arch,
366 'buildd' => \$option_buildd,
369 Pod::Usage::pod2usage(2);
373 Pod::Usage::pod2usage(1);
375 if ($option_version) {
376 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
378 This program is free software: you can redistribute it and/or modify
379 it under the terms of the GNU General Public License as published by
380 the Free Software Foundation, either version 3 of the License, or
381 (at your option) any later version.
383 This program is distributed in the hope that it will be useful,
384 but WITHOUT ANY WARRANTY; without even the implied warranty of
385 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
386 GNU General Public License for more details.
388 You should have received a copy of the GNU General Public License
389 along with this program. If not, see <http://www.gnu.org/licenses/>.
402 # Input lines, contain only the lines with compiler commands.
406 my $continuation = 0;
407 my $complete_line = undef;
408 while (my $line = <>) {
409 # dpkg-buildflags only provides hardening flags since 1.16.1, don't check
410 # for hardening flags in buildd mode if an older dpkg-dev is used. Default
411 # flags (-g -O2) are still checked.
413 # Packages which were built before 1.16.1 but used their own hardening
414 # flags are not checked.
415 if ($option_buildd and not $start
416 and $line =~ /^Toolchain package versions: /) {
417 require Dpkg::Version;
418 if ($line !~ /dpkg-dev_(\S+)/
419 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
429 # If hardening wrapper is used (wraps calls to gcc and adds hardening
430 # flags automatically) we can't perform any checks, abort.
431 if (not $start and $line =~ /^Build-Depends: .*\bhardening-wrapper\b/) {
432 error_hardening_wrapper();
437 # We skip over unimportant lines at the beginning of the log to prevent
439 $start = 1 if $line =~ /^dpkg-buildpackage:/;
441 # And stop at the end of the build log. Package details (reported by the
442 # buildd logs) are not important for us. This also prevents false
444 last if $line =~ /^Build finished at \d{8}-\d{4}$/;
446 # Detect architecture automatically unless overridden.
448 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
452 # Ignore compiler warnings for now.
453 next if $line =~ /$warning_regex/o;
455 if ($line =~ /\033/) { # esc
456 # Remove all ANSI color sequences which are sometimes used in
457 # non-verbose builds.
458 $line = Term::ANSIColor::colorstrip($line);
459 # Also strip '\0xf' (delete previous character), used by Elinks' build
462 # And "ESC(B" which seems to be used on armhf and hurd (not sure what
464 $line =~ s/\033\(B//g;
467 # Check if this line indicates a non verbose build.
468 my $non_verbose = is_non_verbose_build($line);
470 # One line may contain multiple commands (";"). Treat each one as single
471 # line. parse_line() is slow, only use it when necessary.
472 my @line = (not $line =~ /;/)
474 : Text::ParseWords::parse_line(';', 1, $line);
475 foreach $line (@line) {
476 # Add newline, drop all other whitespace at the end of a line.
483 # Join lines, but leave the "\" in place so it's clear where the
484 # original line break was.
485 chomp $complete_line;
486 $complete_line .= ' ' . $line;
488 # Line continuation, line ends with "\".
489 if ($line =~ /\\\s*$/) {
491 # Start line continuation.
492 if (not defined $complete_line) {
493 $complete_line = $line;
498 if (not $continuation) {
499 # Use the complete line if a line continuation occurred.
500 if (defined $complete_line) {
501 $line = $complete_line;
502 $complete_line = undef;
505 # Ignore lines with no compiler commands.
506 next if $line !~ /\b$cc_regex(?:\s|\\)/o and not $non_verbose;
508 # Ignore false positives.
510 # `./configure` output.
511 next if not $non_verbose
512 and $line =~ /^(?:checking|(?:C|c)onfigure:) /;
513 next if $line =~ /^\s*(?:Host\s+)?(?:C\s+)?
514 (?:C|c)ompiler[\s.]*:?\s+
516 (?:\s-std=[a-z0-9:+]+)?\s*$
518 or $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex\s*$/o
519 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
520 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
522 next if $line =~ /^Making [a-z]+ in \S+/; # e.g. "[...] in c++"
524 # Check if additional hardening options were used. Used to ensure
525 # they are used for the complete build.
526 $harden_pie = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
527 $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
534 if (scalar @input == 0) {
535 print "No compiler commands!\n";
540 # Option or auto detected.
542 # The following was partially copied from dpkg-dev 1.16.1.2
543 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
544 # copyright Raphaƫl Hertzog <hertzog@debian.org>, Kees Cook
545 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
546 # later. Keep it in sync.
549 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
551 # Disable unsupported hardening options.
552 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
555 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
561 # Check the specified hardening options, same order as dpkg-buildflags.
563 @cflags = (@cflags, @cflags_pie);
564 @cxxflags = (@cxxflags, @cflags_pie);
565 @ldflags = (@ldflags, @ldflags_pie);
568 @cflags = (@cflags, @cflags_stack);
569 @cxxflags = (@cxxflags, @cflags_stack);
571 if ($harden_fortify) {
572 @cflags = (@cflags, @cflags_fortify);
573 @cxxflags = (@cxxflags, @cflags_fortify);
574 @cppflags = (@cppflags, @cppflags_fortify);
576 if ($harden_format) {
577 @cflags = (@cflags, @cflags_format);
578 @cxxflags = (@cxxflags, @cflags_format);
581 @ldflags = (@ldflags, @ldflags_relro);
583 if ($harden_bindnow) {
584 @ldflags = (@ldflags, @ldflags_bindnow);
587 for (my $i = 0; $i < scalar @input; $i++) {
588 my $line = $input[$i];
591 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
592 error_non_verbose_build($line);
596 # Even if it's a verbose build, we might have to skip this line.
599 # Remove everything until and including the compiler command. Makes checks
601 $line =~ s/^.*?$cc_regex//o;
603 # Skip unnecessary tests when only preprocessing.
604 my $flag_preprocess = 0;
610 # Preprocess, compile, assemble.
611 if ($line =~ /\s(-E|-S|-c)\b/) {
613 $flag_preprocess = 1 if $1 eq '-E';
614 $compile = 1 if $1 eq '-S' or $1 eq '-c';
615 # Otherwise assume we are linking.
620 # Get all file extensions on this line.
621 my @extensions = $line =~ /$file_extension_regex/go;
622 # Ignore all unknown extensions to speedup the search below.
623 @extensions = grep { exists $extension{$_} } @extensions;
625 # These file types don't require preprocessing.
626 if (extension_found(\%extensions_no_preprocess, @extensions)) {
629 # These file types require preprocessing.
630 if (extension_found(\%extensions_preprocess, @extensions)) {
634 # If there are source files then it's compiling/linking in one step and we
635 # must check both. We only check for source files here, because header
636 # files cause too many false positives.
637 if (not $flag_preprocess
638 and extension_found(\%extensions_compile_link, @extensions)) {
639 # Assembly files don't need CFLAGS.
640 if (not extension_found(\%extensions_compile, @extensions)
641 and extension_found(\%extensions_no_compile, @extensions)) {
649 # Assume CXXFLAGS are required when a C++ file is specified in the
653 and extension_found(\%extensions_compile_cpp, @extensions)) {
658 # Check hardening flags.
660 if ($compile and not all_flags_used($line, \@missing, @cflags)
661 # Libraries linked with -fPIC don't have to (and can't) be linked
662 # with -fPIE as well. It's no error if only PIE flags are missing.
663 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)
664 # Assume dpkg-buildflags returns the correct flags.
665 and not $line =~ /`dpkg-buildflags --get CFLAGS`/) {
666 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
668 } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
669 # Libraries linked with -fPIC don't have to (and can't) be linked
670 # with -fPIE as well. It's no error if only PIE flags are missing.
671 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)
672 # Assume dpkg-buildflags returns the correct flags.
673 and not $line =~ /`dpkg-buildflags --get CXXFLAGS`/) {
674 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
677 if ($preprocess and not all_flags_used($line, \@missing, @cppflags)
678 # Assume dpkg-buildflags returns the correct flags.
679 and not $line =~ /`dpkg-buildflags --get CPPFLAGS`/) {
680 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
683 if ($link and not all_flags_used($line, \@missing, @ldflags)
684 # Same here, -fPIC conflicts with -fPIE.
685 and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)
686 # Assume dpkg-buildflags returns the correct flags.
687 and not $line =~ /`dpkg-buildflags --get LDFLAGS`/) {
688 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
700 blhc - build log hardening check, checks build logs for missing hardening flags
704 B<blhc> [options] <dpkg-buildpackage build log file>
706 --all force +all (+pie, +bindnow) check
707 --arch set architecture (autodetected)
708 --bindnow force +bindbow check
709 --buildd parser mode for buildds
710 --color use colored output
711 --pie force +pie check
712 --help available options
713 --version version number and license
717 blhc is a small tool which checks build logs for missing hardening flags and
718 other important warnings. It's licensed under the GPL 3 or later.
726 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
731 Set the specific architecture (e.g. amd64, armel, etc.), automatically
732 disables hardening flags not available on this architecture. Is detected
733 automatically if dpkg-buildpackage is used.
737 Force check for all +bindnow hardening flags. By default it's auto detected.
741 Special mode for buildds when automatically parsing log files. The following
742 changes are in effect:
748 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
755 Use colored (ANSI) output for warning messages.
759 Force check for all +pie hardening flags. By default it's auto detected.
761 =item B<-h -? --help>
763 Print available options.
767 Print version number and license.
771 Auto detection for B<--pie> and B<--bindnow> only works if at least one
772 command uses the required hardening flag (e.g. -fPIE). Then it's required for
773 all other commands as well.
777 The exit status is a "bit mask", each listed status is ORed when the error
778 condition occurs to get the result.
788 No compiler commands were found.
792 Invalid arguments/options given to blhc.
800 Missing hardening flags.
804 Hardening wrapper detected, no tests performed.
810 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
812 =head1 COPYRIGHT AND LICENSE
814 Copyright (C) 2012 by Simon Ruderich
816 This program is free software: you can redistribute it and/or modify
817 it under the terms of the GNU General Public License as published by
818 the Free Software Foundation, either version 3 of the License, or
819 (at your option) any later version.
821 This program is distributed in the hope that it will be useful,
822 but WITHOUT ANY WARRANTY; without even the implied warranty of
823 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
824 GNU General Public License for more details.
826 You should have received a copy of the GNU General Public License
827 along with this program. If not, see <http://www.gnu.org/licenses/>.