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