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