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