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_cpp_regex = qr/
43 cc | cp | cxx | cpp | CPP | c\+\+ | C
47 my $source_preprocess_compile_regex = qr/
53 | $source_preprocess_compile_cpp_regex
55 | F | FOR | fpp | FPP | FTN | F90 | F95 | F03 | F08
57 my $source_preprocess_no_compile_regex = qr/
61 my $source_preprocess_regex = qr/
62 $source_preprocess_compile_regex
63 | $source_preprocess_no_compile_regex
65 # Regex for source files which don't require preprocessing.
66 my $source_no_preprocess_compile_cpp_regex = qr/
72 my $source_no_preprocess_compile_regex = qr/
76 | $source_no_preprocess_compile_cpp_regex
80 | f | for | ftn | f90 | f95 | f03 | f08
82 my $source_no_preprocess_no_compile_regex = qr/
86 my $source_no_preprocess_regex = qr/
87 $source_no_preprocess_compile_regex
88 | $source_no_preprocess_no_compile_regex
90 # Regex for header files which require preprocessing.
91 my $header_preprocess_regex = qr/
92 # C, C++, Objective-C, Objective-C++
95 | hh | H | hp | hxx | hpp | HPP | h\+\+ | tcc
97 # Regexps to match files with the given characteristics.
98 my $file_no_preprocess_regex = qr/
100 \.(?: $source_no_preprocess_regex)\b
102 my $file_preprocess_regex = qr/
104 \.(?: $header_preprocess_regex
105 | $source_preprocess_regex)\b
107 my $file_compile_link_regex = qr/
109 \.(?: $source_preprocess_regex
110 | $source_no_preprocess_regex)\b
112 my $file_compile_regex = qr/
114 \.(?: $source_preprocess_compile_regex
115 | $source_no_preprocess_compile_regex)\b
117 my $file_no_compile_regex = qr/
119 \.(?: $source_preprocess_no_compile_regex
120 | $source_no_preprocess_no_compile_regex)\b
122 my $file_compile_cpp_regex = qr/
124 \.(?: $source_preprocess_compile_cpp_regex
125 | $source_no_preprocess_compile_cpp_regex)\b
128 # Expected (hardening) flags. All flags are used as regexps.
133 my @cflags_format = (
136 '-Werror=format-security',
138 my @cflags_fortify = (
139 # fortify needs at least -O1, but -O2 is recommended anyway
143 '--param=ssp-buffer-size=4',
152 # @cxxflags_* is the same as @cflags_*.
154 my @cppflags_fortify = (
155 '-D_FORTIFY_SOURCE=2',
158 my @ldflags_relro = (
161 my @ldflags_bindnow = (
168 # Renaming rules for the output so the regex parts are not visible.
170 '-O(?:2|3)' => '-O2',
171 '-Wl,(-z,)?relro' => '-Wl,-z,relro',
172 '-Wl,(-z,)?now' => '-Wl,-z,now',
175 # Use colored (ANSI) output?
182 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
184 # Rename flags if requested.
185 my @missing_flags = map {
186 (exists $flag_renames_ref->{$_})
187 ? $flag_renames_ref->{$_}
189 } @{$missing_flags_ref};
191 my $flags = join ' ', @missing_flags;
192 printf "%s (%s)%s %s",
193 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
196 sub error_non_verbose_build {
200 error_color('NONVERBOSE BUILD', 'red'),
201 error_color(':', 'yellow'),
204 sub error_hardening_wrapper {
206 error_color('HARDENING WRAPPER', 'red'),
207 error_color(':', 'yellow'),
208 'no checks possible, aborting';
211 my ($message, $color) = @_;
214 return Term::ANSIColor::colored($message, $color);
221 my ($line, @flags) = @_;
223 foreach my $flag (@flags) {
224 return 1 if $line =~ /\s$flag(?:\s|\\)/;
230 my ($line, $missing_flags_ref, @flags) = @_;
232 my @missing_flags = ();
233 foreach my $flag (@flags) {
234 if ($line !~ /\s$flag(?:\s|\\)/) {
235 push @missing_flags, $flag;
239 return 1 if scalar @missing_flags == 0;
241 @{$missing_flags_ref} = @missing_flags;
245 # Modifies $missing_flags_ref array.
246 sub pic_pie_conflict {
247 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
249 return 0 if not $pie;
250 return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
252 my %flags = map { $_ => 1 } @flags_pie;
254 # Remove all PIE flags from @missing_flags as they are not required with
257 not exists $flags{$_}
258 } @{$missing_flags_ref};
259 @{$missing_flags_ref} = @result;
261 # We got a conflict when no flags are left, thus only PIE flags were
262 # missing. If other flags were missing abort because the conflict is not
264 return scalar @result == 0;
267 sub is_non_verbose_build {
268 my ($line, $next_line, $skip_ref) = @_;
270 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
271 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
272 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
273 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
274 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
280 # On the first pass we only check if this line is verbose or not.
281 return 1 if not defined $next_line;
283 # Second pass, we have access to the next line.
286 # CMake and other build systems print the non-verbose messages also when
287 # building verbose. If a compiler and the file name occurs in the next
288 # line, treat it as verbose build.
290 # Get filename, we can't use the complete path as only parts of it are
291 # used in the real compiler command.
292 $file =~ m{/([a-zA-Z0-9._-]+)$};
295 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/) {
296 # We still have to skip the current line as it doesn't contain any
309 # Hardening options. Not all architectures support all hardening options.
310 my $harden_format = 1;
311 my $harden_fortify = 1;
312 my $harden_stack = 1;
313 my $harden_relro = 1;
314 my $harden_bindnow = 0;
317 # Parse command line arguments.
319 my $option_version = 0;
321 my $option_arch = undef;
322 my $option_buildd = 0;
324 if (not Getopt::Long::GetOptions(
325 'help|h|?' => \$option_help,
326 'version' => \$option_version,
328 'pie' => \$harden_pie,
329 'bindnow' => \$harden_bindnow,
330 'all' => \$option_all,
332 'color' => \$option_color,
333 'arch=s' => \$option_arch,
334 'buildd' => \$option_buildd,
337 Pod::Usage::pod2usage(2);
341 Pod::Usage::pod2usage(1);
343 if ($option_version) {
344 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
346 This program is free software: you can redistribute it and/or modify
347 it under the terms of the GNU General Public License as published by
348 the Free Software Foundation, either version 3 of the License, or
349 (at your option) any later version.
351 This program is distributed in the hope that it will be useful,
352 but WITHOUT ANY WARRANTY; without even the implied warranty of
353 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
354 GNU General Public License for more details.
356 You should have received a copy of the GNU General Public License
357 along with this program. If not, see <http://www.gnu.org/licenses/>.
370 # Input lines, contain only the lines with compiler commands.
374 my $continuation = 0;
375 my $complete_line = undef;
376 while (my $line = <>) {
377 # dpkg-buildflags only provides hardening flags since 1.16.1, don't check
378 # for hardening flags in buildd mode if an older dpkg-dev is used. Default
379 # flags (-g -O2) are still checked.
381 # Packages which were built before 1.16.1 but used their own hardening
382 # flags are not checked.
383 if ($option_buildd and not $start
384 and $line =~ /^Toolchain package versions: /) {
385 require Dpkg::Version;
386 if ($line !~ /dpkg-dev_(\S+)/
387 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
397 # If hardening wrapper is used (wraps calls to gcc and adds hardening
398 # flags automatically) we can't perform any checks, abort.
399 if (not $start and $line =~ /^Build-Depends: .*\bhardening-wrapper\b/) {
400 error_hardening_wrapper();
405 # We skip over unimportant lines at the beginning of the log to prevent
407 $start = 1 if $line =~ /^dpkg-buildpackage:/;
409 # And stop at the end of the build log. Package details (reported by the
410 # buildd logs) are not important for us. This also prevents false
412 last if $line =~ /^Build finished at \d{8}-\d{4}$/;
414 # Detect architecture automatically unless overridden.
416 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
420 # Ignore compiler warnings for now.
421 next if $line =~ /$warning_regex/;
423 # Remove all ANSI color sequences which are sometimes used in non-verbose
425 $line = Term::ANSIColor::colorstrip($line);
426 # Also strip '\0xf' (delete previous character), used by Elinks' build
429 # And "ESC(B" which seems to be used on armhf and hurd (not sure what it
431 $line =~ s/\033\(B//g;
433 # Check if this line indicates a non verbose build.
434 my $non_verbose = is_non_verbose_build($line);
436 # One line may contain multiple commands (";"). Treat each one as single
437 # line. parse_line() is slow, only use it when necessary.
438 my @line = (not $line =~ /;/)
440 : Text::ParseWords::parse_line(';', 1, $line);
441 foreach $line (@line) {
442 # Add newline, drop all other whitespace at the end of a line.
449 # Join lines, but leave the "\" in place so it's clear where the
450 # original line break was.
451 chomp $complete_line;
452 $complete_line .= ' ' . $line;
454 # Line continuation, line ends with "\".
455 if ($line =~ /\\\s*$/) {
457 # Start line continuation.
458 if (not defined $complete_line) {
459 $complete_line = $line;
464 if (not $continuation) {
465 # Use the complete line if a line continuation occurred.
466 if (defined $complete_line) {
467 $line = $complete_line;
468 $complete_line = undef;
471 # Ignore lines with no compiler commands.
472 next if $line !~ /\b$cc_regex(?:\s|\\)/ and not $non_verbose;
474 # Ignore false positives.
476 # `./configure` output.
477 next if not $non_verbose
478 and $line =~ /^(?:checking|(?:C|c)onfigure:) /;
479 next if $line =~ /^\s*(?:Host\s+)?(?:C\s+)?
480 (?:C|c)ompiler[\s.]*:?\s+
482 (?:\s-std=[a-z0-9:+]+)?\s*$
484 or $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex\s*$/
485 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
486 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
488 next if $line =~ /^Making [a-z]+ in \S+/; # e.g. "[...] in c++"
490 # Check if additional hardening options were used. Used to ensure
491 # they are used for the complete build.
492 $harden_pie = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
493 $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
500 if (scalar @input == 0) {
501 print "No compiler commands!\n";
506 # Option or auto detected.
508 # The following was partially copied from dpkg-dev 1.16.1.2
509 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
510 # copyright Raphaƫl Hertzog <hertzog@debian.org>, Kees Cook
511 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
512 # later. Keep it in sync.
515 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
517 # Disable unsupported hardening options.
518 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
521 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
527 # Check the specified hardening options, same order as dpkg-buildflags.
529 @cflags = (@cflags, @cflags_pie);
530 @cxxflags = (@cxxflags, @cflags_pie);
531 @ldflags = (@ldflags, @ldflags_pie);
534 @cflags = (@cflags, @cflags_stack);
535 @cxxflags = (@cxxflags, @cflags_stack);
537 if ($harden_fortify) {
538 @cflags = (@cflags, @cflags_fortify);
539 @cxxflags = (@cxxflags, @cflags_fortify);
540 @cppflags = (@cppflags, @cppflags_fortify);
542 if ($harden_format) {
543 @cflags = (@cflags, @cflags_format);
544 @cxxflags = (@cxxflags, @cflags_format);
547 @ldflags = (@ldflags, @ldflags_relro);
549 if ($harden_bindnow) {
550 @ldflags = (@ldflags, @ldflags_bindnow);
553 for (my $i = 0; $i < scalar @input; $i++) {
554 my $line = $input[$i];
557 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
558 error_non_verbose_build($line);
562 # Even if it's a verbose build, we might have to skip this line.
565 # Skip unnecessary tests when only preprocessing.
566 my $flag_preprocess = 0;
572 # Preprocess, compile, assemble.
573 if ($line =~ /$cc_regex.*?\s(-E|-S|-c)\b/) {
575 $flag_preprocess = 1 if $1 eq '-E';
576 $compile = 1 if $1 eq '-S' or $1 eq '-c';
577 # Otherwise assume we are linking.
582 # These file types don't require preprocessing.
583 if ($line =~ /$file_no_preprocess_regex/) {
586 # These file types require preprocessing.
587 if ($line =~ /$file_preprocess_regex/) {
591 # If there are source files then it's compiling/linking in one step and we
592 # must check both. We only check for source files here, because header
593 # files cause too many false positives.
594 if (not $flag_preprocess and $line =~ /$file_compile_link_regex/) {
595 # Assembly files don't need CFLAGS.
596 if (not $line =~ /$file_compile_regex/
597 and $line =~ /$file_no_compile_regex/) {
605 # Assume CXXFLAGS are required when a C++ file is specified in the
608 if ($compile and $line =~ /$file_compile_cpp_regex/) {
613 # Check hardening flags.
615 if ($compile and not all_flags_used($line, \@missing, @cflags)
616 # Libraries linked with -fPIC don't have to (and can't) be linked
617 # with -fPIE as well. It's no error if only PIE flags are missing.
618 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)
619 # Assume dpkg-buildflags returns the correct flags.
620 and not $line =~ /`dpkg-buildflags --get CFLAGS`/) {
621 error_flags('CFLAGS missing', \@missing, \%flag_renames, $line);
623 } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
624 # Libraries linked with -fPIC don't have to (and can't) be linked
625 # with -fPIE as well. It's no error if only PIE flags are missing.
626 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)
627 # Assume dpkg-buildflags returns the correct flags.
628 and not $line =~ /`dpkg-buildflags --get CXXFLAGS`/) {
629 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $line);
632 if ($preprocess and not all_flags_used($line, \@missing, @cppflags)
633 # Assume dpkg-buildflags returns the correct flags.
634 and not $line =~ /`dpkg-buildflags --get CPPFLAGS`/) {
635 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $line);
638 if ($link and not all_flags_used($line, \@missing, @ldflags)
639 # Same here, -fPIC conflicts with -fPIE.
640 and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)
641 # Assume dpkg-buildflags returns the correct flags.
642 and not $line =~ /`dpkg-buildflags --get LDFLAGS`/) {
643 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $line);
655 blhc - build log hardening check, checks build logs for missing hardening flags
659 B<blhc> [options] <dpkg-buildpackage build log file>
661 --all force +all (+pie, +bindnow) check
662 --arch set architecture (autodetected)
663 --bindnow force +bindbow check
664 --buildd parser mode for buildds
665 --color use colored output
666 --pie force +pie check
667 --help available options
668 --version version number and license
672 blhc is a small tool which checks build logs for missing hardening flags and
673 other important warnings. It's licensed under the GPL 3 or later.
681 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
686 Set the specific architecture (e.g. amd64, armel, etc.), automatically
687 disables hardening flags not available on this architecture. Is detected
688 automatically if dpkg-buildpackage is used.
692 Force check for all +bindnow hardening flags. By default it's auto detected.
696 Special mode for buildds when automatically parsing log files. The following
697 changes are in effect:
703 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
710 Use colored (ANSI) output for warning messages.
714 Force check for all +pie hardening flags. By default it's auto detected.
716 =item B<-h -? --help>
718 Print available options.
722 Print version number and license.
726 Auto detection for B<--pie> and B<--bindnow> only works if at least one
727 command uses the required hardening flag (e.g. -fPIE). Then it's required for
728 all other commands as well.
732 The exit status is a "bit mask", each listed status is ORed when the error
733 condition occurs to get the result.
743 No compiler commands were found.
747 Invalid arguments/options given to blhc.
755 Missing hardening flags.
759 Hardening wrapper detected, no tests performed.
765 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
767 =head1 COPYRIGHT AND LICENSE
769 Copyright (C) 2012 by Simon Ruderich
771 This program is free software: you can redistribute it and/or modify
772 it under the terms of the GNU General Public License as published by
773 the Free Software Foundation, either version 3 of the License, or
774 (at your option) any later version.
776 This program is distributed in the hope that it will be useful,
777 but WITHOUT ANY WARRANTY; without even the implied warranty of
778 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
779 GNU General Public License for more details.
781 You should have received a copy of the GNU General Public License
782 along with this program. If not, see <http://www.gnu.org/licenses/>.