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