]> ruderich.org/simon Gitweb - blhc/blhc.git/blob - bin/blhc
Remove duplication when creating %extension.
[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 Term::ANSIColor ();
26 use Text::ParseWords ();
27
28 our $VERSION = '0.01';
29
30
31 # CONSTANTS/VARIABLES
32
33 # Regex to catch compiler commands.
34 my $cc_regex = qr/
35     (?<!\.)(?:cc|gcc|g\+\+|c\+\+)
36     (?:-[\d.]+)?
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 Mr),
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 ),
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 sx ),
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 # Renaming rules for the output so the regex parts are not visible. Also
193 # stores string values of flag regexps above, see compile_flag_regexp().
194 my %flag_renames = (
195     '-O(?:2|3)'         => '-O2',
196     '-Wl,(?:-z,)?relro' => '-Wl,-z,relro',
197     '-Wl,(?:-z,)?now'   => '-Wl,-z,now',
198 );
199
200 my %exit_code = (
201     no_compiler_commands => 1 << 0,
202     # used by POD::Usage => 1 << 1,
203     non_verbose_build    => 1 << 2,
204     flags_missing        => 1 << 3,
205     hardening_wrapper    => 1 << 4,
206     invalid_cmake        => 1 << 5,
207 );
208
209 # Statistics of missing flags and non-verbose build commands. Used for
210 # $option_buildd.
211 my %statistics = (
212     preprocess          => 0,
213     preprocess_missing  => 0,
214     compile             => 0,
215     compile_missing     => 0,
216     compile_cpp         => 0,
217     compile_cpp_missing => 0,
218     link                => 0,
219     link_missing        => 0,
220     commands            => 0,
221     commands_nonverbose => 0,
222 );
223
224 # Use colored (ANSI) output?
225 my $option_color;
226
227
228 # FUNCTIONS
229
230 sub error_flags {
231     my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
232
233     # Get string value of qr//-escaped regexps and if requested rename them.
234     my @missing_flags = map {
235             $flag_renames_ref->{$_}
236         } @{$missing_flags_ref};
237
238     my $flags = join ' ', @missing_flags;
239     printf "%s (%s)%s %s",
240            error_color($message, 'red'), $flags, error_color(':', 'yellow'),
241            $line;
242 }
243 sub error_non_verbose_build {
244     my ($line) = @_;
245
246     printf "%s%s %s",
247            error_color('NONVERBOSE BUILD', 'red'),
248            error_color(':', 'yellow'),
249            $line;
250 }
251 sub error_invalid_cmake {
252     my ($version) = @_;
253
254     printf "%s%s %s\n",
255             error_color('INVALID CMAKE', 'red'),
256             error_color(':', 'yellow'),
257             $version;
258 }
259 sub error_hardening_wrapper {
260     printf "%s%s %s\n",
261             error_color('HARDENING WRAPPER', 'red'),
262             error_color(':', 'yellow'),
263             'no checks possible, aborting';
264 }
265 sub error_color {
266     my ($message, $color) = @_;
267
268     if ($option_color) {
269         return Term::ANSIColor::colored($message, $color);
270     } else {
271         return $message;
272     }
273 }
274
275 sub any_flags_used {
276     my ($line, @flags) = @_;
277
278     foreach my $flag (@flags) {
279         return 1 if $line =~ /$flag/;
280     }
281
282     return 0;
283 }
284 sub all_flags_used {
285     my ($line, $missing_flags_ref, @flags) = @_;
286
287     my @missing_flags = ();
288     foreach my $flag (@flags) {
289         if (not $line =~ /$flag/) {
290             push @missing_flags, $flag;
291         }
292     }
293
294     return 1 if scalar @missing_flags == 0;
295
296     @{$missing_flags_ref} = @missing_flags;
297     return 0;
298 }
299
300 # Modifies $missing_flags_ref array.
301 sub pic_pie_conflict {
302     my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
303
304     return 0 if not $pie;
305     return 0 if not any_flags_used($line, @def_ldflags_pic);
306
307     my %flags = map { $_ => 1 } @flags_pie;
308
309     # Remove all PIE flags from @missing_flags as they are not required with
310     # -fPIC.
311     my @result = grep {
312         not exists $flags{$_}
313     } @{$missing_flags_ref};
314     @{$missing_flags_ref} = @result;
315
316     # We got a conflict when no flags are left, thus only PIE flags were
317     # missing. If other flags were missing abort because the conflict is not
318     # the problem.
319     return scalar @result == 0;
320 }
321
322 sub is_non_verbose_build {
323     my ($line, $next_line, $skip_ref) = @_;
324
325     if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
326                 or $line =~ /^\s*\[?(?:CC|CCLD|C\+\+|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
327                 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
328                 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
329                 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
330         return 0;
331     }
332
333     # False positives.
334     return 0 if $line =~ /^\s*C\+\+.+?:\s+(?:yes|no)\s*$/;
335
336     my $file = $1;
337
338     # On the first pass we only check if this line is verbose or not.
339     return 1 if not defined $next_line;
340
341     # Second pass, we have access to the next line.
342     ${$skip_ref} = 0;
343
344     # CMake and other build systems print the non-verbose messages also when
345     # building verbose. If a compiler and the file name occurs in the next
346     # line, treat it as verbose build.
347     if (defined $file) {
348         # Get filename, we can't use the complete path as only parts of it are
349         # used in the real compiler command.
350         $file =~ m{/([^/\s]+)$};
351         $file = $1;
352
353         if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/o) {
354             # We still have to skip the current line as it doesn't contain any
355             # compiler commands.
356             ${$skip_ref} = 1;
357             return 0;
358         }
359     }
360
361     return 1;
362 }
363
364 sub compile_flag_regexp {
365     my ($flag_renames_ref, @flags) = @_;
366
367     my @result = ();
368     foreach my $flag (@flags) {
369         # Store flag name in replacement string for correct flags in messages
370         # with qr//ed flag regexps.
371         $flag_renames_ref->{qr/\s$flag(?:\s|\\)/}
372             = (exists $flag_renames_ref->{$flag})
373                 ? $flag_renames_ref->{$flag}
374                 : $flag;
375
376         # Compile flag regexp for faster execution.
377         push @result, qr/\s$flag(?:\s|\\)/;
378     }
379     return @result;
380 }
381
382 sub extension_found {
383     my ($extensions_ref, @extensions) = @_;
384
385     my $found = 0;
386     foreach my $extension (@extensions) {
387         if (exists $extensions_ref->{$extension}) {
388             $found = 1;
389             last;
390         }
391     }
392     return $found;
393 }
394
395
396 # MAIN
397
398 # Parse command line arguments.
399 my $option_help    = 0;
400 my $option_version = 0;
401 my $option_pie     = 0;
402 my $option_bindnow = 0;
403 my $option_all     = 0;
404 my $option_arch    = undef;
405 my $option_buildd  = 0;
406    $option_color   = 0;
407 if (not Getopt::Long::GetOptions(
408             'help|h|?' => \$option_help,
409             'version'  => \$option_version,
410             # Hardening options.
411             'pie'      => \$option_pie,
412             'bindnow'  => \$option_bindnow,
413             'all'      => \$option_all,
414             # Misc.
415             'color'    => \$option_color,
416             'arch=s'   => \$option_arch,
417             'buildd'   => \$option_buildd,
418         )) {
419     require Pod::Usage;
420     Pod::Usage::pod2usage(2);
421 }
422 if ($option_help) {
423     require Pod::Usage;
424     Pod::Usage::pod2usage(1);
425 }
426 if ($option_version) {
427     print "blhc $VERSION  Copyright (C) 2012  Simon Ruderich
428
429 This program is free software: you can redistribute it and/or modify
430 it under the terms of the GNU General Public License as published by
431 the Free Software Foundation, either version 3 of the License, or
432 (at your option) any later version.
433
434 This program is distributed in the hope that it will be useful,
435 but WITHOUT ANY WARRANTY; without even the implied warranty of
436 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
437 GNU General Public License for more details.
438
439 You should have received a copy of the GNU General Public License
440 along with this program.  If not, see <http://www.gnu.org/licenses/>.
441 ";
442     exit 0;
443 }
444
445 if ($option_all) {
446     $option_pie     = 1;
447     $option_bindnow = 1;
448 }
449
450 # Precompile all flag regexps. any_flags_used(), all_flags_used() get a lot
451 # faster with this.
452 @def_cflags           = compile_flag_regexp(\%flag_renames, @def_cflags);
453 @def_cflags_format    = compile_flag_regexp(\%flag_renames, @def_cflags_format);
454 @def_cflags_fortify   = compile_flag_regexp(\%flag_renames, @def_cflags_fortify);
455 @def_cflags_stack     = compile_flag_regexp(\%flag_renames, @def_cflags_stack);
456 @def_cflags_pie       = compile_flag_regexp(\%flag_renames, @def_cflags_pie);
457 @def_cxxflags         = compile_flag_regexp(\%flag_renames, @def_cxxflags);
458 @def_cppflags         = compile_flag_regexp(\%flag_renames, @def_cppflags);
459 @def_cppflags_fortify = compile_flag_regexp(\%flag_renames, @def_cppflags_fortify);
460 @def_ldflags          = compile_flag_regexp(\%flag_renames, @def_ldflags);
461 @def_ldflags_relro    = compile_flag_regexp(\%flag_renames, @def_ldflags_relro);
462 @def_ldflags_bindnow  = compile_flag_regexp(\%flag_renames, @def_ldflags_bindnow);
463 @def_ldflags_pie      = compile_flag_regexp(\%flag_renames, @def_ldflags_pie);
464 @def_ldflags_pic      = compile_flag_regexp(\%flag_renames, @def_ldflags_pic);
465
466 # Final exit code.
467 my $exit = 0;
468
469 FILE: foreach my $file (@ARGV) {
470     print "checking '$file'...\n" if scalar @ARGV > 1;
471
472     open my $fh, '<', $file or die "$!: $file";
473
474     # Architecture of this file.
475     my $arch = $option_arch;
476
477     # Hardening options. Not all architectures support all hardening options.
478     my $harden_format  = 1;
479     my $harden_fortify = 1;
480     my $harden_stack   = 1;
481     my $harden_relro   = 1;
482     my $harden_bindnow = $option_bindnow; # defaults to 0
483     my $harden_pie     = $option_pie;     # defaults to 0
484
485     while (my $line = <$fh>) {
486         # dpkg-buildflags only provides hardening flags since 1.16.1, don't
487         # check for hardening flags in buildd mode if an older dpkg-dev is
488         # used. Default flags (-g -O2) are still checked.
489         #
490         # Packages which were built before 1.16.1 but used their own hardening
491         # flags are not checked.
492         if ($option_buildd and $line =~ /^Toolchain package versions: /) {
493             require Dpkg::Version;
494             if ($line !~ /\bdpkg-dev_(\S+)/
495                     or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
496                 $harden_format  = 0;
497                 $harden_fortify = 0;
498                 $harden_stack   = 0;
499                 $harden_relro   = 0;
500                 $harden_bindnow = 0;
501                 $harden_pie     = 0;
502             }
503         }
504
505         # The following two versions of CMake in Debian obeyed CPPFLAGS, but
506         # this was later dropped because upstream rejected the patch. Thus
507         # build logs with these versions will have fortify hardening flags
508         # enabled, even though they may be not correctly set and are missing
509         # when build with later CMake versions. Thanks to Aron Xu for letting
510         # me know.
511         if ($line =~ /^Package versions: /
512                 and $line =~ /\bcmake_(\S+)/
513                 and ($1 eq '2.8.7-1' or $1 eq '2.8.7-2')) {
514             if (not $option_buildd) {
515                 error_invalid_cmake($1);
516             } else {
517                 print "W-invalid-cmake-used $1\n";
518             }
519             $exit |= $exit_code{invalid_cmake};
520         }
521
522         # If hardening wrapper is used (wraps calls to gcc and adds hardening
523         # flags automatically) we can't perform any checks, abort.
524         if ($line =~ /^Build-Depends: .*\bhardening-wrapper\b/) {
525             if (not $option_buildd) {
526                 error_hardening_wrapper();
527             } else {
528                 print "I-hardening-wrapper-used\n";
529             }
530             $exit |= $exit_code{hardening_wrapper};
531             next FILE;
532         }
533
534         # We skip over unimportant lines at the beginning of the log to
535         # prevent false positives.
536         last if $line =~ /^dpkg-buildpackage:/;
537     }
538
539     # Input lines, contain only the lines with compiler commands.
540     my @input = ();
541
542     my $continuation = 0;
543     my $complete_line = undef;
544     while (my $line = <$fh>) {
545         # And stop at the end of the build log. Package details (reported by
546         # the buildd logs) are not important for us. This also prevents false
547         # positives.
548         last if $line =~ /^Build finished at \d{8}-\d{4}$/;
549
550         # Detect architecture automatically unless overridden.
551         if (not $arch
552                 and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
553             $arch = $1;
554         }
555
556         # Ignore compiler warnings for now.
557         next if $line =~ /$warning_regex/o;
558
559         if ($line =~ /\033/) { # esc
560             # Remove all ANSI color sequences which are sometimes used in
561             # non-verbose builds.
562             $line = Term::ANSIColor::colorstrip($line);
563             # Also strip '\0xf' (delete previous character), used by Elinks'
564             # build system.
565             $line =~ s/\x0f//g;
566             # And "ESC(B" which seems to be used on armhf and hurd (not sure
567             # what it does).
568             $line =~ s/\033\(B//g;
569         }
570
571         # Check if this line indicates a non verbose build.
572         my $non_verbose = is_non_verbose_build($line);
573
574         # One line may contain multiple commands (";"). Treat each one as
575         # single line. parse_line() is slow, only use it when necessary.
576         my @line = (not $line =~ /;/)
577                  ? ($line)
578                  : map {
579                        # Ensure newline at the line end - necessary for
580                        # correct parsing later.
581                        $_ =~ s/\s+$//;
582                        $_ .= "\n";
583                    } Text::ParseWords::parse_line(';', 1, $line);
584         foreach $line (@line) {
585             if ($continuation) {
586                 $continuation = 0;
587
588                 # Join lines, but leave the "\" in place so it's clear where
589                 # the original line break was.
590                 chomp $complete_line;
591                 $complete_line .= ' ' . $line;
592             }
593             # Line continuation, line ends with "\".
594             if ($line =~ /\\\s*$/) {
595                 $continuation = 1;
596                 # Start line continuation.
597                 if (not defined $complete_line) {
598                     $complete_line = $line;
599                 }
600                 next;
601             }
602
603             if (not $continuation) {
604                 # Use the complete line if a line continuation occurred.
605                 if (defined $complete_line) {
606                     $line = $complete_line;
607                     $complete_line = undef;
608                 }
609
610                 # Ignore lines with no compiler commands.
611                 next if not $non_verbose
612                         and not $line =~ /\b$cc_regex(?:\s|\\)/o;
613                 # Ignore lines with no filenames with extensions. May miss
614                 # some non-verbose builds (e.g. "gcc -o test" [sic!]), but
615                 # shouldn't be a problem as the log will most likely contain
616                 # other non-verbose commands which are detected.
617                 next if not $non_verbose
618                         and not $line =~ /$file_extension_regex/o;
619
620                 # Ignore false positives.
621                 #
622                 # `./configure` output.
623                 next if not $non_verbose
624                         and $line =~ /^(?:checking|(?:C|c)onfigure:) /;
625                 next if $line =~ /^\s*(?:Host\s+)?(?:C(?:\+\+)?\s+)?
626                                    (?:C|c)ompiler[\s.]*:?\s+
627                                  /xo;
628                 next if $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex_full\s*$/o;
629
630                 # Check if additional hardening options were used. Used to
631                 # ensure they are used for the complete build.
632                 $harden_pie     = 1 if any_flags_used($line, @def_cflags_pie, @def_ldflags_pie);
633                 $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);
634
635                 push @input, $line;
636             }
637         }
638     }
639
640     close $fh;
641
642     if (scalar @input == 0) {
643         if (not $option_buildd) {
644             print "No compiler commands!\n";
645         } else {
646             print "W-no-compiler-commands\n";
647         }
648         $exit |= $exit_code{no_compiler_commands};
649         next FILE;
650     }
651
652     if ($option_buildd) {
653         $statistics{commands} += scalar @input;
654     }
655
656     # Option or auto detected.
657     if ($arch) {
658         # The following was partially copied from dpkg-dev 1.16.1.2
659         # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
660         # copyright Raphaël Hertzog <hertzog@debian.org>, Kees Cook
661         # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
662         # later. Keep it in sync.
663
664         require Dpkg::Arch;
665         my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($arch);
666
667         # Disable unsupported hardening options.
668         if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $arch eq 'arm') {
669             $harden_stack = 0;
670         }
671         if ($cpu =~ /^(ia64|hppa|avr32)$/) {
672             $harden_relro   = 0;
673             $harden_bindnow = 0;
674         }
675     }
676
677     # Default values.
678     my @cflags   = @def_cflags;
679     my @cxxflags = @def_cxxflags;
680     my @cppflags = @def_cppflags;
681     my @ldflags  = @def_ldflags;
682     # Check the specified hardening options, same order as dpkg-buildflags.
683     if ($harden_pie) {
684         @cflags   = (@cflags,   @def_cflags_pie);
685         @cxxflags = (@cxxflags, @def_cflags_pie);
686         @ldflags  = (@ldflags,  @def_ldflags_pie);
687     }
688     if ($harden_stack) {
689         @cflags   = (@cflags,   @def_cflags_stack);
690         @cxxflags = (@cxxflags, @def_cflags_stack);
691     }
692     if ($harden_fortify) {
693         @cflags   = (@cflags,   @def_cflags_fortify);
694         @cxxflags = (@cxxflags, @def_cflags_fortify);
695         @cppflags = (@cppflags, @def_cppflags_fortify);
696     }
697     if ($harden_format) {
698         @cflags   = (@cflags,   @def_cflags_format);
699         @cxxflags = (@cxxflags, @def_cflags_format);
700     }
701     if ($harden_relro) {
702         @ldflags = (@ldflags, @def_ldflags_relro);
703     }
704     if ($harden_bindnow) {
705         @ldflags = (@ldflags, @def_ldflags_bindnow);
706     }
707
708     for (my $i = 0; $i < scalar @input; $i++) {
709         my $line = $input[$i];
710
711         my $skip = 0;
712         if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
713             if (not $option_buildd) {
714                 error_non_verbose_build($line);
715             } else {
716                 $statistics{commands_nonverbose}++;
717             }
718             $exit |= $exit_code{non_verbose_build};
719             next;
720         }
721         # Even if it's a verbose build, we might have to skip this line.
722         next if $skip;
723
724         # Remove everything until and including the compiler command. Makes
725         # checks easier and faster.
726         $line =~ s/^.*?$cc_regex//o;
727         # "([...] test.c)" is not detected as 'test.c' - fix this by removing
728         # the brace and similar characters.
729         $line =~ s/['")]+$//;
730
731         # Skip unnecessary tests when only preprocessing.
732         my $flag_preprocess = 0;
733
734         my $preprocess = 0;
735         my $compile    = 0;
736         my $link       = 0;
737
738         # Preprocess, compile, assemble.
739         if ($line =~ /\s(-E|-S|-c)\b/) {
740             $preprocess      = 1;
741             $flag_preprocess = 1 if $1 eq '-E';
742             $compile         = 1 if $1 eq '-S' or $1 eq '-c';
743         # Otherwise assume we are linking.
744         } else {
745             $link = 1;
746         }
747
748         # Get all file extensions on this line.
749         my @extensions = $line =~ /$file_extension_regex/go;
750         # Ignore all unknown extensions to speedup the search below.
751         @extensions = grep { exists $extension{$_} } @extensions;
752
753         # These file types don't require preprocessing.
754         if (extension_found(\%extensions_no_preprocess, @extensions)) {
755             $preprocess = 0;
756         }
757         # These file types require preprocessing.
758         if (extension_found(\%extensions_preprocess, @extensions)) {
759             $preprocess = 1;
760         }
761
762         # If there are source files then it's compiling/linking in one step
763         # and we must check both. We only check for source files here, because
764         # header files cause too many false positives.
765         if (not $flag_preprocess
766                 and extension_found(\%extensions_compile_link, @extensions)) {
767             # Assembly files don't need CFLAGS.
768             if (not extension_found(\%extensions_compile, @extensions)
769                     and extension_found(\%extensions_no_compile, @extensions)) {
770                 $compile = 0;
771             # But the rest does.
772             } else {
773                 $compile = 1;
774             }
775         }
776
777         # Assume CXXFLAGS are required when a C++ file is specified in the
778         # compiler line.
779         my $compile_cpp = 0;
780         if ($compile
781                 and extension_found(\%extensions_compile_cpp, @extensions)) {
782             $compile     = 0;
783             $compile_cpp = 1;
784         }
785
786         if ($option_buildd) {
787             $statistics{preprocess}++  if $preprocess;
788             $statistics{compile}++     if $compile;
789             $statistics{compile_cpp}++ if $compile_cpp;
790             $statistics{link}++        if $link;
791         }
792
793         # Check hardening flags.
794         my @missing;
795         if ($compile and not all_flags_used($line, \@missing, @cflags)
796                 # Libraries linked with -fPIC don't have to (and can't) be
797                 # linked with -fPIE as well. It's no error if only PIE flags
798                 # are missing.
799                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
800                 # Assume dpkg-buildflags returns the correct flags.
801                 and not $line =~ /`dpkg-buildflags --get CFLAGS`/) {
802             if (not $option_buildd) {
803                 error_flags('CFLAGS missing', \@missing, \%flag_renames, $input[$i]);
804             } else {
805                 $statistics{compile_missing}++;
806             }
807             $exit |= $exit_code{flags_missing};
808         } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
809                 # Libraries linked with -fPIC don't have to (and can't) be
810                 # linked with -fPIE as well. It's no error if only PIE flags
811                 # are missing.
812                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
813                 # Assume dpkg-buildflags returns the correct flags.
814                 and not $line =~ /`dpkg-buildflags --get CXXFLAGS`/) {
815             if (not $option_buildd) {
816                 error_flags('CXXFLAGS missing', \@missing, \%flag_renames, $input[$i]);
817             } else {
818                 $statistics{compile_cpp_missing}++;
819             }
820             $exit |= $exit_code{flags_missing};
821         }
822         if ($preprocess and not all_flags_used($line, \@missing, @cppflags)
823                 # Assume dpkg-buildflags returns the correct flags.
824                 and not $line =~ /`dpkg-buildflags --get CPPFLAGS`/) {
825             if (not $option_buildd) {
826                 error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $input[$i]);
827             } else {
828                 $statistics{preprocess_missing}++;
829             }
830             $exit |= $exit_code{flags_missing};
831         }
832         if ($link and not all_flags_used($line, \@missing, @ldflags)
833                 # Same here, -fPIC conflicts with -fPIE.
834                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
835                 # Assume dpkg-buildflags returns the correct flags.
836                 and not $line =~ /`dpkg-buildflags --get LDFLAGS`/) {
837             if (not $option_buildd) {
838                 error_flags('LDFLAGS missing', \@missing, \%flag_renames, $input[$i]);
839             } else {
840                 $statistics{link_missing}++;
841             }
842             $exit |= $exit_code{flags_missing};
843         }
844     }
845 }
846
847 # Print statistics for buildd mode, only output in this mode.
848 if ($option_buildd) {
849     my @warning;
850
851     if ($statistics{preprocess_missing}) {
852         push @warning, sprintf "CPPFLAGS %d (of %d)",
853                                $statistics{preprocess_missing},
854                                $statistics{preprocess};
855     }
856     if ($statistics{compile_missing}) {
857         push @warning, sprintf "CFLAGS %d (of %d)",
858                                $statistics{compile_missing},
859                                $statistics{compile};
860     }
861     if ($statistics{compile_cpp_missing}) {
862         push @warning, sprintf "CXXFLAGS %d (of %d)",
863                                $statistics{compile_cpp_missing},
864                                $statistics{compile_cpp};
865     }
866     if ($statistics{link_missing}) {
867         push @warning, sprintf "LDFLAGS %d (of %d)",
868                                $statistics{link_missing},
869                                $statistics{link};
870     }
871     if (scalar @warning) {
872         local $" = ', '; # array join string
873         print "W-dpkg-buildflags-missing @warning missing\n";
874     }
875
876     if ($statistics{commands_nonverbose}) {
877         printf "W-compiler-flags-hidden %d (of %d) hidden\n",
878                $statistics{commands_nonverbose},
879                $statistics{commands},
880     }
881 }
882
883
884 exit $exit;
885
886
887 __END__
888
889 =head1 NAME
890
891 blhc - build log hardening check, checks build logs for missing hardening flags
892
893 =head1 SYNOPSIS
894
895 B<blhc> [I<options>] I<E<lt>dpkg-buildpackage build log fileE<gt>..>
896
897 =head1 DESCRIPTION
898
899 blhc is a small tool which checks build logs for missing hardening flags and
900 other important warnings. It's licensed under the GPL 3 or later.
901
902 =head1 OPTIONS
903
904 =over 8
905
906 =item B<--all>
907
908 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
909 auto detected.
910
911 =item B<--arch> I<architecture>
912
913 Set the specific architecture (e.g. amd64, armel, etc.), automatically
914 disables hardening flags not available on this architecture. Is detected
915 automatically if dpkg-buildpackage is used.
916
917 =item B<--bindnow>
918
919 Force check for all +bindnow hardening flags. By default it's auto detected.
920
921 =item B<--buildd>
922
923 Special mode for buildds when automatically parsing log files. The following
924 changes are in effect:
925
926 =over 2
927
928 =item
929
930 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
931 detected).
932
933 =back
934
935 =item B<--color>
936
937 Use colored (ANSI) output for warning messages.
938
939 =item B<--pie>
940
941 Force check for all +pie hardening flags. By default it's auto detected.
942
943 =item B<-h -? --help>
944
945 Print available options.
946
947 =item B<--version>
948
949 Print version number and license.
950
951 =back
952
953 Auto detection for B<--pie> and B<--bindnow> only works if at least one
954 command uses the required hardening flag (e.g. -fPIE). Then it's required for
955 all other commands as well.
956
957 =head1 EXIT STATUS
958
959 The exit status is a "bit mask", each listed status is ORed when the error
960 condition occurs to get the result.
961
962 =over 4
963
964 =item B<0>
965
966 Success.
967
968 =item B<1>
969
970 No compiler commands were found.
971
972 =item B<2>
973
974 Invalid arguments/options given to blhc.
975
976 =item B<4>
977
978 Non verbose build.
979
980 =item B<8>
981
982 Missing hardening flags.
983
984 =item B<16>
985
986 Hardening wrapper detected, no tests performed.
987
988 =back
989
990 =head1 AUTHOR
991
992 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
993
994 =head1 COPYRIGHT AND LICENSE
995
996 Copyright (C) 2012 by Simon Ruderich
997
998 This program is free software: you can redistribute it and/or modify
999 it under the terms of the GNU General Public License as published by
1000 the Free Software Foundation, either version 3 of the License, or
1001 (at your option) any later version.
1002
1003 This program is distributed in the hope that it will be useful,
1004 but WITHOUT ANY WARRANTY; without even the implied warranty of
1005 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1006 GNU General Public License for more details.
1007
1008 You should have received a copy of the GNU General Public License
1009 along with this program.  If not, see <http://www.gnu.org/licenses/>.
1010
1011 =cut