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',
161 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
163 # Rename flags if requested.
164 my @missing_flags = map {
165 (exists $flag_renames_ref->{$_})
166 ? $flag_renames_ref->{$_}
168 } @{$missing_flags_ref};
170 my $flags = join ' ', @missing_flags;
171 printf "%s (%s)%s %s",
172 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
175 sub error_non_verbose_build {
179 error_color('NONVERBOSE BUILD', 'red'),
180 error_color(':', 'yellow'),
183 sub error_hardening_wrapper {
185 error_color('HARDENING WRAPPER', 'red'),
186 error_color(':', 'yellow'),
187 'no checks possible, aborting';
190 my ($message, $color) = @_;
192 # Use colors when writing to a terminal.
194 return Term::ANSIColor::colored($message, $color);
201 my ($line, @flags) = @_;
203 foreach my $flag (@flags) {
204 return 1 if $line =~ /\s$flag(?:\s|\\)/;
210 my ($line, $missing_flags_ref, @flags) = @_;
212 my @missing_flags = ();
213 foreach my $flag (@flags) {
214 if ($line !~ /\s$flag(?:\s|\\)/) {
215 push @missing_flags, $flag;
219 return 1 if scalar @missing_flags == 0;
221 @{$missing_flags_ref} = @missing_flags;
225 # Modifies $missing_flags_ref array.
226 sub pic_pie_conflict {
227 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
229 return 0 if not $pie;
230 return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
232 my %flags = map { $_ => 1 } @flags_pie;
234 # Remove all PIE flags from @missing_flags as they are not required with
237 not exists $flags{$_}
238 } @{$missing_flags_ref};
239 @{$missing_flags_ref} = @result;
241 # We got a conflict when no flags are left, thus only PIE flags were
242 # missing. If other flags were missing abort because the conflict is not
244 return scalar @result == 0;
247 sub is_non_verbose_build {
248 my ($line, $next_line, $skip_ref) = @_;
250 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
251 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
252 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
253 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
254 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
260 # On the first pass we only check if this line is verbose or not.
261 return 1 if not defined $next_line;
263 # Second pass, we have access to the next line.
266 # CMake and other build systems print the non-verbose messages also when
267 # building verbose. If a compiler and the file name occurs in the next
268 # line, treat it as verbose build.
270 # Get filename, we can't use the complete path as only parts of it are
271 # used in the real compiler command.
272 $file =~ m{/([a-zA-Z0-9._-]+)$};
275 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/) {
276 # We still have to skip the current line as it doesn't contain any
289 # Hardening options. Not all architectures support all hardening options.
290 my $harden_format = 1;
291 my $harden_fortify = 1;
292 my $harden_stack = 1;
293 my $harden_relro = 1;
294 my $harden_bindnow = 0;
297 # Parse command line arguments.
299 my $option_version = 0;
301 my $option_arch = undef;
302 my $option_buildd = 0;
303 if (not Getopt::Long::GetOptions(
304 'help|h|?' => \$option_help,
305 'version' => \$option_version,
307 'pie' => \$harden_pie,
308 'bindnow' => \$harden_bindnow,
309 'all' => \$option_all,
311 'arch' => \$option_arch,
312 'buildd' => \$option_buildd,
315 Pod::Usage::pod2usage(2);
319 Pod::Usage::pod2usage(1);
321 if ($option_version) {
322 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
324 This program is free software: you can redistribute it and/or modify
325 it under the terms of the GNU General Public License as published by
326 the Free Software Foundation, either version 3 of the License, or
327 (at your option) any later version.
329 This program is distributed in the hope that it will be useful,
330 but WITHOUT ANY WARRANTY; without even the implied warranty of
331 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
332 GNU General Public License for more details.
334 You should have received a copy of the GNU General Public License
335 along with this program. If not, see <http://www.gnu.org/licenses/>.
348 # Input lines, contain only the lines with compiler commands.
352 my $continuation = 0;
353 my $complete_line = undef;
354 while (my $line = <>) {
355 # dpkg-buildflags only provides hardening flags since 1.16.1, don't check
356 # for hardening flags in buildd mode if an older dpkg-dev is used. Default
357 # flags (-g -O2) are still checked.
359 # Packages which were built before 1.16.1 but used their own hardening
360 # flags are not checked.
361 if ($option_buildd and not $start
362 and $line =~ /^Toolchain package versions: /) {
363 require Dpkg::Version;
364 if ($line !~ /dpkg-dev_(\S+)/
365 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
375 # If hardening wrapper is used (wraps calls to gcc and adds hardening
376 # flags automatically) we can't perform any checks, abort.
377 if (not $start and $line =~ /^Build-Depends: .*\bhardening-wrapper\b/) {
378 error_hardening_wrapper();
383 # We skip over unimportant lines at the beginning of the log to prevent
385 $start = 1 if $line =~ /^dpkg-buildpackage:/;
387 # And stop at the end of the build log. Package details (reported by the
388 # buildd logs) are not important for us. This also prevents false
390 last if $line =~ /^Build finished at \d{8}-\d{4}$/;
392 # Detect architecture automatically unless overridden.
394 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
398 # Ignore compiler warnings for now.
399 next if $line =~ /$warning_regex/;
401 # Remove all ANSI color sequences which are sometimes used in non-verbose
403 $line = Term::ANSIColor::colorstrip($line);
404 # Also strip '\0xf' (delete previous character), used by Elinks' build
407 # And "ESC(B" which seems to be used on armhf and hurd (not sure what it
409 $line =~ s/\033\(B//g;
411 # Check if this line indicates a non verbose build.
412 my $non_verbose = is_non_verbose_build($line);
414 # One line may contain multiple commands (";"). Treat each one as single
415 # line. parse_line() is slow, only use it when necessary.
416 my @line = (not $line =~ /;/)
418 : Text::ParseWords::parse_line(';', 1, $line);
419 foreach $line (@line) {
420 # Add newline, drop all other whitespace at the end of a line.
427 # Join lines, but leave the "\" in place so it's clear where the
428 # original line break was.
429 chomp $complete_line;
430 $complete_line .= ' ' . $line;
432 # Line continuation, line ends with "\".
433 if ($line =~ /\\\s*$/) {
435 # Start line continuation.
436 if (not defined $complete_line) {
437 $complete_line = $line;
442 if (not $continuation) {
443 # Use the complete line if a line continuation occurred.
444 if (defined $complete_line) {
445 $line = $complete_line;
446 $complete_line = undef;
449 # Ignore lines with no compiler commands.
450 next if $line !~ /\b$cc_regex(?:\s|\\)/ and not $non_verbose;
452 # Ignore false positives.
454 # `./configure` output.
455 next if not $non_verbose
456 and $line =~ /^(?:checking|(?:C|c)onfigure:) /;
457 next if $line =~ /^\s*(?:Host\s+)?(?:C\s+)?
458 (?:C|c)ompiler[\s.]*:?\s+
460 (?:\s-std=[a-z0-9:+]+)?\s*$
462 or $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex\s*$/
463 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
464 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
466 # Check if additional hardening options were used. Used to ensure
467 # they are used for the complete build.
468 $harden_pie = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
469 $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
476 if (scalar @input == 0) {
477 print "No compiler commands!\n";
482 # Option or auto detected.
484 # The following was partially copied from dpkg-dev 1.16.1.2
485 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
486 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
487 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
488 # later. Keep it in sync.
491 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
493 # Disable unsupported hardening options.
494 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
497 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
503 # Check the specified hardening options, same order as dpkg-buildflags.
505 @cflags = (@cflags, @cflags_pie);
506 @ldflags = (@ldflags, @ldflags_pie);
509 @cflags = (@cflags, @cflags_stack);
511 if ($harden_fortify) {
512 @cflags = (@cflags, @cflags_fortify);
513 @cppflags = (@cppflags, @cppflags_fortify);
515 if ($harden_format) {
516 @cflags = (@cflags, @cflags_format);
519 @ldflags = (@ldflags, @ldflags_relro);
521 if ($harden_bindnow) {
522 @ldflags = (@ldflags, @ldflags_bindnow);
525 for (my $i = 0; $i < scalar @input; $i++) {
526 my $line = $input[$i];
529 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
530 error_non_verbose_build($line);
534 # Even if it's a verbose build, we might have to skip this line.
537 # Skip unnecessary tests when only preprocessing.
538 my $flag_preprocess = 0;
544 # Preprocess, compile, assemble.
545 if ($line =~ /$cc_regex.*?\s(-E|-S|-c)\b/) {
547 $flag_preprocess = 1 if $1 eq '-E';
548 $compile = 1 if $1 eq '-S' or $1 eq '-c';
549 # Otherwise assume we are linking.
554 # These file types don't require preprocessing.
555 if ($line =~ /$file_no_preprocess_regex/) {
558 # These file types require preprocessing.
559 if ($line =~ /$file_preprocess_regex/) {
563 # If there are source files then it's compiling/linking in one step and we
564 # must check both. We only check for source files here, because header
565 # files cause too many false positives.
566 if (not $flag_preprocess and $line =~ /$file_compile_link_regex/) {
567 # Assembly files don't need CFLAGS.
568 if (not $line =~ /$file_compile_regex/
569 and $line =~ /$file_no_compile_regex/) {
577 # Check hardening flags.
579 if ($compile and not all_flags_used($line, \@missing, @cflags)
580 # Libraries linked with -fPIC don't have to (and can't) be linked
581 # with -fPIE as well. It's no error if only PIE flags are missing.
582 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)
583 # Assume dpkg-buildflags returns the correct flags.
584 and not $line =~ /`dpkg-buildflags --get (?:CFLAGS|CXXFLAGS)`/) {
585 error_flags('CFLAGS missing', \@missing, \%flag_renames, $line);
588 if ($preprocess and not all_flags_used($line, \@missing, @cppflags)
589 # Assume dpkg-buildflags returns the correct flags.
590 and not $line =~ /`dpkg-buildflags --get CPPFLAGS`/) {
591 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $line);
594 if ($link and not all_flags_used($line, \@missing, @ldflags)
595 # Same here, -fPIC conflicts with -fPIE.
596 and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)
597 # Assume dpkg-buildflags returns the correct flags.
598 and not $line =~ /`dpkg-buildflags --get LDFLAGS`/) {
599 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $line);
611 blhc - build log hardening check, checks build logs for missing hardening flags
615 B<blhc> [-h -? --help]
617 B<blhc> [--pie] [--bindnow] [--all]
619 --help available options
620 --version version number and license
621 --pie force +pie check
622 --bindnow force +bindbow check
623 --all force +all (+pie, +bindnow) check
624 --arch set architecture (autodetected)
625 --buildd parser mode for buildds
629 blhc is a small tool which checks build logs for missing hardening flags and
630 other important warnings. It's licensed under the GPL 3 or later.
636 =item B<-h -? --help>
638 Print available options.
642 Print version number and license.
646 Force check for all +pie hardening flags. By default it's auto detected.
650 Force check for all +bindnow hardening flags. By default it's auto detected.
654 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
659 Set the specific architecture (e.g. amd64, armel, etc.), automatically
660 disables hardening flags not available on this architecture. Is detected
661 automatically if dpkg-buildpackage is used.
665 Special mode for buildds when automatically parsing log files. The following
666 changes are in effect:
672 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
679 Auto detection for B<--pie> and B<--bindnow> only works if at least one
680 command uses the required hardening flag (e.g. -fPIE). Then it's required for
681 all other commands as well.
685 The exit status is a "bit mask", each listed status is ORed when the error
686 condition occurs to get the result.
696 No compiler commands were found.
700 Invalid arguments/options given to blhc.
708 Missing hardening flags.
712 Hardening wrapper detected, no tests performed.
718 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
720 =head1 COPYRIGHT AND LICENSE
722 Copyright (C) 2012 by Simon Ruderich
724 This program is free software: you can redistribute it and/or modify
725 it under the terms of the GNU General Public License as published by
726 the Free Software Foundation, either version 3 of the License, or
727 (at your option) any later version.
729 This program is distributed in the hope that it will be useful,
730 but WITHOUT ANY WARRANTY; without even the implied warranty of
731 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
732 GNU General Public License for more details.
734 You should have received a copy of the GNU General Public License
735 along with this program. If not, see <http://www.gnu.org/licenses/>.