]> ruderich.org/simon Gitweb - blhc/blhc.git/blob - bin/blhc
don't check for source fortification in debug lines
[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-2013  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.04';
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-2013  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 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.17.11
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
996                 $cpu =~ /^(?:hppa|mips|mipsel|avr32)$/) {
997             $harden_pie = 0;
998         }
999         if ($cpu =~ /^(?:ia64|alpha|mips|mipsel|hppa)$/ or $arch eq 'arm') {
1000             $harden_stack = 0;
1001             $harden_stack_strong = 0;
1002         }
1003         if ($arch =~ /^(?:m68k|or1k|powerpcspe|sh4|x32)$/) {
1004             $harden_stack_strong = 0;
1005         }
1006         if ($cpu =~ /^(?:ia64|hppa|avr32)$/) {
1007             $harden_relro   = 0;
1008             $harden_bindnow = 0;
1009         }
1010     }
1011
1012     # Default values.
1013     my @cflags   = @def_cflags;
1014     my @cxxflags = @def_cxxflags;
1015     my @cppflags = @def_cppflags;
1016     my @ldflags  = @def_ldflags;
1017     # Check the specified hardening options, same order as dpkg-buildflags.
1018     if ($harden_pie) {
1019         @cflags   = (@cflags,   @def_cflags_pie);
1020         @cxxflags = (@cxxflags, @def_cflags_pie);
1021         @ldflags  = (@ldflags,  @def_ldflags_pie);
1022     }
1023     if ($harden_stack_strong) {
1024         @cflags   = (@cflags,   @def_cflags_stack_strong);
1025         @cxxflags = (@cxxflags, @def_cflags_stack_strong);
1026     } elsif ($harden_stack) {
1027         @cflags   = (@cflags,   @def_cflags_stack);
1028         @cxxflags = (@cxxflags, @def_cflags_stack);
1029     }
1030     if ($harden_fortify) {
1031         @cflags   = (@cflags,   @def_cflags_fortify);
1032         @cxxflags = (@cxxflags, @def_cflags_fortify);
1033         @cppflags = (@cppflags, @def_cppflags_fortify);
1034     }
1035     if ($harden_format) {
1036         @cflags   = (@cflags,   @def_cflags_format);
1037         @cxxflags = (@cxxflags, @def_cflags_format);
1038     }
1039     if ($harden_relro) {
1040         @ldflags = (@ldflags, @def_ldflags_relro);
1041     }
1042     if ($harden_bindnow) {
1043         @ldflags = (@ldflags, @def_ldflags_bindnow);
1044     }
1045
1046     # Stores normal CFLAGS when @cflags_ada are temporarily used.
1047     my @cflags_backup;
1048     # Ada CFLAGS, only set if ada is used.
1049     my @cflags_ada;
1050     # Ada doesn't support format hardening flags, see #680117 for more
1051     # information. Filter them out if ada is used.
1052     if ($ada and $harden_format) {
1053         @cflags_ada = grep {
1054             my $ok = 1;
1055             foreach my $flag (@def_cflags_format) {
1056                 $ok = 0 if $_ eq $flag;
1057             }
1058             $ok;
1059         } @cflags;
1060     }
1061
1062     # Hack to fix cppflags_fortify_broken() if --ignore-flag
1063     # -D_FORTIFY_SOURCE=2 is used to ignore missing fortification. Only works
1064     # as long as @def_cppflags_fortify contains only one variable.
1065     if (scalar @def_cppflags_fortify == 0) {
1066         $harden_fortify = 0;
1067     }
1068
1069     # Ignore flags for this arch if requested.
1070     if ($arch and exists $option_ignore_arch_flag{$arch}) {
1071         my @local_flag_refs = (\@cflags, \@cxxflags, \@cppflags, \@ldflags);
1072
1073         remove_flags(\@local_flag_refs,
1074                      \%flag_renames,
1075                      @{$option_ignore_arch_flag{$arch}});
1076     }
1077
1078     my @ignore_line = @option_ignore_line;
1079     # Ignore lines for this arch if requested.
1080     if ($arch and exists $option_ignore_arch_line{$arch}) {
1081         @ignore_line = (@ignore_line, @{$option_ignore_arch_line{$arch}});
1082     }
1083
1084 LINE:
1085     for (my $i = 0; $i < scalar @input; $i++) {
1086         my $line = $input[$i];
1087
1088         # Ignore line if requested.
1089         foreach my $ignore (@ignore_line) {
1090             next LINE if $line =~ /$ignore/;
1091         }
1092
1093         my $skip = 0;
1094         if ($input_nonverbose[$i]
1095                 and is_non_verbose_build($line, $input[$i + 1], \$skip)) {
1096             if (not $option_buildd) {
1097                 error_non_verbose_build($line);
1098                 $exit |= $exit_code{non_verbose_build};
1099             } else {
1100                 $statistics{commands_nonverbose}++;
1101             }
1102             next;
1103         }
1104         # Even if it's a verbose build, we might have to skip this line (see
1105         # is_non_verbose_build()).
1106         next if $skip;
1107
1108         # Remove everything until and including the compiler command. Makes
1109         # checks easier and faster.
1110         $line =~ s/^.*?$cc_regex//o;
1111         # "([...] test.c)" is not detected as 'test.c' - fix this by removing
1112         # the brace and similar characters at the line end.
1113         $line =~ s/['")]+$//;
1114
1115         # Skip unnecessary tests when only preprocessing.
1116         my $flag_preprocess = 0;
1117
1118         my $dependency = 0;
1119         my $preprocess = 0;
1120         my $compile    = 0;
1121         my $link       = 0;
1122
1123         # Preprocess, compile, assemble.
1124         if ($line =~ /\s(-E|-S|-c)\b/) {
1125             $preprocess      = 1;
1126             $flag_preprocess = 1 if $1 eq '-E';
1127             $compile         = 1 if $1 eq '-S' or $1 eq '-c';
1128         # Dependency generation for Makefiles. The other flags (-MF -MG -MP
1129         # -MT -MQ) are always used with -M/-MM.
1130         } elsif ($line =~ /\s(?:-M|-MM)\b/) {
1131             $dependency = 1;
1132         # Otherwise assume we are linking.
1133         } else {
1134             $link = 1;
1135         }
1136
1137         # -MD/-MMD also cause dependency generation, but they don't imply -E!
1138         if ($line =~ /\s(?:-MD|-MMD)\b/) {
1139             $dependency      = 0;
1140             $flag_preprocess = 0;
1141         }
1142
1143         # Dependency generation for Makefiles, no preprocessing or other flags
1144         # needed.
1145         next if $dependency;
1146
1147         # Get all file extensions on this line.
1148         my @extensions = $line =~ /$file_extension_regex/go;
1149         # Ignore all unknown extensions to speedup the search below.
1150         @extensions = grep { exists $extension{$_} } @extensions;
1151
1152         # These file types don't require preprocessing.
1153         if (extension_found(\%extensions_no_preprocess, @extensions)) {
1154             $preprocess = 0;
1155         }
1156         # These file types require preprocessing.
1157         if (extension_found(\%extensions_preprocess, @extensions)) {
1158             $preprocess = 1;
1159         }
1160
1161         if (not $flag_preprocess) {
1162             # If there are source files then it's compiling/linking in one
1163             # step and we must check both. We only check for source files
1164             # here, because header files cause too many false positives.
1165             if (extension_found(\%extensions_compile_link, @extensions)) {
1166                 # Assembly files don't need CFLAGS.
1167                 if (not extension_found(\%extensions_compile, @extensions)
1168                         and extension_found(\%extensions_no_compile, @extensions)) {
1169                     $compile = 0;
1170                 # But the rest does.
1171                 } else {
1172                     $compile = 1;
1173                 }
1174             # No compilable extensions found, either linking or compiling
1175             # header flags.
1176             #
1177             # If there are also no object files we are just compiling headers
1178             # (.h -> .h.gch). Don't check for linker flags in this case. Due
1179             # to our liberal checks for compiler lines, this also reduces the
1180             # number of false positives considerably.
1181             } elsif ($link
1182                     and not extension_found(\%extensions_object, @extensions)) {
1183                 $link = 0;
1184             }
1185         }
1186
1187         my $compile_cpp = 0;
1188         my $compile_ada = 0;
1189         # Assume CXXFLAGS are required when a C++ file is specified in the
1190         # compiler line.
1191         if ($compile
1192                 and extension_found(\%extensions_compile_cpp, @extensions)) {
1193             $compile     = 0;
1194             $compile_cpp = 1;
1195         # Ada needs special CFLAGS, use them if only ada files are compiled.
1196         } elsif ($ada
1197                     and $compile
1198                     and array_equal(\@extensions,
1199                                     \@source_no_preprocess_compile_ada)) {
1200             $compile_ada = 1;
1201             @cflags_backup = @cflags;
1202             @cflags        = @cflags_ada;
1203         }
1204
1205         if ($option_buildd) {
1206             $statistics{preprocess}++  if $preprocess;
1207             $statistics{compile}++     if $compile;
1208             $statistics{compile_cpp}++ if $compile_cpp;
1209             $statistics{link}++        if $link;
1210         }
1211
1212         # Check if there are flags indicating a debug build. If that's true,
1213         # skip the check for -O2. This prevents fortification, but that's fine
1214         # for a debug build.
1215         if (any_flags_used($line, @def_cflags_debug)) {
1216             remove_flags([\@cflags], \%flag_renames, $def_cflags[1]);
1217             remove_flags([\@cppflags], \%flag_renames, $def_cppflags_fortify[0]);
1218         }
1219
1220         # Check hardening flags.
1221         my @missing;
1222         if ($compile and not all_flags_used($line, \@missing, @cflags)
1223                 # Libraries linked with -fPIC don't have to (and can't) be
1224                 # linked with -fPIE as well. It's no error if only PIE flags
1225                 # are missing.
1226                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1227                 # Assume dpkg-buildflags returns the correct flags.
1228                 and index($line, '`dpkg-buildflags --get CFLAGS`') == -1) {
1229             if (not $option_buildd) {
1230                 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1231                 $exit |= $exit_code{flags_missing};
1232             } else {
1233                 $statistics{compile_missing}++;
1234             }
1235         } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
1236                 # Libraries linked with -fPIC don't have to (and can't) be
1237                 # linked with -fPIE as well. It's no error if only PIE flags
1238                 # are missing.
1239                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1240                 # Assume dpkg-buildflags returns the correct flags.
1241                 and index($line, '`dpkg-buildflags --get CXXFLAGS`') == -1) {
1242             if (not $option_buildd) {
1243                 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1244                 $exit |= $exit_code{flags_missing};
1245             } else {
1246                 $statistics{compile_cpp_missing}++;
1247             }
1248         }
1249         if ($preprocess
1250                 and (not all_flags_used($line, \@missing, @cppflags)
1251                     # The fortify flag might be overwritten, detect that.
1252                      or ($harden_fortify
1253                          and cppflags_fortify_broken($line, \@missing)))
1254                 # Assume dpkg-buildflags returns the correct flags.
1255                 and index($line, '`dpkg-buildflags --get CPPFLAGS`') == -1) {
1256             if (not $option_buildd) {
1257                 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1258                 $exit |= $exit_code{flags_missing};
1259             } else {
1260                 $statistics{preprocess_missing}++;
1261             }
1262         }
1263         if ($link and not all_flags_used($line, \@missing, @ldflags)
1264                 # Same here, -fPIC conflicts with -fPIE.
1265                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
1266                 # Assume dpkg-buildflags returns the correct flags.
1267                 and index($line, '`dpkg-buildflags --get LDFLAGS`') == -1) {
1268             if (not $option_buildd) {
1269                 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
1270                 $exit |= $exit_code{flags_missing};
1271             } else {
1272                 $statistics{link_missing}++;
1273             }
1274         }
1275
1276         # Restore normal CFLAGS.
1277         if ($compile_ada) {
1278             @cflags = @cflags_backup;
1279         }
1280     }
1281 }
1282
1283 # Print statistics for buildd mode, only output in this mode.
1284 if ($option_buildd) {
1285     my @warning;
1286
1287     if ($statistics{preprocess_missing}) {
1288         push @warning, sprintf 'CPPFLAGS %d (of %d)',
1289                                $statistics{preprocess_missing},
1290                                $statistics{preprocess};
1291     }
1292     if ($statistics{compile_missing}) {
1293         push @warning, sprintf 'CFLAGS %d (of %d)',
1294                                $statistics{compile_missing},
1295                                $statistics{compile};
1296     }
1297     if ($statistics{compile_cpp_missing}) {
1298         push @warning, sprintf 'CXXFLAGS %d (of %d)',
1299                                $statistics{compile_cpp_missing},
1300                                $statistics{compile_cpp};
1301     }
1302     if ($statistics{link_missing}) {
1303         push @warning, sprintf 'LDFLAGS %d (of %d)',
1304                                $statistics{link_missing},
1305                                $statistics{link};
1306     }
1307     if (scalar @warning) {
1308         local $" = ', '; # array join string
1309         print "$buildd_tag{flags_missing}|@warning missing|\n";
1310     }
1311
1312     if ($statistics{commands_nonverbose}) {
1313         printf "$buildd_tag{non_verbose_build}|%d (of %d) hidden|\n",
1314                $statistics{commands_nonverbose},
1315                $statistics{commands},
1316     }
1317 }
1318
1319
1320 exit $exit;
1321
1322
1323 __END__
1324
1325 =head1 NAME
1326
1327 blhc - build log hardening check, checks build logs for missing hardening flags
1328
1329 =head1 SYNOPSIS
1330
1331 B<blhc> [I<options>] I<< <dpkg-buildpackage build log file>.. >>
1332
1333 =head1 DESCRIPTION
1334
1335 blhc is a small tool which checks build logs for missing hardening flags. It's
1336 licensed under the GPL 3 or later.
1337
1338 It's designed to check build logs generated by Debian's dpkg-buildpackage (or
1339 tools using dpkg-buildpackage like pbuilder or sbuild (which is used for the
1340 official buildd build logs)) to help maintainers detect missing hardening
1341 flags in their packages.
1342
1343 Only gcc is detected as compiler at the moment. If other compilers support
1344 hardening flags as well, please report them.
1345
1346 If there's no output, no flags are missing and the build log is fine.
1347
1348 See F<README> for details about performed checks, auto-detection and
1349 limitations.
1350
1351 =head1 OPTIONS
1352
1353 =over 8
1354
1355 =item B<--all>
1356
1357 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
1358 auto detected.
1359
1360 =item B<--arch> I<architecture>
1361
1362 Set the specific architecture (e.g. amd64, armel, etc.), automatically
1363 disables hardening flags not available on this architecture. Is detected
1364 automatically if dpkg-buildpackage is used.
1365
1366 =item B<--bindnow>
1367
1368 Force check for all +bindnow hardening flags. By default it's auto detected.
1369
1370 =item B<--buildd>
1371
1372 Special mode for buildds when automatically parsing log files. The following
1373 changes are in effect:
1374
1375 =over 2
1376
1377 =item *
1378
1379 Print tags instead of normal warnings, see L</"BUILDD TAGS"> for a list of
1380 possible tags.
1381
1382 =item *
1383
1384 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
1385 detected).
1386
1387 =item *
1388
1389 Don't require Term::ANSIColor.
1390
1391 =item *
1392
1393 Return exit code 0, unless there was a error (-I, -W messages don't count as
1394 error).
1395
1396 =back
1397
1398 =item B<--color>
1399
1400 Use colored (ANSI) output for warning messages.
1401
1402 =item B<--ignore-arch> I<arch>
1403
1404 Ignore build logs from architectures matching I<arch>. I<arch> is a string.
1405
1406 Used to prevent false positives. This option can be specified multiple times.
1407
1408 =item B<--ignore-arch-flag> I<arch>:I<flag>
1409
1410 Like B<--ignore-flag>, but only ignore flag on I<arch>.
1411
1412 =item B<--ignore-arch-line> I<arch>:I<line>
1413
1414 Like B<--ignore-line>, but only ignore line on I<arch>.
1415
1416 =item B<--ignore-flag> I<flag>
1417
1418 Don't print an error when the specific flag is missing in a compiler line.
1419 I<flag> is a string.
1420
1421 Used to prevent false positives. This option can be specified multiple times.
1422
1423 =item B<--ignore-line> I<regex>
1424
1425 Ignore lines matching the given Perl regex. I<regex> is automatically anchored
1426 at the beginning and end of the line to prevent false negatives.
1427
1428 B<NOTE>: Not the input lines are checked, but the lines which are displayed in
1429 warnings (which have line continuation resolved).
1430
1431 Used to prevent false positives. This option can be specified multiple times.
1432
1433 =item B<--pie>
1434
1435 Force check for all +pie hardening flags. By default it's auto detected.
1436
1437 =item B<-h -? --help>
1438
1439 Print available options.
1440
1441 =item B<--version>
1442
1443 Print version number and license.
1444
1445 =back
1446
1447 Auto detection for B<--pie> and B<--bindnow> only works if at least one
1448 command uses the required hardening flag (e.g. -fPIE). Then it's required for
1449 all other commands as well.
1450
1451 =head1 EXAMPLES
1452
1453 Normal usage, parse a single log file.
1454
1455     blhc path/to/log/file
1456
1457 If there's no output, no flags are missing and the build log is fine.
1458
1459 Parse multiple log files. The exit code is ORed over all files.
1460
1461     blhc path/to/directory/with/log/files/*
1462
1463 Don't treat missing C<-g> as error:
1464
1465     blhc --ignore-flag -g path/to/log/file
1466
1467 Don't treat missing C<-pie> on kfreebsd-amd64 as error:
1468
1469     blhc --ignore-arch-flag kfreebsd-amd64:-pie path/to/log/file
1470
1471 Ignore lines consisting exactly of C<./script gcc file> which would cause a
1472 false positive.
1473
1474     blhc --ignore-line '\./script gcc file' path/to/log/file
1475
1476 Ignore lines matching C<./script gcc file> somewhere in the line.
1477
1478     blhc --ignore-line '.*\./script gcc file.*' path/to/log/file
1479
1480 Use blhc with pbuilder.
1481
1482     pbuilder path/to/package.dsc | tee path/log/file
1483     blhc path/to/file || echo flags missing
1484
1485 =head1 BUILDD TAGS
1486
1487 The following tags are used in I<--buildd> mode. In braces the additional data
1488 which is displayed.
1489
1490 =over 2
1491
1492 =item B<I-hardening-wrapper-used>
1493
1494 The package uses hardening-wrapper which intercepts calls to gcc and adds
1495 hardening flags. The build log doesn't contain any hardening flags and thus
1496 can't be checked by blhc.
1497
1498 =item B<W-compiler-flags-hidden> (summary of hidden lines)
1499
1500 Build log contains lines which hide the real compiler flags. For example:
1501
1502     CC test-a.c
1503     CC test-b.c
1504     CC test-c.c
1505     LD test
1506
1507 Most of the time either C<export V=1> or C<export verbose=1> in
1508 F<debian/rules> fixes builds with hidden compiler flags. Sometimes C<.SILENT>
1509 in a F<Makefile> must be removed. And as last resort the F<Makefile> must be
1510 patched to remove the C<@>s hiding the real compiler commands.
1511
1512 =item B<W-dpkg-buildflags-missing> (summary of missing flags)
1513
1514 CPPFLAGS, CFLAGS, CXXFLAGS, LDFLAGS missing.
1515
1516 =item B<I-invalid-cmake-used> (version)
1517
1518 By default CMake ignores CPPFLAGS thus missing those hardening flags. Debian
1519 patched CMake in versions 2.8.7-1 and 2.8.7-2 to respect CPPFLAGS, but this
1520 patch was rejected by upstream and later reverted in Debian. Thus those two
1521 versions show correct usage of CPPFLAGS even if the package doesn't correctly
1522 handle them (for example by passing them to CFLAGS). To prevent false
1523 negatives just blacklist those two versions.
1524
1525 =item B<I-no-compiler-commands>
1526
1527 No compiler commands were detected. Either the log contains none or they were
1528 not correctly detected by blhc (please report the bug in this case).
1529
1530 =back
1531
1532 =head1 EXIT STATUS
1533
1534 The exit status is a "bit mask", each listed status is ORed when the error
1535 condition occurs to get the result.
1536
1537 =over 4
1538
1539 =item B<0>
1540
1541 Success.
1542
1543 =item B<1>
1544
1545 No compiler commands were found.
1546
1547 =item B<2>
1548
1549 Invalid arguments/options given to blhc.
1550
1551 =item B<4>
1552
1553 Non verbose build.
1554
1555 =item B<8>
1556
1557 Missing hardening flags.
1558
1559 =item B<16>
1560
1561 Hardening wrapper detected, no tests performed.
1562
1563 =item B<32>
1564
1565 Invalid CMake version used. See B<I-invalid-cmake-used> under L</"BUILDD
1566 TAGS"> for a detailed explanation.
1567
1568 =back
1569
1570 =head1 AUTHOR
1571
1572 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
1573
1574 Thanks to to Bernhard R. Link E<lt>brlink@debian.orgE<gt> and Jaria Alto
1575 E<lt>jari.aalto@cante.netE<gt> for their valuable input and suggestions.
1576
1577 =head1 LICENSE AND COPYRIGHT
1578
1579 Copyright (C) 2012-2013 by Simon Ruderich
1580
1581 This program is free software: you can redistribute it and/or modify
1582 it under the terms of the GNU General Public License as published by
1583 the Free Software Foundation, either version 3 of the License, or
1584 (at your option) any later version.
1585
1586 This program is distributed in the hope that it will be useful,
1587 but WITHOUT ANY WARRANTY; without even the implied warranty of
1588 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1589 GNU General Public License for more details.
1590
1591 You should have received a copy of the GNU General Public License
1592 along with this program.  If not, see <http://www.gnu.org/licenses/>.
1593
1594 =head1 SEE ALSO
1595
1596 L<hardening-check(1)>, L<dpkg-buildflags(1)>
1597
1598 =cut