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 # Regex for source files which require preprocessing.
41 my $source_preprocess_compile_regex = qr/
47 | cc | cp | cxx | cpp | CPP | c\+\+ | C
51 | F | FOR | fpp | FPP | FTN | F90 | F95 | F03 | F08
53 my $source_preprocess_no_compile_regex = qr/
57 my $source_preprocess_regex = qr/
58 $source_preprocess_compile_regex
59 | $source_preprocess_no_compile_regex
61 # Regex for source files which don't require preprocessing.
62 my $source_no_preprocess_compile_regex = qr/
72 | f | for | ftn | f90 | f95 | f03 | f08
74 my $source_no_preprocess_no_compile_regex = qr/
78 my $source_no_preprocess_regex = qr/
79 $source_no_preprocess_compile_regex
80 | $source_no_preprocess_no_compile_regex
82 # Regex for header files which require preprocessing.
83 my $header_preprocess_regex = qr/
84 # C, C++, Objective-C, Objective-C++
87 | hh | H | hp | hxx | hpp | HPP | h\+\+ | tcc
89 # Regexps to match files with the given characteristics.
90 my $file_no_preprocess_regex = qr/
92 \.(?: $source_no_preprocess_regex)\b
94 my $file_preprocess_regex = qr/
96 \.(?: $header_preprocess_regex
97 | $source_preprocess_regex)\b
99 my $file_compile_link_regex = qr/
101 \.(?: $source_preprocess_regex
102 | $source_no_preprocess_regex)\b
104 my $file_compile_regex = qr/
106 \.(?: $source_preprocess_compile_regex
107 | $source_no_preprocess_compile_regex)\b
109 my $file_no_compile_regex = qr/
111 \.(?: $source_preprocess_no_compile_regex
112 | $source_no_preprocess_no_compile_regex)\b
115 # Expected (hardening) flags. All flags are used as regexps.
120 my @cflags_format = (
123 '-Werror=format-security',
125 my @cflags_fortify = (
126 # fortify needs at least -O1, but -O2 is recommended anyway
130 '--param=ssp-buffer-size=4',
136 my @cppflags_fortify = (
137 '-D_FORTIFY_SOURCE=2',
140 my @ldflags_relro = (
143 my @ldflags_bindnow = (
150 # Renaming rules for the output so the regex parts are not visible.
152 '-O(?:2|3)' => '-O2',
153 '-Wl,(-z,)?relro' => '-Wl,-z,relro',
154 '-Wl,(-z,)?now' => '-Wl,-z,now',
157 # Use colored (ANSI) output?
164 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
166 # Rename flags if requested.
167 my @missing_flags = map {
168 (exists $flag_renames_ref->{$_})
169 ? $flag_renames_ref->{$_}
171 } @{$missing_flags_ref};
173 my $flags = join ' ', @missing_flags;
174 printf "%s (%s)%s %s",
175 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
178 sub error_non_verbose_build {
182 error_color('NONVERBOSE BUILD', 'red'),
183 error_color(':', 'yellow'),
186 sub error_hardening_wrapper {
188 error_color('HARDENING WRAPPER', 'red'),
189 error_color(':', 'yellow'),
190 'no checks possible, aborting';
193 my ($message, $color) = @_;
196 return Term::ANSIColor::colored($message, $color);
203 my ($line, @flags) = @_;
205 foreach my $flag (@flags) {
206 return 1 if $line =~ /\s$flag(?:\s|\\)/;
212 my ($line, $missing_flags_ref, @flags) = @_;
214 my @missing_flags = ();
215 foreach my $flag (@flags) {
216 if ($line !~ /\s$flag(?:\s|\\)/) {
217 push @missing_flags, $flag;
221 return 1 if scalar @missing_flags == 0;
223 @{$missing_flags_ref} = @missing_flags;
227 # Modifies $missing_flags_ref array.
228 sub pic_pie_conflict {
229 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
231 return 0 if not $pie;
232 return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
234 my %flags = map { $_ => 1 } @flags_pie;
236 # Remove all PIE flags from @missing_flags as they are not required with
239 not exists $flags{$_}
240 } @{$missing_flags_ref};
241 @{$missing_flags_ref} = @result;
243 # We got a conflict when no flags are left, thus only PIE flags were
244 # missing. If other flags were missing abort because the conflict is not
246 return scalar @result == 0;
249 sub is_non_verbose_build {
250 my ($line, $next_line, $skip_ref) = @_;
252 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
253 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
254 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
255 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
256 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
262 # On the first pass we only check if this line is verbose or not.
263 return 1 if not defined $next_line;
265 # Second pass, we have access to the next line.
268 # CMake and other build systems print the non-verbose messages also when
269 # building verbose. If a compiler and the file name occurs in the next
270 # line, treat it as verbose build.
272 # Get filename, we can't use the complete path as only parts of it are
273 # used in the real compiler command.
274 $file =~ m{/([a-zA-Z0-9._-]+)$};
277 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/) {
278 # We still have to skip the current line as it doesn't contain any
291 # Hardening options. Not all architectures support all hardening options.
292 my $harden_format = 1;
293 my $harden_fortify = 1;
294 my $harden_stack = 1;
295 my $harden_relro = 1;
296 my $harden_bindnow = 0;
299 # Parse command line arguments.
301 my $option_version = 0;
303 my $option_arch = undef;
304 my $option_buildd = 0;
306 if (not Getopt::Long::GetOptions(
307 'help|h|?' => \$option_help,
308 'version' => \$option_version,
310 'pie' => \$harden_pie,
311 'bindnow' => \$harden_bindnow,
312 'all' => \$option_all,
314 'color' => \$option_color,
315 'arch' => \$option_arch,
316 'buildd' => \$option_buildd,
319 Pod::Usage::pod2usage(2);
323 Pod::Usage::pod2usage(1);
325 if ($option_version) {
326 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
328 This program is free software: you can redistribute it and/or modify
329 it under the terms of the GNU General Public License as published by
330 the Free Software Foundation, either version 3 of the License, or
331 (at your option) any later version.
333 This program is distributed in the hope that it will be useful,
334 but WITHOUT ANY WARRANTY; without even the implied warranty of
335 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
336 GNU General Public License for more details.
338 You should have received a copy of the GNU General Public License
339 along with this program. If not, see <http://www.gnu.org/licenses/>.
352 # Input lines, contain only the lines with compiler commands.
356 my $continuation = 0;
357 my $complete_line = undef;
358 while (my $line = <>) {
359 # dpkg-buildflags only provides hardening flags since 1.16.1, don't check
360 # for hardening flags in buildd mode if an older dpkg-dev is used. Default
361 # flags (-g -O2) are still checked.
363 # Packages which were built before 1.16.1 but used their own hardening
364 # flags are not checked.
365 if ($option_buildd and not $start
366 and $line =~ /^Toolchain package versions: /) {
367 require Dpkg::Version;
368 if ($line !~ /dpkg-dev_(\S+)/
369 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
379 # If hardening wrapper is used (wraps calls to gcc and adds hardening
380 # flags automatically) we can't perform any checks, abort.
381 if (not $start and $line =~ /^Build-Depends: .*\bhardening-wrapper\b/) {
382 error_hardening_wrapper();
387 # We skip over unimportant lines at the beginning of the log to prevent
389 $start = 1 if $line =~ /^dpkg-buildpackage:/;
391 # And stop at the end of the build log. Package details (reported by the
392 # buildd logs) are not important for us. This also prevents false
394 last if $line =~ /^Build finished at \d{8}-\d{4}$/;
396 # Detect architecture automatically unless overridden.
398 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
402 # Ignore compiler warnings for now.
403 next if $line =~ /$warning_regex/;
405 # Remove all ANSI color sequences which are sometimes used in non-verbose
407 $line = Term::ANSIColor::colorstrip($line);
408 # Also strip '\0xf' (delete previous character), used by Elinks' build
411 # And "ESC(B" which seems to be used on armhf and hurd (not sure what it
413 $line =~ s/\033\(B//g;
415 # Check if this line indicates a non verbose build.
416 my $non_verbose = is_non_verbose_build($line);
418 # One line may contain multiple commands (";"). Treat each one as single
419 # line. parse_line() is slow, only use it when necessary.
420 my @line = (not $line =~ /;/)
422 : Text::ParseWords::parse_line(';', 1, $line);
423 foreach $line (@line) {
424 # Add newline, drop all other whitespace at the end of a line.
431 # Join lines, but leave the "\" in place so it's clear where the
432 # original line break was.
433 chomp $complete_line;
434 $complete_line .= ' ' . $line;
436 # Line continuation, line ends with "\".
437 if ($line =~ /\\\s*$/) {
439 # Start line continuation.
440 if (not defined $complete_line) {
441 $complete_line = $line;
446 if (not $continuation) {
447 # Use the complete line if a line continuation occurred.
448 if (defined $complete_line) {
449 $line = $complete_line;
450 $complete_line = undef;
453 # Ignore lines with no compiler commands.
454 next if $line !~ /\b$cc_regex(?:\s|\\)/ and not $non_verbose;
456 # Ignore false positives.
458 # `./configure` output.
459 next if not $non_verbose
460 and $line =~ /^(?:checking|(?:C|c)onfigure:) /;
461 next if $line =~ /^\s*(?:Host\s+)?(?:C\s+)?
462 (?:C|c)ompiler[\s.]*:?\s+
464 (?:\s-std=[a-z0-9:+]+)?\s*$
466 or $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex\s*$/
467 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
468 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
470 # Check if additional hardening options were used. Used to ensure
471 # they are used for the complete build.
472 $harden_pie = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
473 $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
480 if (scalar @input == 0) {
481 print "No compiler commands!\n";
486 # Option or auto detected.
488 # The following was partially copied from dpkg-dev 1.16.1.2
489 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
490 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
491 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
492 # later. Keep it in sync.
495 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
497 # Disable unsupported hardening options.
498 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
501 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
507 # Check the specified hardening options, same order as dpkg-buildflags.
509 @cflags = (@cflags, @cflags_pie);
510 @ldflags = (@ldflags, @ldflags_pie);
513 @cflags = (@cflags, @cflags_stack);
515 if ($harden_fortify) {
516 @cflags = (@cflags, @cflags_fortify);
517 @cppflags = (@cppflags, @cppflags_fortify);
519 if ($harden_format) {
520 @cflags = (@cflags, @cflags_format);
523 @ldflags = (@ldflags, @ldflags_relro);
525 if ($harden_bindnow) {
526 @ldflags = (@ldflags, @ldflags_bindnow);
529 for (my $i = 0; $i < scalar @input; $i++) {
530 my $line = $input[$i];
533 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
534 error_non_verbose_build($line);
538 # Even if it's a verbose build, we might have to skip this line.
541 # Skip unnecessary tests when only preprocessing.
542 my $flag_preprocess = 0;
548 # Preprocess, compile, assemble.
549 if ($line =~ /$cc_regex.*?\s(-E|-S|-c)\b/) {
551 $flag_preprocess = 1 if $1 eq '-E';
552 $compile = 1 if $1 eq '-S' or $1 eq '-c';
553 # Otherwise assume we are linking.
558 # These file types don't require preprocessing.
559 if ($line =~ /$file_no_preprocess_regex/) {
562 # These file types require preprocessing.
563 if ($line =~ /$file_preprocess_regex/) {
567 # If there are source files then it's compiling/linking in one step and we
568 # must check both. We only check for source files here, because header
569 # files cause too many false positives.
570 if (not $flag_preprocess and $line =~ /$file_compile_link_regex/) {
571 # Assembly files don't need CFLAGS.
572 if (not $line =~ /$file_compile_regex/
573 and $line =~ /$file_no_compile_regex/) {
581 # Check hardening flags.
583 if ($compile and not all_flags_used($line, \@missing, @cflags)
584 # Libraries linked with -fPIC don't have to (and can't) be linked
585 # with -fPIE as well. It's no error if only PIE flags are missing.
586 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)
587 # Assume dpkg-buildflags returns the correct flags.
588 and not $line =~ /`dpkg-buildflags --get (?:CFLAGS|CXXFLAGS)`/) {
589 error_flags('CFLAGS missing', \@missing, \%flag_renames, $line);
592 if ($preprocess and not all_flags_used($line, \@missing, @cppflags)
593 # Assume dpkg-buildflags returns the correct flags.
594 and not $line =~ /`dpkg-buildflags --get CPPFLAGS`/) {
595 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $line);
598 if ($link and not all_flags_used($line, \@missing, @ldflags)
599 # Same here, -fPIC conflicts with -fPIE.
600 and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)
601 # Assume dpkg-buildflags returns the correct flags.
602 and not $line =~ /`dpkg-buildflags --get LDFLAGS`/) {
603 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $line);
615 blhc - build log hardening check, checks build logs for missing hardening flags
619 B<blhc> [-h -? --help]
621 B<blhc> [--pie] [--bindnow] [--all]
623 --help available options
624 --version version number and license
625 --pie force +pie check
626 --bindnow force +bindbow check
627 --all force +all (+pie, +bindnow) check
628 --arch set architecture (autodetected)
629 --buildd parser mode for buildds
630 --color use colored output
634 blhc is a small tool which checks build logs for missing hardening flags and
635 other important warnings. It's licensed under the GPL 3 or later.
641 =item B<-h -? --help>
643 Print available options.
647 Print version number and license.
651 Force check for all +pie hardening flags. By default it's auto detected.
655 Force check for all +bindnow hardening flags. By default it's auto detected.
659 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
664 Set the specific architecture (e.g. amd64, armel, etc.), automatically
665 disables hardening flags not available on this architecture. Is detected
666 automatically if dpkg-buildpackage is used.
670 Special mode for buildds when automatically parsing log files. The following
671 changes are in effect:
677 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
684 Use colored (ANSI) output for warning messages.
688 Auto detection for B<--pie> and B<--bindnow> only works if at least one
689 command uses the required hardening flag (e.g. -fPIE). Then it's required for
690 all other commands as well.
694 The exit status is a "bit mask", each listed status is ORed when the error
695 condition occurs to get the result.
705 No compiler commands were found.
709 Invalid arguments/options given to blhc.
717 Missing hardening flags.
721 Hardening wrapper detected, no tests performed.
727 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
729 =head1 COPYRIGHT AND LICENSE
731 Copyright (C) 2012 by Simon Ruderich
733 This program is free software: you can redistribute it and/or modify
734 it under the terms of the GNU General Public License as published by
735 the Free Software Foundation, either version 3 of the License, or
736 (at your option) any later version.
738 This program is distributed in the hope that it will be useful,
739 but WITHOUT ANY WARRANTY; without even the implied warranty of
740 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
741 GNU General Public License for more details.
743 You should have received a copy of the GNU General Public License
744 along with this program. If not, see <http://www.gnu.org/licenses/>.