]> ruderich.org/simon Gitweb - blhc/blhc.git/blob - bin/blhc
Detect compile type (preprocess, compile, link) correctly.
[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
27 our $VERSION = '0.01';
28
29
30 # CONSTANTS/VARIABLES
31
32 # Regex to catch compiler commands.
33 my $cc_regex = qr/(?:[a-z0-9_]+-(?:linux|kfreebsd)-gnu(?:eabi|eabihf)?-)?
34                   (?:(?<!\.)cc|gcc|g\+\+|c\+\+)
35                   (?:-[\d.]+)?/x;
36 # Regex to catch (GCC) compiler warnings.
37 my $warning_regex = qr/^(.+?):([0-9]+):[0-9]+: warning: (.+?) \[(.+?)\]$/;
38
39 # Regex for source files which require preprocessing.
40 my $source_preprocess_compile_regex = qr/
41     # C
42       c
43     # Objective-C
44     | m
45     # C++
46     | cc | cp | cxx | cpp | CPP | c\+\+ | C
47     # Objective-C++
48     | mm | M
49     # Fortran
50     | F | FOR | fpp | FPP | FTN | F90 | F95 | F03 | F08
51     /x;
52 my $source_preprocess_no_compile_regex = qr/
53     # Assembly
54       s
55     /x;
56 my $source_preprocess_regex = qr/
57       $source_preprocess_compile_regex
58     | $source_preprocess_no_compile_regex
59     /x;
60 # Regex for source files which don't require preprocessing.
61 my $source_no_preprocess_compile_regex = qr/
62     # C
63       i
64     # C++
65     | ii
66     # Objective-C
67     | mi
68     # Objective-C++
69     | mii
70     # Fortran
71     | f | for | ftn | f90 | f95 | f03 | f08
72     /x;
73 my $source_no_preprocess_no_compile_regex = qr/
74     # Assembly
75       S | sx
76     /x;
77 my $source_no_preprocess_regex = qr/
78       $source_no_preprocess_compile_regex
79     | $source_no_preprocess_no_compile_regex
80     /x;
81 # Regex for header files which require preprocessing.
82 my $header_preprocess_regex = qr/
83     # C, C++, Objective-C, Objective-C++
84       h
85     # C++
86     | hh | H | hp | hxx | hpp | HPP | h\+\+ | tcc
87     /x;
88 # Regexps to match files with the given characteristics.
89 my $file_no_preprocess_regex = qr/
90     $cc_regex.+?
91     \.(?: $source_no_preprocess_regex)\b
92     /x;
93 my $file_preprocess_regex = qr/
94     $cc_regex.+?
95     \.(?: $header_preprocess_regex
96         | $source_preprocess_regex)\b
97     /x;
98 my $file_compile_link_regex = qr/
99     $cc_regex.+?
100     \.(?: $source_preprocess_regex
101         | $source_no_preprocess_regex)\b
102     /x;
103 my $file_compile_regex = qr/
104     $cc_regex.+?
105     \.(?: $source_preprocess_compile_regex
106         | $source_no_preprocess_compile_regex)\b
107     /x;
108 my $file_no_compile_regex = qr/
109     $cc_regex.+
110     \.(?: $source_preprocess_no_compile_regex
111         | $source_no_preprocess_no_compile_regex)\b
112     /x;
113
114 # Expected (hardening) flags. All flags are used as regexps.
115 my @cflags = (
116     '-g',
117     '-O(?:2|3)',
118 );
119 my @cflags_format = (
120     '-Wformat',
121     '-Wformat-security',
122     '-Werror=format-security',
123 );
124 my @cflags_fortify = (
125     # fortify needs at least -O1, but -O2 is recommended anyway
126 );
127 my @cflags_stack = (
128     '-fstack-protector',
129     '--param=ssp-buffer-size=4',
130 );
131 my @cflags_pie = (
132     '-fPIE',
133 );
134 my @cppflags = ();
135 my @cppflags_fortify = (
136     '-D_FORTIFY_SOURCE=2',
137 );
138 my @ldflags = ();
139 my @ldflags_relro = (
140     '-Wl,(-z,)?relro',
141 );
142 my @ldflags_bindnow = (
143     '-Wl,(-z,)?now',
144 );
145 my @ldflags_pie = (
146     '-fPIE',
147     '-pie',
148 );
149 # Renaming rules for the output so the regex parts are not visible.
150 my %flag_renames = (
151     '-O(?:2|3)'       => '-O2',
152     '-Wl,(-z,)?relro' => '-Wl,-z,relro',
153     '-Wl,(-z,)?now'   => '-Wl,-z,now',
154 );
155
156
157 # FUNCTIONS
158
159 sub error_flags {
160     my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
161
162     # Rename flags if requested.
163     my @missing_flags = map {
164         (exists $flag_renames_ref->{$_})
165             ? $flag_renames_ref->{$_}
166             : $_
167     } @{$missing_flags_ref};
168
169     my $flags = join ' ', @missing_flags;
170     printf "%s (%s)%s %s",
171            error_color($message, 'red'), $flags, error_color(':', 'yellow'),
172            $line;
173 }
174 sub error_non_verbose_build {
175     my ($line) = @_;
176
177     printf "%s%s %s",
178            error_color('NONVERBOSE BUILD', 'red'),
179            error_color(':', 'yellow'),
180            $line;
181 }
182 sub error_color {
183     my ($message, $color) = @_;
184
185     # Use colors when writing to a terminal.
186     if (-t STDOUT) {
187         return Term::ANSIColor::colored($message, $color);
188     } else {
189         return $message;
190     }
191 }
192
193 sub any_flags_used {
194     my ($line, @flags) = @_;
195
196     foreach my $flag (@flags) {
197         return 1 if $line =~ /\s$flag(?:\s|\\)/;
198     }
199
200     return 0;
201 }
202 sub all_flags_used {
203     my ($line, $missing_flags_ref, @flags) = @_;
204
205     my @missing_flags = ();
206     foreach my $flag (@flags) {
207         if ($line !~ /\s$flag(?:\s|\\)/) {
208             push @missing_flags, $flag;
209         }
210     }
211
212     return 1 if scalar @missing_flags == 0;
213
214     @{$missing_flags_ref} = @missing_flags;
215     return 0;
216 }
217
218 # Modifies $missing_flags_ref array.
219 sub pic_pie_conflict {
220     my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
221
222     return 0 if not $pie;
223     return 0 if not any_flags_used($line, ('-fPIC', '-fpic'));
224
225     my %flags = map { $_ => 1 } @flags_pie;
226
227     # Remove all PIE flags from @missing_flags as they are not required with
228     # -fPIC.
229     my @result = grep {
230         not exists $flags{$_}
231     } @{$missing_flags_ref};
232     @{$missing_flags_ref} = @result;
233
234     # We got a conflict when no flags are left, thus only PIE flags were
235     # missing. If other flags were missing abort because the conflict is not
236     # the problem.
237     return scalar @result == 0;
238 }
239
240 sub is_non_verbose_build {
241     my ($line, $next_line, $skip_ref) = @_;
242
243     if (not ($line =~ /^checking if you want to see long compiling messages\.\.\. no/
244                 or $line =~ /^\s*\[?(?:CC|CCLD|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
245                 or $line =~ /^\s*(?:C|c)ompiling\s+(.+?)(?:\.\.\.)?$/
246                 or $line =~ /^\s*(?:B|b)uilding (?:program|shared library)\s+(.+?)$/
247                 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
248         return 0;
249     }
250
251     my $file = $1;
252
253     # On the first pass we only check if this line is verbose or not.
254     return 1 if not defined $next_line;
255
256     # Second pass, we have access to the next line.
257     ${$skip_ref} = 0;
258
259     # CMake and other build systems print the non-verbose messages also when
260     # building verbose. If a compiler and the file name occurs in the next
261     # line, treat it as verbose build.
262     if (defined $file) {
263         # Get filename, we can't use the complete path as only parts of it are
264         # used in the real compiler command.
265         $file =~ m{/([a-zA-Z0-9._-]+)$};
266         $file = $1;
267
268         if ($next_line =~ /\Q$file\E/ and $next_line =~ /$cc_regex/) {
269             # We still have to skip the current line as it doesn't contain any
270             # compiler commands.
271             ${$skip_ref} = 1;
272             return 0;
273         }
274     }
275
276     return 1;
277 }
278
279
280 # MAIN
281
282 # Hardening options. Not all architectures support all hardening options.
283 my $harden_format  = 1;
284 my $harden_fortify = 1;
285 my $harden_stack   = 1;
286 my $harden_relro   = 1;
287 my $harden_bindnow = 0;
288 my $harden_pie     = 0;
289
290 # Parse command line arguments.
291 my $option_help    = 0;
292 my $option_version = 0;
293 my $option_all     = 0;
294 my $option_arch    = undef;
295 my $option_buildd  = 0;
296 if (not Getopt::Long::GetOptions(
297             'help|h|?' => \$option_help,
298             'version'  => \$option_version,
299             # Hardening options.
300             'pie'      => \$harden_pie,
301             'bindnow'  => \$harden_bindnow,
302             'all'      => \$option_all,
303             # Misc.
304             'arch'     => \$option_arch,
305             'buildd'   => \$option_buildd,
306         )) {
307     require Pod::Usage;
308     Pod::Usage::pod2usage(2);
309 }
310 if ($option_help) {
311     require Pod::Usage;
312     Pod::Usage::pod2usage(1);
313 }
314 if ($option_version) {
315     print "blhc $VERSION  Copyright (C) 2012  Simon Ruderich
316
317 This program is free software: you can redistribute it and/or modify
318 it under the terms of the GNU General Public License as published by
319 the Free Software Foundation, either version 3 of the License, or
320 (at your option) any later version.
321
322 This program is distributed in the hope that it will be useful,
323 but WITHOUT ANY WARRANTY; without even the implied warranty of
324 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
325 GNU General Public License for more details.
326
327 You should have received a copy of the GNU General Public License
328 along with this program.  If not, see <http://www.gnu.org/licenses/>.
329 ";
330     exit 0;
331 }
332
333 if ($option_all) {
334     $harden_pie     = 1;
335     $harden_bindnow = 1;
336 }
337
338 # Final exit code.
339 my $exit = 0;
340
341 # Input lines, contain only the lines with compiler commands.
342 my @input = ();
343
344 my $start = 0;
345 my $continuation = 0;
346 my $complete_line = undef;
347 while (my $line = <>) {
348     # dpkg-buildflags only provides hardening flags since 1.16.1, don't check
349     # for hardening flags in buildd mode if an older dpkg-dev is used. Default
350     # flags (-g -O2) are still checked.
351     #
352     # Packages which were built before 1.16.1 but used their own hardening
353     # flags are not checked.
354     if ($option_buildd and not $start
355             and $line =~ /^Toolchain package versions: /) {
356         require Dpkg::Version;
357         if ($line !~ /dpkg-dev_(\S+)/
358                 or Dpkg::Version::version_compare($1, '1.16.1') < 0) {
359             $harden_format  = 0;
360             $harden_fortify = 0;
361             $harden_stack   = 0;
362             $harden_relro   = 0;
363             $harden_bindnow = 0;
364             $harden_pie     = 0;
365         }
366     }
367
368     # We skip over unimportant lines at the beginning of the log to prevent
369     # false positives.
370     $start = 1 if $line =~ /^dpkg-buildpackage:/;
371     next if not $start;
372
373     # Detect architecture automatically unless overridden.
374     if (not $option_arch
375             and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
376         $option_arch = $1;
377     }
378
379     # Ignore compiler warnings for now.
380     next if $line =~ /$warning_regex/;
381
382     # Remove all ANSI color sequences which are sometimes used in non-verbose
383     # builds.
384     $line = Term::ANSIColor::colorstrip($line);
385     # Also strip '\0xf' (delete previous character), used by Elinks' build
386     # system.
387     $line =~ s/\x0f//g;
388     # And "ESC(B" which seems to be used on armhf and hurd (not sure what it
389     # does).
390     $line =~ s/\033\(B//g;
391
392     # Check if this line indicates a non verbose build.
393     my $non_verbose = is_non_verbose_build($line);
394
395     # One line may contain multiple commands (";"). Treat each one as single
396     # line.
397     my @line = split /(?<!\\);/, $line;
398     foreach $line (@line) {
399         # Add newline, drop all other whitespace at the end of a line.
400         $line =~ s/\s+$//;
401         $line .= "\n";
402
403         if ($continuation) {
404             $continuation = 0;
405
406             # Join lines, but leave the "\" in place so it's clear where the
407             # original line break was.
408             chomp $complete_line;
409             $complete_line .= ' ' . $line;
410         }
411         # Line continuation, line ends with "\".
412         if ($line =~ /\\\s*$/) {
413             $continuation = 1;
414             # Start line continuation.
415             if (not defined $complete_line) {
416                 $complete_line = $line;
417             }
418             next;
419         }
420
421         if (not $continuation) {
422             # Use the complete line if a line continuation occurred.
423             if (defined $complete_line) {
424                 $line = $complete_line;
425                 $complete_line = undef;
426             }
427
428             # Ignore lines with no compiler commands.
429             next if $line !~ /\b$cc_regex(?:\s|\\)/ and not $non_verbose;
430
431             # Ignore false positives.
432             #
433             # `./configure` output.
434             next if not $non_verbose and $line =~ /^checking /;
435             next if $line =~ /^\s*(?:Host\s+)?(?:C\s+)?
436                                (?:C|c)ompiler[\s.]*:?\s+
437                                $cc_regex
438                                (?:\s-std=[a-z0-9:+]+)?\s*$
439                              /x
440                     or $line =~ /^\s*(?:- )?(?:HOST_)?(?:CC|CXX)\s*=\s*$cc_regex\s*$/
441                     or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
442                     or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
443             # Debian buildd output.
444             next if $line =~ /^\s*Depends: .*?$cc_regex.*?$/
445                     and $line !~ /\s-./; # option, prevent false negatives
446
447
448             push @input, $line;
449         }
450     }
451 }
452
453 if (scalar @input == 0) {
454     print "No compiler commands!\n";
455     $exit |= 1;
456     exit $exit;
457 }
458
459 # Option or auto detected.
460 if ($option_arch) {
461     # The following was partially copied from dpkg-dev 1.16.1.2
462     # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
463     # copyright RaphaĆ«l Hertzog <hertzog@debian.org>, Kees Cook
464     # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
465     # later. Keep it in sync.
466
467     require Dpkg::Arch;
468     my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
469
470     # Disable unsupported hardening options.
471     if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
472         $harden_stack = 0;
473     }
474     if ($cpu =~ /^(ia64|hppa|avr32)$/) {
475         $harden_relro   = 0;
476         $harden_bindnow = 0;
477     }
478 }
479
480 # Check if additional hardening options were used. Used to ensure they are
481 # used for the complete build.
482 foreach my $line (@input) {
483     $harden_pie     = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
484     $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
485 }
486
487 # Check the specified hardening options, same order as dpkg-buildflags.
488 if ($harden_pie) {
489     @cflags  = (@cflags,  @cflags_pie);
490     @ldflags = (@ldflags, @ldflags_pie);
491 }
492 if ($harden_stack) {
493     @cflags = (@cflags, @cflags_stack);
494 }
495 if ($harden_fortify) {
496     @cflags   = (@cflags,   @cflags_fortify);
497     @cppflags = (@cppflags, @cppflags_fortify);
498 }
499 if ($harden_format) {
500     @cflags = (@cflags, @cflags_format);
501 }
502 if ($harden_relro) {
503     @ldflags = (@ldflags, @ldflags_relro);
504 }
505 if ($harden_bindnow) {
506     @ldflags = (@ldflags, @ldflags_bindnow);
507 }
508
509 for (my $i = 0; $i < scalar @input; $i++) {
510     my $line = $input[$i];
511
512     my $skip = 0;
513     if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
514         error_non_verbose_build($line);
515         $exit |= 1 << 2;
516         next;
517     }
518     # Even if it's a verbose build, we might have to skip this line.
519     next if $skip;
520
521     # Skip unnecessary tests when only preprocessing.
522     my $flag_preprocess = 0;
523
524     my $preprocess = 0;
525     my $compile    = 0;
526     my $link       = 0;
527
528     # Preprocess, compile, assemble.
529     if ($line =~ /$cc_regex.*?\s(-E|-S|-c)\b/) {
530         $preprocess      = 1;
531         $flag_preprocess = 1 if $1 eq '-E';
532         $compile         = 1 if $1 eq '-S' or $1 eq '-c';
533     # Otherwise assume we are linking.
534     } else {
535         $link = 1;
536     }
537
538     # These file types don't require preprocessing.
539     if ($line =~ /$file_no_preprocess_regex/) {
540         $preprocess = 0;
541     }
542     # These file types require preprocessing.
543     if ($line =~ /$file_preprocess_regex/) {
544         $preprocess = 1;
545     }
546
547     # If there are source files then it's compiling/linking in one step and we
548     # must check both. We only check for source files here, because header
549     # files cause too many false positives.
550     if (not $flag_preprocess and $line =~ /$file_compile_link_regex/) {
551         # Assembly files don't need CFLAGS.
552         if (not $line =~ /$file_compile_regex/
553                 and $line =~ /$file_no_compile_regex/) {
554             $compile = 0;
555         # But the rest does.
556         } else {
557             $compile = 1;
558         }
559     }
560
561     # Check hardening flags.
562     my @missing;
563     if ($compile and not all_flags_used($line, \@missing, @cflags)
564             # Libraries linked with -fPIC don't have to (and can't) be linked
565             # with -fPIE as well. It's no error if only PIE flags are missing.
566             and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)) {
567         error_flags('CFLAGS missing', \@missing, \%flag_renames, $line);
568         $exit |= 1 << 3;
569     }
570     if ($preprocess and not all_flags_used($line, \@missing, @cppflags)) {
571         error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $line);
572         $exit |= 1 << 3;
573     }
574     if ($link and not all_flags_used($line, \@missing, @ldflags)
575             # Same here, -fPIC conflicts with -fPIE.
576             and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)) {
577         error_flags('LDFLAGS missing', \@missing, \%flag_renames, $line);
578         $exit |= 1 << 3;
579     }
580 }
581
582 exit $exit;
583
584
585 __END__
586
587 =head1 NAME
588
589 blhc - build log hardening check, checks build logs for missing hardening flags
590
591 =head1 SYNOPSIS
592
593 B<blhc> [-h -? --help]
594
595 B<blhc> [--pie] [--bindnow] [--all]
596
597     --help                  available options
598     --version               version number and license
599     --pie                   force +pie check
600     --bindnow               force +bindbow check
601     --all                   force +all (+pie, +bindnow) check
602     --arch                  set architecture (autodetected)
603     --buildd                parser mode for buildds
604
605 =head1 DESCRIPTION
606
607 blhc is a small tool which checks build logs for missing hardening flags and
608 other important warnings. It's licensed under the GPL 3 or later.
609
610 =head1 OPTIONS
611
612 =over 8
613
614 =item B<-h -? --help>
615
616 Print available options.
617
618 =item B<--version>
619
620 Print version number and license.
621
622 =item B<--pie>
623
624 Force check for all +pie hardening flags. By default it's auto detected.
625
626 =item B<--bindnow>
627
628 Force check for all +bindnow hardening flags. By default it's auto detected.
629
630 =item B<--all>
631
632 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
633 auto detected.
634
635 =item B<--arch>
636
637 Set the specific architecture (e.g. amd64, armel, etc.), automatically
638 disables hardening flags not available on this architecture. Is detected
639 automatically if dpkg-buildpackage is used.
640
641 =item B<--buildd>
642
643 Special mode for buildds when automatically parsing log files. The following
644 changes are in effect:
645
646 =over 2
647
648 =item
649
650 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
651 detected).
652
653 =back
654
655 =back
656
657 Auto detection for B<--pie> and B<--bindnow> only works if at least one
658 command uses the required hardening flag (e.g. -fPIE). Then it's required for
659 all other commands as well.
660
661 =head1 EXIT STATUS
662
663 The exit status is a "bit mask", each listed status is ORed when the error
664 condition occurs to get the result.
665
666 =over 8
667
668 =item B<0>
669
670 Success.
671
672 =item B<1>
673
674 No compiler commands were found.
675
676 =item B<2>
677
678 Invalid arguments/options given to blhc.
679
680 =item B<4>
681
682 Non verbose build.
683
684 =item B<8>
685
686 Missing hardening flags.
687
688 =back
689
690 =head1 AUTHOR
691
692 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
693
694 =head1 COPYRIGHT AND LICENSE
695
696 Copyright (C) 2012 by Simon Ruderich
697
698 This program is free software: you can redistribute it and/or modify
699 it under the terms of the GNU General Public License as published by
700 the Free Software Foundation, either version 3 of the License, or
701 (at your option) any later version.
702
703 This program is distributed in the hope that it will be useful,
704 but WITHOUT ANY WARRANTY; without even the implied warranty of
705 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
706 GNU General Public License for more details.
707
708 You should have received a copy of the GNU General Public License
709 along with this program.  If not, see <http://www.gnu.org/licenses/>.
710
711 =cut