]> ruderich.org/simon Gitweb - blhc/blhc.git/blob - bin/blhc
Correctly detect linking for CGI binaries (e.g. test.cgi).
[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     '-O(?:2|3)',
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     '-O(?:2|3)'       => '-O2',
75     '-Wl,(-z,)?relro' => '-Wl,-z,relro',
76     '-Wl,(-z,)?now'   => '-Wl,-z,now',
77 );
78
79
80 # FUNCTIONS
81
82 sub error_flags {
83     my ($message, $missing_flags_ref, $flag_renames_ref, $line) = @_;
84
85     # Rename flags if requested.
86     my @missing_flags = map {
87         (exists $flag_renames_ref->{$_})
88             ? $flag_renames_ref->{$_}
89             : $_
90     } @{$missing_flags_ref};
91
92     my $flags = join ' ', @missing_flags;
93     printf "%s (%s)%s %s",
94            error_color($message, 'red'), $flags, error_color(':', 'yellow'),
95            $line;
96 }
97 sub error_non_verbose_build {
98     my ($line) = @_;
99
100     printf "%s%s %s",
101            error_color('NONVERBOSE BUILD', 'red'),
102            error_color(':', 'yellow'),
103            $line;
104 }
105 sub error_color {
106     my ($message, $color) = @_;
107
108     # Use colors when writing to a terminal.
109     if (-t STDOUT) {
110         return Term::ANSIColor::colored($message, $color);
111     } else {
112         return $message;
113     }
114 }
115
116 sub any_flags_used {
117     my ($line, @flags) = @_;
118
119     foreach my $flag (@flags) {
120         return 1 if $line =~ /\s$flag(?:\s|\\|$)/;
121     }
122
123     return 0;
124 }
125 sub all_flags_used {
126     my ($line, $missing_flags_ref, @flags) = @_;
127
128     my @missing_flags = ();
129     foreach my $flag (@flags) {
130         if ($line !~ /\s$flag(?:\s|\\|$)/) {
131             push @missing_flags, $flag;
132         }
133     }
134
135     if (scalar @missing_flags == 0) {
136         return 1;
137     }
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)\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 if (not Getopt::Long::GetOptions(
221             'help|h|?' => \$option_help,
222             'version'  => \$option_version,
223             # Hardening options.
224             'pie'      => \$harden_pie,
225             'bindnow'  => \$harden_bindnow,
226             'all'      => \$option_all,
227             # Misc.
228             'arch'     => \$option_arch,
229         )) {
230     require Pod::Usage;
231     Pod::Usage::pod2usage(2);
232 }
233 if ($option_help) {
234     require Pod::Usage;
235     Pod::Usage::pod2usage(1);
236 }
237 if ($option_version) {
238     print "blhc $VERSION  Copyright (C) 2012  Simon Ruderich
239
240 This program is free software: you can redistribute it and/or modify
241 it under the terms of the GNU General Public License as published by
242 the Free Software Foundation, either version 3 of the License, or
243 (at your option) any later version.
244
245 This program is distributed in the hope that it will be useful,
246 but WITHOUT ANY WARRANTY; without even the implied warranty of
247 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
248 GNU General Public License for more details.
249
250 You should have received a copy of the GNU General Public License
251 along with this program.  If not, see <http://www.gnu.org/licenses/>.
252 ";
253     exit 0;
254 }
255
256 if ($option_all) {
257     $harden_pie     = 1;
258     $harden_bindnow = 1;
259 }
260
261 # Final exit code.
262 my $exit = 0;
263
264 # Input lines, contain only the lines with compiler commands.
265 my @input = ();
266
267 my $start = 0;
268 my $continuation = 0;
269 my $complete_line = undef;
270 while (my $line = <>) {
271     # We skip over unimportant lines at the beginning to prevent false
272     # positives.
273     $start = 1 if $line =~ /^dpkg-buildpackage:/;
274     next if not $start;
275
276     # Detect architecture automatically unless overridden.
277     if (not $option_arch
278             and $line =~ /^dpkg-buildpackage: host architecture (.+)$/) {
279         $option_arch = $1;
280     }
281
282     # Ignore compiler warnings for now.
283     next if $line =~ /$warning_regex/;
284
285     # Check if this line indicates a non verbose build.
286     my $non_verbose = is_non_verbose_build($line);
287
288     # One line may contain multiple commands (";"). Treat each one as single
289     # line.
290     my @line = split /(?<!\\);/, $line;
291     foreach $line (@line) {
292         # Add newline, drop all other whitespace at the end of a line.
293         $line =~ s/\s+$//;
294         $line .= "\n";
295
296         if ($continuation) {
297             $continuation = 0;
298
299             # Join lines, but leave the "\" in place so it's clear where the
300             # original line break was.
301             chomp $complete_line;
302             $complete_line .= ' ' . $line;
303         }
304         # Line continuation, line ends with "\".
305         if ($line =~ /\\\s*$/) {
306             $continuation = 1;
307             # Start line continuation.
308             if (not defined $complete_line) {
309                 $complete_line = $line;
310             }
311             next;
312         }
313
314         if (not $continuation) {
315             # Use the complete line if a line continuation occurred.
316             if (defined $complete_line) {
317                 $line = $complete_line;
318                 $complete_line = undef;
319             }
320
321             # Ignore lines with no compiler commands.
322             next if $line !~ /\b$cc_regex(?:\s|\\)/ and not $non_verbose;
323
324             # Ignore false positives.
325             #
326             # `./configure` output.
327             next if not $non_verbose and $line =~ /^checking /;
328             next if $line =~ /^\s*(?:C|c)ompiler[\s.]*:\s+$cc_regex(?:\s-std=[a-z0-9:+]+)?\s*$/
329                     or $line =~ /^\s*- (?:CC|CXX)\s*=\s*$cc_regex\s*$/
330                     or $line =~ /^\s*-- Check for working (?:C|CXX) compiler: /
331                     or $line =~ /^\s*(?:echo )?Using [A-Z_]+\s*=\s*/;
332
333             push @input, $line;
334         }
335     }
336 }
337
338 if (scalar @input == 0) {
339     print "No compiler commands!\n";
340     $exit |= 1;
341     exit $exit;
342 }
343
344 # Option or auto detected.
345 if ($option_arch) {
346     # The following was partially copied from dpkg-dev 1.16.1.2
347     # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, add_hardening_flags()),
348     # copyright RaphaĆ«l Hertzog <hertzog@debian.org>, Kees Cook
349     # <kees@debian.org>, Canonical, Ltd. licensed under GPL version 2 or
350     # later. Keep it in sync.
351
352     require Dpkg::Arch;
353     my ($abi, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($option_arch);
354
355     # Disable unsupported hardening options.
356     if ($cpu =~ /^(ia64|alpha|mips|mipsel|hppa)$/ or $option_arch eq 'arm') {
357         $harden_stack = 0;
358     }
359     if ($cpu =~ /^(ia64|hppa|avr32)$/) {
360         $harden_relro   = 0;
361         $harden_bindnow = 0;
362     }
363 }
364
365 # Check if additional hardening options were used. Used to ensure they are
366 # used for the complete build.
367 foreach my $line (@input) {
368     $harden_pie     = 1 if any_flags_used($line, @cflags_pie, @ldflags_pie);
369     $harden_bindnow = 1 if any_flags_used($line, @ldflags_bindnow);
370 }
371
372 # Check the specified hardening options, same order as dpkg-buildflags.
373 if ($harden_pie) {
374     @cflags  = (@cflags,  @cflags_pie);
375     @ldflags = (@ldflags, @ldflags_pie);
376 }
377 if ($harden_stack) {
378     @cflags = (@cflags, @cflags_stack);
379 }
380 if ($harden_fortify) {
381     @cflags   = (@cflags,   @cflags_fortify);
382     @cppflags = (@cppflags, @cppflags_fortify);
383 }
384 if ($harden_format) {
385     @cflags = (@cflags, @cflags_format);
386 }
387 if ($harden_relro) {
388     @ldflags = (@ldflags, @ldflags_relro);
389 }
390 if ($harden_bindnow) {
391     @ldflags = (@ldflags, @ldflags_bindnow);
392 }
393
394 for (my $i = 0; $i < scalar @input; $i++) {
395     my $line = $input[$i];
396
397     my $skip = 0;
398     if (is_non_verbose_build($line, $input[$i + 1], \$skip)) {
399         error_non_verbose_build($line);
400         $exit |= 1 << 2;
401         next;
402     }
403     # Even if it's a verbose build, we might have to skip this line.
404     next if $skip;
405
406
407     # Is this a compiler or linker command?
408     my $compiler = 1;
409     my $linker   = 0;
410
411     # Linker commands.
412     if ($line =~ m{\s-o                        # -o
413                    [\s\\]*\s+                  # possible line continuation
414                    (?:[/.A-Za-z0-9~_-]+/)?     # path to file
415                         [A-Za-z0-9~_-]+        # binary name (no dots!)
416                    (?:[0-9.]*\.so[0-9.]*[a-z]? # library (including version)
417                     |\.la
418                     |\.cgi)?                   # CGI binary
419                    (?:\s|\\|$)                 # end of file name
420                   }x
421             or $line =~ /^libtool: link: /
422             or $line =~ m{\s*/bin/bash .+?libtool\s+(.+?\s+)?--mode=(re)?link}) {
423         $compiler = 0;
424         $linker   = 1;
425     }
426
427     # If there are source files then it's compiling/linking in one step and we
428     # must check both.
429     if ($line =~ /\.(?:c|cc|cpp)\b/) {
430         $compiler = 1;
431     }
432
433     # Check hardening flags.
434     my @missing;
435     if ($compiler and not all_flags_used($line, \@missing, @cflags)
436             # Libraries linked with -fPIC don't have to (and can't) be linked
437             # with -fPIE as well. It's no error if only PIE flags are missing.
438             and not pic_pie_conflict($line, $harden_pie, \@missing, @cflags_pie)) {
439         error_flags('CFLAGS missing', \@missing, \%flag_renames, $line);
440         $exit |= 1 << 3;
441     }
442     if ($compiler and not all_flags_used($line, \@missing, @cppflags)) {
443         error_flags('CPPFLAGS missing', \@missing, \%flag_renames, $line);
444         $exit |= 1 << 3;
445     }
446     if ($linker and not all_flags_used($line, \@missing, @ldflags)
447             # Same here, -fPIC conflicts with -fPIE.
448             and not pic_pie_conflict($line, $harden_pie, \@missing, @ldflags_pie)) {
449         error_flags('LDFLAGS missing', \@missing, \%flag_renames, $line);
450         $exit |= 1 << 3;
451     }
452 }
453
454 exit $exit;
455
456
457 __END__
458
459 =head1 NAME
460
461 blhc - build log hardening check, checks build logs for missing hardening flags
462
463 =head1 SYNOPSIS
464
465 B<blhc> [-h -? --help]
466
467 B<blhc> [--pie] [--bindnow] [--all]
468
469     --help                  available options
470     --version               version number and license
471     --pie                   force +pie check
472     --bindnow               force +bindbow check
473     --all                   force +all (+pie, +bindnow) check
474     --arch                  set architecture (autodetected)
475
476 =head1 DESCRIPTION
477
478 blhc is a small tool which checks build logs for missing hardening flags and
479 other important warnings. It's licensed under the GPL 3 or later.
480
481 =head1 OPTIONS
482
483 =over 8
484
485 =item B<-h -? --help>
486
487 Print available options.
488
489 =item B<--version>
490
491 Print version number and license.
492
493 =item B<--pie>
494
495 Force check for all +pie hardening flags. By default it's auto detected.
496
497 =item B<--bindnow>
498
499 Force check for all +bindnow hardening flags. By default it's auto detected.
500
501 =item B<--all>
502
503 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
504 auto detected.
505
506 =item B<--arch>
507
508 Set the specific architecture (e.g. amd64, armel, etc.), automatically
509 disables hardening flags not available on this architecture. Is detected
510 automatically if dpkg-buildpackage is used.
511
512 =back
513
514 Auto detection only works if at least one command uses the required hardening
515 flag (e.g. -fPIE). Then it's required for all other commands as well.
516
517 =head1 EXIT STATUS
518
519 The exit status is a "bit mask", each listed status is ORed when the error
520 condition occurs to get the result.
521
522 =over 8
523
524 =item B<0>
525
526 Success.
527
528 =item B<1>
529
530 No compiler commands were found.
531
532 =item B<2>
533
534 Invalid arguments/options given to blhc.
535
536 =item B<4>
537
538 Non verbose build.
539
540 =item B<8>
541
542 Missing hardening flags.
543
544 =back
545
546 =head1 AUTHOR
547
548 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
549
550 =head1 COPYRIGHT AND LICENSE
551
552 Copyright (C) 2012 by Simon Ruderich
553
554 This program is free software: you can redistribute it and/or modify
555 it under the terms of the GNU General Public License as published by
556 the Free Software Foundation, either version 3 of the License, or
557 (at your option) any later version.
558
559 This program is distributed in the hope that it will be useful,
560 but WITHOUT ANY WARRANTY; without even the implied warranty of
561 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
562 GNU General Public License for more details.
563
564 You should have received a copy of the GNU General Public License
565 along with this program.  If not, see <http://www.gnu.org/licenses/>.
566
567 =cut