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