]> ruderich.org/simon Gitweb - blhc/blhc.git/blob - bin/blhc
9040a084c873e691faae0801f8531588ec046883
[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-2024  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 Text::ParseWords ();
26
27 our $VERSION = '0.13';
28
29
30 # CONSTANTS/VARIABLES
31
32 # Regex to catch compiler commands.
33 my $cc_regex = qr/
34     (?<!\s-)               # ignore options, e.g. "-c++" [sic!] (used by swig)
35     (?<!\.)                # ignore file names, e.g. "test.gcc"
36     (?:cc|gcc|g\+\+|c\+\+|gfortran|mpicc|mpicxx|mpifort)
37     (?:-[\d.]+)?           # version suffix, e.g. "gcc-4.6"
38     /x;
39 # Full regex which matches the complete compiler name. Used in a few places to
40 # prevent false negatives.
41 my $cc_regex_full_prefix = qr/
42     [a-z0-9_]+-(?:linux-|kfreebsd-)?gnu(?:eabi|eabihf)?
43     /x;
44 my $cc_regex_full = qr/
45     (?:$cc_regex_full_prefix-)?
46     $cc_regex
47     /x;
48 # Regex to check if a line contains a compiler command.
49 my $cc_regex_normal = qr/
50     \b$cc_regex(?:\s|\\)
51     /x;
52 my $rustc_regex = qr/
53     \brustc\b
54     /x;
55 # Regex to catch (GCC) compiler warnings.
56 my $warning_regex = qr/^(.+?):(\d+):\d+: warning: (.+?) \[(.+?)\]$/;
57 # Regex to catch libtool commands and not lines which show commands executed
58 # by libtool (e.g. libtool: link: ...).
59 my $libtool_regex = qr/\blibtool["']?\s.*--mode=/;
60 my $libtool_link_regex = qr/\blibtool: link: /;
61
62 # List of source file extensions which require preprocessing.
63 my @source_preprocess_compile_cpp = (
64     # C++
65     qw( cc cp cxx cpp CPP c++ C ),
66     # Objective-C++
67     qw( mm M ),
68 );
69 my @source_preprocess_compile_fortran = (
70     # Fortran
71     qw( F FOR fpp FPP FTN F90 F95 F03 F08 ),
72 );
73 my @source_preprocess_compile = (
74     # C
75     qw( c ),
76     # Objective-C
77     qw( m ),
78     # (Objective-)C++
79     @source_preprocess_compile_cpp,
80     # Fortran
81     @source_preprocess_compile_fortran,
82 );
83 my @source_preprocess_no_compile = (
84     # Assembly
85     qw( S sx ),
86 );
87 my @source_preprocess = (
88     @source_preprocess_compile,
89     @source_preprocess_no_compile,
90 );
91 # List of source file extensions which don't require preprocessing.
92 my @source_no_preprocess_compile_cpp = (
93     # C++
94     qw( ii ),
95     # Objective-C++
96     qw( mii ),
97 );
98 my @source_no_preprocess_compile_ada = (
99     # Ada source
100     qw( ada ),
101     # Ada body
102     qw( adb ),
103 );
104 my @source_no_preprocess_compile_fortran = (
105     # Fortran
106     qw( f for ftn f90 f95 f03 f08 ),
107 );
108 my @source_no_preprocess_compile = (
109     # C
110     qw( i ),
111     # (Objective-)C++
112     @source_no_preprocess_compile_cpp,
113     # Objective-C
114     qw( mi ),
115     # Fortran
116     @source_no_preprocess_compile_fortran,
117     # Ada
118     @source_no_preprocess_compile_ada,
119 );
120 my @source_no_preprocess_no_compile_ada = (
121     # Ada specification
122     qw( ads ),
123 );
124 my @source_no_preprocess_no_compile = (
125     # Assembly
126     qw( s ),
127     # Ada
128     @source_no_preprocess_no_compile_ada,
129 );
130 my @source_no_preprocess = (
131     @source_no_preprocess_compile,
132     @source_no_preprocess_no_compile,
133 );
134 # List of header file extensions which require preprocessing.
135 my @header_preprocess = (
136     # C, C++, Objective-C, Objective-C++
137     qw( h ),
138     # C++
139     qw( hh H hp hxx hpp HPP h++ tcc ),
140 );
141 # Object files.
142 my @object = (
143     # Normal object files.
144     qw ( o ),
145     # Libtool object files.
146     qw ( lo la ),
147     # Dynamic libraries. bzip2 uses .sho.
148     qw ( so sho ),
149     # Static libraries.
150     qw ( a ),
151 );
152
153 # Hashes for fast extensions lookup to check if a file falls in one of these
154 # categories.
155 my %extensions_no_preprocess = map { $_ => 1 } (
156     # There's no @header_no_preprocess.
157     @source_no_preprocess,
158 );
159 my %extensions_preprocess = map { $_ => 1 } (
160     @header_preprocess,
161     @source_preprocess,
162 );
163 my %extensions_compile_link = map { $_ => 1 } (
164     @source_preprocess,
165     @source_no_preprocess,
166 );
167 my %extensions_compile = map { $_ => 1 } (
168     @source_preprocess_compile,
169     @source_no_preprocess_compile,
170 );
171 my %extensions_no_compile = map { $_ => 1 } (
172     @source_preprocess_no_compile,
173     @source_no_preprocess_no_compile,
174 );
175 my %extensions_compile_cpp = map { $_ => 1 } (
176     @source_preprocess_compile_cpp,
177     @source_no_preprocess_compile_cpp,
178 );
179 my %extensions_ada = map { $_ => 1 } (
180     @source_no_preprocess_compile_ada,
181     @source_no_preprocess_no_compile_ada,
182 );
183 my %extensions_fortran = map { $_ => 1 } (
184     @source_no_preprocess_compile_fortran,
185     @source_preprocess_compile_fortran,
186 );
187 my %extensions_object = map { $_ => 1 } (
188     @object,
189 );
190 my %extension = map { $_ => 1 } (
191     @source_no_preprocess,
192     @header_preprocess,
193     @source_preprocess,
194     @object,
195 );
196
197 # Regexp to match file extensions.
198 my $file_extension_regex = qr/
199     \s
200     \S+             # Filename without extension.
201     \.
202     ([^\/\\.,;:\s]+)# File extension.
203     (?=\s|\\)       # At end of word. Can't use \b because some files have non
204                     # word characters at the end and because \b matches double
205                     # extensions (like .cpp.o). Works always as all lines are
206                     # terminated with "\n".
207     /x;
208
209 # Expected (hardening) flags. All flags are used as regexps (and compiled to
210 # real regexps below for better execution speed).
211 my @def_cflags = (
212     '-g3?',
213     '-O(?:2|3)', # keep at index 1, search for @def_cflags_debug to change it
214 );
215 my @def_cflags_debug = (
216     # These flags indicate a debug build which disables checks for -O2.
217     '-O0',
218     '-Og',
219 );
220 my @def_cflags_format = (
221     '-Wformat(?:=2)?', # -Wformat=2 implies -Wformat, accept it too
222     '-Werror=format-security', # implies -Wformat-security
223 );
224 my @def_cflags_fortify = (
225     # fortify needs at least -O1, but -O2 is recommended anyway
226 );
227 my @def_cflags_stack = (
228     '-fstack-protector', # keep first, used by cflags_stack_broken()
229     '--param[= ]ssp-buffer-size=4',
230 );
231 my @def_cflags_stack_strong = (
232     '-fstack-protector-strong', # keep first, used by cflags_stack_broken()
233 );
234 my @def_cflags_stack_bad = (
235     # Blacklist all stack protector options for simplicity.
236     '-fno-stack-protector',
237     '-fno-stack-protector-all',
238     '-fno-stack-protector-strong',
239 );
240 my @def_cflags_pie = (
241     '-fPIE',
242 );
243 my @def_cxxflags = (
244     @def_cflags,
245 );
246 # @def_cxxflags_* is the same as @def_cflags_*.
247 my @def_cppflags = ();
248 my @def_cppflags_fortify = (
249     '-D_FORTIFY_SOURCE=[23]', # must be first, see cppflags_fortify_broken()
250     # If you add another flag fix hack below (search for "Hack to fix") and
251     # $def_cppflags_fortify[0].
252 );
253 my @def_cppflags_fortify_bad = (
254     # These flags may overwrite -D_FORTIFY_SOURCE=2.
255     '-U_FORTIFY_SOURCE',
256     '-D_FORTIFY_SOURCE=0',
257     '-D_FORTIFY_SOURCE=1',
258 );
259 my @def_ldflags = ();
260 my @def_ldflags_relro = (
261     '-Wl,(?:-z,)?relro',
262 );
263 my @def_ldflags_bindnow = (
264     '-Wl,(?:-z,)?now',
265 );
266 my @def_ldflags_pie = (
267     '-fPIE',
268     '-pie',
269 );
270 my @def_ldflags_pic = (
271     '-fPIC',
272     '-fpic',
273     '-shared',
274 );
275 # References to all flags checked by the flag checker.
276 my @flag_refs = (
277     \@def_cflags,
278     \@def_cflags_format,
279     \@def_cflags_fortify,
280     \@def_cflags_stack,
281     \@def_cflags_stack_strong,
282     \@def_cflags_stack_bad,
283     \@def_cflags_pie,
284     \@def_cxxflags,
285     \@def_cppflags,
286     \@def_cppflags_fortify,
287     \@def_ldflags,
288     \@def_ldflags_relro,
289     \@def_ldflags_bindnow,
290     \@def_ldflags_pie,
291 );
292 # References to all used flags.
293 my @flag_refs_all = (
294     @flag_refs,
295     \@def_cflags_debug,
296     \@def_cppflags_fortify_bad,
297     \@def_ldflags_pic,
298 );
299 # Renaming rules for the output so the regex parts are not visible. Also
300 # stores string values of flag regexps above, see compile_flag_regexp().
301 my %flag_renames = (
302     '-g3?'                         => '-g',
303     '-O(?:2|3)'                    => '-O2',
304     '-Wformat(?:=2)?'              => '-Wformat',
305     '--param[= ]ssp-buffer-size=4' => '--param=ssp-buffer-size=4',
306     '-D_FORTIFY_SOURCE=[23]'       => '-D_FORTIFY_SOURCE=2',
307     '-Wl,(?:-z,)?relro'            => '-Wl,-z,relro',
308     '-Wl,(?:-z,)?now'              => '-Wl,-z,now',
309 );
310
311 my %exit_code = (
312     no_compiler_commands => 1 << 0,
313     # used by POD::Usage => 1 << 1,
314     non_verbose_build    => 1 << 2,
315     flags_missing        => 1 << 3,
316     hardening_wrapper    => 1 << 4,
317     invalid_cmake        => 1 << 5,
318 );
319
320 my %buildd_tag = (
321     no_compiler_commands => 'I-no-compiler-commands',
322     non_verbose_build    => 'W-compiler-flags-hidden',
323     flags_missing        => 'W-dpkg-buildflags-missing',
324     hardening_wrapper    => 'I-hardening-wrapper-used',
325     invalid_cmake        => 'I-invalid-cmake-used',
326 );
327
328 # Statistics of missing flags and non-verbose build commands. Used for
329 # $option_buildd.
330 my %statistics = (
331     preprocess          => 0,
332     preprocess_missing  => 0,
333     compile             => 0,
334     compile_missing     => 0,
335     compile_cpp         => 0,
336     compile_cpp_missing => 0,
337     link                => 0,
338     link_missing        => 0,
339     commands            => 0,
340     commands_nonverbose => 0,
341 );
342
343 # Use colored (ANSI) output?
344 my $option_color;
345
346
347 # FUNCTIONS
348
349 sub split_line {
350     my ($line) = @_;
351
352     my @work = ($line);
353     foreach my $delim (';', '&&', '||') {
354         my @x;
355         foreach (@work) {
356             push @x, Text::ParseWords::parse_line(qr/\Q$delim\E/, 1, $_);
357         }
358         @work = @x;
359     }
360
361     return map {
362         # Ensure newline at the line end - necessary for
363         # correct parsing later.
364         $_ =~ s/\s+$//;
365         $_ .= "\n";
366     } @work;
367 }
368
369 sub error_flags {
370     my ($message, $missing_flags_ref, $flag_renames_ref, $line, $number) = @_;
371
372     # Get string value of qr//-escaped regexps and if requested rename them.
373     my @missing_flags = map {
374             $flag_renames_ref->{$_}
375         } @{$missing_flags_ref};
376
377     my $flags = join ' ', @missing_flags;
378     printf '%d:', $number if defined $number;
379     printf '%s (%s)%s %s',
380            error_color($message, 'red'), $flags, error_color(':', 'yellow'),
381            $line;
382
383     return;
384 }
385 sub error_non_verbose_build {
386     my ($line, $number) = @_;
387
388     printf '%d:', $number if defined $number;
389     printf '%s%s %s',
390            error_color('NONVERBOSE BUILD', 'red'),
391            error_color(':', 'yellow'),
392            $line;
393
394     return;
395 }
396 sub error_invalid_cmake {
397     my ($version) = @_;
398
399     printf "%s%s %s\n",
400             error_color('INVALID CMAKE', 'red'),
401             error_color(':', 'yellow'),
402             $version;
403
404     return;
405 }
406 sub error_hardening_wrapper {
407     printf "%s%s %s\n",
408             error_color('HARDENING WRAPPER', 'red'),
409             error_color(':', 'yellow'),
410             'no checks possible, aborting';
411
412     return;
413 }
414 sub error_color {
415     my ($message, $color) = @_;
416
417     if ($option_color) {
418         return Term::ANSIColor::colored($message, $color);
419     } else {
420         return $message;
421     }
422 }
423
424 sub any_flags_used {
425     my ($line, @flags) = @_;
426
427     foreach my $flag (@flags) {
428         return 1 if $line =~ /$flag/;
429     }
430
431     return 0;
432 }
433 sub all_flags_used {
434     my ($line, $missing_flags_ref, @flags) = @_;
435
436     my @missing_flags = ();
437     foreach my $flag (@flags) {
438         if (not $line =~ /$flag/) {
439             push @missing_flags, $flag;
440         }
441     }
442
443     return 1 if scalar @missing_flags == 0;
444
445     @{$missing_flags_ref} = @missing_flags;
446     return 0;
447 }
448 # Check if any of \@bad_flags occurs after $good_flag. Doesn't check if
449 # $good_flag is present.
450 sub flag_overwritten {
451     my ($line, $good_flag, $bad_flags) = @_;
452
453     if (not any_flags_used($line, @{$bad_flags})) {
454         return 0;
455     }
456
457     my $bad_pos = 0;
458     foreach my $flag (@{$bad_flags}) {
459         while ($line =~ /$flag/g) {
460             if ($bad_pos < $+[0]) {
461                 $bad_pos = $+[0];
462             }
463         }
464     }
465     my $good_pos = 0;
466     while ($line =~ /$good_flag/g) {
467         $good_pos = $+[0];
468     }
469     if ($good_pos > $bad_pos) {
470         return 0;
471     }
472     return 1;
473 }
474
475 sub cppflags_fortify_broken {
476     my ($line, $missing_flags) = @_;
477
478     # $def_cppflags_fortify[0] must be -D_FORTIFY_SOURCE=2!
479     my $fortify_source = $def_cppflags_fortify[0];
480
481     # Some build systems enable/disable fortify source multiple times, check
482     # the final result.
483     if (not flag_overwritten($line,
484                              $fortify_source,
485                              \@def_cppflags_fortify_bad)) {
486         return 0;
487     }
488     push @{$missing_flags}, $fortify_source;
489     return 1;
490 }
491
492 sub cflags_stack_broken {
493     my ($line, $missing_flags, $strong) = @_;
494
495     my $flag = $strong ? $def_cflags_stack_strong[0]
496                        : $def_cflags_stack[0];
497
498     if (not flag_overwritten($line, $flag, \@def_cflags_stack_bad)) {
499         return 0;
500     }
501     push @{$missing_flags}, $flag;
502     return 1;
503 }
504
505 # Modifies $missing_flags_ref array.
506 sub pic_pie_conflict {
507     my ($line, $pie, $missing_flags_ref, @flags_pie) = @_;
508
509     return 0 if not $pie;
510     return 0 if not any_flags_used($line, @def_ldflags_pic);
511
512     my %flags = map { $_ => 1 } @flags_pie;
513
514     # Remove all PIE flags from @missing_flags as they are not required with
515     # -fPIC.
516     my @result = grep {
517         not exists $flags{$_}
518     } @{$missing_flags_ref};
519     @{$missing_flags_ref} = @result;
520
521     # We got a conflict when no flags are left, thus only PIE flags were
522     # missing. If other flags were missing abort because the conflict is not
523     # the problem.
524     return scalar @result == 0;
525 }
526
527 sub is_non_verbose_build {
528     my ($line, $cargo, $skip_ref, $input_ref, $line_offset, $line_count) = @_;
529
530     if ($line =~ /$libtool_regex/o) {
531         # libtool's --silent hides the real compiler flags.
532         if ($line =~ /\s--silent/) {
533             return 1;
534         # If --silent is not present, skip this line as some compiler flags
535         # might be missing (e.g. -fPIE) which are handled correctly by libtool
536         # internally. libtool displays the real compiler command on the next
537         # line, so the flags are checked as usual.
538         } else {
539             ${$skip_ref} = 1;
540             return 0;
541         }
542     }
543
544     if (not (index($line, 'checking if you want to see long compiling messages... no') == 0
545                 or $line =~ /^\s*\[?(?:CC|CCLD|C\+\+|CXX|CXXLD|LD|LINK)\]?\s+(.+?)$/
546                 or $line =~ /^\s*[][\/0-9 ]*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/
547                 or $line =~ /^\s*[Bb]uilding (?:program|shared library)\s+(.+?)$/
548                 or $line =~ /^\s*\[[\d ]+%\] Building (?:C|CXX) object (.+?)$/)) {
549         return 0;
550     }
551
552     # False positives.
553     #
554     # C++ compiler setting.
555     return 0 if $line =~ /^\s*C\+\+.+?:\s+(?:yes|no)\s*$/;
556     return 0 if $line =~ /^\s*C\+\+ Library: stdc\+\+$/;
557     # "Compiling" non binary files.
558     return 0 if $line =~ /^\s*Compiling \S+\.(?:py|pyx|el)['"]?\s*(?:\.\.\.|because it changed\.)?$/;
559     return 0 if $line =~ /^\s*[Cc]ompiling catalog \S+\.po\b/;
560     # cargo build
561     return 0 if $cargo and $line =~ m{^\s*Compiling\s+\S+\s+v\S+(?:\s+\(/<<PKGBUILDDIR>>\))?$};
562     # "Compiling" with no file name.
563     if ($line =~ /^\s*[Cc]ompiling\s+(.+?)(?:\.\.\.)?$/) {
564         # $file_extension_regex may need spaces around the filename.
565         return 0 if not " $1 " =~ /$file_extension_regex/o;
566     }
567
568     my $file = $1;
569
570     # On the first pass we only check if this line is verbose or not.
571     return 1 if not defined $input_ref;
572
573     # Second pass, we have access to the next lines.
574     ${$skip_ref} = 0;
575
576     # CMake and other build systems print the non-verbose messages also when
577     # building verbose. If a compiler and the file name occurs in the next
578     # lines, treat it as verbose build.
579     if (defined $file) {
580         # Get filename, we can't use the complete path as only parts of it are
581         # used in the real compiler command.
582         $file =~ m{/([^/\s]+)$};
583         $file = $1;
584
585         for (my $i = 1; $i <= $line_count; $i++) {
586             my $next_line = $input_ref->[$line_offset + $i];
587             last unless defined $next_line;
588
589             if (index($next_line, $file) != -1 and $next_line =~ /$cc_regex/o) {
590                 # Not a non-verbose line, but we still have to skip the
591                 # current line as it doesn't contain any compiler commands.
592                 ${$skip_ref} = 1;
593                 return 0;
594             }
595         }
596     }
597
598     return 1;
599 }
600
601 # Remove @flags from $flag_refs_ref, uses $flag_renames_ref as reference.
602 sub remove_flags {
603     my ($flag_refs_ref, $flag_renames_ref, @flags) = @_;
604
605     my %removes = map { $_ => 1 } @flags;
606     foreach my $flags (@{$flag_refs_ref}) {
607         @{$flags} = grep {
608             # Flag found as string.
609             not exists $removes{$_}
610             # Flag found as string representation of regexp.
611                 and (not defined $flag_renames_ref->{$_}
612                         or not exists $removes{$flag_renames_ref->{$_}})
613         } @{$flags};
614     }
615
616     return;
617 }
618
619 # Modifies $flag_renames_ref hash.
620 sub compile_flag_regexp {
621     my ($flag_renames_ref, @flags) = @_;
622
623     my @result = ();
624     foreach my $flag (@flags) {
625         # Compile flag regexp for faster execution.
626         my $regex = qr/\s(['"]?)$flag\1(?:\s|\\)/;
627
628         # Store flag name in replacement string for correct flags in messages
629         # with qr//ed flag regexps.
630         $flag_renames_ref->{$regex}
631             = (exists $flag_renames_ref->{$flag})
632                 ? $flag_renames_ref->{$flag}
633                 : $flag;
634
635         push @result, $regex;
636     }
637     return @result;
638 }
639
640 # Does any extension in @extensions exist in %{$extensions_ref}?
641 sub extension_found {
642     my ($extensions_ref, @extensions) = @_;
643
644     foreach my $extension (@extensions) {
645         if (exists $extensions_ref->{$extension}) {
646             return 1;
647         }
648     }
649     return 0;
650 }
651
652
653 # MAIN
654
655 # Parse command line arguments.
656 my $option_help             = 0;
657 my $option_version          = 0;
658 my $option_pie              = 0;
659 my $option_bindnow          = 0;
660 my @option_ignore_arch      = ();
661 my @option_ignore_flag      = ();
662 my @option_ignore_arch_flag = ();
663 my @option_ignore_line      = ();
664 my @option_ignore_arch_line = ();
665 my $option_all              = 0;
666 my $option_arch             = undef;
667 my $option_buildd           = 0;
668 my $option_debian           = 0;
669    $option_color            = 0;
670 my $option_line_numbers     = 0;
671 if (not Getopt::Long::GetOptions(
672             'help|h|?'           => \$option_help,
673             'version'            => \$option_version,
674             # Hardening options.
675             'pie'                => \$option_pie,
676             'bindnow'            => \$option_bindnow,
677             'all'                => \$option_all,
678             # Ignore.
679             'ignore-arch=s'      => \@option_ignore_arch,
680             'ignore-flag=s'      => \@option_ignore_flag,
681             'ignore-arch-flag=s' => \@option_ignore_arch_flag,
682             'ignore-line=s'      => \@option_ignore_line,
683             'ignore-arch-line=s' => \@option_ignore_arch_line,
684             # Misc.
685             'color'              => \$option_color,
686             'arch=s'             => \$option_arch,
687             'buildd'             => \$option_buildd,
688             'debian'             => \$option_debian,
689             'line-numbers'       => \$option_line_numbers,
690         )) {
691     require Pod::Usage;
692     Pod::Usage::pod2usage(2);
693 }
694 if ($option_help) {
695     require Pod::Usage;
696     Pod::Usage::pod2usage(1);
697 }
698 if ($option_version) {
699     print <<"EOF";
700 blhc $VERSION  Copyright (C) 2012-2024  Simon Ruderich
701
702 This program is free software: you can redistribute it and/or modify
703 it under the terms of the GNU General Public License as published by
704 the Free Software Foundation, either version 3 of the License, or
705 (at your option) any later version.
706
707 This program is distributed in the hope that it will be useful,
708 but WITHOUT ANY WARRANTY; without even the implied warranty of
709 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
710 GNU General Public License for more details.
711
712 You should have received a copy of the GNU General Public License
713 along with this program.  If not, see <http://www.gnu.org/licenses/>.
714 EOF
715     exit 0;
716 }
717
718 # Arguments missing.
719 if (scalar @ARGV == 0) {
720     require Pod::Usage;
721     Pod::Usage::pod2usage(2);
722 }
723
724 # Don't load Term::ANSIColor in buildd mode because Term::ANSIColor is not
725 # installed on Debian's buildds.
726 if (not $option_buildd) {
727     require Term::ANSIColor;
728 }
729
730 if ($option_all) {
731     $option_pie     = 1;
732     $option_bindnow = 1;
733 }
734
735 # Precompiled ignores for faster lookup.
736 my %option_ignore_arch_flag = ();
737 my %option_ignore_arch_line = ();
738
739 # Strip flags which should be ignored.
740 if (scalar @option_ignore_flag > 0) {
741     remove_flags(\@flag_refs, \%flag_renames, @option_ignore_flag);
742 }
743 # Same for arch specific ignore flags, but only prepare here.
744 if (scalar @option_ignore_arch_flag > 0) {
745     foreach my $ignore (@option_ignore_arch_flag) {
746         my ($ignore_arch, $ignore_flag) = split /:/, $ignore, 2;
747
748         if (not $ignore_arch or not $ignore_flag) {
749             printf STDERR 'Value "%s" invalid for option ignore-arch-flag '
750                         . '("arch:flag" expected)' . "\n", $ignore;
751             require Pod::Usage;
752             Pod::Usage::pod2usage(2);
753         }
754
755         push @{$option_ignore_arch_flag{$ignore_arch}}, $ignore_flag;
756     }
757 }
758
759 # Precompile all flag regexps. any_flags_used(), all_flags_used() get a lot
760 # faster with this.
761 foreach my $flags (@flag_refs_all) {
762     @{$flags} = compile_flag_regexp(\%flag_renames, @{$flags});
763 }
764
765 # Precompile ignore line regexps, also anchor at beginning and end of line.
766 # Additional entries are also extracted from the build log, see below.
767 foreach my $ignore (@option_ignore_line) {
768     $ignore = qr/^$ignore$/;
769 }
770 # Same for arch specific ignore lines.
771 if (scalar @option_ignore_arch_line > 0) {
772     foreach my $ignore (@option_ignore_arch_line) {
773         my ($ignore_arch, $ignore_line) = split /:/, $ignore, 2;
774
775         if (not $ignore_arch or not $ignore_line) {
776             printf STDERR 'Value "%s" invalid for option ignore-arch-line '
777                         . '("arch:line" expected)' . "\n", $ignore;
778             require Pod::Usage;
779             Pod::Usage::pod2usage(2);
780         }
781
782         push @{$option_ignore_arch_line{$ignore_arch}}, qr/^$ignore_line$/;
783     }
784 }
785
786 # Final exit code.
787 my $exit = 0;
788
789 FILE:
790 foreach my $file (@ARGV) {
791     print "checking '$file'...\n" if scalar @ARGV > 1;
792
793     -f $file or die "No such file: $file";
794
795     open my $fh, '<', $file or die $!;
796
797     # Architecture of this file.
798     my $arch = $option_arch;
799
800     # Hardening options. Not all architectures support all hardening options.
801     my $harden_format  = 1;
802     my $harden_fortify = 1;
803     my $harden_stack   = 1;
804     my $harden_stack_strong = 1;
805     my $harden_relro   = 1;
806     my $harden_bindnow = $option_bindnow; # defaults to 0
807     my $harden_pie     = $option_pie;     # defaults to 0
808
809     # Number of parallel jobs to prevent false positives when detecting
810     # non-verbose builds. As not all jobs declare the number of parallel jobs
811     # use a large enough default.
812     my $parallel = 10;
813
814     # Don't check for PIE flags if automatically applied by the compiler. Only
815     # used in buildd and Debian mode.
816     my $disable_harden_pie = 0;
817     if ($option_debian) {
818         $disable_harden_pie = 1;
819     }
820
821     # Ignore additional false positives if cargo/rust is used
822     my $cargo = 0;
823
824     my $number = 0;
825     while (my $line = <$fh>) {
826         $number++;
827
828         # Detect architecture automatically unless overridden. For buildd logs
829         # only, doesn't use the dpkg-buildpackage header. Necessary to ignore
830         # build logs which aren't built (wrong architecture, build error,
831         # etc.).
832         if (not $arch) {
833             if (index($line, 'Build Architecture: ') == 0) {
834                 $arch = substr $line, 20, -1; # -1 to ignore '\n' at the end
835             # For old logs (sbuild << 0.63.0-1).
836             } elsif (index($line, 'Architecture: ') == 0) {
837                 $arch = substr $line, 14, -1; # -1 to ignore '\n' at the end
838             }
839         }
840
841         # dpkg-buildflags only provides hardening flags since 1.16.1, don't
842         # check for hardening flags in buildd mode if an older dpkg-dev is
843         # used. Default flags (-g -O2) are still checked.
844         #
845         # Packages which were built before 1.16.1 but used their own hardening
846         # flags are not checked.
847         #
848         # Strong stack protector is used since dpkg 1.17.11.
849         #
850         # Recent GCC versions automatically use PIE (only on supported
851         # architectures) and dpkg respects this properly since 1.18.15 and
852         # doesn't pass PIE flags manually.
853         if ($option_buildd
854                 and index($line, 'Toolchain package versions: ') == 0) {
855             require Dpkg::Version;
856
857             my $disable = 1;
858             my $disable_strong = 1;
859
860             if ($line =~ /\bdpkg-dev_(\S+)/) {
861                 if (Dpkg::Version::version_compare($1, '1.16.1') >= 0) {
862                     $disable = 0;
863                 }
864                 if (Dpkg::Version::version_compare($1, '1.17.11') >= 0) {
865                     $disable_strong = 0;
866                 }
867                 if (Dpkg::Version::version_compare($1, '1.18.15') >= 0) {
868                     $disable_harden_pie = 1;
869                 }
870             }
871
872             if ($disable) {
873                 $harden_format  = 0;
874                 $harden_fortify = 0;
875                 $harden_stack   = 0;
876                 $harden_relro   = 0;
877                 $harden_bindnow = 0;
878                 $harden_pie     = 0;
879             }
880             if ($disable_strong) {
881                 $harden_stack_strong = 0;
882             }
883         }
884
885         # The following two versions of CMake in Debian obeyed CPPFLAGS, but
886         # this was later dropped because upstream rejected the patch. Thus
887         # build logs with these versions will have fortify hardening flags
888         # enabled, even though they may be not correctly set and are missing
889         # when build with later CMake versions. Thanks to Aron Xu for letting
890         # me know.
891         if (index($line, 'Package versions: ') == 0
892                 and $line =~ /\bcmake_(\S+)/
893                 and ($1 eq '2.8.7-1' or $1 eq '2.8.7-2')) {
894             if (not $option_buildd) {
895                 error_invalid_cmake($1);
896                 $exit |= $exit_code{invalid_cmake};
897             } else {
898                 print "$buildd_tag{invalid_cmake}|$1|\n";
899             }
900         }
901
902         # Debian's build daemons use "Filtered Build-Depends:" (or just
903         # "Build-Depends:" in older versions) for the build dependencies, but
904         # pbuilder uses "Depends:"; support both.
905         if (index($line, 'Filtered Build-Depends: ') == 0
906                 or index($line, 'Build-Depends: ') == 0
907                 or index($line, 'Depends: ') == 0) {
908             # If hardening wrapper is used (wraps calls to gcc and adds
909             # hardening flags automatically) we can't perform any checks,
910             # abort.
911             if ($line =~ /\bhardening-wrapper\b/) {
912                 if (not $option_buildd) {
913                     error_hardening_wrapper();
914                     $exit |= $exit_code{hardening_wrapper};
915                 } else {
916                     print "$buildd_tag{hardening_wrapper}||\n";
917                 }
918                 next FILE;
919             }
920
921             if ($line =~ /\bcargo\b/) {
922                 $cargo = 1;
923             }
924         }
925
926         # This flags is not always available, but if it is use it.
927         if ($line =~ /^DEB_BUILD_OPTIONS=.*\bparallel=(\d+)/) {
928             $parallel = $1 * 2;
929         }
930
931         # We skip over unimportant lines at the beginning of the log to
932         # prevent false positives.
933         last if index($line, 'dpkg-buildpackage: ') == 0;
934     }
935
936     # Input lines, contain only the lines with compiler commands.
937     my @input = ();
938     # Non-verbose lines in the input. Used to reduce calls to
939     # is_non_verbose_build() (which is quite slow) in the second loop when
940     # it's already clear if a line is non-verbose or not.
941     my @input_nonverbose = ();
942     # Input line number.
943     my @input_number = ();
944
945     my $continuation = 0;
946     my $complete_line = undef;
947     my $non_verbose;
948     while (my $line = <$fh>) {
949         $number++;
950
951         # And stop at the end of the build log. Package details (reported by
952         # the buildd logs) are not important for us. This also prevents false
953         # positives.
954         last if index($line, 'Build finished at ') == 0
955                 and $line =~ /^Build finished at \d{8}-\d{4}$/;
956
957         if (not $continuation) {
958             $non_verbose = 0;
959         }
960
961         # Detect architecture automatically unless overridden.
962         if (not $arch
963                 and index($line, 'dpkg-buildpackage: info: host architecture ') == 0) {
964             $arch = substr $line, 43, -1; # -1 to ignore '\n' at the end
965         # Older versions of dpkg-buildpackage
966         } elsif (not $arch
967                 and index($line, 'dpkg-buildpackage: host architecture ') == 0) {
968             $arch = substr $line, 37, -1; # -1 to ignore '\n' at the end
969
970             # Old buildd logs use e.g. "host architecture is alpha", remove
971             # the "is", otherwise debarch_to_debtriplet() will not detect the
972             # architecture.
973             if (index($arch, 'is ') == 0) {
974                 $arch = substr $arch, 3;
975             }
976         }
977
978         # Permit dynamic excludes from within the build log to ignore false
979         # positives. Cannot use a separate config file as we often only have
980         # the build log itself.
981         if (index($line, 'blhc: ignore-line-regexp: ') == 0) {
982             my $ignore = substr $line, 26, -1; # -1 to ignore '\n' at the end
983             push @option_ignore_line, qr/^$ignore$/;
984             next;
985         }
986
987         next if $line =~ /^\s*#/;
988         # Ignore compiler warnings for now.
989         next if $line =~ /$warning_regex/o;
990
991         if (not $option_buildd and index($line, "\033") != -1) { # \033 = esc
992             # Remove all ANSI color sequences which are sometimes used in
993             # non-verbose builds.
994             $line = Term::ANSIColor::colorstrip($line);
995             # Also strip '\0xf' (delete previous character), used by Elinks'
996             # build system.
997             $line =~ s/\x0f//g;
998             # And "ESC(B" which seems to be used on armhf and hurd (not sure
999             # what it does).
1000             $line =~ s/\033\(B//g;
1001         }
1002
1003         # Check if this line indicates a non verbose build.
1004         my $skip = 0;
1005         $non_verbose |= is_non_verbose_build($line, $cargo, \$skip);
1006         next if $skip;
1007
1008         # Treat each command as a single line so we don't ignore valid
1009         # commands when handling false positives. split_line() is slow, only
1010         # use it when necessary.
1011         my @line = ($line !~ /(?:;|&&|\|\|)/)
1012                  ? ($line)
1013                  : split_line($line);
1014         foreach my $line (@line) {
1015             if ($continuation) {
1016                 $continuation = 0;
1017
1018                 # Join lines, but leave the "\" in place so it's clear where
1019                 # the original line break was.
1020                 chomp $complete_line;
1021                 $complete_line .= ' ' . $line;
1022             }
1023             # Line continuation, line ends with "\".
1024             if ($line =~ /\\$/) {
1025                 $continuation = 1;
1026                 # Start line continuation.
1027                 if (not defined $complete_line) {
1028                     $complete_line = $line;
1029                 }
1030                 next;
1031             }
1032
1033             # Use the complete line if a line continuation occurred.
1034             if (defined $complete_line) {
1035                 $line = $complete_line;
1036                 $complete_line = undef;
1037             }
1038
1039             my $noenv = $line;
1040             # Strip (basic) environment variables for compiler detection. This
1041             # prevents false positives when environment variables contain
1042             # compiler binaries. Nested quotes, command substitution, etc. is
1043             # not supported.
1044             $noenv =~ s/^
1045                 \s*
1046                 (?:
1047                     [a-zA-Z_]+          # environment variable name
1048                     =
1049                     (?:
1050                         [^\s"'\$`\\]+   # non-quoted string
1051                         |
1052                         '[^"'\$`\\]*'   # single-quoted string
1053                         |
1054                         "[^"'\$`\\]*"   # double-quoted string
1055                     )
1056                     \s+
1057                 )*
1058             //x;
1059             # Ignore lines with no compiler commands.
1060             next if not $non_verbose
1061                     and not $noenv =~ /$cc_regex_normal/o;
1062             # Ignore lines with no filenames with extensions. May miss some
1063             # non-verbose builds (e.g. "gcc -o test" [sic!]), but shouldn't be
1064             # a problem as the log will most likely contain other non-verbose
1065             # commands which are detected.
1066             next if not $non_verbose
1067                     and not $line =~ /$file_extension_regex/o;
1068
1069             # Ignore false positives.
1070             #
1071             # `./configure` output.
1072             next if not $non_verbose
1073                     and $line =~ /^(?:checking|[Cc]onfigure:) /;
1074             next if $line =~ /^\s*(?:Host\s+)?(?:C(?:\+\+)?\s+)?
1075                                 [Cc]ompiler[\s.]*:?\s+
1076                                 /x;
1077             next if $line =~ m{^\s*(?:-\s)?(?:HOST_)?(?:CC|CXX)
1078                                 \s*=\s*$cc_regex_full
1079                                 # optional compiler options, don't allow
1080                                 # "everything" here to prevent false negatives
1081                                 \s*(?:\s-\S+)*\s*$}xo;
1082             # `echo` is never a compiler command
1083             next if $line =~ /^\s*echo\s/;
1084             # Ignore calls to `make` because they can contain environment
1085             # variables which look like compiler commands, e.g. CC=).
1086             next if $line =~ /^\s*make\s/;
1087             # `moc-qt4`/`moc-qt5` contain '-I.../linux-g++' in their command
1088             # line (or similar for other architectures) which gets recognized
1089             # as a compiler line, but `moc-qt*` is only a preprocessor for Qt
1090             # C++ files. No hardening flags are relevant during this step,
1091             # thus ignore `moc-qt*` lines. The resulting files will be
1092             # compiled in a separate step (and therefore checked).
1093             next if $line =~ m{^\S+(?:/bin/moc(?:-qt[45])?|/lib/qt6/libexec/moc)
1094                                \s.+\s
1095                                -I\S+/mkspecs/[a-z]+-g\++(?:-64)?
1096                                \s}x;
1097             # nvcc is not a regular C compiler
1098             next if $line =~ m{^\S+/bin/nvcc\s};
1099             # Ignore false positives when the line contains only CC=gcc but no
1100             # other gcc command.
1101             if ($line =~ /(.*)CC=$cc_regex_full(.*)/o) {
1102                 my $before = $1;
1103                 my $after  = $2;
1104                 next if     not $before =~ /$cc_regex_normal/o
1105                         and not $after  =~ /$cc_regex_normal/o;
1106             }
1107             # Ignore false positives caused by gcc -v. It outputs a line
1108             # looking like a normal compiler line but which is sometimes
1109             # missing hardening flags, although the normal compiler line
1110             # contains them.
1111             next if $line =~ m{^\s+/usr/lib/gcc/$cc_regex_full_prefix/
1112                                    [0-9.]+/cc1(?:plus)?}xo;
1113             # Ignore false positive with `rm` which may remove files which
1114             # look like a compiler executable thus causing the line to be
1115             # treated as a normal compiler line.
1116             next if $line =~ m{^\s*rm\s+};
1117             next if $line =~ m{^\s*dwz\s+};
1118             # Some build systems emit "gcc > file".
1119             next if $line =~ m{$cc_regex_normal\s*>\s*\S+}o;
1120             # Hex output may contain "cc".
1121             next if $line =~ m#(?:\b[0-9a-fA-F]{2,}\b\s*){5}#;
1122             # Meson build output
1123             next if $line =~ /^C\+\+ linker for the host machine: /;
1124             # Embedded `gcc -print-*` commands
1125             next if $line =~ /`$cc_regex_normal\s*[^`]*-print-\S+`/;
1126             # cmake checking for compiler flags without setting CPPFLAGS
1127             next if $line =~ m{^\s*/usr/(bin|lib)/(ccache/)?c\+\+ (?:-std=\S+ )?-dM -E -c /usr/share/cmake-\S+/Modules/CMakeCXXCompilerABI\.cpp};
1128             # Some rustc lines look like linker commands
1129             next if $cargo and $line =~ /$rustc_regex/o;
1130
1131             # Check if additional hardening options were used. Used to ensure
1132             # they are used for the complete build.
1133             $harden_pie     = 1 if any_flags_used($line, @def_cflags_pie,
1134                                                          @def_ldflags_pie);
1135             $harden_bindnow = 1 if any_flags_used($line, @def_ldflags_bindnow);
1136
1137             push @input, $line;
1138             push @input_nonverbose, $non_verbose;
1139             push @input_number, $number if $option_line_numbers;
1140         }
1141     }
1142
1143     close $fh or die $!;
1144
1145     # Ignore arch if requested.
1146     if (scalar @option_ignore_arch > 0 and $arch) {
1147         foreach my $ignore (@option_ignore_arch) {
1148             if ($arch eq $ignore) {
1149                 print "ignoring architecture '$arch'\n";
1150                 next FILE;
1151             }
1152         }
1153     }
1154
1155     if (scalar @input == 0) {
1156         if (not $option_buildd) {
1157             print "No compiler commands!\n";
1158             $exit |= $exit_code{no_compiler_commands};
1159         } else {
1160             print "$buildd_tag{no_compiler_commands}||\n";
1161         }
1162         next FILE;
1163     }
1164
1165     if ($option_buildd) {
1166         $statistics{commands} += scalar @input;
1167     }
1168
1169     # Option or auto detected.
1170     if ($arch) {
1171         # The following was partially copied from dpkg-dev 1.22.0
1172         # (/usr/share/perl5/Dpkg/Vendor/Debian.pm, set_build_features and
1173         # _add_build_flags()), copyright Raphaël Hertzog <hertzog@debian.org>,
1174         # Guillem Jover <guillem@debian.org>, Kees Cook <kees@debian.org>,
1175         # Canonical, Ltd. licensed under GPL version 2 or later. Keep it in
1176         # sync.
1177
1178         require Dpkg::Arch;
1179         my ($os, $cpu);
1180         # Recent dpkg versions use a quadruplet for arch. Support both.
1181         eval {
1182             (undef, undef, $os, $cpu) = Dpkg::Arch::debarch_to_debtuple($arch);
1183         };
1184         if ($@) {
1185             (undef, $os, $cpu) = Dpkg::Arch::debarch_to_debtriplet($arch);
1186         }
1187
1188         my %builtin_pie_arch = map { $_ => 1 } qw(
1189             amd64
1190             arm64
1191             armel
1192             armhf
1193             hurd-amd64
1194             hurd-i386
1195             i386
1196             kfreebsd-amd64
1197             kfreebsd-i386
1198             loong64
1199             mips
1200             mips64
1201             mips64el
1202             mips64r6
1203             mips64r6el
1204             mipsel
1205             mipsn32
1206             mipsn32el
1207             mipsn32r6
1208             mipsn32r6el
1209             mipsr6
1210             mipsr6el
1211             powerpc
1212             ppc64
1213             ppc64el
1214             riscv64
1215             s390x
1216             sparc
1217             sparc64
1218         );
1219
1220         # Disable unsupported hardening options.
1221         if ($disable_harden_pie and exists $builtin_pie_arch{$arch}) {
1222             $harden_pie = 0;
1223         }
1224         if ($os !~ /^(?:linux|kfreebsd|hurd)$/
1225                 or $cpu =~ /^(?:alpha|hppa|ia64)$/) {
1226             $harden_pie = 0;
1227         }
1228         if ($cpu =~ /^(?:ia64|alpha|hppa|nios2)$/ or $arch eq 'arm') {
1229             $harden_stack = 0;
1230             $harden_stack_strong = 0;
1231         }
1232         if ($cpu =~ /^(?:ia64|hppa)$/) {
1233             $harden_relro   = 0;
1234             $harden_bindnow = 0;
1235         }
1236     }
1237
1238     # Default values.
1239     my @cflags   = @def_cflags;
1240     my @cxxflags = @def_cxxflags;
1241     my @cppflags = @def_cppflags;
1242     my @ldflags  = @def_ldflags;
1243     # Check the specified hardening options, same order as dpkg-buildflags.
1244     if ($harden_pie) {
1245         @cflags   = (@cflags,   @def_cflags_pie);
1246         @cxxflags = (@cxxflags, @def_cflags_pie);
1247         @ldflags  = (@ldflags,  @def_ldflags_pie);
1248     }
1249     if ($harden_stack_strong) {
1250         @cflags   = (@cflags,   @def_cflags_stack_strong);
1251         @cxxflags = (@cxxflags, @def_cflags_stack_strong);
1252     } elsif ($harden_stack) {
1253         @cflags   = (@cflags,   @def_cflags_stack);
1254         @cxxflags = (@cxxflags, @def_cflags_stack);
1255     }
1256     if ($harden_fortify) {
1257         @cflags   = (@cflags,   @def_cflags_fortify);
1258         @cxxflags = (@cxxflags, @def_cflags_fortify);
1259         @cppflags = (@cppflags, @def_cppflags_fortify);
1260     }
1261     if ($harden_format) {
1262         @cflags   = (@cflags,   @def_cflags_format);
1263         @cxxflags = (@cxxflags, @def_cflags_format);
1264     }
1265     if ($harden_relro) {
1266         @ldflags = (@ldflags, @def_ldflags_relro);
1267     }
1268     if ($harden_bindnow) {
1269         @ldflags = (@ldflags, @def_ldflags_bindnow);
1270     }
1271
1272     # Ada doesn't support format hardening flags, see #680117 for more
1273     # information. Same for fortran.
1274     my @cflags_backup;
1275     my @cflags_noformat = grep {
1276         my $ok = 1;
1277         foreach my $flag (@def_cflags_format) {
1278             $ok = 0 if $_ eq $flag;
1279         }
1280         $ok;
1281     } @cflags;
1282
1283     # Hack to fix cppflags_fortify_broken() if --ignore-flag
1284     # -D_FORTIFY_SOURCE=2 is used to ignore missing fortification. Only works
1285     # as long as @def_cppflags_fortify contains only one variable.
1286     if (scalar @def_cppflags_fortify == 0) {
1287         $harden_fortify = 0;
1288     }
1289
1290     # Ignore flags for this arch if requested.
1291     if ($arch and exists $option_ignore_arch_flag{$arch}) {
1292         my @local_flag_refs = (\@cflags, \@cxxflags, \@cppflags, \@ldflags);
1293
1294         remove_flags(\@local_flag_refs,
1295                      \%flag_renames,
1296                      @{$option_ignore_arch_flag{$arch}});
1297     }
1298
1299     my @ignore_line = @option_ignore_line;
1300     # Ignore lines for this arch if requested.
1301     if ($arch and exists $option_ignore_arch_line{$arch}) {
1302         @ignore_line = (@ignore_line, @{$option_ignore_arch_line{$arch}});
1303     }
1304
1305 LINE:
1306     for (my $i = 0; $i < scalar @input; $i++) {
1307         my $line = $input[$i];
1308
1309         # Ignore line if requested.
1310         foreach my $ignore (@ignore_line) {
1311             next LINE if $line =~ /$ignore/;
1312         }
1313
1314         my $skip = 0;
1315         if ($input_nonverbose[$i]
1316                 and is_non_verbose_build($line, $cargo, \$skip,
1317                                          \@input, $i, $parallel)) {
1318             if (not $option_buildd) {
1319                 error_non_verbose_build($line, $input_number[$i]);
1320                 $exit |= $exit_code{non_verbose_build};
1321             } else {
1322                 $statistics{commands_nonverbose}++;
1323             }
1324             next;
1325         }
1326         # Even if it's a verbose build, we might have to skip this line (see
1327         # is_non_verbose_build()).
1328         next if $skip;
1329
1330         my $orig_line = $line;
1331
1332         # Remove everything until and including the compiler command. Makes
1333         # checks easier and faster.
1334         $line =~ s/^.*?$cc_regex//o;
1335         # "([...] test.c)" is not detected as 'test.c' - fix this by removing
1336         # the brace and similar characters at the line end.
1337         $line =~ s/['")]+$//;
1338
1339         # Skip unnecessary tests when only preprocessing.
1340         my $flag_preprocess = 0;
1341
1342         my $dependency = 0;
1343         my $preprocess = 0;
1344         my $compile    = 0;
1345         my $link       = 0;
1346
1347         # Preprocess, compile, assemble.
1348         if ($line =~ /\s(-E|-S|-c)\b/) {
1349             $preprocess      = 1;
1350             $flag_preprocess = 1 if $1 eq '-E';
1351             $compile         = 1 if $1 eq '-S' or $1 eq '-c';
1352         # Dependency generation for Makefiles. The other flags (-MF -MG -MP
1353         # -MT -MQ) are always used with -M/-MM.
1354         } elsif ($line =~ /\s(?:-M|-MM)\b/) {
1355             $dependency = 1;
1356         # Otherwise assume we are linking.
1357         } else {
1358             $link = 1;
1359         }
1360
1361         # -MD/-MMD also cause dependency generation, but they don't imply -E!
1362         if ($line =~ /\s(?:-MD|-MMD)\b/) {
1363             $dependency      = 0;
1364             $flag_preprocess = 0;
1365         }
1366
1367         # Dependency generation for Makefiles, no preprocessing or other flags
1368         # needed.
1369         next if $dependency;
1370
1371         # Get all file extensions on this line.
1372         my @extensions = $line =~ /$file_extension_regex/go;
1373         # Ignore all unknown extensions to speedup the search below.
1374         @extensions = grep { exists $extension{$_} } @extensions;
1375
1376         # These file types don't require preprocessing.
1377         if (extension_found(\%extensions_no_preprocess, @extensions)) {
1378             $preprocess = 0;
1379         }
1380         # These file types require preprocessing.
1381         if (extension_found(\%extensions_preprocess, @extensions)) {
1382             # Prevent false positives with "libtool: link: g++ -include test.h
1383             # .." compiler lines.
1384             if ($orig_line !~ /$libtool_link_regex/o) {
1385                 $preprocess = 1;
1386             }
1387         }
1388
1389         if (not $flag_preprocess) {
1390             # If there are source files then it's compiling/linking in one
1391             # step and we must check both. We only check for source files
1392             # here, because header files cause too many false positives.
1393             if (extension_found(\%extensions_compile_link, @extensions)) {
1394                 # Assembly files don't need CFLAGS.
1395                 if (not extension_found(\%extensions_compile, @extensions)
1396                         and extension_found(\%extensions_no_compile, @extensions)) {
1397                     $compile = 0;
1398                 # But the rest does.
1399                 } else {
1400                     $compile = 1;
1401                 }
1402             # No compilable extensions found, either linking or compiling
1403             # header flags.
1404             #
1405             # If there are also no object files we are just compiling headers
1406             # (.h -> .h.gch). Don't check for linker flags in this case. Due
1407             # to our liberal checks for compiler lines, this also reduces the
1408             # number of false positives considerably.
1409             } elsif ($link
1410                     and not extension_found(\%extensions_object, @extensions)) {
1411                 $link = 0;
1412             }
1413         }
1414
1415         my $compile_cpp = 0;
1416         my $restore_cflags = 0;
1417         # Assume CXXFLAGS are required when a C++ file is specified in the
1418         # compiler line.
1419         if ($compile
1420                 and extension_found(\%extensions_compile_cpp, @extensions)) {
1421             $compile     = 0;
1422             $compile_cpp = 1;
1423         # Ada needs special CFLAGS
1424         } elsif (extension_found(\%extensions_ada, @extensions)) {
1425             $restore_cflags = 1;
1426             $preprocess = 0; # Ada uses no CPPFLAGS
1427             @cflags_backup = @cflags;
1428             @cflags        = @cflags_noformat;
1429         # Same for fortran
1430         } elsif (extension_found(\%extensions_fortran, @extensions)) {
1431             $restore_cflags = 1;
1432             @cflags_backup = @cflags;
1433             @cflags        = @cflags_noformat;
1434         }
1435
1436         if ($option_buildd) {
1437             $statistics{preprocess}++  if $preprocess;
1438             $statistics{compile}++     if $compile;
1439             $statistics{compile_cpp}++ if $compile_cpp;
1440             $statistics{link}++        if $link;
1441         }
1442
1443         # Check if there are flags indicating a debug build. If that's true,
1444         # skip the check for -O2. This prevents fortification, but that's fine
1445         # for a debug build.
1446         if (any_flags_used($line, @def_cflags_debug)) {
1447             remove_flags([\@cflags], \%flag_renames, $def_cflags[1]);
1448             remove_flags([\@cppflags], \%flag_renames, $def_cppflags_fortify[0]);
1449         }
1450
1451         # Check hardening flags.
1452         my @missing;
1453         if ($compile and (not all_flags_used($line, \@missing, @cflags)
1454                     or (($harden_stack or $harden_stack_strong)
1455                         and cflags_stack_broken($line, \@missing,
1456                                                 $harden_stack_strong)))
1457                 # Libraries linked with -fPIC don't have to (and can't) be
1458                 # linked with -fPIE as well. It's no error if only PIE flags
1459                 # are missing.
1460                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1461                 # Assume dpkg-buildflags returns the correct flags.
1462                 and index($line, '`dpkg-buildflags --get CFLAGS`') == -1) {
1463             if (not $option_buildd) {
1464                 error_flags('CFLAGS missing', \@missing, \%flag_renames,
1465                             $input[$i], $input_number[$i]);
1466                 $exit |= $exit_code{flags_missing};
1467             } else {
1468                 $statistics{compile_missing}++;
1469             }
1470         } elsif ($compile_cpp and not all_flags_used($line, \@missing, @cflags)
1471                 # Libraries linked with -fPIC don't have to (and can't) be
1472                 # linked with -fPIE as well. It's no error if only PIE flags
1473                 # are missing.
1474                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_cflags_pie)
1475                 # Assume dpkg-buildflags returns the correct flags.
1476                 and index($line, '`dpkg-buildflags --get CXXFLAGS`') == -1) {
1477             if (not $option_buildd) {
1478                 error_flags('CXXFLAGS missing', \@missing, \%flag_renames,
1479                             $input[$i], $input_number[$i]);
1480                 $exit |= $exit_code{flags_missing};
1481             } else {
1482                 $statistics{compile_cpp_missing}++;
1483             }
1484         }
1485         if ($preprocess
1486                 and (not all_flags_used($line, \@missing, @cppflags)
1487                     # The fortify flag might be overwritten, detect that.
1488                      or ($harden_fortify
1489                          and cppflags_fortify_broken($line, \@missing)))
1490                 # Assume dpkg-buildflags returns the correct flags.
1491                 and index($line, '`dpkg-buildflags --get CPPFLAGS`') == -1) {
1492             if (not $option_buildd) {
1493                 error_flags('CPPFLAGS missing', \@missing, \%flag_renames,
1494                             $input[$i], $input_number[$i]);
1495                 $exit |= $exit_code{flags_missing};
1496             } else {
1497                 $statistics{preprocess_missing}++;
1498             }
1499         }
1500         if ($link and not all_flags_used($line, \@missing, @ldflags)
1501                 # Same here, -fPIC conflicts with -fPIE.
1502                 and not pic_pie_conflict($line, $harden_pie, \@missing, @def_ldflags_pie)
1503                 # Assume dpkg-buildflags returns the correct flags.
1504                 and index($line, '`dpkg-buildflags --get LDFLAGS`') == -1) {
1505             if (not $option_buildd) {
1506                 error_flags('LDFLAGS missing', \@missing, \%flag_renames,
1507                             $input[$i], $input_number[$i]);
1508                 $exit |= $exit_code{flags_missing};
1509             } else {
1510                 $statistics{link_missing}++;
1511             }
1512         }
1513
1514         # Restore normal CFLAGS.
1515         if ($restore_cflags) {
1516             @cflags = @cflags_backup;
1517         }
1518     }
1519 }
1520
1521 # Print statistics for buildd mode, only output in this mode.
1522 if ($option_buildd) {
1523     my @warning;
1524
1525     if ($statistics{preprocess_missing}) {
1526         push @warning, sprintf 'CPPFLAGS %d (of %d)',
1527                                $statistics{preprocess_missing},
1528                                $statistics{preprocess};
1529     }
1530     if ($statistics{compile_missing}) {
1531         push @warning, sprintf 'CFLAGS %d (of %d)',
1532                                $statistics{compile_missing},
1533                                $statistics{compile};
1534     }
1535     if ($statistics{compile_cpp_missing}) {
1536         push @warning, sprintf 'CXXFLAGS %d (of %d)',
1537                                $statistics{compile_cpp_missing},
1538                                $statistics{compile_cpp};
1539     }
1540     if ($statistics{link_missing}) {
1541         push @warning, sprintf 'LDFLAGS %d (of %d)',
1542                                $statistics{link_missing},
1543                                $statistics{link};
1544     }
1545     if (scalar @warning) {
1546         local $" = ', '; # array join string
1547         print "$buildd_tag{flags_missing}|@warning missing|\n";
1548     }
1549
1550     if ($statistics{commands_nonverbose}) {
1551         printf "$buildd_tag{non_verbose_build}|%d (of %d) hidden|\n",
1552                $statistics{commands_nonverbose},
1553                $statistics{commands},
1554     }
1555 }
1556
1557
1558 exit $exit;
1559
1560
1561 __END__
1562
1563 =head1 NAME
1564
1565 blhc - build log hardening check, checks build logs for missing hardening flags
1566
1567 =head1 SYNOPSIS
1568
1569 B<blhc> [I<options>] I<< <dpkg-buildpackage build log file>.. >>
1570
1571 =head1 DESCRIPTION
1572
1573 blhc is a small tool which checks build logs for missing hardening flags. It's
1574 licensed under the GPL 3 or later.
1575
1576 It's designed to check build logs generated by Debian's dpkg-buildpackage (or
1577 tools using dpkg-buildpackage like pbuilder or sbuild (which is used for the
1578 official buildd build logs)) to help maintainers detect missing hardening
1579 flags in their packages.
1580
1581 Only gcc is detected as compiler at the moment. If other compilers support
1582 hardening flags as well, please report them.
1583
1584 If there's no output, no flags are missing and the build log is fine.
1585
1586 See F<README> for details about performed checks, auto-detection and
1587 limitations.
1588
1589 =head1 FALSE POSITIVES
1590
1591 To suppress false positives you can embed the following string in the build
1592 log:
1593
1594     blhc: ignore-line-regexp: REGEXP
1595
1596 All lines fully matching REGEXP (see B<--ignore-line> for details) will be
1597 ignored. The string can be embedded multiple times to ignore different
1598 regexps.
1599
1600 Please use this feature sparingly so that missing flags are not overlooked. If
1601 you find false positives which affect more packages please report a bug.
1602
1603 To generate this string simply use echo in C<debian/rules>; make sure to use @
1604 to suppress the echo command itself as it could also trigger a false positive.
1605 If the build process takes a long time edit the C<.build> file in place and
1606 tweak the ignore string until B<blhc --all --debian package.build> no longer
1607 reports any false positives.
1608
1609 =head1 OPTIONS
1610
1611 =over 8
1612
1613 =item B<--all>
1614
1615 Force check for all +all (+pie, +bindnow) hardening flags. By default it's
1616 auto detected.
1617
1618 =item B<--arch> I<architecture>
1619
1620 Set the specific architecture (e.g. amd64, armel, etc.), automatically
1621 disables hardening flags not available on this architecture. Is detected
1622 automatically if dpkg-buildpackage is used.
1623
1624 =item B<--bindnow>
1625
1626 Force check for all +bindnow hardening flags. By default it's auto detected.
1627
1628 =item B<--buildd>
1629
1630 Special mode for buildds when automatically parsing log files. The following
1631 changes are in effect:
1632
1633 =over 2
1634
1635 =item *
1636
1637 Print tags instead of normal warnings, see L</"BUILDD TAGS"> for a list of
1638 possible tags.
1639
1640 =item *
1641
1642 Don't check hardening flags in old log files (if dpkg-dev << 1.16.1 is
1643 detected).
1644
1645 =item *
1646
1647 Don't require Term::ANSIColor.
1648
1649 =item *
1650
1651 Return exit code 0, unless there was a error (-I, -W messages don't count as
1652 error).
1653
1654 =back
1655
1656 =item B<--debian>
1657
1658 Apply Debian-specific settings. At the moment this only disables checking for
1659 PIE which is automatically applied by Debian's GCC and no longer requires a
1660 compiler command line argument.
1661
1662 =item B<--color>
1663
1664 Use colored (ANSI) output for warning messages.
1665
1666 =item B<--line-numbers>
1667
1668 Display line numbers.
1669
1670 =item B<--ignore-arch> I<arch>
1671
1672 Ignore build logs from architectures matching I<arch>. I<arch> is a string.
1673
1674 Used to prevent false positives. This option can be specified multiple times.
1675
1676 =item B<--ignore-arch-flag> I<arch>:I<flag>
1677
1678 Like B<--ignore-flag>, but only ignore flag on I<arch>.
1679
1680 =item B<--ignore-arch-line> I<arch>:I<line>
1681
1682 Like B<--ignore-line>, but only ignore line on I<arch>.
1683
1684 =item B<--ignore-flag> I<flag>
1685
1686 Don't print an error when the specific flag is missing in a compiler line.
1687 I<flag> is a string.
1688
1689 Used to prevent false positives. This option can be specified multiple times.
1690
1691 =item B<--ignore-line> I<regex>
1692
1693 Ignore lines matching the given Perl regex. I<regex> is automatically anchored
1694 at the beginning and end of the line to prevent false negatives.
1695
1696 B<NOTE>: Not the input lines are checked, but the lines which are displayed in
1697 warnings (which have line continuation resolved).
1698
1699 Used to prevent false positives. This option can be specified multiple times.
1700
1701 =item B<--pie>
1702
1703 Force check for all +pie hardening flags. By default it's auto detected.
1704
1705 =item B<-h -? --help>
1706
1707 Print available options.
1708
1709 =item B<--version>
1710
1711 Print version number and license.
1712
1713 =back
1714
1715 Auto detection for B<--pie> and B<--bindnow> only works if at least one
1716 command uses the required hardening flag (e.g. -fPIE). Then it's required for
1717 all other commands as well.
1718
1719 =head1 EXAMPLES
1720
1721 Normal usage, parse a single log file.
1722
1723     blhc path/to/log/file
1724
1725 If there's no output, no flags are missing and the build log is fine.
1726
1727 Parse multiple log files. The exit code is ORed over all files.
1728
1729     blhc path/to/directory/with/log/files/*
1730
1731 Don't treat missing C<-g> as error:
1732
1733     blhc --ignore-flag -g path/to/log/file
1734
1735 Don't treat missing C<-pie> on kfreebsd-amd64 as error:
1736
1737     blhc --ignore-arch-flag kfreebsd-amd64:-pie path/to/log/file
1738
1739 Ignore lines consisting exactly of C<./script gcc file> which would cause a
1740 false positive.
1741
1742     blhc --ignore-line '\./script gcc file' path/to/log/file
1743
1744 Ignore lines matching C<./script gcc file> somewhere in the line.
1745
1746     blhc --ignore-line '.*\./script gcc file.*' path/to/log/file
1747
1748 Use blhc with pbuilder.
1749
1750     pbuilder path/to/package.dsc | tee path/log/file
1751     blhc path/to/file || echo flags missing
1752
1753 Assume this build log was created on a Debian system and thus don't warn about
1754 missing PIE flags if the current architecture injects them automatically (this
1755 is enabled in buildd mode per default). C<--arch> is necessary if the build
1756 log contains no architecture information as written by dpkg-buildpackage.
1757
1758     blhc --debian --all --arch=amd64 path/to/log/file
1759
1760 =head1 BUILDD TAGS
1761
1762 The following tags are used in I<--buildd> mode. In braces the additional data
1763 which is displayed.
1764
1765 =over 2
1766
1767 =item B<I-hardening-wrapper-used>
1768
1769 The package uses hardening-wrapper which intercepts calls to gcc and adds
1770 hardening flags. The build log doesn't contain any hardening flags and thus
1771 can't be checked by blhc.
1772
1773 =item B<W-compiler-flags-hidden> (summary of hidden lines)
1774
1775 Build log contains lines which hide the real compiler flags. For example:
1776
1777     CC test-a.c
1778     CC test-b.c
1779     CC test-c.c
1780     LD test
1781
1782 Most of the time either C<export V=1> or C<export verbose=1> in
1783 F<debian/rules> fixes builds with hidden compiler flags. Sometimes C<.SILENT>
1784 in a F<Makefile> must be removed. And as last resort the F<Makefile> must be
1785 patched to remove the C<@>s hiding the real compiler commands.
1786
1787 =item B<W-dpkg-buildflags-missing> (summary of missing flags)
1788
1789 CPPFLAGS, CFLAGS, CXXFLAGS, LDFLAGS missing.
1790
1791 =item B<I-invalid-cmake-used> (version)
1792
1793 By default CMake ignores CPPFLAGS thus missing those hardening flags. Debian
1794 patched CMake in versions 2.8.7-1 and 2.8.7-2 to respect CPPFLAGS, but this
1795 patch was rejected by upstream and later reverted in Debian. Thus those two
1796 versions show correct usage of CPPFLAGS even if the package doesn't correctly
1797 handle them (for example by passing them to CFLAGS). To prevent false
1798 negatives just blacklist those two versions.
1799
1800 =item B<I-no-compiler-commands>
1801
1802 No compiler commands were detected. Either the log contains none or they were
1803 not correctly detected by blhc (please report the bug in this case).
1804
1805 =back
1806
1807 =head1 EXIT STATUS
1808
1809 The exit status is a "bit mask", each listed status is ORed when the error
1810 condition occurs to get the result.
1811
1812 =over 4
1813
1814 =item B<0>
1815
1816 Success.
1817
1818 =item B<1>
1819
1820 No compiler commands were found.
1821
1822 =item B<2>
1823
1824 Invalid arguments/options given to blhc.
1825
1826 =item B<4>
1827
1828 Non verbose build.
1829
1830 =item B<8>
1831
1832 Missing hardening flags.
1833
1834 =item B<16>
1835
1836 Hardening wrapper detected, no tests performed.
1837
1838 =item B<32>
1839
1840 Invalid CMake version used. See B<I-invalid-cmake-used> under L</"BUILDD
1841 TAGS"> for a detailed explanation.
1842
1843 =back
1844
1845 =head1 AUTHOR
1846
1847 Simon Ruderich, E<lt>simon@ruderich.orgE<gt>
1848
1849 Thanks to to Bernhard R. Link E<lt>brlink@debian.orgE<gt> and Jaria Alto
1850 E<lt>jari.aalto@cante.netE<gt> for their valuable input and suggestions.
1851
1852 =head1 LICENSE AND COPYRIGHT
1853
1854 Copyright (C) 2012-2024 by Simon Ruderich
1855
1856 This program is free software: you can redistribute it and/or modify
1857 it under the terms of the GNU General Public License as published by
1858 the Free Software Foundation, either version 3 of the License, or
1859 (at your option) any later version.
1860
1861 This program is distributed in the hope that it will be useful,
1862 but WITHOUT ANY WARRANTY; without even the implied warranty of
1863 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
1864 GNU General Public License for more details.
1865
1866 You should have received a copy of the GNU General Public License
1867 along with this program.  If not, see <http://www.gnu.org/licenses/>.
1868
1869 =head1 SEE ALSO
1870
1871 L<hardening-check(1)>, L<dpkg-buildflags(1)>
1872
1873 =cut