]> ruderich.org/simon Gitweb - blhc/blhc.git/blob - bin/blhc
Fix architecture detection when checking multiple files.
[blhc/blhc.git] / bin / blhc
1 #!/usr/bin/perl
2
3 # Build log hardening check, checks build logs for missing hardening flags.
4
5 # Copyright (C) 2012  Simon Ruderich
6 #
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.
11 #
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.
16 #
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/>.
19
20
21 use strict;
22 use warnings;
23
24 use Getopt::Long ();
25 use Term::ANSIColor ();
26 use Text::ParseWords ();
27
28 our $VERSION = '0.01';
29
30
31 # CONSTANTS/VARIABLES
32
33 # Regex to catch compiler commands.
34 my $cc_regex = qr/
35     (?<!\.)(?:cc|gcc|g\+\+|c\+\+)
36     (?:-[\d.]+)?
37     /x;
38 # Full regex which matches the complete compiler name. Used in a few places to
39 # prevent false negatives.
40 my $cc_regex_full = qr/
41     (?:[a-z0-9_]+-(?:linux-|kfreebsd-)?gnu(?:eabi|eabihf)?-)?
42     $cc_regex
43     /x;
44 # Regex to catch (GCC) compiler warnings.
45 my $warning_regex = qr/^(.+?):([0-9]+):[0-9]+: warning: (.+?) \[(.+?)\]$/;
46
47 # List of source file extensions which require preprocessing.
48 my @source_preprocess_compile_cpp = (
49     # C++
50     qw( cc cp cxx cpp CPP c++ C ),
51     # Objective-C++
52     qw( mm Mr),
53 );
54 my @source_preprocess_compile = (
55     # C
56     qw( c ),
57     # Objective-C
58     qw( m ),
59     # (Objective-)C++
60     @source_preprocess_compile_cpp,
61     # Fortran
62     qw( F FOR fpp FPP FTN F90 F95 F03 F08 ),
63 );
64 my @source_preprocess_no_compile = (
65     # Assembly
66     qw( s ),
67 );
68 my @source_preprocess = (
69     @source_preprocess_compile,
70     @source_preprocess_no_compile,
71 );
72 # List of source file extensions which don't require preprocessing.
73 my @source_no_preprocess_compile_cpp = (
74     # C++
75     qw( ii ),
76     # Objective-C++
77     qw( mii ),
78 );
79 my @source_no_preprocess_compile = (
80     # C
81     qw( i ),
82     # (Objective-)C++
83     @source_no_preprocess_compile_cpp,
84     # Objective-C
85     qw( mi ),
86     # Fortran
87     qw( f for ftn f90 f95 f03 f08 ),
88 );
89 my @source_no_preprocess_no_compile = (
90     # Assembly
91     qw( S sx ),
92 );
93 my @source_no_preprocess = (
94     @source_no_preprocess_compile,
95     @source_no_preprocess_no_compile,
96 );
97 # List of header file extensions which require preprocessing.
98 my @header_preprocess = (
99     # C, C++, Objective-C, Objective-C++
100     qw( h ),
101     # C++
102     qw( hh H hp hxx hpp HPP h++ tcc ),
103 );
104
105 # Hashes for fast extensions lookup to check if a file falls in one of these
106 # categories.
107 my %extensions_no_preprocess = map { $_ => 1 } (
108     @source_no_preprocess,
109 );
110 my %extensions_preprocess = map { $_ => 1 } (
111     @header_preprocess,
112     @source_preprocess,
113 );
114 my %extensions_compile_link = map { $_ => 1 } (
115     @source_preprocess,
116     @source_no_preprocess,
117 );
118 my %extensions_compile = map { $_ => 1 } (
119     @source_preprocess_compile,
120     @source_no_preprocess_compile,
121 );
122 my %extensions_no_compile = map { $_ => 1 } (
123     @source_preprocess_no_compile,
124     @source_no_preprocess_no_compile,
125 );
126 my %extensions_compile_cpp = map { $_ => 1 } (
127     @source_preprocess_compile_cpp,
128     @source_no_preprocess_compile_cpp,
129 );
130 my %extension = map { $_ => 1 } (
131     @source_no_preprocess,
132     @source_no_preprocess_compile,
133     @source_no_preprocess_compile_cpp,
134     @source_no_preprocess_no_compile,
135     @header_preprocess,
136     @source_preprocess,
137     @source_preprocess_compile,
138     @source_preprocess_compile_cpp,
139     @source_preprocess_no_compile,
140 );
141
142 # Regexp to match file extensions.
143 my $file_extension_regex = qr/
144     \s
145     \S+             # Filename without extension.
146     \.
147     ([^\\.,;:\s]+)  # File extension.
148     (?=\s|\\)       # At end of word. Can't use \b because some files have non
149                     # word characters at the end and because \b matches double
150                     # extensions (like .cpp.o). Works always as all lines are
151                     # terminated with "\n".
152     /x;
153
154 # Expected (hardening) flags. All flags are used as regexps.
155 my @def_cflags = (
156     '-g',
157     '-O(?:2|3)',
158 );
159 my @def_cflags_format = (
160     '-Wformat',
161     '-Wformat-security',
162     '-Werror=format-security',
163 );
164 my @def_cflags_fortify = (
165     # fortify needs at least -O1, but -O2 is recommended anyway
166 );
167 my @def_cflags_stack = (
168     '-fstack-protector',
169     '--param=ssp-buffer-size=4',
170 );
171 my @def_cflags_pie = (
172     '-fPIE',
173 );
174 my @def_cxxflags = (
175     @def_cflags,
176 );
177 # @def_cxxflags_* is the same as @def_cflags_*.
178 my @def_cppflags = ();
179 my @def_cppflags_fortify = (
180     '-D_FORTIFY_SOURCE=2',
181 );
182 my @def_ldflags = ();
183 my @def_ldflags_relro = (
184     '-Wl,(-z,)?relro',
185 );
186 my @def_ldflags_bindnow = (
187     '-Wl,(-z,)?now',
188 );
189 my @def_ldflags_pie = (
190     '-fPIE',
191     '-pie',
192 );
193 my @def_ldflags_pic = (
194     '-fPIC',
195     '-fpic',
196     '-shared',
197 );
198 # Renaming rules for the output so the regex parts are not visible. Also
199 # stores string values of flag regexps above, see compile_flag_regexp().
200 my %flag_renames = (
201     '-O(?:2|3)'       => '-O2',
202     '-Wl,(-z,)?relro' => '-Wl,-z,relro',
203     '-Wl,(-z,)?now'   => '-Wl,-z,now',
204 );
205
206 my %exit_code = (
207     no_compiler_commands => 1 << 0,
208     # used by POD::Usage => 1 << 1,
209     non_verbose_build    => 1 << 2,
210     flags_missing        => 1 << 3,
211     hardening_wrapper    => 1 << 4,
212     invalid_cmake        => 1 << 5,
213 );
214
215 # Statistics of missing flags and non-verbose build commands. Used for
216 # $option_buildd.
217 my %statistics = (
218     preprocess          => 0,
219     preprocess_missing  => 0,
220     compile             => 0,
221     compile_missing     => 0,
222     compile_cpp         => 0,
223     compile_cpp_missing => 0,
224     link                => 0,
225     link_missing        => 0,
226     commands            => 0,
227     commands_nonverbose => 0,
228 );
229
230 # Use colored (ANSI) output?
231 my $option_color;
232
233
234 # FUNCTIONS
235
236 sub error_flags {
237     my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
238
239     # Get string value of qr//-escaped regexps and if requested rename them.
240     my @missing_flags = map {
241             $flag_renames_ref->{$_}
242         } @{$missing_flags_ref};
243
244     my $flags = join ' ', @missing_flags;
245     printf "%s (%s)%s %s",
246            error_color($message, 'red'), $flags, error_color(':', 'yellow'),
247            $line;
248 }
249 sub error_non_verbose_build {
250     my ($line) = @_;
251
252     printf "%s%s %s",
253            error_color('NONVERBOSE BUILD', 'red'),
254            error_color(':', 'yellow'),
255            $line;
256 }
257 sub error_invalid_cmake {
258     my ($version) = @_;
259
260     printf "%s%s %s\n",
261             error_color('INVALID CMAKE', 'red'),
262             error_color(':', 'yellow'),
263             $version;
264 }
265 sub error_hardening_wrapper {
266     printf "%s%s %s\n",
267             error_color('HARDENING WRAPPER', 'red'),
268             error_color(':', 'yellow'),
269             'no checks possible, aborting';
270 }
271 sub error_color {
272     my ($message, $color) = @_;
273
274     if ($option_color) {
275         return Term::ANSIColor::colored($message, $color);
276     } else {
277         return $message;
278     }
279 }
280
281 sub any_flags_used {
282     my ($line, @flags) = @_;
283
284     foreach my $flag (@flags) {
285         return 1 if $line =~ /$flag/;
286     }
287
288     return 0;
289 }
290 sub all_flags_used {
291     my ($line, $missing_flags_ref, @flags) = @_;
292
293     my @missing_flags = ();
294     foreach my $flag (@flags) {
295         if (not $line =~ /$flag/) {
296             push @missing_flags, $flag;
297         }
298     }
299
300     return 1 if scalar @missing_flags == 0;
301
302     @{$missing_flags_ref} = @missing_flags;
303     return 0;
304 }
305
306 # Modifies $missing_flags_ref array.
307 sub pic_pie_conflict {
308     my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
309
310     return 0 if not $pie;
311     return 0 if not any_flags_used($line, @def_ldflags_pic);
312
313     my %flags = map { $_ => 1 } @flags_pie;
314
315     # Remove all PIE flags from @missing_flags as they are not required with
316     # -fPIC.
317     my @result = grep {
318         not exists $flags{$_}
319     } @{$missing_flags_ref};
320     @{$missing_flags_ref} = @result;
321
322     # We got a conflict when no flags are left, thus only PIE flags were
323     # missing. If other flags were missing abort because the conflict is not
324     # the problem.
325     return scalar @result == 0;
326 }
327
328 sub is_non_verbose_build {
329     my ($line, $next_line, $skip_ref) = @_;
330
331     if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
332                 or $line =~ /^\s*\[?(?:CC|CCLD|C\+\+|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
333                 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
334                 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
335                 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
336         return 0;
337     }
338
339     # False positives.
340     return 0 if $line =~ /^\s*C\+\+.+?:\s+(?:yes|no)\s*$/;
341
342     my $file = $1;
343
344     # On the first pass we only check if this line is verbose or not.
345     return 1 if not defined $next_line;
346
347     # Second pass, we have access to the next line.
348     ${$skip_ref} = 0;
349
350     # CMake and other build systems print the non-verbose messages also when
351     # building verbose. If a compiler and the file name occurs in the next
352     # line, treat it as verbose build.
353     if (defined $file) {
354         # Get filename, we can't use the complete path as only parts of it are
355         # used in the real compiler command.
356         $file =~ m{/([^/\s]+)$};
357         $file = $1;
358
359         if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/o) {
360             # We still have to skip the current line as it doesn't contain any
361             # compiler commands.
362             ${$skip_ref} = 1;
363             return 0;
364         }
365     }
366
367     return 1;
368 }
369
370 sub compile_flag_regexp {
371     my ($flag_renames_ref, @flags) = @_;
372
373     my @result = ();
374     foreach my $flag (@flags) {
375         # Store flag name in replacement string for correct flags in messages
376         # with qr//ed flag regexps.
377         $flag_renames_ref->{qr/\s$flag(?:\s|\\)/}
378             = (exists $flag_renames_ref->{$flag})
379                 ? $flag_renames_ref->{$flag}
380                 : $flag;
381
382         # Compile flag regexp for faster execution.
383         push @result, qr/\s$flag(?:\s|\\)/;
384     }
385     return @result;
386 }
387
388 sub extension_found {
389     my ($extensions_ref, @extensions) = @_;
390
391     my $found = 0;
392     foreach my $extension (@extensions) {
393         if (exists $extensions_ref->{$extension}) {
394             $found = 1;
395             last;
396         }
397     }
398     return $found;
399 }
400
401
402 # MAIN
403
404 # Parse command line arguments.
405 my $option_help    = 0;
406 my $option_version = 0;
407 my $option_pie     = 0;
408 my $option_bindnow = 0;
409 my $option_all     = 0;
410 my $option_arch    = undef;
411 my $option_buildd  = 0;
412    $option_color   = 0;
413 if (not Getopt::Long::GetOptions(
414             'help|h|?' => \$option_help,
415             'version'  => \$option_version,
416             # Hardening options.
417             'pie'      => \$option_pie,
418             'bindnow'  => \$option_bindnow,
419             'all'      => \$option_all,
420             # Misc.
421             'color'    => \$option_color,
422             'arch=s'   => \$option_arch,
423             'buildd'   => \$option_buildd,
424         )) {
425     require Pod::Usage;
426     Pod::Usage::pod2usage(2);
427 }
428 if ($option_help) {
429     require Pod::Usage;
430     Pod::Usage::pod2usage(1);
431 }
432 if ($option_version) {
433     print "blhc $VERSION  Copyright (C) 2012  Simon Ruderich
434
435 This program is free software: you can redistribute it and/or modify
436 it under the terms of the GNU General Public License as published by
437 the Free Software Foundation, either version 3 of the License, or
438 (at your option) any later version.
439
440 This program is distributed in the hope that it will be useful,
441 but WITHOUT ANY WARRANTY; without even the implied warranty of
442 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
443 GNU General Public License for more details.
444
445 You should have received a copy of the GNU General Public License
446 along with this program.  If not, see <http://www.gnu.org/licenses/>.
447 ";
448     exit 0;
449 }
450
451 if ($option_all) {
452     $option_pie     = 1;
453     $option_bindnow = 1;
454 }
455
456 # Precompile all flag regexps. any_flags_used(), all_flags_used() get a lot
457 # faster with this.
458 @def_cflags           = compile_flag_regexp(\%flag_renames, @def_cflags);
459 @def_cflags_format    = compile_flag_regexp(\%flag_renames, @def_cflags_format);
460 @def_cflags_fortify   = compile_flag_regexp(\%flag_renames, @def_cflags_fortify);
461 @def_cflags_stack     = compile_flag_regexp(\%flag_renames, @def_cflags_stack);
462 @def_cflags_pie       = compile_flag_regexp(\%flag_renames, @def_cflags_pie);
463 @def_cxxflags         = compile_flag_regexp(\%flag_renames, @def_cxxflags);
464 @def_cppflags         = compile_flag_regexp(\%flag_renames, @def_cppflags);
465 @def_cppflags_fortify = compile_flag_regexp(\%flag_renames, @def_cppflags_fortify);
466 @def_ldflags          = compile_flag_regexp(\%flag_renames, @def_ldflags);
467 @def_ldflags_relro    = compile_flag_regexp(\%flag_renames, @def_ldflags_relro);
468 @def_ldflags_bindnow  = compile_flag_regexp(\%flag_renames, @def_ldflags_bindnow);
469 @def_ldflags_pie      = compile_flag_regexp(\%flag_renames, @def_ldflags_pie);
470 @def_ldflags_pic      = compile_flag_regexp(\%flag_renames, @def_ldflags_pic);
471
472 # Final exit code.
473 my $exit = 0;
474
475 FILE: foreach my $file (@ARGV) {
476     open my $fh, '<', $file or die "$!: $file";
477
478     # Architecture of this file.
479     my $arch = $option_arch;
480
481     # Hardening options. Not all architectures support all hardening options.
482     my $harden_format  = 1;
483     my $harden_fortify = 1;
484     my $harden_stack   = 1;
485     my $harden_relro   = 1;
486     my $harden_bindnow = $option_bindnow; # defaults to 0
487     my $harden_pie     = $option_pie;     # defaults to 0
488
489     while (my $line = <$fh>) {
490         # dpkg-buildflags only provides hardening flags since 1.16.1, don't
491         # check for hardening flags in buildd mode if an older dpkg-dev is
492         # used. Default flags (-g -O2) are still checked.
493         #
494         # Packages which were built before 1.16.1 but used their own hardening
495         # flags are not checked.
496         if ($option_buildd and $line =~ /^Toolchain package versions: /) {
497             require Dpkg::Version;
498             if ($line !~ /\bdpkg-dev_(\S+)/
499                     or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
500                 $harden_format  = 0;
501                 $harden_fortify = 0;
502                 $harden_stack   = 0;
503                 $harden_relro   = 0;
504                 $harden_bindnow = 0;
505                 $harden_pie     = 0;
506             }
507         }
508
509         # The following two versions of CMake in Debian obeyed CPPFLAGS, but
510         # this was later dropped because upstream rejected the patch. Thus
511         # build logs with these versions will have fortify hardening flags
512         # enabled, even though they may be not correctly set and are missing
513         # when build with later CMake versions. Thanks to Aron Xu for letting
514         # me know.
515         if ($line =~ /^Package versions: /
516                 and $line =~ /\bcmake_(\S+)/
517                 and ($1 eq '2.8.7-1' or $1 eq '2.8.7-2')) {
518             if (not $option_buildd) {
519                 error_invalid_cmake($1);
520             } else {
521                 print "W-invalid-cmake-used $1\n";
522             }
523             $exit |= $exit_code{invalid_cmake};
524         }
525
526         # If hardening wrapper is used (wraps calls to gcc and adds hardening
527         # flags automatically) we can't perform any checks, abort.
528         if ($line =~ /^Build-Depends: .*\bhardening-wrapper\b/) {
529             if (not $option_buildd) {
530                 error_hardening_wrapper();
531             } else {
532                 print "I-hardening-wrapper-used\n";
533             }
534             $exit |= $exit_code{hardening_wrapper};
535             next FILE;
536         }
537
538         # We skip over unimportant lines at the beginning of the log to
539         # prevent false positives.
540         last if $line =~ /^dpkg-buildpackage:/;
541     }
542
543     # Input lines, contain only the lines with compiler commands.
544     my @input = ();
545
546     my $continuation = 0;
547     my $complete_line = undef;
548     while (my $line = <$fh>) {
549         # And stop at the end of the build log. Package details (reported by
550         # the buildd logs) are not important for us. This also prevents false
551         # positives.
552         last if $line =~ /^Build finished at \d{8}-\d{4}$/;
553
554         # Detect architecture automatically unless overridden.
555         if (not $arch
556                 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
557             $arch = $1;
558         }
559
560         # Ignore compiler warnings for now.
561         next if $line =~ /$warning_regex/o;
562
563         if ($line =~ /\033/) { # esc
564             # Remove all ANSI color sequences which are sometimes used in
565             # non-verbose builds.
566             $line = Term::ANSIColor::colorstrip($line);
567             # Also strip '\0xf' (delete previous character), used by Elinks'
568             # build system.
569             $line =~ s/\x0f//g;
570             # And "ESC(B" which seems to be used on armhf and hurd (not sure
571             # what it does).
572             $line =~ s/\033\(B//g;
573         }
574
575         # Check if this line indicates a non verbose build.
576         my $non_verbose = is_non_verbose_build($line);
577
578         # One line may contain multiple commands (";"). Treat each one as
579         # single line. parse_line() is slow, only use it when necessary.
580         my @line = (not $line =~ /;/)
581                  ? ($line)
582                  : map {
583                        # Ensure newline at the line end - necessary for
584                        # correct parsing later.
585                        $_ =~ s/\s+$//;
586                        $_ .= "\n";
587                    } Text::ParseWords::parse_line(';', 1, $line);
588         foreach $line (@line) {
589             if ($continuation) {
590                 $continuation = 0;
591
592                 # Join lines, but leave the "\" in place so it's clear where
593                 # the original line break was.
594                 chomp $complete_line;
595                 $complete_line .= ' ' . $line;
596             }
597             # Line continuation, line ends with "\".
598             if ($line =~ /\\\s*$/) {
599                 $continuation = 1;
600                 # Start line continuation.
601                 if (not defined $complete_line) {
602                     $complete_line = $line;
603                 }
604                 next;
605             }
606
607             if (not $continuation) {
608                 # Use the complete line if a line continuation occurred.
609                 if (defined $complete_line) {
610                     $line = $complete_line;
611                     $complete_line = undef;
612                 }
613
614                 # Ignore lines with no compiler commands.
615                 next if not $non_verbose
616                         and not $line =~ /\b$cc_regex(?:\s|\\)/o;
617                 # Ignore lines with no filenames with extensions. May miss
618                 # some non-verbose builds (e.g. "gcc -o test" [sic!]), but
619                 # shouldn't be a problem as the log will most likely contain
620                 # other non-verbose commands which are detected.
621                 next if not $non_verbose
622                         and not $line =~ /$file_extension_regex/o;
623
624                 # Ignore false positives.
625                 #
626                 # `./configure` output.
627                 next if not $non_verbose
628                         and $line =~ /^(?:checking|(?:C|c)onfigure:) /;
629                 next if $line =~ /^\s*(?:Host\s+)?(?:C(?:\+\+)?\s+)?
630                                    (?:C|c)ompiler[\s.]*:?\s+
631                                  /xo;
632                 next if $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex_full\s*$/o;
633
634                 # Check if additional hardening options were used. Used to
635                 # ensure they are used for the complete build.
636                 $harden_pie     = 1 if any_flags_used($line, @def_cflags_pie, @def_ldflags_pie);
637                 $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);
638
639                 push @input, $line;
640             }
641         }
642     }
643
644     close $fh;
645
646     if (scalar @input == 0) {
647         if (not $option_buildd) {
648             print "No compiler commands!\n";
649         } else {
650             print "W-no-compiler-commands\n";
651         }
652         $exit |= $exit_code{no_compiler_commands};
653         next FILE;
654     }
655
656     if ($option_buildd) {
657         $statistics{commands} += scalar @input;
658     }
659
660     # Option or auto detected.
661     if ($arch) {
662         # The following was partially copied from dpkg-dev 1.16.1.2
663         # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
664         # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
665         # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
666         # later. Keep it in sync.
667
668         require Dpkg::Arch;
669         my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($arch);
670
671         # Disable unsupported hardening options.
672         if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $arch eq 'arm') {
673             $harden_stack = 0;
674         }
675         if ($cpu =~ /^(ia64|hppa|avr32)$/) {
676             $harden_relro   = 0;
677             $harden_bindnow = 0;
678         }
679     }
680
681     # Default values.
682     my @cflags   = @def_cflags;
683     my @cxxflags = @def_cxxflags;
684     my @cppflags = @def_cppflags;
685     my @ldflags  = @def_ldflags;
686     # Check the specified hardening options, same order as dpkg-buildflags.
687     if ($harden_pie) {
688         @cflags   = (@cflags,   @def_cflags_pie);
689         @cxxflags = (@cxxflags, @def_cflags_pie);
690         @ldflags  = (@ldflags,  @def_ldflags_pie);
691     }
692     if ($harden_stack) {
693         @cflags   = (@cflags,   @def_cflags_stack);
694         @cxxflags = (@cxxflags, @def_cflags_stack);
695     }
696     if ($harden_fortify) {
697         @cflags   = (@cflags,   @def_cflags_fortify);
698         @cxxflags = (@cxxflags, @def_cflags_fortify);
699         @cppflags = (@cppflags, @def_cppflags_fortify);
700     }
701     if ($harden_format) {
702         @cflags   = (@cflags,   @def_cflags_format);
703         @cxxflags = (@cxxflags, @def_cflags_format);
704     }
705     if ($harden_relro) {
706         @ldflags = (@ldflags, @def_ldflags_relro);
707     }
708     if ($harden_bindnow) {
709         @ldflags = (@ldflags, @def_ldflags_bindnow);
710     }
711
712     for (my $i = 0; $i < scalar @input; $i++) {
713         my $line = $input[$i];
714
715         my $skip = 0;
716         if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
717             if (not $option_buildd) {
718                 error_non_verbose_build($line);
719             } else {
720                 $statistics{commands_nonverbose}++;
721             }
722             $exit |= $exit_code{non_verbose_build};
723             next;
724         }
725         # Even if it's a verbose build, we might have to skip this line.
726         next if $skip;
727
728         # Remove everything until and including the compiler command. Makes
729         # checks easier and faster.
730         $line =~ s/^.*?$cc_regex//o;
731         # "([...] test.c)" is not detected as 'test.c' - fix this by removing
732         # the brace and similar characters.
733         $line =~ s/['")]+$//;
734
735         # Skip unnecessary tests when only preprocessing.
736         my $flag_preprocess = 0;
737
738         my $preprocess = 0;
739         my $compile    = 0;
740         my $link       = 0;
741
742         # Preprocess, compile, assemble.
743         if ($line =~ /\s(-E|-S|-c)\b/) {
744             $preprocess      = 1;
745             $flag_preprocess = 1 if $1 eq '-E';
746             $compile         = 1 if $1 eq '-S' or $1 eq '-c';
747         # Otherwise assume we are linking.
748         } else {
749             $link = 1;
750         }
751
752         # Get all file extensions on this line.
753         my @extensions = $line =~ /$file_extension_regex/go;
754         # Ignore all unknown extensions to speedup the search below.
755         @extensions = grep { exists $extension{$_} } @extensions;
756
757         # These file types don't require preprocessing.
758         if (extension_found(\%extensions_no_preprocess, @extensions)) {
759             $preprocess = 0;
760         }
761         # These file types require preprocessing.
762         if (extension_found(\%extensions_preprocess, @extensions)) {
763             $preprocess = 1;
764         }
765
766         # If there are source files then it's compiling/linking in one step
767         # and we must check both. We only check for source files here, because
768         # header files cause too many false positives.
769         if (not $flag_preprocess
770                 and extension_found(\%extensions_compile_link, @extensions)) {
771             # Assembly files don't need CFLAGS.
772             if (not extension_found(\%extensions_compile, @extensions)
773                     and extension_found(\%extensions_no_compile, @extensions)) {
774                 $compile = 0;
775             # But the rest does.
776             } else {
777                 $compile = 1;
778             }
779         }
780
781         # Assume CXXFLAGS are required when a C++ file is specified in the
782         # compiler line.
783         my $compile_cpp = 0;
784         if ($compile
785                 and extension_found(\%extensions_compile_cpp, @extensions)) {
786             $compile     = 0;
787             $compile_cpp = 1;
788         }
789
790         if ($option_buildd) {
791             $statistics{preprocess}++  if $preprocess;
792             $statistics{compile}++     if $compile;
793             $statistics{compile_cpp}++ if $compile_cpp;
794             $statistics{link}++        if $link;
795         }
796
797         # Check hardening flags.
798         my @missing;
799         if ($compile and not all_flags_used($line, \@missing, @cflags)
800                 # Libraries linked with -fPIC don't have to (and can't) be
801                 # linked with -fPIE as well. It's no error if only PIE flags
802                 # are missing.
803                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
804                 # Assume dpkg-buildflags returns the correct flags.
805                 and not $line =~ /`dpkg-buildflags --get CFLAGS`/) {
806             if (not $option_buildd) {
807                 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
808             } else {
809                 $statistics{compile_missing}++;
810             }
811             $exit |= $exit_code{flags_missing};
812         } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
813                 # Libraries linked with -fPIC don't have to (and can't) be
814                 # linked with -fPIE as well. It's no error if only PIE flags
815                 # are missing.
816                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
817                 # Assume dpkg-buildflags returns the correct flags.
818                 and not $line =~ /`dpkg-buildflags --get CXXFLAGS`/) {
819             if (not $option_buildd) {
820                 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
821             } else {
822                 $statistics{compile_cpp_missing}++;
823             }
824             $exit |= $exit_code{flags_missing};
825         }
826         if ($preprocess and not all_flags_used($line, \@missing, @cppflags)
827                 # Assume dpkg-buildflags returns the correct flags.
828                 and not $line =~ /`dpkg-buildflags --get CPPFLAGS`/) {
829             if (not $option_buildd) {
830                 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
831             } else {
832                 $statistics{preprocess_missing}++;
833             }
834             $exit |= $exit_code{flags_missing};
835         }
836         if ($link and not all_flags_used($line, \@missing, @ldflags)
837                 # Same here, -fPIC conflicts with -fPIE.
838                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
839                 # Assume dpkg-buildflags returns the correct flags.
840                 and not $line =~ /`dpkg-buildflags --get LDFLAGS`/) {
841             if (not $option_buildd) {
842                 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
843             } else {
844                 $statistics{link_missing}++;
845             }
846             $exit |= $exit_code{flags_missing};
847         }
848     }
849 }
850
851 # Print statistics for buildd mode, only output in this mode.
852 if ($option_buildd) {
853     my @warning;
854
855     if ($statistics{preprocess_missing}) {
856         push @warning, sprintf "CPPFLAGS %d (of %d)",
857                                $statistics{preprocess_missing},
858                                $statistics{preprocess};
859     }
860     if ($statistics{compile_missing}) {
861         push @warning, sprintf "CFLAGS %d (of %d)",
862                                $statistics{compile_missing},
863                                $statistics{compile};
864     }
865     if ($statistics{compile_cpp_missing}) {
866         push @warning, sprintf "CXXFLAGS %d (of %d)",
867                                $statistics{compile_cpp_missing},
868                                $statistics{compile_cpp};
869     }
870     if ($statistics{link_missing}) {
871         push @warning, sprintf "LDFLAGS %d (of %d)",
872                                $statistics{link_missing},
873                                $statistics{link};
874     }
875     if (scalar @warning) {
876         local $" = ', '; # array join string
877         print "W-dpkg-buildflags-missing @warning missing\n";
878     }
879
880     if ($statistics{commands_nonverbose}) {
881         printf "W-compiler-flags-hidden %d (of %d) hidden\n",
882                $statistics{commands_nonverbose},
883                $statistics{commands},
884     }
885 }
886
887
888 exit $exit;
889
890
891 __END__
892
893 =head1 NAME
894
895 blhc - build log hardening check, checks build logs for missing hardening flags
896
897 =head1 SYNOPSIS
898
899 B<blhc> [I<options>] I<E<lt>dpkg-buildpackage build log fileE<gt>..>
900
901 =head1 DESCRIPTION
902
903 blhc is a small tool which checks build logs for missing hardening flags and
904 other important warnings. It's licensed under the GPL 3 or later.
905
906 =head1 OPTIONS
907
908 =over 8
909
910 =item B<--all>
911
912 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
913 auto detected.
914
915 =item B<--arch> I<architecture>
916
917 Set the specific architecture (e.g. amd64, armel, etc.), automatically
918 disables hardening flags not available on this architecture. Is detected
919 automatically if dpkg-buildpackage is used.
920
921 =item B<--bindnow>
922
923 Force check for all +bindnow hardening flags. By default it's auto detected.
924
925 =item B<--buildd>
926
927 Special mode for buildds when automatically parsing log files. The following
928 changes are in effect:
929
930 =over 2
931
932 =item
933
934 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
935 detected).
936
937 =back
938
939 =item B<--color>
940
941 Use colored (ANSI) output for warning messages.
942
943 =item B<--pie>
944
945 Force check for all +pie hardening flags. By default it's auto detected.
946
947 =item B<-h -? --help>
948
949 Print available options.
950
951 =item B<--version>
952
953 Print version number and license.
954
955 =back
956
957 Auto detection for B<--pie> and B<--bindnow> only works if at least one
958 command uses the required hardening flag (e.g. -fPIE). Then it's required for
959 all other commands as well.
960
961 =head1 EXIT STATUS
962
963 The exit status is a "bit mask", each listed status is ORed when the error
964 condition occurs to get the result.
965
966 =over 4
967
968 =item B<0>
969
970 Success.
971
972 =item B<1>
973
974 No compiler commands were found.
975
976 =item B<2>
977
978 Invalid arguments/options given to blhc.
979
980 =item B<4>
981
982 Non verbose build.
983
984 =item B<8>
985
986 Missing hardening flags.
987
988 =item B<16>
989
990 Hardening wrapper detected, no tests performed.
991
992 =back
993
994 =head1 AUTHOR
995
996 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
997
998 =head1 COPYRIGHT AND LICENSE
999
1000 Copyright (C) 2012 by Simon Ruderich
1001
1002 This program is free software: you can redistribute it and/or modify
1003 it under the terms of the GNU General Public License as published by
1004 the Free Software Foundation, either version 3 of the License, or
1005 (at your option) any later version.
1006
1007 This program is distributed in the hope that it will be useful,
1008 but WITHOUT ANY WARRANTY; without even the implied warranty of
1009 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1010 GNU General Public License for more details.
1011
1012 You should have received a copy of the GNU General Public License
1013 along with this program.  If not, see <http://www.gnu.org/licenses/>.
1014
1015 =cut