2 # SPDX-License-Identifier: GPL-2.0-only
4 # (c) 2017 Tobin C. Harding <me@tobin.cc>
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);
35 # Directories to scan.
36 my @DIRS = ('/proc', '/sys');
38 # Timer for parsing each file, in seconds.
41 # Kernel addresses vary by architecture. We can only auto-detect the following
42 # architectures (using `uname -m`). (flag --32-bit overrides auto-detection.)
43 my @SUPPORTED_ARCHITECTURES = ('x86_64', 'ppc64', 'x86');
45 # Command line options.
49 my $output_raw = ""; # Write raw results to file.
50 my $input_raw = ""; # Read raw results from file instead of scanning.
51 my $suppress_dmesg = 0; # Don't show dmesg in output.
52 my $squash_by_path = 0; # Summary report grouped by absolute path.
53 my $squash_by_filename = 0; # Summary report grouped by filename.
54 my $kernel_config_file = ""; # Kernel configuration file.
55 my $opt_32bit = 0; # Scan 32-bit kernel.
56 my $page_offset_32bit = 0; # Page offset for 32-bit kernel.
58 # Skip these absolute paths.
63 '/sys/firmware/devicetree',
64 '/sys/kernel/tracing/trace_pipe',
65 '/sys/kernel/debug/tracing/trace_pipe',
66 '/sys/kernel/security/apparmor/revision');
68 # 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 Display this help and exit.
103 Scans the running kernel for potential leaking addresses.
110 'd|debug' => \$debug,
112 'o|output-raw=s' => \$output_raw,
113 'i|input-raw=s' => \$input_raw,
114 'suppress-dmesg' => \$suppress_dmesg,
115 'squash-by-path' => \$squash_by_path,
116 'squash-by-filename' => \$squash_by_filename,
118 'kernel-config-file=s' => \$kernel_config_file,
119 '32-bit' => \$opt_32bit,
120 'page-offset-32-bit=o' => \$page_offset_32bit,
126 format_output($input_raw);
130 if (!$input_raw and ($squash_by_path or $squash_by_filename)) {
131 printf "\nSummary reporting only available with --input-raw=<file>\n";
132 printf "(First run scan with --output-raw=<file>.)\n";
136 if (!(is_supported_architecture() or $opt_32bit or $page_offset_32bit)) {
137 printf "\nScript does not support your architecture, sorry.\n";
138 printf "\nCurrently we support: \n\n";
139 foreach(@SUPPORTED_ARCHITECTURES) {
144 printf("If you are running a 32-bit architecture you may use:\n");
145 printf("\n\t--32-bit or --page-offset-32-bit=<page offset>\n\n");
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() or is_ix86_32());
175 # Allow --32-bit or --page-offset-32-bit to override
176 if ($opt_32bit or $page_offset_32bit) {
185 state $arch = `uname -m`;
188 if ($arch =~ m/i[3456]86/) {
197 my $arch = `uname -m`;
200 if ($arch eq $desc) {
208 state $is = is_arch('x86_64');
214 state $is = is_arch('ppc64');
218 # Gets config option value from kernel config file.
219 # Returns "" on error or if config option not found.
220 sub get_kernel_config_option
227 # Allow --kernel-config-file to override.
228 if ($kernel_config_file ne "") {
229 @config_files = ($kernel_config_file);
230 } elsif (-R "/proc/config.gz") {
231 my $tmp_file = "/tmp/tmpkconf";
233 if (system("gunzip < /proc/config.gz > $tmp_file")) {
234 dprint("system(gunzip < /proc/config.gz) failed\n");
237 @config_files = ($tmp_file);
240 my $file = '/boot/config-' . `uname -r`;
242 @config_files = ($file, '/boot/config');
245 foreach my $file (@config_files) {
246 dprint("parsing config file: $file\n");
247 $value = option_from_file($option, $file);
253 if ($tmp_file ne "") {
254 system("rm -f $tmp_file");
260 # Parses $file and returns kernel configuration option value.
263 my ($option, $file) = @_;
267 open(my $fh, "<", $file) or return "";
268 while (my $line = <$fh> ) {
269 if ($line =~ /^$option/) {
270 ($str, $val) = split /=/, $line;
280 sub is_false_positive
285 return is_false_positive_32bit($match);
288 # 64 bit false positives.
290 if ($match =~ '\b(0x)?(f|F){16}\b' or
291 $match =~ '\b(0x)?0{16}\b') {
295 if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
302 sub is_false_positive_32bit
305 state $page_offset = get_page_offset();
307 if ($match =~ '\b(0x)?(f|F){8}\b') {
311 if (hex($match) < $page_offset) {
318 # returns integer value
322 my $default_offset = 0xc0000000;
324 # Allow --page-offset-32bit to override.
325 if ($page_offset_32bit != 0) {
326 return $page_offset_32bit;
329 $page_offset = get_kernel_config_option('CONFIG_PAGE_OFFSET');
331 return $default_offset;
336 sub is_in_vsyscall_memory_region
340 my $hex = hex($match);
341 my $region_min = hex("0xffffffffff600000");
342 my $region_max = hex("0xffffffffff601000");
344 return ($hex >= $region_min and $hex <= $region_max);
347 # True if argument potentially contains a kernel address.
354 if ($line =~ '^SigBlk:' or
355 $line =~ '^SigIgn:' or
356 $line =~ '^SigCgt:') {
360 if ($line =~ '\bKEY=[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b' or
361 $line =~ '\b[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b') {
365 $address_re = get_address_re();
366 while ($line =~ /($address_re)/g) {
367 if (!is_false_positive($1)) {
378 return '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
379 } elsif (is_32bit()) {
380 return '\b(0x)?[[:xdigit:]]{8}\b';
383 return get_x86_64_re();
388 # We handle page table levels but only if explicitly configured using
389 # CONFIG_PGTABLE_LEVELS. If config file parsing fails or config option
390 # is not found we default to using address regular expression suitable
391 # for 4 page table levels.
392 state $ptl = get_kernel_config_option('CONFIG_PGTABLE_LEVELS');
395 return '\b(0x)?ff[[:xdigit:]]{14}\b';
397 return '\b(0x)?ffff[[:xdigit:]]{12}\b';
402 open my $cmd, '-|', 'dmesg';
404 if (may_leak_address($_)) {
405 print 'dmesg: ' . $_;
411 # True if we should skip this path.
416 foreach (@skip_abs) {
417 return 1 if (/^$path$/);
420 my($filename, $dirs, $suffix) = fileparse($path);
421 foreach (@skip_any) {
422 return 1 if (/^$filename$/);
433 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required.
440 die unless $@ eq "alarm\n"; # Propagate unexpected errors.
441 printf STDERR "timed out parsing: %s\n", $file;
457 open my $fh, "<", $file or return;
460 if (may_leak_address($_)) {
461 printf("$file: $_\n");
467 # Checks if the actual path name is leaking a kernel address.
468 sub check_path_for_leaks
472 if (may_leak_address($path)) {
473 printf("Path name may contain address: $path\n");
477 # Recursively walk directory tree.
482 while (my $pwd = shift @dirs) {
483 next if (!opendir(DIR, $pwd));
484 my @files = readdir(DIR);
487 foreach my $file (@files) {
488 next if ($file eq '.' or $file eq '..');
490 my $path = "$pwd/$file";
493 # skip /proc/PID except /proc/1
494 next if (($path =~ /^\/proc\/[0-9]+$/) &&
495 ($path !~ /^\/proc\/1$/));
497 next if (skip($path));
499 check_path_for_leaks($path);
506 dprint("parsing: $path\n");
507 timed_parse_file($path);
516 # Default is to show raw results.
517 if ($raw or (!$squash_by_path and !$squash_by_filename)) {
518 dump_raw_output($file);
522 my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
524 printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
526 if (!$suppress_dmesg) {
530 if ($squash_by_filename) {
531 squash_by($files, 'filename');
534 if ($squash_by_path) {
535 squash_by($paths, 'path');
543 open (my $fh, '<', $file) or die "$0: $file: $!\n";
545 if ($suppress_dmesg) {
546 if ("dmesg:" eq substr($_, 0, 6)) {
559 my $total = 0; # Total number of lines parsed.
560 my @dmesg; # dmesg output.
561 my %files; # Unique filenames containing leaks.
562 my %paths; # Unique paths containing leaks.
564 open (my $fh, '<', $file) or die "$0: $file: $!\n";
565 while (my $line = <$fh>) {
568 if ("dmesg:" eq substr($line, 0, 6)) {
573 cache_path(\%paths, $line);
574 cache_filename(\%files, $line);
577 return $total, \@dmesg, \%paths, \%files;
584 print "\ndmesg output:\n";
587 print "<no results>\n";
592 my $index = index($_, ': ');
593 $index += 2; # skid ': '
594 print substr($_, $index);
600 my ($ref, $desc) = @_;
602 print "\nResults squashed by $desc (excl dmesg). ";
603 print "Displaying [<number of results> <$desc>], <example result>\n";
605 if (keys %$ref == 0) {
606 print "<no results>\n";
610 foreach(keys %$ref) {
611 my $lines = $ref->{$_};
612 my $length = @$lines;
613 printf "[%d %s] %s", $length, $_, @$lines[0];
619 my ($paths, $line) = @_;
621 my $index = index($line, ': ');
622 my $path = substr($line, 0, $index);
624 $index += 2; # skip ': '
625 add_to_cache($paths, $path, substr($line, $index));
630 my ($files, $line) = @_;
632 my $index = index($line, ': ');
633 my $path = substr($line, 0, $index);
634 my $filename = basename($path);
636 $index += 2; # skip ': '
637 add_to_cache($files, $filename, substr($line, $index));
642 my ($cache, $key, $value) = @_;
644 if (!$cache->{$key}) {
647 push @{$cache->{$key}}, $value;