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) {
147 my $archname = `uname -m`;
148 printf("Machine hardware name (`uname -m`): %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());
176 my $arch = `uname -m`;
179 if ($arch eq $desc) {
187 return is_arch('x86_64');
192 return is_arch('ppc64');
195 # Gets config option value from kernel config file.
196 # Returns "" on error or if config option not found.
197 sub get_kernel_config_option
204 # Allow --kernel-config-file to override.
205 if ($kernel_config_file ne "") {
206 @config_files = ($kernel_config_file);
207 } elsif (-R "/proc/config.gz") {
208 my $tmp_file = "/tmp/tmpkconf";
210 if (system("gunzip < /proc/config.gz > $tmp_file")) {
211 dprint "$0: system(gunzip < /proc/config.gz) failed\n";
214 @config_files = ($tmp_file);
217 my $file = '/boot/config-' . `uname -r`;
219 @config_files = ($file, '/boot/config');
222 foreach my $file (@config_files) {
223 dprint("parsing config file: %s\n", $file);
224 $value = option_from_file($option, $file);
230 if ($tmp_file ne "") {
231 system("rm -f $tmp_file");
237 # Parses $file and returns kernel configuration option value.
240 my ($option, $file) = @_;
244 open(my $fh, "<", $file) or return "";
245 while (my $line = <$fh> ) {
246 if ($line =~ /^$option/) {
247 ($str, $val) = split /=/, $line;
257 sub is_false_positive
261 if ($match =~ '\b(0x)?(f|F){16}\b' or
262 $match =~ '\b(0x)?0{16}\b') {
266 if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
273 sub is_in_vsyscall_memory_region
277 my $hex = hex($match);
278 my $region_min = hex("0xffffffffff600000");
279 my $region_max = hex("0xffffffffff601000");
281 return ($hex >= $region_min and $hex <= $region_max);
284 # True if argument potentially contains a kernel address.
291 if ($line =~ '^SigBlk:' or
292 $line =~ '^SigIgn:' or
293 $line =~ '^SigCgt:') {
297 if ($line =~ '\bKEY=[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b' or
298 $line =~ '\b[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b') {
302 $address_re = get_address_re();
303 while (/($address_re)/g) {
304 if (!is_false_positive($1)) {
315 return get_x86_64_re();
316 } elsif (is_ppc64()) {
317 return '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
323 # We handle page table levels but only if explicitly configured using
324 # CONFIG_PGTABLE_LEVELS. If config file parsing fails or config option
325 # is not found we default to using address regular expression suitable
326 # for 4 page table levels.
327 state $ptl = get_kernel_config_option('CONFIG_PGTABLE_LEVELS');
330 return '\b(0x)?ff[[:xdigit:]]{14}\b';
332 return '\b(0x)?ffff[[:xdigit:]]{12}\b';
337 open my $cmd, '-|', 'dmesg';
339 if (may_leak_address($_)) {
340 print 'dmesg: ' . $_;
346 # True if we should skip this path.
349 my ($path, $paths_abs, $paths_any) = @_;
351 foreach (@$paths_abs) {
352 return 1 if (/^$path$/);
355 my($filename, $dirs, $suffix) = fileparse($path);
356 foreach (@$paths_any) {
357 return 1 if (/^$filename$/);
366 return skip($path, \@skip_parse_files_abs, \@skip_parse_files_any);
374 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required.
381 die unless $@ eq "alarm\n"; # Propagate unexpected errors.
382 printf STDERR "timed out parsing: %s\n", $file;
394 if (skip_parse($file)) {
395 dprint "skipping file: $file\n";
398 dprint "parsing: $file\n";
400 open my $fh, "<", $file or return;
402 if (may_leak_address($_)) {
403 print $file . ': ' . $_;
410 # True if we should skip walking this directory.
414 return skip($path, \@skip_walk_dirs_abs, \@skip_walk_dirs_any)
417 # Recursively walk directory tree.
422 while (my $pwd = shift @dirs) {
423 next if (skip_walk($pwd));
424 next if (!opendir(DIR, $pwd));
425 my @files = readdir(DIR);
428 foreach my $file (@files) {
429 next if ($file eq '.' or $file eq '..');
431 my $path = "$pwd/$file";
437 timed_parse_file($path);
447 # Default is to show raw results.
448 if ($raw or (!$squash_by_path and !$squash_by_filename)) {
449 dump_raw_output($file);
453 my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
455 printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
457 if (!$suppress_dmesg) {
461 if ($squash_by_filename) {
462 squash_by($files, 'filename');
465 if ($squash_by_path) {
466 squash_by($paths, 'path');
474 open (my $fh, '<', $file) or die "$0: $file: $!\n";
476 if ($suppress_dmesg) {
477 if ("dmesg:" eq substr($_, 0, 6)) {
490 my $total = 0; # Total number of lines parsed.
491 my @dmesg; # dmesg output.
492 my %files; # Unique filenames containing leaks.
493 my %paths; # Unique paths containing leaks.
495 open (my $fh, '<', $file) or die "$0: $file: $!\n";
496 while (my $line = <$fh>) {
499 if ("dmesg:" eq substr($line, 0, 6)) {
504 cache_path(\%paths, $line);
505 cache_filename(\%files, $line);
508 return $total, \@dmesg, \%paths, \%files;
515 print "\ndmesg output:\n";
518 print "<no results>\n";
523 my $index = index($_, ': ');
524 $index += 2; # skid ': '
525 print substr($_, $index);
531 my ($ref, $desc) = @_;
533 print "\nResults squashed by $desc (excl dmesg). ";
534 print "Displaying [<number of results> <$desc>], <example result>\n";
536 if (keys %$ref == 0) {
537 print "<no results>\n";
541 foreach(keys %$ref) {
542 my $lines = $ref->{$_};
543 my $length = @$lines;
544 printf "[%d %s] %s", $length, $_, @$lines[0];
550 my ($paths, $line) = @_;
552 my $index = index($line, ': ');
553 my $path = substr($line, 0, $index);
555 $index += 2; # skip ': '
556 add_to_cache($paths, $path, substr($line, $index));
561 my ($files, $line) = @_;
563 my $index = index($line, ': ');
564 my $path = substr($line, 0, $index);
565 my $filename = basename($path);
567 $index += 2; # skip ': '
568 add_to_cache($files, $filename, substr($line, $index));
573 my ($cache, $key, $value) = @_;
575 if (!$cache->{$key}) {
578 push @{$cache->{$key}}, $value;