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