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