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