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