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