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 = (
178 # @def_cxxflags_* is the same as @def_cflags_*.
179 my @def_cppflags = ();
180 my @def_cppflags_fortify = (
181 '-D_FORTIFY_SOURCE=2',
183 my @def_ldflags = ();
184 my @def_ldflags_relro = (
187 my @def_ldflags_bindnow = (
190 my @def_ldflags_pie = (
194 # Renaming rules for the output so the regex parts are not visible.
196 '-O(?:2|3)' => '-O2',
197 '-Wl,(-z,)?relro' => '-Wl,-z,relro',
198 '-Wl,(-z,)?now' => '-Wl,-z,now',
201 # Use colored (ANSI) output?
208 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
210 # Rename flags if requested.
211 my @missing_flags = map {
212 (exists $flag_renames_ref->{$_})
213 ? $flag_renames_ref->{$_}
215 } @{$missing_flags_ref};
217 my $flags = join ' ', @missing_flags;
218 printf "%s (%s)%s %s",
219 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
222 sub error_non_verbose_build {
226 error_color('NONVERBOSE BUILD', 'red'),
227 error_color(':', 'yellow'),
230 sub error_hardening_wrapper {
232 error_color('HARDENING WRAPPER', 'red'),
233 error_color(':', 'yellow'),
234 'no checks possible, aborting';
237 my ($message, $color) = @_;
240 return Term::ANSIColor::colored($message, $color);
247 my ($line, @flags) = @_;
249 foreach my $flag (@flags) {
250 return 1 if $line =~ /\s$flag(?:\s|\\)/;
256 my ($line, $missing_flags_ref, @flags) = @_;
258 my @missing_flags = ();
259 foreach my $flag (@flags) {
260 if ($line !~ /\s$flag(?:\s|\\)/) {
261 push @missing_flags, $flag;
265 return 1 if scalar @missing_flags == 0;
267 @{$missing_flags_ref} = @missing_flags;
271 # Modifies $missing_flags_ref array.
272 sub pic_pie_conflict {
273 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
275 return 0 if not $pie;
276 return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
278 my %flags = map { $_ => 1 } @flags_pie;
280 # Remove all PIE flags from @missing_flags as they are not required with
283 not exists $flags{$_}
284 } @{$missing_flags_ref};
285 @{$missing_flags_ref} = @result;
287 # We got a conflict when no flags are left, thus only PIE flags were
288 # missing. If other flags were missing abort because the conflict is not
290 return scalar @result == 0;
293 sub is_non_verbose_build {
294 my ($line, $next_line, $skip_ref) = @_;
296 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
297 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
298 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
299 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
300 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
306 # On the first pass we only check if this line is verbose or not.
307 return 1 if not defined $next_line;
309 # Second pass, we have access to the next line.
312 # CMake and other build systems print the non-verbose messages also when
313 # building verbose. If a compiler and the file name occurs in the next
314 # line, treat it as verbose build.
316 # Get filename, we can't use the complete path as only parts of it are
317 # used in the real compiler command.
318 $file =~ m{/([a-zA-Z0-9._-]+)$};
321 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/o) {
322 # We still have to skip the current line as it doesn't contain any
332 sub extension_found {
333 my ($extensions_ref, @extensions) = @_;
336 foreach my $extension (@extensions) {
337 if (exists $extensions_ref->{$extension}) {
348 # Parse command line arguments.
350 my $option_version = 0;
352 my $option_bindnow = 0;
354 my $option_arch = undef;
355 my $option_buildd = 0;
357 if (not Getopt::Long::GetOptions(
358 'help|h|?' => \$option_help,
359 'version' => \$option_version,
361 'pie' => \$option_pie,
362 'bindnow' => \$option_bindnow,
363 'all' => \$option_all,
365 'color' => \$option_color,
366 'arch=s' => \$option_arch,
367 'buildd' => \$option_buildd,
370 Pod::Usage::pod2usage(2);
374 Pod::Usage::pod2usage(1);
376 if ($option_version) {
377 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
379 This program is free software: you can redistribute it and/or modify
380 it under the terms of the GNU General Public License as published by
381 the Free Software Foundation, either version 3 of the License, or
382 (at your option) any later version.
384 This program is distributed in the hope that it will be useful,
385 but WITHOUT ANY WARRANTY; without even the implied warranty of
386 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
387 GNU General Public License for more details.
389 You should have received a copy of the GNU General Public License
390 along with this program. If not, see <http://www.gnu.org/licenses/>.
403 FILE: foreach my $file (@ARGV) {
404 open my $fh, '<', $file or die "$!: $file";
406 # Hardening options. Not all architectures support all hardening options.
407 my $harden_format = 1;
408 my $harden_fortify = 1;
409 my $harden_stack = 1;
410 my $harden_relro = 1;
411 my $harden_bindnow = $option_bindnow; # defaults to 0
412 my $harden_pie = $option_pie; # defaults to 0
414 while (my $line = <$fh>) {
415 # dpkg-buildflags only provides hardening flags since 1.16.1, don't
416 # check for hardening flags in buildd mode if an older dpkg-dev is
417 # used. Default flags (-g -O2) are still checked.
419 # Packages which were built before 1.16.1 but used their own hardening
420 # flags are not checked.
421 if ($option_buildd and $line =~ /^Toolchain package versions: /) {
422 require Dpkg::Version;
423 if ($line !~ /dpkg-dev_(\S+)/
424 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
434 # If hardening wrapper is used (wraps calls to gcc and adds hardening
435 # flags automatically) we can't perform any checks, abort.
436 if ($line =~ /^Build-Depends: .*\bhardening-wrapper\b/) {
437 error_hardening_wrapper();
442 # We skip over unimportant lines at the beginning of the log to
443 # prevent false positives.
444 last if $line =~ /^dpkg-buildpackage:/;
447 # Input lines, contain only the lines with compiler commands.
450 my $continuation = 0;
451 my $complete_line = undef;
452 while (my $line = <$fh>) {
453 # And stop at the end of the build log. Package details (reported by
454 # the buildd logs) are not important for us. This also prevents false
456 last if $line =~ /^Build finished at \d{8}-\d{4}$/;
458 # Detect architecture automatically unless overridden.
460 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
464 # Ignore compiler warnings for now.
465 next if $line =~ /$warning_regex/o;
467 if ($line =~ /\033/) { # esc
468 # Remove all ANSI color sequences which are sometimes used in
469 # non-verbose builds.
470 $line = Term::ANSIColor::colorstrip($line);
471 # Also strip '\0xf' (delete previous character), used by Elinks'
474 # And "ESC(B" which seems to be used on armhf and hurd (not sure
476 $line =~ s/\033\(B//g;
479 # Check if this line indicates a non verbose build.
480 my $non_verbose = is_non_verbose_build($line);
482 # One line may contain multiple commands (";"). Treat each one as
483 # single line. parse_line() is slow, only use it when necessary.
484 my @line = (not $line =~ /;/)
487 # Ensure newline at the line end - necessary for
488 # correct parsing later.
491 } Text::ParseWords::parse_line(';', 1, $line);
492 foreach $line (@line) {
496 # Join lines, but leave the "\" in place so it's clear where
497 # the original line break was.
498 chomp $complete_line;
499 $complete_line .= ' ' . $line;
501 # Line continuation, line ends with "\".
502 if ($line =~ /\\\s*$/) {
504 # Start line continuation.
505 if (not defined $complete_line) {
506 $complete_line = $line;
511 if (not $continuation) {
512 # Use the complete line if a line continuation occurred.
513 if (defined $complete_line) {
514 $line = $complete_line;
515 $complete_line = undef;
518 # Ignore lines with no compiler commands.
519 next if $line !~ /\b$cc_regex(?:\s|\\)/o and not $non_verbose;
521 # Ignore false positives.
523 # `./configure` output.
524 next if not $non_verbose
525 and $line =~ /^(?:checking|(?:C|c)onfigure:) /;
526 next if $line =~ /^\s*(?:Host\s+)?(?:C\s+)?
527 (?:C|c)ompiler[\s.]*:?\s+
529 (?:\s-std=[a-z0-9:+]+)?\s*$
531 or $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex_full\s*$/o
532 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
533 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
535 next if $line =~ /^Making [a-z]+ in \S+/; # e.g. "[...] in c++"
537 # Check if additional hardening options were used. Used to
538 # ensure they are used for the complete build.
539 $harden_pie = 1 if any_flags_used($line, @def_cflags_pie, @def_ldflags_pie);
540 $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);
549 if (scalar @input == 0) {
550 print "No compiler commands!\n";
555 # Option or auto detected.
557 # The following was partially copied from dpkg-dev 1.16.1.2
558 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
559 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
560 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
561 # later. Keep it in sync.
564 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
566 # Disable unsupported hardening options.
567 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
570 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
577 my @cflags = @def_cflags;
578 my @cxxflags = @def_cxxflags;
579 my @cppflags = @def_cppflags;
580 my @ldflags = @def_ldflags;
581 # Check the specified hardening options, same order as dpkg-buildflags.
583 @cflags = (@cflags, @def_cflags_pie);
584 @cxxflags = (@cxxflags, @def_cflags_pie);
585 @ldflags = (@ldflags, @def_ldflags_pie);
588 @cflags = (@cflags, @def_cflags_stack);
589 @cxxflags = (@cxxflags, @def_cflags_stack);
591 if ($harden_fortify) {
592 @cflags = (@cflags, @def_cflags_fortify);
593 @cxxflags = (@cxxflags, @def_cflags_fortify);
594 @cppflags = (@cppflags, @def_cppflags_fortify);
596 if ($harden_format) {
597 @cflags = (@cflags, @def_cflags_format);
598 @cxxflags = (@cxxflags, @def_cflags_format);
601 @ldflags = (@ldflags, @def_ldflags_relro);
603 if ($harden_bindnow) {
604 @ldflags = (@ldflags, @def_ldflags_bindnow);
607 for (my $i = 0; $i < scalar @input; $i++) {
608 my $line = $input[$i];
611 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
612 error_non_verbose_build($line);
616 # Even if it's a verbose build, we might have to skip this line.
619 # Remove everything until and including the compiler command. Makes
620 # checks easier and faster.
621 $line =~ s/^.*?$cc_regex//o;
623 # Skip unnecessary tests when only preprocessing.
624 my $flag_preprocess = 0;
630 # Preprocess, compile, assemble.
631 if ($line =~ /\s(-E|-S|-c)\b/) {
633 $flag_preprocess = 1 if $1 eq '-E';
634 $compile = 1 if $1 eq '-S' or $1 eq '-c';
635 # Otherwise assume we are linking.
640 # Get all file extensions on this line.
641 my @extensions = $line =~ /$file_extension_regex/go;
642 # Ignore all unknown extensions to speedup the search below.
643 @extensions = grep { exists $extension{$_} } @extensions;
645 # These file types don't require preprocessing.
646 if (extension_found(\%extensions_no_preprocess, @extensions)) {
649 # These file types require preprocessing.
650 if (extension_found(\%extensions_preprocess, @extensions)) {
654 # If there are source files then it's compiling/linking in one step
655 # and we must check both. We only check for source files here, because
656 # header files cause too many false positives.
657 if (not $flag_preprocess
658 and extension_found(\%extensions_compile_link, @extensions)) {
659 # Assembly files don't need CFLAGS.
660 if (not extension_found(\%extensions_compile, @extensions)
661 and extension_found(\%extensions_no_compile, @extensions)) {
669 # Assume CXXFLAGS are required when a C++ file is specified in the
673 and extension_found(\%extensions_compile_cpp, @extensions)) {
678 # Check hardening flags.
680 if ($compile and not all_flags_used($line, \@missing, @cflags)
681 # Libraries linked with -fPIC don't have to (and can't) be
682 # linked with -fPIE as well. It's no error if only PIE flags
684 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
685 # Assume dpkg-buildflags returns the correct flags.
686 and not $line =~ /`dpkg-buildflags --get CFLAGS`/) {
687 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
689 } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
690 # Libraries linked with -fPIC don't have to (and can't) be
691 # linked with -fPIE as well. It's no error if only PIE flags
693 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
694 # Assume dpkg-buildflags returns the correct flags.
695 and not $line =~ /`dpkg-buildflags --get CXXFLAGS`/) {
696 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
699 if ($preprocess and not all_flags_used($line, \@missing, @cppflags)
700 # Assume dpkg-buildflags returns the correct flags.
701 and not $line =~ /`dpkg-buildflags --get CPPFLAGS`/) {
702 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
705 if ($link and not all_flags_used($line, \@missing, @ldflags)
706 # Same here, -fPIC conflicts with -fPIE.
707 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
708 # Assume dpkg-buildflags returns the correct flags.
709 and not $line =~ /`dpkg-buildflags --get LDFLAGS`/) {
710 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
723 blhc - build log hardening check, checks build logs for missing hardening flags
727 B<blhc> [options] <dpkg-buildpackage build log file>..
729 --all force +all (+pie, +bindnow) check
730 --arch set architecture (autodetected)
731 --bindnow force +bindbow check
732 --buildd parser mode for buildds
733 --color use colored output
734 --pie force +pie check
735 --help available options
736 --version version number and license
740 blhc is a small tool which checks build logs for missing hardening flags and
741 other important warnings. It's licensed under the GPL 3 or later.
749 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
754 Set the specific architecture (e.g. amd64, armel, etc.), automatically
755 disables hardening flags not available on this architecture. Is detected
756 automatically if dpkg-buildpackage is used.
760 Force check for all +bindnow hardening flags. By default it's auto detected.
764 Special mode for buildds when automatically parsing log files. The following
765 changes are in effect:
771 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
778 Use colored (ANSI) output for warning messages.
782 Force check for all +pie hardening flags. By default it's auto detected.
784 =item B<-h -? --help>
786 Print available options.
790 Print version number and license.
794 Auto detection for B<--pie> and B<--bindnow> only works if at least one
795 command uses the required hardening flag (e.g. -fPIE). Then it's required for
796 all other commands as well.
800 The exit status is a "bit mask", each listed status is ORed when the error
801 condition occurs to get the result.
811 No compiler commands were found.
815 Invalid arguments/options given to blhc.
823 Missing hardening flags.
827 Hardening wrapper detected, no tests performed.
833 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
835 =head1 COPYRIGHT AND LICENSE
837 Copyright (C) 2012 by Simon Ruderich
839 This program is free software: you can redistribute it and/or modify
840 it under the terms of the GNU General Public License as published by
841 the Free Software Foundation, either version 3 of the License, or
842 (at your option) any later version.
844 This program is distributed in the hope that it will be useful,
845 but WITHOUT ANY WARRANTY; without even the implied warranty of
846 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
847 GNU General Public License for more details.
849 You should have received a copy of the GNU General Public License
850 along with this program. If not, see <http://www.gnu.org/licenses/>.