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