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 return 1 if scalar @missing_flags == 0;
139 @{$missing_flags_ref} = @missing_flags;
143 # Modifies $missing_flags_ref array.
144 sub pic_pie_conflict {
145 my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
147 return 0 if not $pie;
148 return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
150 my %flags = map { $_ => 1 } @flags_pie;
152 # Remove all PIE flags from @missing_flags as they are not required with
155 not exists $flags{$_}
156 } @{$missing_flags_ref};
157 @{$missing_flags_ref} = @result;
159 # We got a conflict when no flags are left, thus only PIE flags were
160 # missing. If other flags were missing abort because the conflict is not
162 return scalar @result == 0;
165 sub is_non_verbose_build {
166 my ($line, $next_line, $skip_ref) = @_;
168 if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
169 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
170 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
171 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
172 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
178 # On the first pass we only check if this line is verbose or not.
179 return 1 if not defined $next_line;
181 # Second pass, we have access to the next line.
184 # CMake and other build systems print the non-verbose messages also when
185 # building verbose. If a compiler and the file name occurs in the next
186 # line, treat it as verbose build.
188 # Get filename, we can't use the complete path as only parts of it are
189 # used in the real compiler command.
190 $file =~ m{/([a-zA-Z0-9._-]+)$};
193 if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/) {
194 # We still have to skip the current line as it doesn't contain any
207 # Hardening options. Not all architectures support all hardening options.
208 my $harden_format = 1;
209 my $harden_fortify = 1;
210 my $harden_stack = 1;
211 my $harden_relro = 1;
212 my $harden_bindnow = 0;
215 # Parse command line arguments.
217 my $option_version = 0;
219 my $option_arch = undef;
220 my $option_buildd = 0;
221 if (not Getopt::Long::GetOptions(
222 'help|h|?' => \$option_help,
223 'version' => \$option_version,
225 'pie' => \$harden_pie,
226 'bindnow' => \$harden_bindnow,
227 'all' => \$option_all,
229 'arch' => \$option_arch,
230 'buildd' => \$option_buildd,
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 # dpkg-buildflags only provides hardening flags since 1.16.1, don't check
274 # for hardening flags in buildd mode if an older dpkg-dev is used. Default
275 # flags (-g -O2) are still checked.
277 # Packages which were built before 1.16.1 but used their own hardening
278 # flags are not checked.
279 if ($option_buildd and not $start
280 and $line =~ /^Toolchain package versions: /) {
281 require Dpkg::Version;
282 if ($line !~ /dpkg-dev_(\S+)/
283 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
293 # We skip over unimportant lines at the beginning of the log to prevent
295 $start = 1 if $line =~ /^dpkg-buildpackage:/;
298 # Detect architecture automatically unless overridden.
300 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
304 # Ignore compiler warnings for now.
305 next if $line =~ /$warning_regex/;
307 # Remove all ANSI color sequences which are sometimes used in non-verbose
309 $line = Term::ANSIColor::colorstrip($line);
310 # Also strip '\0xf' (delete previous character), used by Elinks' build
313 # And "ESC(B" which seems to be used on armhf and hurd (not sure what it
315 $line =~ s/\033\(B//g;
317 # Check if this line indicates a non verbose build.
318 my $non_verbose = is_non_verbose_build($line);
320 # One line may contain multiple commands (";"). Treat each one as single
322 my @line = split /(?<!\\);/, $line;
323 foreach $line (@line) {
324 # Add newline, drop all other whitespace at the end of a line.
331 # Join lines, but leave the "\" in place so it's clear where the
332 # original line break was.
333 chomp $complete_line;
334 $complete_line .= ' ' . $line;
336 # Line continuation, line ends with "\".
337 if ($line =~ /\\\s*$/) {
339 # Start line continuation.
340 if (not defined $complete_line) {
341 $complete_line = $line;
346 if (not $continuation) {
347 # Use the complete line if a line continuation occurred.
348 if (defined $complete_line) {
349 $line = $complete_line;
350 $complete_line = undef;
353 # Ignore lines with no compiler commands.
354 next if $line !~ /\b$cc_regex(?:\s|\\)/ and not $non_verbose;
356 # Ignore false positives.
358 # `./configure` output.
359 next if not $non_verbose and $line =~ /^checking /;
360 next if $line =~ /^\s*(?:C\s+)?
361 (?:C|c)ompiler[\s.]*:\s+
363 (?:\s-std=[a-z0-9:+]+)?\s*$
365 or $line =~ /^\s*(?:- )?(?:CC|CXX)\s*=\s*$cc_regex\s*$/
366 or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
367 or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
368 # Debian buildd output.
369 next if $line =~ /^\s*Depends: .*?$cc_regex.*?$/
370 and $line !~ /\s-./; # option, prevent false negatives
378 if (scalar @input == 0) {
379 print "No compiler commands!\n";
384 # Option or auto detected.
386 # The following was partially copied from dpkg-dev 1.16.1.2
387 # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
388 # copyright Raphaƫl Hertzog <hertzog@debian.org>, Kees Cook
389 # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
390 # later. Keep it in sync.
393 my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
395 # Disable unsupported hardening options.
396 if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
399 if ($cpu =~ /^(ia64|hppa|avr32)$/) {
405 # Check if additional hardening options were used. Used to ensure they are
406 # used for the complete build.
407 foreach my $line (@input) {
408 $harden_pie = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
409 $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
412 # Check the specified hardening options, same order as dpkg-buildflags.
414 @cflags = (@cflags, @cflags_pie);
415 @ldflags = (@ldflags, @ldflags_pie);
418 @cflags = (@cflags, @cflags_stack);
420 if ($harden_fortify) {
421 @cflags = (@cflags, @cflags_fortify);
422 @cppflags = (@cppflags, @cppflags_fortify);
424 if ($harden_format) {
425 @cflags = (@cflags, @cflags_format);
428 @ldflags = (@ldflags, @ldflags_relro);
430 if ($harden_bindnow) {
431 @ldflags = (@ldflags, @ldflags_bindnow);
434 for (my $i = 0; $i < scalar @input; $i++) {
435 my $line = $input[$i];
438 if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
439 error_non_verbose_build($line);
443 # Even if it's a verbose build, we might have to skip this line.
447 # Is this a compiler or linker command?
452 if ($line =~ m{\s-o # -o
453 [\s\\]*\s+ # possible line continuation
454 (?:[/.A-Za-z0-9~_-]+/)? # path to file
455 [A-Za-z0-9~_-]+ # binary name (no dots!)
456 (?:[0-9.]*\.so[0-9.]*[a-z]? # library (including version)
458 |\.cgi)? # CGI binary
459 (?:\s|\\|$) # end of file name
461 or $line =~ /^libtool: link: /
462 or $line =~ m{\s*/bin/bash .+?libtool\s+(.+?\s+)?--mode=(re)?link}) {
467 # If there are source files then it's compiling/linking in one step and we
469 if ($line =~ /\.(?:c|cc|cpp)\b/) {
473 # Check hardening flags.
475 if ($compiler and not all_flags_used($line, \@missing, @cflags)
476 # Libraries linked with -fPIC don't have to (and can't) be linked
477 # with -fPIE as well. It's no error if only PIE flags are missing.
478 and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)) {
479 error_flags('CFLAGS missing', \@missing, \%flag_renames, $line);
482 if ($compiler and not all_flags_used($line, \@missing, @cppflags)) {
483 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $line);
486 if ($linker and not all_flags_used($line, \@missing, @ldflags)
487 # Same here, -fPIC conflicts with -fPIE.
488 and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)) {
489 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $line);
501 blhc - build log hardening check, checks build logs for missing hardening flags
505 B<blhc> [-h -? --help]
507 B<blhc> [--pie] [--bindnow] [--all]
509 --help available options
510 --version version number and license
511 --pie force +pie check
512 --bindnow force +bindbow check
513 --all force +all (+pie, +bindnow) check
514 --arch set architecture (autodetected)
515 --buildd parser mode for buildds
519 blhc is a small tool which checks build logs for missing hardening flags and
520 other important warnings. It's licensed under the GPL 3 or later.
526 =item B<-h -? --help>
528 Print available options.
532 Print version number and license.
536 Force check for all +pie hardening flags. By default it's auto detected.
540 Force check for all +bindnow hardening flags. By default it's auto detected.
544 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
549 Set the specific architecture (e.g. amd64, armel, etc.), automatically
550 disables hardening flags not available on this architecture. Is detected
551 automatically if dpkg-buildpackage is used.
555 Special mode for buildds when automatically parsing log files. The following
556 changes are in effect:
562 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
569 Auto detection for B<--pie> and B<--bindnow> only works if at least one
570 command uses the required hardening flag (e.g. -fPIE). Then it's required for
571 all other commands as well.
575 The exit status is a "bit mask", each listed status is ORed when the error
576 condition occurs to get the result.
586 No compiler commands were found.
590 Invalid arguments/options given to blhc.
598 Missing hardening flags.
604 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
606 =head1 COPYRIGHT AND LICENSE
608 Copyright (C) 2012 by Simon Ruderich
610 This program is free software: you can redistribute it and/or modify
611 it under the terms of the GNU General Public License as published by
612 the Free Software Foundation, either version 3 of the License, or
613 (at your option) any later version.
615 This program is distributed in the hope that it will be useful,
616 but WITHOUT ANY WARRANTY; without even the implied warranty of
617 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
618 GNU General Public License for more details.
620 You should have received a copy of the GNU General Public License
621 along with this program. If not, see <http://www.gnu.org/licenses/>.