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