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