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