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'),
184 my ($message, $color) = @_;
186 # Use colors when writing to a terminal.
188 return Term::ANSIColor::colored($message, $color);
195 my ($line, @flags) = @_;
197 foreach my $flag (@flags) {
198 return 1 if $line =~ /\s$flag(?:\s|\\)/;
204 my ($line, $missing_flags_ref, @flags) = @_;
206 my @missing_flags = ();
207 foreach my $flag (@flags) {
208 if ($line !~ /\s$flag(?:\s|\\)/) {
209 push @missing_flags, $flag;
213 return 1 if scalar @missing_flags == 0;
215 @{$missing_flags_ref} = @missing_flags;
219 # Modifies $missing_flags_ref array.
220 sub pic_pie_conflict {
221 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
223 return 0 if not $pie;
224 return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
226 my %flags = map { $_ => 1 } @flags_pie;
228 # Remove all PIE flags from @missing_flags as they are not required with
231 not exists $flags{$_}
232 } @{$missing_flags_ref};
233 @{$missing_flags_ref} = @result;
235 # We got a conflict when no flags are left, thus only PIE flags were
236 # missing. If other flags were missing abort because the conflict is not
238 return scalar @result == 0;
241 sub is_non_verbose_build {
242 my ($line, $next_line, $skip_ref) = @_;
244 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
245 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
246 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
247 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
248 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
254 # On the first pass we only check if this line is verbose or not.
255 return 1 if not defined $next_line;
257 # Second pass, we have access to the next line.
260 # CMake and other build systems print the non-verbose messages also when
261 # building verbose. If a compiler and the file name occurs in the next
262 # line, treat it as verbose build.
264 # Get filename, we can't use the complete path as only parts of it are
265 # used in the real compiler command.
266 $file =~ m{/([a-zA-Z0-9._-]+)$};
269 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/) {
270 # We still have to skip the current line as it doesn't contain any
283 # Hardening options. Not all architectures support all hardening options.
284 my $harden_format = 1;
285 my $harden_fortify = 1;
286 my $harden_stack = 1;
287 my $harden_relro = 1;
288 my $harden_bindnow = 0;
291 # Parse command line arguments.
293 my $option_version = 0;
295 my $option_arch = undef;
296 my $option_buildd = 0;
297 if (not Getopt::Long::GetOptions(
298 'help|h|?' => \$option_help,
299 'version' => \$option_version,
301 'pie' => \$harden_pie,
302 'bindnow' => \$harden_bindnow,
303 'all' => \$option_all,
305 'arch' => \$option_arch,
306 'buildd' => \$option_buildd,
309 Pod::Usage::pod2usage(2);
313 Pod::Usage::pod2usage(1);
315 if ($option_version) {
316 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
318 This program is free software: you can redistribute it and/or modify
319 it under the terms of the GNU General Public License as published by
320 the Free Software Foundation, either version 3 of the License, or
321 (at your option) any later version.
323 This program is distributed in the hope that it will be useful,
324 but WITHOUT ANY WARRANTY; without even the implied warranty of
325 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
326 GNU General Public License for more details.
328 You should have received a copy of the GNU General Public License
329 along with this program. If not, see <http://www.gnu.org/licenses/>.
342 # Input lines, contain only the lines with compiler commands.
346 my $continuation = 0;
347 my $complete_line = undef;
348 while (my $line = <>) {
349 # dpkg-buildflags only provides hardening flags since 1.16.1, don't check
350 # for hardening flags in buildd mode if an older dpkg-dev is used. Default
351 # flags (-g -O2) are still checked.
353 # Packages which were built before 1.16.1 but used their own hardening
354 # flags are not checked.
355 if ($option_buildd and not $start
356 and $line =~ /^Toolchain package versions: /) {
357 require Dpkg::Version;
358 if ($line !~ /dpkg-dev_(\S+)/
359 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
369 # We skip over unimportant lines at the beginning of the log to prevent
371 $start = 1 if $line =~ /^dpkg-buildpackage:/;
374 # Detect architecture automatically unless overridden.
376 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
380 # Ignore compiler warnings for now.
381 next if $line =~ /$warning_regex/;
383 # Remove all ANSI color sequences which are sometimes used in non-verbose
385 $line = Term::ANSIColor::colorstrip($line);
386 # Also strip '\0xf' (delete previous character), used by Elinks' build
389 # And "ESC(B" which seems to be used on armhf and hurd (not sure what it
391 $line =~ s/\033\(B//g;
393 # Check if this line indicates a non verbose build.
394 my $non_verbose = is_non_verbose_build($line);
396 # One line may contain multiple commands (";"). Treat each one as single
397 # line. parse_line() is slow, only use it when necessary.
398 my @line = (not $line =~ /;/)
400 : Text::ParseWords::parse_line(';', 1, $line);
401 foreach $line (@line) {
402 # Add newline, drop all other whitespace at the end of a line.
409 # Join lines, but leave the "\" in place so it's clear where the
410 # original line break was.
411 chomp $complete_line;
412 $complete_line .= ' ' . $line;
414 # Line continuation, line ends with "\".
415 if ($line =~ /\\\s*$/) {
417 # Start line continuation.
418 if (not defined $complete_line) {
419 $complete_line = $line;
424 if (not $continuation) {
425 # Use the complete line if a line continuation occurred.
426 if (defined $complete_line) {
427 $line = $complete_line;
428 $complete_line = undef;
431 # Ignore lines with no compiler commands.
432 next if $line !~ /\b$cc_regex(?:\s|\\)/ and not $non_verbose;
434 # Ignore false positives.
436 # `./configure` output.
437 next if not $non_verbose and $line =~ /^checking /;
438 next if $line =~ /^\s*(?:Host\s+)?(?:C\s+)?
439 (?:C|c)ompiler[\s.]*:?\s+
441 (?:\s-std=[a-z0-9:+]+)?\s*$
443 or $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex\s*$/
444 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
445 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
446 # Debian buildd output.
447 next if $line =~ /^\s*Depends: .*?$cc_regex.*?$/
448 and $line !~ /\s-./; # option, prevent false negatives
456 if (scalar @input == 0) {
457 print "No compiler commands!\n";
462 # Option or auto detected.
464 # The following was partially copied from dpkg-dev 1.16.1.2
465 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
466 # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
467 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
468 # later. Keep it in sync.
471 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
473 # Disable unsupported hardening options.
474 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
477 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
483 # Check if additional hardening options were used. Used to ensure they are
484 # used for the complete build.
485 foreach my $line (@input) {
486 $harden_pie = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
487 $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
490 # Check the specified hardening options, same order as dpkg-buildflags.
492 @cflags = (@cflags, @cflags_pie);
493 @ldflags = (@ldflags, @ldflags_pie);
496 @cflags = (@cflags, @cflags_stack);
498 if ($harden_fortify) {
499 @cflags = (@cflags, @cflags_fortify);
500 @cppflags = (@cppflags, @cppflags_fortify);
502 if ($harden_format) {
503 @cflags = (@cflags, @cflags_format);
506 @ldflags = (@ldflags, @ldflags_relro);
508 if ($harden_bindnow) {
509 @ldflags = (@ldflags, @ldflags_bindnow);
512 for (my $i = 0; $i < scalar @input; $i++) {
513 my $line = $input[$i];
516 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
517 error_non_verbose_build($line);
521 # Even if it's a verbose build, we might have to skip this line.
524 # Skip unnecessary tests when only preprocessing.
525 my $flag_preprocess = 0;
531 # Preprocess, compile, assemble.
532 if ($line =~ /$cc_regex.*?\s(-E|-S|-c)\b/) {
534 $flag_preprocess = 1 if $1 eq '-E';
535 $compile = 1 if $1 eq '-S' or $1 eq '-c';
536 # Otherwise assume we are linking.
541 # These file types don't require preprocessing.
542 if ($line =~ /$file_no_preprocess_regex/) {
545 # These file types require preprocessing.
546 if ($line =~ /$file_preprocess_regex/) {
550 # If there are source files then it's compiling/linking in one step and we
551 # must check both. We only check for source files here, because header
552 # files cause too many false positives.
553 if (not $flag_preprocess and $line =~ /$file_compile_link_regex/) {
554 # Assembly files don't need CFLAGS.
555 if (not $line =~ /$file_compile_regex/
556 and $line =~ /$file_no_compile_regex/) {
564 # Check hardening flags.
566 if ($compile and not all_flags_used($line, \@missing, @cflags)
567 # Libraries linked with -fPIC don't have to (and can't) be linked
568 # with -fPIE as well. It's no error if only PIE flags are missing.
569 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)) {
570 error_flags('CFLAGS missing', \@missing, \%flag_renames, $line);
573 if ($preprocess and not all_flags_used($line, \@missing, @cppflags)) {
574 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $line);
577 if ($link and not all_flags_used($line, \@missing, @ldflags)
578 # Same here, -fPIC conflicts with -fPIE.
579 and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)) {
580 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $line);
592 blhc - build log hardening check, checks build logs for missing hardening flags
596 B<blhc> [-h -? --help]
598 B<blhc> [--pie] [--bindnow] [--all]
600 --help available options
601 --version version number and license
602 --pie force +pie check
603 --bindnow force +bindbow check
604 --all force +all (+pie, +bindnow) check
605 --arch set architecture (autodetected)
606 --buildd parser mode for buildds
610 blhc is a small tool which checks build logs for missing hardening flags and
611 other important warnings. It's licensed under the GPL 3 or later.
617 =item B<-h -? --help>
619 Print available options.
623 Print version number and license.
627 Force check for all +pie hardening flags. By default it's auto detected.
631 Force check for all +bindnow hardening flags. By default it's auto detected.
635 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
640 Set the specific architecture (e.g. amd64, armel, etc.), automatically
641 disables hardening flags not available on this architecture. Is detected
642 automatically if dpkg-buildpackage is used.
646 Special mode for buildds when automatically parsing log files. The following
647 changes are in effect:
653 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
660 Auto detection for B<--pie> and B<--bindnow> only works if at least one
661 command uses the required hardening flag (e.g. -fPIE). Then it's required for
662 all other commands as well.
666 The exit status is a "bit mask", each listed status is ORed when the error
667 condition occurs to get the result.
677 No compiler commands were found.
681 Invalid arguments/options given to blhc.
689 Missing hardening flags.
695 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
697 =head1 COPYRIGHT AND LICENSE
699 Copyright (C) 2012 by Simon Ruderich
701 This program is free software: you can redistribute it and/or modify
702 it under the terms of the GNU General Public License as published by
703 the Free Software Foundation, either version 3 of the License, or
704 (at your option) any later version.
706 This program is distributed in the hope that it will be useful,
707 but WITHOUT ANY WARRANTY; without even the implied warranty of
708 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
709 GNU General Public License for more details.
711 You should have received a copy of the GNU General Public License
712 along with this program. If not, see <http://www.gnu.org/licenses/>.