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