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