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 ();
27 our $VERSION = '0.01';
32 # Regex to catch compiler commands.
33 my $cc_regex = qr/(?:[a-z0-9_]+-(?:linux|kfreebsd)-gnu(?:eabi|eabihf)?-)?
34 (?:(?<!\.)cc|gcc|g\+\+|c\+\+)
36 # Regex to catch (GCC) compiler warnings.
37 my $warning_regex = qr/^(.+?):([0-9]+):[0-9]+: warning: (.+?) \[(.+?)\]$/;
39 # Regex for source files which require preprocessing.
40 my $source_preprocess_compile_regex = qr/
46 | cc | cp | cxx | cpp | CPP | c\+\+ | C
50 | F | FOR | fpp | FPP | FTN | F90 | F95 | F03 | F08
52 my $source_preprocess_no_compile_regex = qr/
56 my $source_preprocess_regex = qr/
57 $source_preprocess_compile_regex
58 | $source_preprocess_no_compile_regex
60 # Regex for source files which don't require preprocessing.
61 my $source_no_preprocess_compile_regex = qr/
71 | f | for | ftn | f90 | f95 | f03 | f08
73 my $source_no_preprocess_no_compile_regex = qr/
77 my $source_no_preprocess_regex = qr/
78 $source_no_preprocess_compile_regex
79 | $source_no_preprocess_no_compile_regex
81 # Regex for header files which require preprocessing.
82 my $header_preprocess_regex = qr/
83 # C, C++, Objective-C, Objective-C++
86 | hh | H | hp | hxx | hpp | HPP | h\+\+ | tcc
88 # Regexps to match files with the given characteristics.
89 my $file_no_preprocess_regex = qr/
91 \.(?: $source_no_preprocess_regex)\b
93 my $file_preprocess_regex = qr/
95 \.(?: $header_preprocess_regex
96 | $source_preprocess_regex)\b
98 my $file_compile_link_regex = qr/
100 \.(?: $source_preprocess_regex
101 | $source_no_preprocess_regex)\b
103 my $file_compile_regex = qr/
105 \.(?: $source_preprocess_compile_regex
106 | $source_no_preprocess_compile_regex)\b
108 my $file_no_compile_regex = qr/
110 \.(?: $source_preprocess_no_compile_regex
111 | $source_no_preprocess_no_compile_regex)\b
114 # Expected (hardening) flags. All flags are used as regexps.
119 my @cflags_format = (
122 '-Werror=format-security',
124 my @cflags_fortify = (
125 # fortify needs at least -O1, but -O2 is recommended anyway
129 '--param=ssp-buffer-size=4',
135 my @cppflags_fortify = (
136 '-D_FORTIFY_SOURCE=2',
139 my @ldflags_relro = (
142 my @ldflags_bindnow = (
149 # Renaming rules for the output so the regex parts are not visible.
151 '-O(?:2|3)' => '-O2',
152 '-Wl,(-z,)?relro' => '-Wl,-z,relro',
153 '-Wl,(-z,)?now' => '-Wl,-z,now',
160 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
162 # Rename flags if requested.
163 my @missing_flags = map {
164 (exists $flag_renames_ref->{$_})
165 ? $flag_renames_ref->{$_}
167 } @{$missing_flags_ref};
169 my $flags = join ' ', @missing_flags;
170 printf "%s (%s)%s %s",
171 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
174 sub error_non_verbose_build {
178 error_color('NONVERBOSE BUILD', 'red'),
179 error_color(':', 'yellow'),
183 my ($message, $color) = @_;
185 # Use colors when writing to a terminal.
187 return Term::ANSIColor::colored($message, $color);
194 my ($line, @flags) = @_;
196 foreach my $flag (@flags) {
197 return 1 if $line =~ /\s$flag(?:\s|\\)/;
203 my ($line, $missing_flags_ref, @flags) = @_;
205 my @missing_flags = ();
206 foreach my $flag (@flags) {
207 if ($line !~ /\s$flag(?:\s|\\)/) {
208 push @missing_flags, $flag;
212 return 1 if scalar @missing_flags == 0;
214 @{$missing_flags_ref} = @missing_flags;
218 # Modifies $missing_flags_ref array.
219 sub pic_pie_conflict {
220 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
222 return 0 if not $pie;
223 return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
225 my %flags = map { $_ => 1 } @flags_pie;
227 # Remove all PIE flags from @missing_flags as they are not required with
230 not exists $flags{$_}
231 } @{$missing_flags_ref};
232 @{$missing_flags_ref} = @result;
234 # We got a conflict when no flags are left, thus only PIE flags were
235 # missing. If other flags were missing abort because the conflict is not
237 return scalar @result == 0;
240 sub is_non_verbose_build {
241 my ($line, $next_line, $skip_ref) = @_;
243 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
244 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
245 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
246 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
247 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
253 # On the first pass we only check if this line is verbose or not.
254 return 1 if not defined $next_line;
256 # Second pass, we have access to the next line.
259 # CMake and other build systems print the non-verbose messages also when
260 # building verbose. If a compiler and the file name occurs in the next
261 # line, treat it as verbose build.
263 # Get filename, we can't use the complete path as only parts of it are
264 # used in the real compiler command.
265 $file =~ m{/([a-zA-Z0-9._-]+)$};
268 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/) {
269 # We still have to skip the current line as it doesn't contain any
282 # Hardening options. Not all architectures support all hardening options.
283 my $harden_format = 1;
284 my $harden_fortify = 1;
285 my $harden_stack = 1;
286 my $harden_relro = 1;
287 my $harden_bindnow = 0;
290 # Parse command line arguments.
292 my $option_version = 0;
294 my $option_arch = undef;
295 my $option_buildd = 0;
296 if (not Getopt::Long::GetOptions(
297 'help|h|?' => \$option_help,
298 'version' => \$option_version,
300 'pie' => \$harden_pie,
301 'bindnow' => \$harden_bindnow,
302 'all' => \$option_all,
304 'arch' => \$option_arch,
305 'buildd' => \$option_buildd,
308 Pod::Usage::pod2usage(2);
312 Pod::Usage::pod2usage(1);
314 if ($option_version) {
315 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
317 This program is free software: you can redistribute it and/or modify
318 it under the terms of the GNU General Public License as published by
319 the Free Software Foundation, either version 3 of the License, or
320 (at your option) any later version.
322 This program is distributed in the hope that it will be useful,
323 but WITHOUT ANY WARRANTY; without even the implied warranty of
324 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
325 GNU General Public License for more details.
327 You should have received a copy of the GNU General Public License
328 along with this program. If not, see <http://www.gnu.org/licenses/>.
341 # Input lines, contain only the lines with compiler commands.
345 my $continuation = 0;
346 my $complete_line = undef;
347 while (my $line = <>) {
348 # dpkg-buildflags only provides hardening flags since 1.16.1, don't check
349 # for hardening flags in buildd mode if an older dpkg-dev is used. Default
350 # flags (-g -O2) are still checked.
352 # Packages which were built before 1.16.1 but used their own hardening
353 # flags are not checked.
354 if ($option_buildd and not $start
355 and $line =~ /^Toolchain package versions: /) {
356 require Dpkg::Version;
357 if ($line !~ /dpkg-dev_(\S+)/
358 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
368 # We skip over unimportant lines at the beginning of the log to prevent
370 $start = 1 if $line =~ /^dpkg-buildpackage:/;
373 # Detect architecture automatically unless overridden.
375 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
379 # Ignore compiler warnings for now.
380 next if $line =~ /$warning_regex/;
382 # Remove all ANSI color sequences which are sometimes used in non-verbose
384 $line = Term::ANSIColor::colorstrip($line);
385 # Also strip '\0xf' (delete previous character), used by Elinks' build
388 # And "ESC(B" which seems to be used on armhf and hurd (not sure what it
390 $line =~ s/\033\(B//g;
392 # Check if this line indicates a non verbose build.
393 my $non_verbose = is_non_verbose_build($line);
395 # One line may contain multiple commands (";"). Treat each one as single
397 my @line = split /(?<!\\);/, $line;
398 foreach $line (@line) {
399 # Add newline, drop all other whitespace at the end of a line.
406 # Join lines, but leave the "\" in place so it's clear where the
407 # original line break was.
408 chomp $complete_line;
409 $complete_line .= ' ' . $line;
411 # Line continuation, line ends with "\".
412 if ($line =~ /\\\s*$/) {
414 # Start line continuation.
415 if (not defined $complete_line) {
416 $complete_line = $line;
421 if (not $continuation) {
422 # Use the complete line if a line continuation occurred.
423 if (defined $complete_line) {
424 $line = $complete_line;
425 $complete_line = undef;
428 # Ignore lines with no compiler commands.
429 next if $line !~ /\b$cc_regex(?:\s|\\)/ and not $non_verbose;
431 # Ignore false positives.
433 # `./configure` output.
434 next if not $non_verbose and $line =~ /^checking /;
435 next if $line =~ /^\s*(?:Host\s+)?(?:C\s+)?
436 (?:C|c)ompiler[\s.]*:?\s+
438 (?:\s-std=[a-z0-9:+]+)?\s*$
440 or $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex\s*$/
441 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
442 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
443 # Debian buildd output.
444 next if $line =~ /^\s*Depends: .*?$cc_regex.*?$/
445 and $line !~ /\s-./; # option, prevent false negatives
453 if (scalar @input == 0) {
454 print "No compiler commands!\n";
459 # Option or auto detected.
461 # The following was partially copied from dpkg-dev 1.16.1.2
462 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
463 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
464 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
465 # later. Keep it in sync.
468 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
470 # Disable unsupported hardening options.
471 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
474 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
480 # Check if additional hardening options were used. Used to ensure they are
481 # used for the complete build.
482 foreach my $line (@input) {
483 $harden_pie = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
484 $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
487 # Check the specified hardening options, same order as dpkg-buildflags.
489 @cflags = (@cflags, @cflags_pie);
490 @ldflags = (@ldflags, @ldflags_pie);
493 @cflags = (@cflags, @cflags_stack);
495 if ($harden_fortify) {
496 @cflags = (@cflags, @cflags_fortify);
497 @cppflags = (@cppflags, @cppflags_fortify);
499 if ($harden_format) {
500 @cflags = (@cflags, @cflags_format);
503 @ldflags = (@ldflags, @ldflags_relro);
505 if ($harden_bindnow) {
506 @ldflags = (@ldflags, @ldflags_bindnow);
509 for (my $i = 0; $i < scalar @input; $i++) {
510 my $line = $input[$i];
513 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
514 error_non_verbose_build($line);
518 # Even if it's a verbose build, we might have to skip this line.
521 # Skip unnecessary tests when only preprocessing.
522 my $flag_preprocess = 0;
528 # Preprocess, compile, assemble.
529 if ($line =~ /$cc_regex.*?\s(-E|-S|-c)\b/) {
531 $flag_preprocess = 1 if $1 eq '-E';
532 $compile = 1 if $1 eq '-S' or $1 eq '-c';
533 # Otherwise assume we are linking.
538 # These file types don't require preprocessing.
539 if ($line =~ /$file_no_preprocess_regex/) {
542 # These file types require preprocessing.
543 if ($line =~ /$file_preprocess_regex/) {
547 # If there are source files then it's compiling/linking in one step and we
548 # must check both. We only check for source files here, because header
549 # files cause too many false positives.
550 if (not $flag_preprocess and $line =~ /$file_compile_link_regex/) {
551 # Assembly files don't need CFLAGS.
552 if (not $line =~ /$file_compile_regex/
553 and $line =~ /$file_no_compile_regex/) {
561 # Check hardening flags.
563 if ($compile and not all_flags_used($line, \@missing, @cflags)
564 # Libraries linked with -fPIC don't have to (and can't) be linked
565 # with -fPIE as well. It's no error if only PIE flags are missing.
566 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)) {
567 error_flags('CFLAGS missing', \@missing, \%flag_renames, $line);
570 if ($preprocess and not all_flags_used($line, \@missing, @cppflags)) {
571 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $line);
574 if ($link and not all_flags_used($line, \@missing, @ldflags)
575 # Same here, -fPIC conflicts with -fPIE.
576 and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)) {
577 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $line);
589 blhc - build log hardening check, checks build logs for missing hardening flags
593 B<blhc> [-h -? --help]
595 B<blhc> [--pie] [--bindnow] [--all]
597 --help available options
598 --version version number and license
599 --pie force +pie check
600 --bindnow force +bindbow check
601 --all force +all (+pie, +bindnow) check
602 --arch set architecture (autodetected)
603 --buildd parser mode for buildds
607 blhc is a small tool which checks build logs for missing hardening flags and
608 other important warnings. It's licensed under the GPL 3 or later.
614 =item B<-h -? --help>
616 Print available options.
620 Print version number and license.
624 Force check for all +pie hardening flags. By default it's auto detected.
628 Force check for all +bindnow hardening flags. By default it's auto detected.
632 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
637 Set the specific architecture (e.g. amd64, armel, etc.), automatically
638 disables hardening flags not available on this architecture. Is detected
639 automatically if dpkg-buildpackage is used.
643 Special mode for buildds when automatically parsing log files. The following
644 changes are in effect:
650 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
657 Auto detection for B<--pie> and B<--bindnow> only works if at least one
658 command uses the required hardening flag (e.g. -fPIE). Then it's required for
659 all other commands as well.
663 The exit status is a "bit mask", each listed status is ORed when the error
664 condition occurs to get the result.
674 No compiler commands were found.
678 Invalid arguments/options given to blhc.
686 Missing hardening flags.
692 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
694 =head1 COPYRIGHT AND LICENSE
696 Copyright (C) 2012 by Simon Ruderich
698 This program is free software: you can redistribute it and/or modify
699 it under the terms of the GNU General Public License as published by
700 the Free Software Foundation, either version 3 of the License, or
701 (at your option) any later version.
703 This program is distributed in the hope that it will be useful,
704 but WITHOUT ANY WARRANTY; without even the implied warranty of
705 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
706 GNU General Public License for more details.
708 You should have received a copy of the GNU General Public License
709 along with this program. If not, see <http://www.gnu.org/licenses/>.