3 # (c) 2017 Tobin C. Harding <me@tobin.cc>
4 # Licensed under the terms of the GNU GPL License version 2
6 # leaking_addresses.pl: Scan 64 bit kernel for potential leaking addresses.
7 # - Scans dmesg output.
8 # - Walks directory tree and parses each file (for each directory in @DIRS).
10 # Use --debug to output path before parsing, this is useful to find files that
11 # cause the script to choke.
19 use Term::ANSIColor qw(:constants);
20 use Getopt::Long qw(:config no_auto_abbrev);
28 # Directories to scan.
29 my @DIRS = ('/proc', '/sys');
31 # Timer for parsing each file, in seconds.
34 # Script can only grep for kernel addresses on the following architectures. If
35 # your architecture is not listed here and has a grep'able kernel address please
36 # consider submitting a patch.
37 my @SUPPORTED_ARCHITECTURES = ('x86_64', 'ppc64');
39 # Command line options.
43 my $output_raw = ""; # Write raw results to file.
44 my $input_raw = ""; # Read raw results from file instead of scanning.
45 my $suppress_dmesg = 0; # Don't show dmesg in output.
46 my $squash_by_path = 0; # Summary report grouped by absolute path.
47 my $squash_by_filename = 0; # Summary report grouped by filename.
48 my $kernel_config_file = ""; # Kernel configuration file.
50 # Do not parse these files (absolute path).
51 my @skip_parse_files_abs = ('/proc/kmsg',
53 '/proc/fs/ext4/sdb1/mb_groups',
55 '/sys/firmware/devicetree',
57 '/sys/kernel/debug/tracing/trace_pipe',
58 '/sys/kernel/security/apparmor/revision');
60 # Do not parse these files under any subdirectory.
61 my @skip_parse_files_any = ('0',
73 # Do not walk these directories (absolute path).
74 my @skip_walk_dirs_abs = ();
76 # Do not walk these directories under any subdirectory.
77 my @skip_walk_dirs_any = ('self',
97 -o, --output-raw=<file> Save results for future processing.
98 -i, --input-raw=<file> Read results from file instead of scanning.
99 --raw Show raw results (default).
100 --suppress-dmesg Do not show dmesg results.
101 --squash-by-path Show one result per unique path.
102 --squash-by-filename Show one result per unique filename.
103 --kernel-config-file=<file> Kernel configuration file (e.g /boot/config)
104 -d, --debug Display debugging output.
105 -h, --help, --version Display this help and exit.
107 Scans the running (64 bit) kernel for potential leaking addresses.
114 'd|debug' => \$debug,
117 'o|output-raw=s' => \$output_raw,
118 'i|input-raw=s' => \$input_raw,
119 'suppress-dmesg' => \$suppress_dmesg,
120 'squash-by-path' => \$squash_by_path,
121 'squash-by-filename' => \$squash_by_filename,
123 'kernel-config-file=s' => \$kernel_config_file,
129 format_output($input_raw);
133 if (!$input_raw and ($squash_by_path or $squash_by_filename)) {
134 printf "\nSummary reporting only available with --input-raw=<file>\n";
135 printf "(First run scan with --output-raw=<file>.)\n";
139 if (!is_supported_architecture()) {
140 printf "\nScript does not support your architecture, sorry.\n";
141 printf "\nCurrently we support: \n\n";
142 foreach(@SUPPORTED_ARCHITECTURES) {
146 my $archname = $Config{archname};
147 printf "\n\$ perl -MConfig -e \'print \"\$Config{archname}\\n\"\'\n";
148 printf "%s\n", $archname;
154 open my $fh, '>', $output_raw or die "$0: $output_raw: $!\n";
165 printf(STDERR @_) if $debug;
168 sub is_supported_architecture
170 return (is_x86_64() or is_ppc64());
175 my $archname = $Config{archname};
177 if ($archname =~ m/x86_64/) {
185 my $archname = $Config{archname};
187 if ($archname =~ m/powerpc/ and $archname =~ m/64/) {
193 # Gets config option value from kernel config file.
194 # Returns "" on error or if config option not found.
195 sub get_kernel_config_option
202 # Allow --kernel-config-file to override.
203 if ($kernel_config_file ne "") {
204 @config_files = ($kernel_config_file);
205 } elsif (-R "/proc/config.gz") {
206 my $tmp_file = "/tmp/tmpkconf";
208 if (system("gunzip < /proc/config.gz > $tmp_file")) {
209 dprint "$0: system(gunzip < /proc/config.gz) failed\n";
212 @config_files = ($tmp_file);
215 my $file = '/boot/config-' . `uname -r`;
217 @config_files = ($file, '/boot/config');
220 foreach my $file (@config_files) {
221 dprint("parsing config file: %s\n", $file);
222 $value = option_from_file($option, $file);
228 if ($tmp_file ne "") {
229 system("rm -f $tmp_file");
235 # Parses $file and returns kernel configuration option value.
238 my ($option, $file) = @_;
242 open(my $fh, "<", $file) or return "";
243 while (my $line = <$fh> ) {
244 if ($line =~ /^$option/) {
245 ($str, $val) = split /=/, $line;
255 sub is_false_positive
259 if ($match =~ '\b(0x)?(f|F){16}\b' or
260 $match =~ '\b(0x)?0{16}\b') {
264 if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
271 sub is_in_vsyscall_memory_region
275 my $hex = hex($match);
276 my $region_min = hex("0xffffffffff600000");
277 my $region_max = hex("0xffffffffff601000");
279 return ($hex >= $region_min and $hex <= $region_max);
282 # True if argument potentially contains a kernel address.
289 if ($line =~ '^SigBlk:' or
290 $line =~ '^SigIgn:' or
291 $line =~ '^SigCgt:') {
295 if ($line =~ '\bKEY=[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b' or
296 $line =~ '\b[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b') {
300 $address_re = get_address_re();
301 while (/($address_re)/g) {
302 if (!is_false_positive($1)) {
313 return get_x86_64_re();
314 } elsif (is_ppc64()) {
315 return '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
321 # We handle page table levels but only if explicitly configured using
322 # CONFIG_PGTABLE_LEVELS. If config file parsing fails or config option
323 # is not found we default to using address regular expression suitable
324 # for 4 page table levels.
325 state $ptl = get_kernel_config_option('CONFIG_PGTABLE_LEVELS');
328 return '\b(0x)?ff[[:xdigit:]]{14}\b';
330 return '\b(0x)?ffff[[:xdigit:]]{12}\b';
335 open my $cmd, '-|', 'dmesg';
337 if (may_leak_address($_)) {
338 print 'dmesg: ' . $_;
344 # True if we should skip this path.
347 my ($path, $paths_abs, $paths_any) = @_;
349 foreach (@$paths_abs) {
350 return 1 if (/^$path$/);
353 my($filename, $dirs, $suffix) = fileparse($path);
354 foreach (@$paths_any) {
355 return 1 if (/^$filename$/);
364 return skip($path, \@skip_parse_files_abs, \@skip_parse_files_any);
372 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required.
379 die unless $@ eq "alarm\n"; # Propagate unexpected errors.
380 printf STDERR "timed out parsing: %s\n", $file;
392 if (skip_parse($file)) {
393 dprint "skipping file: $file\n";
396 dprint "parsing: $file\n";
398 open my $fh, "<", $file or return;
400 if (may_leak_address($_)) {
401 print $file . ': ' . $_;
408 # True if we should skip walking this directory.
412 return skip($path, \@skip_walk_dirs_abs, \@skip_walk_dirs_any)
415 # Recursively walk directory tree.
420 while (my $pwd = shift @dirs) {
421 next if (skip_walk($pwd));
422 next if (!opendir(DIR, $pwd));
423 my @files = readdir(DIR);
426 foreach my $file (@files) {
427 next if ($file eq '.' or $file eq '..');
429 my $path = "$pwd/$file";
435 timed_parse_file($path);
445 # Default is to show raw results.
446 if ($raw or (!$squash_by_path and !$squash_by_filename)) {
447 dump_raw_output($file);
451 my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
453 printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
455 if (!$suppress_dmesg) {
459 if ($squash_by_filename) {
460 squash_by($files, 'filename');
463 if ($squash_by_path) {
464 squash_by($paths, 'path');
472 open (my $fh, '<', $file) or die "$0: $file: $!\n";
474 if ($suppress_dmesg) {
475 if ("dmesg:" eq substr($_, 0, 6)) {
488 my $total = 0; # Total number of lines parsed.
489 my @dmesg; # dmesg output.
490 my %files; # Unique filenames containing leaks.
491 my %paths; # Unique paths containing leaks.
493 open (my $fh, '<', $file) or die "$0: $file: $!\n";
494 while (my $line = <$fh>) {
497 if ("dmesg:" eq substr($line, 0, 6)) {
502 cache_path(\%paths, $line);
503 cache_filename(\%files, $line);
506 return $total, \@dmesg, \%paths, \%files;
513 print "\ndmesg output:\n";
516 print "<no results>\n";
521 my $index = index($_, ': ');
522 $index += 2; # skid ': '
523 print substr($_, $index);
529 my ($ref, $desc) = @_;
531 print "\nResults squashed by $desc (excl dmesg). ";
532 print "Displaying [<number of results> <$desc>], <example result>\n";
534 if (keys %$ref == 0) {
535 print "<no results>\n";
539 foreach(keys %$ref) {
540 my $lines = $ref->{$_};
541 my $length = @$lines;
542 printf "[%d %s] %s", $length, $_, @$lines[0];
548 my ($paths, $line) = @_;
550 my $index = index($line, ': ');
551 my $path = substr($line, 0, $index);
553 $index += 2; # skip ': '
554 add_to_cache($paths, $path, substr($line, $index));
559 my ($files, $line) = @_;
561 my $index = index($line, ': ');
562 my $path = substr($line, 0, $index);
563 my $filename = basename($path);
565 $index += 2; # skip ': '
566 add_to_cache($files, $filename, substr($line, $index));
571 my ($cache, $key, $value) = @_;
573 if (!$cache->{$key}) {
576 push @{$cache->{$key}}, $value;