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