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