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