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