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 the 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.
14 # When the system is idle it is likely that most files under /proc/PID will be
15 # identical for various processes. Scanning _all_ the PIDs under /proc is
16 # unnecessary and implies that we are thoroughly scanning /proc. This is _not_
17 # the case because there may be ways userspace can trigger creation of /proc
18 # files that leak addresses but were not present during a scan. For these two
19 # reasons we exclude all PID directories under /proc except '1/'
27 use Term::ANSIColor qw(:constants);
28 use Getopt::Long qw(:config no_auto_abbrev);
36 # Directories to scan.
37 my @DIRS = ('/proc', '/sys');
39 # Timer for parsing each file, in seconds.
42 # Kernel addresses vary by architecture. We can only auto-detect the following
43 # architectures (using `uname -m`). (flag --32-bit overrides auto-detection.)
44 my @SUPPORTED_ARCHITECTURES = ('x86_64', 'ppc64', 'x86');
46 # Command line options.
50 my $output_raw = ""; # Write raw results to file.
51 my $input_raw = ""; # Read raw results from file instead of scanning.
52 my $suppress_dmesg = 0; # Don't show dmesg in output.
53 my $squash_by_path = 0; # Summary report grouped by absolute path.
54 my $squash_by_filename = 0; # Summary report grouped by filename.
55 my $kernel_config_file = ""; # Kernel configuration file.
56 my $opt_32bit = 0; # Scan 32-bit kernel.
57 my $page_offset_32bit = 0; # Page offset for 32-bit kernel.
59 # Skip these absolute paths.
63 '/sys/firmware/devicetree',
64 '/sys/kernel/debug/tracing/trace_pipe',
65 '/sys/kernel/security/apparmor/revision');
67 # Skip these under any subdirectory.
91 -o, --output-raw=<file> Save results for future processing.
92 -i, --input-raw=<file> Read results from file instead of scanning.
93 --raw Show raw results (default).
94 --suppress-dmesg Do not show dmesg results.
95 --squash-by-path Show one result per unique path.
96 --squash-by-filename Show one result per unique filename.
97 --kernel-config-file=<file> Kernel configuration file (e.g /boot/config)
98 --32-bit Scan 32-bit kernel.
99 --page-offset-32-bit=o Page offset (for 32-bit kernel 0xABCD1234).
100 -d, --debug Display debugging output.
101 -h, --help, --version Display this help and exit.
103 Scans the running kernel for potential leaking addresses.
110 'd|debug' => \$debug,
113 'o|output-raw=s' => \$output_raw,
114 'i|input-raw=s' => \$input_raw,
115 'suppress-dmesg' => \$suppress_dmesg,
116 'squash-by-path' => \$squash_by_path,
117 'squash-by-filename' => \$squash_by_filename,
119 'kernel-config-file=s' => \$kernel_config_file,
120 '32-bit' => \$opt_32bit,
121 'page-offset-32-bit=o' => \$page_offset_32bit,
127 format_output($input_raw);
131 if (!$input_raw and ($squash_by_path or $squash_by_filename)) {
132 printf "\nSummary reporting only available with --input-raw=<file>\n";
133 printf "(First run scan with --output-raw=<file>.)\n";
137 if (!(is_supported_architecture() or $opt_32bit or $page_offset_32bit)) {
138 printf "\nScript does not support your architecture, sorry.\n";
139 printf "\nCurrently we support: \n\n";
140 foreach(@SUPPORTED_ARCHITECTURES) {
145 printf("If you are running a 32-bit architecture you may use:\n");
146 printf("\n\t--32-bit or --page-offset-32-bit=<page offset>\n\n");
148 my $archname = `uname -m`;
149 printf("Machine hardware name (`uname -m`): %s\n", $archname);
155 open my $fh, '>', $output_raw or die "$0: $output_raw: $!\n";
166 printf(STDERR @_) if $debug;
169 sub is_supported_architecture
171 return (is_x86_64() or is_ppc64() or is_ix86_32());
176 # Allow --32-bit or --page-offset-32-bit to override
177 if ($opt_32bit or $page_offset_32bit) {
186 state $arch = `uname -m`;
189 if ($arch =~ m/i[3456]86/) {
198 my $arch = `uname -m`;
201 if ($arch eq $desc) {
209 state $is = is_arch('x86_64');
215 state $is = is_arch('ppc64');
219 # Gets config option value from kernel config file.
220 # Returns "" on error or if config option not found.
221 sub get_kernel_config_option
228 # Allow --kernel-config-file to override.
229 if ($kernel_config_file ne "") {
230 @config_files = ($kernel_config_file);
231 } elsif (-R "/proc/config.gz") {
232 my $tmp_file = "/tmp/tmpkconf";
234 if (system("gunzip < /proc/config.gz > $tmp_file")) {
235 dprint "$0: system(gunzip < /proc/config.gz) failed\n";
238 @config_files = ($tmp_file);
241 my $file = '/boot/config-' . `uname -r`;
243 @config_files = ($file, '/boot/config');
246 foreach my $file (@config_files) {
247 dprint("parsing config file: %s\n", $file);
248 $value = option_from_file($option, $file);
254 if ($tmp_file ne "") {
255 system("rm -f $tmp_file");
261 # Parses $file and returns kernel configuration option value.
264 my ($option, $file) = @_;
268 open(my $fh, "<", $file) or return "";
269 while (my $line = <$fh> ) {
270 if ($line =~ /^$option/) {
271 ($str, $val) = split /=/, $line;
281 sub is_false_positive
286 return is_false_positive_32bit($match);
289 # 64 bit false positives.
291 if ($match =~ '\b(0x)?(f|F){16}\b' or
292 $match =~ '\b(0x)?0{16}\b') {
296 if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
303 sub is_false_positive_32bit
306 state $page_offset = get_page_offset();
308 if ($match =~ '\b(0x)?(f|F){8}\b') {
312 if (hex($match) < $page_offset) {
319 # returns integer value
323 my $default_offset = 0xc0000000;
325 # Allow --page-offset-32bit to override.
326 if ($page_offset_32bit != 0) {
327 return $page_offset_32bit;
330 $page_offset = get_kernel_config_option('CONFIG_PAGE_OFFSET');
332 return $default_offset;
337 sub is_in_vsyscall_memory_region
341 my $hex = hex($match);
342 my $region_min = hex("0xffffffffff600000");
343 my $region_max = hex("0xffffffffff601000");
345 return ($hex >= $region_min and $hex <= $region_max);
348 # True if argument potentially contains a kernel address.
355 if ($line =~ '^SigBlk:' or
356 $line =~ '^SigIgn:' or
357 $line =~ '^SigCgt:') {
361 if ($line =~ '\bKEY=[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b' or
362 $line =~ '\b[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b') {
366 $address_re = get_address_re();
367 while (/($address_re)/g) {
368 if (!is_false_positive($1)) {
379 return '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
380 } elsif (is_32bit()) {
381 return '\b(0x)?[[:xdigit:]]{8}\b';
384 return get_x86_64_re();
389 # We handle page table levels but only if explicitly configured using
390 # CONFIG_PGTABLE_LEVELS. If config file parsing fails or config option
391 # is not found we default to using address regular expression suitable
392 # for 4 page table levels.
393 state $ptl = get_kernel_config_option('CONFIG_PGTABLE_LEVELS');
396 return '\b(0x)?ff[[:xdigit:]]{14}\b';
398 return '\b(0x)?ffff[[:xdigit:]]{12}\b';
403 open my $cmd, '-|', 'dmesg';
405 if (may_leak_address($_)) {
406 print 'dmesg: ' . $_;
412 # True if we should skip this path.
417 foreach (@skip_abs) {
418 return 1 if (/^$path$/);
421 my($filename, $dirs, $suffix) = fileparse($path);
422 foreach (@skip_any) {
423 return 1 if (/^$filename$/);
434 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required.
441 die unless $@ eq "alarm\n"; # Propagate unexpected errors.
442 printf STDERR "timed out parsing: %s\n", $file;
458 open my $fh, "<", $file or return;
460 if (may_leak_address($_)) {
461 print $file . ': ' . $_;
467 # Recursively walk directory tree.
472 while (my $pwd = shift @dirs) {
473 next if (!opendir(DIR, $pwd));
474 my @files = readdir(DIR);
477 foreach my $file (@files) {
478 next if ($file eq '.' or $file eq '..');
480 my $path = "$pwd/$file";
483 # skip /proc/PID except /proc/1
484 next if (($path =~ /^\/proc\/[0-9]+$/) &&
485 ($path !~ /^\/proc\/1$/));
487 next if (skip($path));
494 dprint "parsing: $path\n";
495 timed_parse_file($path);
504 # Default is to show raw results.
505 if ($raw or (!$squash_by_path and !$squash_by_filename)) {
506 dump_raw_output($file);
510 my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
512 printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
514 if (!$suppress_dmesg) {
518 if ($squash_by_filename) {
519 squash_by($files, 'filename');
522 if ($squash_by_path) {
523 squash_by($paths, 'path');
531 open (my $fh, '<', $file) or die "$0: $file: $!\n";
533 if ($suppress_dmesg) {
534 if ("dmesg:" eq substr($_, 0, 6)) {
547 my $total = 0; # Total number of lines parsed.
548 my @dmesg; # dmesg output.
549 my %files; # Unique filenames containing leaks.
550 my %paths; # Unique paths containing leaks.
552 open (my $fh, '<', $file) or die "$0: $file: $!\n";
553 while (my $line = <$fh>) {
556 if ("dmesg:" eq substr($line, 0, 6)) {
561 cache_path(\%paths, $line);
562 cache_filename(\%files, $line);
565 return $total, \@dmesg, \%paths, \%files;
572 print "\ndmesg output:\n";
575 print "<no results>\n";
580 my $index = index($_, ': ');
581 $index += 2; # skid ': '
582 print substr($_, $index);
588 my ($ref, $desc) = @_;
590 print "\nResults squashed by $desc (excl dmesg). ";
591 print "Displaying [<number of results> <$desc>], <example result>\n";
593 if (keys %$ref == 0) {
594 print "<no results>\n";
598 foreach(keys %$ref) {
599 my $lines = $ref->{$_};
600 my $length = @$lines;
601 printf "[%d %s] %s", $length, $_, @$lines[0];
607 my ($paths, $line) = @_;
609 my $index = index($line, ': ');
610 my $path = substr($line, 0, $index);
612 $index += 2; # skip ': '
613 add_to_cache($paths, $path, substr($line, $index));
618 my ($files, $line) = @_;
620 my $index = index($line, ': ');
621 my $path = substr($line, 0, $index);
622 my $filename = basename($path);
624 $index += 2; # skip ': '
625 add_to_cache($files, $filename, substr($line, $index));
630 my ($cache, $key, $value) = @_;
632 if (!$cache->{$key}) {
635 push @{$cache->{$key}}, $value;