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