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