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.
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 # Kernel addresses vary by architecture. We can only auto-detect the following
35 # architectures (using `uname -m`). (flag --32-bit overrides auto-detection.)
36 my @SUPPORTED_ARCHITECTURES = ('x86_64', 'ppc64', 'x86');
38 # Command line options.
42 my $output_raw = ""; # Write raw results to file.
43 my $input_raw = ""; # Read raw results from file instead of scanning.
44 my $suppress_dmesg = 0; # Don't show dmesg in output.
45 my $squash_by_path = 0; # Summary report grouped by absolute path.
46 my $squash_by_filename = 0; # Summary report grouped by filename.
47 my $kernel_config_file = ""; # Kernel configuration file.
48 my $opt_32bit = 0; # Scan 32-bit kernel.
49 my $page_offset_32bit = 0; # Page offset for 32-bit kernel.
51 # Do not parse these files (absolute path).
52 my @skip_parse_files_abs = ('/proc/kmsg',
54 '/proc/fs/ext4/sdb1/mb_groups',
56 '/sys/firmware/devicetree',
58 '/sys/kernel/debug/tracing/trace_pipe',
59 '/sys/kernel/security/apparmor/revision');
61 # Do not parse these files under any subdirectory.
62 my @skip_parse_files_any = ('0',
74 # Do not walk these directories (absolute path).
75 my @skip_walk_dirs_abs = ();
77 # Do not walk these directories under any subdirectory.
78 my @skip_walk_dirs_any = ('self',
98 -o, --output-raw=<file> Save results for future processing.
99 -i, --input-raw=<file> Read results from file instead of scanning.
100 --raw Show raw results (default).
101 --suppress-dmesg Do not show dmesg results.
102 --squash-by-path Show one result per unique path.
103 --squash-by-filename Show one result per unique filename.
104 --kernel-config-file=<file> Kernel configuration file (e.g /boot/config)
105 --32-bit Scan 32-bit kernel.
106 --page-offset-32-bit=o Page offset (for 32-bit kernel 0xABCD1234).
107 -d, --debug Display debugging output.
108 -h, --help, --version Display this help and exit.
110 Scans the running kernel for potential leaking addresses.
117 'd|debug' => \$debug,
120 'o|output-raw=s' => \$output_raw,
121 'i|input-raw=s' => \$input_raw,
122 'suppress-dmesg' => \$suppress_dmesg,
123 'squash-by-path' => \$squash_by_path,
124 'squash-by-filename' => \$squash_by_filename,
126 'kernel-config-file=s' => \$kernel_config_file,
127 '32-bit' => \$opt_32bit,
128 'page-offset-32-bit=o' => \$page_offset_32bit,
134 format_output($input_raw);
138 if (!$input_raw and ($squash_by_path or $squash_by_filename)) {
139 printf "\nSummary reporting only available with --input-raw=<file>\n";
140 printf "(First run scan with --output-raw=<file>.)\n";
144 if (!(is_supported_architecture() or $opt_32bit or $page_offset_32bit)) {
145 printf "\nScript does not support your architecture, sorry.\n";
146 printf "\nCurrently we support: \n\n";
147 foreach(@SUPPORTED_ARCHITECTURES) {
152 printf("If you are running a 32-bit architecture you may use:\n");
153 printf("\n\t--32-bit or --page-offset-32-bit=<page offset>\n\n");
155 my $archname = `uname -m`;
156 printf("Machine hardware name (`uname -m`): %s\n", $archname);
162 open my $fh, '>', $output_raw or die "$0: $output_raw: $!\n";
173 printf(STDERR @_) if $debug;
176 sub is_supported_architecture
178 return (is_x86_64() or is_ppc64() or is_ix86_32());
183 # Allow --32-bit or --page-offset-32-bit to override
184 if ($opt_32bit or $page_offset_32bit) {
193 my $arch = `uname -m`;
196 if ($arch =~ m/i[3456]86/) {
205 my $arch = `uname -m`;
208 if ($arch eq $desc) {
216 return is_arch('x86_64');
221 return is_arch('ppc64');
224 # Gets config option value from kernel config file.
225 # Returns "" on error or if config option not found.
226 sub get_kernel_config_option
233 # Allow --kernel-config-file to override.
234 if ($kernel_config_file ne "") {
235 @config_files = ($kernel_config_file);
236 } elsif (-R "/proc/config.gz") {
237 my $tmp_file = "/tmp/tmpkconf";
239 if (system("gunzip < /proc/config.gz > $tmp_file")) {
240 dprint "$0: system(gunzip < /proc/config.gz) failed\n";
243 @config_files = ($tmp_file);
246 my $file = '/boot/config-' . `uname -r`;
248 @config_files = ($file, '/boot/config');
251 foreach my $file (@config_files) {
252 dprint("parsing config file: %s\n", $file);
253 $value = option_from_file($option, $file);
259 if ($tmp_file ne "") {
260 system("rm -f $tmp_file");
266 # Parses $file and returns kernel configuration option value.
269 my ($option, $file) = @_;
273 open(my $fh, "<", $file) or return "";
274 while (my $line = <$fh> ) {
275 if ($line =~ /^$option/) {
276 ($str, $val) = split /=/, $line;
286 sub is_false_positive
291 return is_false_positive_32bit($match);
294 # 64 bit false positives.
296 if ($match =~ '\b(0x)?(f|F){16}\b' or
297 $match =~ '\b(0x)?0{16}\b') {
301 if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
308 sub is_false_positive_32bit
311 state $page_offset = get_page_offset();
313 if ($match =~ '\b(0x)?(f|F){8}\b') {
317 if (hex($match) < $page_offset) {
324 # returns integer value
328 my $default_offset = 0xc0000000;
330 # Allow --page-offset-32bit to override.
331 if ($page_offset_32bit != 0) {
332 return $page_offset_32bit;
335 $page_offset = get_kernel_config_option('CONFIG_PAGE_OFFSET');
337 return $default_offset;
342 sub is_in_vsyscall_memory_region
346 my $hex = hex($match);
347 my $region_min = hex("0xffffffffff600000");
348 my $region_max = hex("0xffffffffff601000");
350 return ($hex >= $region_min and $hex <= $region_max);
353 # True if argument potentially contains a kernel address.
360 if ($line =~ '^SigBlk:' or
361 $line =~ '^SigIgn:' or
362 $line =~ '^SigCgt:') {
366 if ($line =~ '\bKEY=[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b' or
367 $line =~ '\b[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b') {
371 $address_re = get_address_re();
372 while (/($address_re)/g) {
373 if (!is_false_positive($1)) {
384 return '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
385 } elsif (is_32bit()) {
386 return '\b(0x)?[[:xdigit:]]{8}\b';
389 return get_x86_64_re();
394 # We handle page table levels but only if explicitly configured using
395 # CONFIG_PGTABLE_LEVELS. If config file parsing fails or config option
396 # is not found we default to using address regular expression suitable
397 # for 4 page table levels.
398 state $ptl = get_kernel_config_option('CONFIG_PGTABLE_LEVELS');
401 return '\b(0x)?ff[[:xdigit:]]{14}\b';
403 return '\b(0x)?ffff[[:xdigit:]]{12}\b';
408 open my $cmd, '-|', 'dmesg';
410 if (may_leak_address($_)) {
411 print 'dmesg: ' . $_;
417 # True if we should skip this path.
420 my ($path, $paths_abs, $paths_any) = @_;
422 foreach (@$paths_abs) {
423 return 1 if (/^$path$/);
426 my($filename, $dirs, $suffix) = fileparse($path);
427 foreach (@$paths_any) {
428 return 1 if (/^$filename$/);
437 return skip($path, \@skip_parse_files_abs, \@skip_parse_files_any);
445 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required.
452 die unless $@ eq "alarm\n"; # Propagate unexpected errors.
453 printf STDERR "timed out parsing: %s\n", $file;
469 if (skip_parse($file)) {
470 dprint "skipping file: $file\n";
473 dprint "parsing: $file\n";
475 open my $fh, "<", $file or return;
477 if (may_leak_address($_)) {
478 print $file . ': ' . $_;
485 # True if we should skip walking this directory.
489 return skip($path, \@skip_walk_dirs_abs, \@skip_walk_dirs_any)
492 # Recursively walk directory tree.
497 while (my $pwd = shift @dirs) {
498 next if (skip_walk($pwd));
499 next if (!opendir(DIR, $pwd));
500 my @files = readdir(DIR);
503 foreach my $file (@files) {
504 next if ($file eq '.' or $file eq '..');
506 my $path = "$pwd/$file";
512 timed_parse_file($path);
522 # Default is to show raw results.
523 if ($raw or (!$squash_by_path and !$squash_by_filename)) {
524 dump_raw_output($file);
528 my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
530 printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
532 if (!$suppress_dmesg) {
536 if ($squash_by_filename) {
537 squash_by($files, 'filename');
540 if ($squash_by_path) {
541 squash_by($paths, 'path');
549 open (my $fh, '<', $file) or die "$0: $file: $!\n";
551 if ($suppress_dmesg) {
552 if ("dmesg:" eq substr($_, 0, 6)) {
565 my $total = 0; # Total number of lines parsed.
566 my @dmesg; # dmesg output.
567 my %files; # Unique filenames containing leaks.
568 my %paths; # Unique paths containing leaks.
570 open (my $fh, '<', $file) or die "$0: $file: $!\n";
571 while (my $line = <$fh>) {
574 if ("dmesg:" eq substr($line, 0, 6)) {
579 cache_path(\%paths, $line);
580 cache_filename(\%files, $line);
583 return $total, \@dmesg, \%paths, \%files;
590 print "\ndmesg output:\n";
593 print "<no results>\n";
598 my $index = index($_, ': ');
599 $index += 2; # skid ': '
600 print substr($_, $index);
606 my ($ref, $desc) = @_;
608 print "\nResults squashed by $desc (excl dmesg). ";
609 print "Displaying [<number of results> <$desc>], <example result>\n";
611 if (keys %$ref == 0) {
612 print "<no results>\n";
616 foreach(keys %$ref) {
617 my $lines = $ref->{$_};
618 my $length = @$lines;
619 printf "[%d %s] %s", $length, $_, @$lines[0];
625 my ($paths, $line) = @_;
627 my $index = index($line, ': ');
628 my $path = substr($line, 0, $index);
630 $index += 2; # skip ': '
631 add_to_cache($paths, $path, substr($line, $index));
636 my ($files, $line) = @_;
638 my $index = index($line, ': ');
639 my $path = substr($line, 0, $index);
640 my $filename = basename($path);
642 $index += 2; # skip ': '
643 add_to_cache($files, $filename, substr($line, $index));
648 my ($cache, $key, $value) = @_;
650 if (!$cache->{$key}) {
653 push @{$cache->{$key}}, $value;