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 # Expected (hardening) flags. All flags are used as regexps.
47 '-Werror=format-security',
49 my @cflags_fortify = (
50 # fortify needs at least -O1, but -O2 is recommended anyway
54 '--param=ssp-buffer-size=4',
60 my @cppflags_fortify = (
61 '-D_FORTIFY_SOURCE=2',
67 my @ldflags_bindnow = (
74 # Renaming rules for the output so the regex parts are not visible.
77 '-Wl,(-z,)?relro' => '-Wl,-z,relro',
78 '-Wl,(-z,)?now' => '-Wl,-z,now',
85 my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
87 # Rename flags if requested.
88 my @missing_flags = map {
89 (exists $flag_renames_ref->{$_})
90 ? $flag_renames_ref->{$_}
92 } @{$missing_flags_ref};
94 my $flags = join ' ', @missing_flags;
95 printf "%s (%s)%s %s",
96 error_color($message, 'red'), $flags, error_color(':', 'yellow'),
99 sub error_non_verbose_build {
103 error_color('NONVERBOSE BUILD', 'red'),
104 error_color(':', 'yellow'),
108 my ($message, $color) = @_;
110 # Use colors when writing to a terminal.
112 return Term::ANSIColor::colored($message, $color);
119 my ($line, @flags) = @_;
121 foreach my $flag (@flags) {
122 return 1 if $line =~ /\s$flag(?:\s|\\|$)/;
128 my ($line, $missing_flags_ref, @flags) = @_;
130 my @missing_flags = ();
131 foreach my $flag (@flags) {
132 if ($line !~ /\s$flag(?:\s|\\|$)/) {
133 push @missing_flags, $flag;
137 if (scalar @missing_flags == 0) {
141 @{$missing_flags_ref} = @missing_flags;
145 # Modifies $missing_flags_ref array.
146 sub pic_pie_conflict {
147 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
149 return 0 if not $pie;
150 return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
152 my %flags = map { $_ => 1 } @flags_pie;
154 # Remove all PIE flags from @missing_flags as they are not required with
157 not exists $flags{$_}
158 } @{$missing_flags_ref};
159 @{$missing_flags_ref} = @result;
161 # We got a conflict when no flags are left, thus only PIE flags were
162 # missing. If other flags were missing abort because the conflict is not
164 return scalar @result == 0;
167 sub is_non_verbose_build {
168 my ($line, $next_line, $skip_ref) = @_;
170 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
171 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD)\]?\s+(.+?)$/
172 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
173 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
174 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
180 # On the first pass we only check if this line is verbose or not.
181 return 1 if not defined $next_line;
183 # Second pass, we have access to the next line.
186 # CMake and other build systems print the non-verbose messages also when
187 # building verbose. If a compiler and the file name occurs in the next
188 # line, treat it as verbose build.
190 # Get filename, we can't use the complete path as only parts of it are
191 # used in the real compiler command.
192 $file =~ m{/([a-zA-Z0-9._-]+)$};
195 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/) {
196 # We still have to skip the current line as it doesn't contain any
209 # Hardening options. Not all architectures support all hardening options.
210 my $harden_format = 1;
211 my $harden_fortify = 1;
212 my $harden_stack = 1;
213 my $harden_relro = 1;
214 my $harden_bindnow = 0;
217 # Parse command line arguments.
219 my $option_version = 0;
221 my $option_arch = undef;
222 if (not Getopt::Long::GetOptions(
223 'help|h|?' => \$option_help,
224 'version' => \$option_version,
226 'pie' => \$harden_pie,
227 'bindnow' => \$harden_bindnow,
228 'all' => \$option_all,
230 'arch' => \$option_arch,
233 Pod::Usage::pod2usage(2);
237 Pod::Usage::pod2usage(1);
239 if ($option_version) {
240 print "blhc $VERSION Copyright (C) 2012 Simon Ruderich
242 This program is free software: you can redistribute it and/or modify
243 it under the terms of the GNU General Public License as published by
244 the Free Software Foundation, either version 3 of the License, or
245 (at your option) any later version.
247 This program is distributed in the hope that it will be useful,
248 but WITHOUT ANY WARRANTY; without even the implied warranty of
249 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
250 GNU General Public License for more details.
252 You should have received a copy of the GNU General Public License
253 along with this program. If not, see <http://www.gnu.org/licenses/>.
266 # Input lines, contain only the lines with compiler commands.
270 my $continuation = 0;
271 my $complete_line = undef;
272 while (my $line = <>) {
273 # We skip over unimportant lines at the beginning to prevent false
275 $start = 1 if $line =~ /^dpkg-buildpackage:/;
278 # Detect architecture automatically unless overridden.
280 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
284 # Ignore compiler warnings for now.
285 next if $line =~ /$warning_regex/;
287 # Remove all ANSI color sequences which are sometimes used in non-verbose
289 $line = Term::ANSIColor::colorstrip($line);
290 # Also strip '\0xf' (delete previous character), used by Elink's build
293 # And "ESC(B" which seems to be used on armhf and hurd (not sure what it
295 $line =~ s/\033\(B//g;
297 # Check if this line indicates a non verbose build.
298 my $non_verbose = is_non_verbose_build($line);
300 # One line may contain multiple commands (";"). Treat each one as single
302 my @line = split /(?<!\\);/, $line;
303 foreach $line (@line) {
304 # Add newline, drop all other whitespace at the end of a line.
311 # Join lines, but leave the "\" in place so it's clear where the
312 # original line break was.
313 chomp $complete_line;
314 $complete_line .= ' ' . $line;
316 # Line continuation, line ends with "\".
317 if ($line =~ /\\\s*$/) {
319 # Start line continuation.
320 if (not defined $complete_line) {
321 $complete_line = $line;
326 if (not $continuation) {
327 # Use the complete line if a line continuation occurred.
328 if (defined $complete_line) {
329 $line = $complete_line;
330 $complete_line = undef;
333 # Ignore lines with no compiler commands.
334 next if $line !~ /\b$cc_regex(?:\s|\\)/ and not $non_verbose;
336 # Ignore false positives.
338 # `./configure` output.
339 next if not $non_verbose and $line =~ /^checking /;
340 next if $line =~ /^\s*(?:C\s+)?
341 (?:C|c)ompiler[\s.]*:\s+
343 (?:\s-std=[a-z0-9:+]+)?\s*$
345 or $line =~ /^\s*(?:- )?(?:CC|CXX)\s*=\s*$cc_regex\s*$/
346 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
347 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
348 # Debian buildd output.
349 next if $line =~ /^\s*Depends: .*?$cc_regex.*?$/
350 and $line !~ /\s-./; # option, prevent false negatives
358 if (scalar @input == 0) {
359 print "No compiler commands!\n";
364 # Option or auto detected.
366 # The following was partially copied from dpkg-dev 1.16.1.2
367 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
368 # copyright Raphaƫl Hertzog <hertzog@debian.org>, Kees Cook
369 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
370 # later. Keep it in sync.
373 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
375 # Disable unsupported hardening options.
376 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
379 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
385 # Check if additional hardening options were used. Used to ensure they are
386 # used for the complete build.
387 foreach my $line (@input) {
388 $harden_pie = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
389 $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
392 # Check the specified hardening options, same order as dpkg-buildflags.
394 @cflags = (@cflags, @cflags_pie);
395 @ldflags = (@ldflags, @ldflags_pie);
398 @cflags = (@cflags, @cflags_stack);
400 if ($harden_fortify) {
401 @cflags = (@cflags, @cflags_fortify);
402 @cppflags = (@cppflags, @cppflags_fortify);
404 if ($harden_format) {
405 @cflags = (@cflags, @cflags_format);
408 @ldflags = (@ldflags, @ldflags_relro);
410 if ($harden_bindnow) {
411 @ldflags = (@ldflags, @ldflags_bindnow);
414 for (my $i = 0; $i < scalar @input; $i++) {
415 my $line = $input[$i];
418 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
419 error_non_verbose_build($line);
423 # Even if it's a verbose build, we might have to skip this line.
427 # Is this a compiler or linker command?
432 if ($line =~ m{\s-o # -o
433 [\s\\]*\s+ # possible line continuation
434 (?:[/.A-Za-z0-9~_-]+/)? # path to file
435 [A-Za-z0-9~_-]+ # binary name (no dots!)
436 (?:[0-9.]*\.so[0-9.]*[a-z]? # library (including version)
438 |\.cgi)? # CGI binary
439 (?:\s|\\|$) # end of file name
441 or $line =~ /^libtool: link: /
442 or $line =~ m{\s*/bin/bash .+?libtool\s+(.+?\s+)?--mode=(re)?link}) {
447 # If there are source files then it's compiling/linking in one step and we
449 if ($line =~ /\.(?:c|cc|cpp)\b/) {
453 # Check hardening flags.
455 if ($compiler and not all_flags_used($line, \@missing, @cflags)
456 # Libraries linked with -fPIC don't have to (and can't) be linked
457 # with -fPIE as well. It's no error if only PIE flags are missing.
458 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)) {
459 error_flags('CFLAGS missing', \@missing, \%flag_renames, $line);
462 if ($compiler and not all_flags_used($line, \@missing, @cppflags)) {
463 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $line);
466 if ($linker and not all_flags_used($line, \@missing, @ldflags)
467 # Same here, -fPIC conflicts with -fPIE.
468 and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)) {
469 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $line);
481 blhc - build log hardening check, checks build logs for missing hardening flags
485 B<blhc> [-h -? --help]
487 B<blhc> [--pie] [--bindnow] [--all]
489 --help available options
490 --version version number and license
491 --pie force +pie check
492 --bindnow force +bindbow check
493 --all force +all (+pie, +bindnow) check
494 --arch set architecture (autodetected)
498 blhc is a small tool which checks build logs for missing hardening flags and
499 other important warnings. It's licensed under the GPL 3 or later.
505 =item B<-h -? --help>
507 Print available options.
511 Print version number and license.
515 Force check for all +pie hardening flags. By default it's auto detected.
519 Force check for all +bindnow hardening flags. By default it's auto detected.
523 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
528 Set the specific architecture (e.g. amd64, armel, etc.), automatically
529 disables hardening flags not available on this architecture. Is detected
530 automatically if dpkg-buildpackage is used.
534 Auto detection only works if at least one command uses the required hardening
535 flag (e.g. -fPIE). Then it's required for all other commands as well.
539 The exit status is a "bit mask", each listed status is ORed when the error
540 condition occurs to get the result.
550 No compiler commands were found.
554 Invalid arguments/options given to blhc.
562 Missing hardening flags.
568 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
570 =head1 COPYRIGHT AND LICENSE
572 Copyright (C) 2012 by Simon Ruderich
574 This program is free software: you can redistribute it and/or modify
575 it under the terms of the GNU General Public License as published by
576 the Free Software Foundation, either version 3 of the License, or
577 (at your option) any later version.
579 This program is distributed in the hope that it will be useful,
580 but WITHOUT ANY WARRANTY; without even the implied warranty of
581 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
582 GNU General Public License for more details.
584 You should have received a copy of the GNU General Public License
585 along with this program. If not, see <http://www.gnu.org/licenses/>.