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 # Skip these absolute paths.
55 '/sys/firmware/devicetree',
56 '/sys/kernel/debug/tracing/trace_pipe',
57 '/sys/kernel/security/apparmor/revision');
59 # Skip these under any subdirectory.
83 -o, --output-raw=<file> Save results for future processing.
84 -i, --input-raw=<file> Read results from file instead of scanning.
85 --raw Show raw results (default).
86 --suppress-dmesg Do not show dmesg results.
87 --squash-by-path Show one result per unique path.
88 --squash-by-filename Show one result per unique filename.
89 --kernel-config-file=<file> Kernel configuration file (e.g /boot/config)
90 --32-bit Scan 32-bit kernel.
91 --page-offset-32-bit=o Page offset (for 32-bit kernel 0xABCD1234).
92 -d, --debug Display debugging output.
93 -h, --help, --version Display this help and exit.
95 Scans the running kernel for potential leaking addresses.
102 'd|debug' => \$debug,
105 'o|output-raw=s' => \$output_raw,
106 'i|input-raw=s' => \$input_raw,
107 'suppress-dmesg' => \$suppress_dmesg,
108 'squash-by-path' => \$squash_by_path,
109 'squash-by-filename' => \$squash_by_filename,
111 'kernel-config-file=s' => \$kernel_config_file,
112 '32-bit' => \$opt_32bit,
113 'page-offset-32-bit=o' => \$page_offset_32bit,
119 format_output($input_raw);
123 if (!$input_raw and ($squash_by_path or $squash_by_filename)) {
124 printf "\nSummary reporting only available with --input-raw=<file>\n";
125 printf "(First run scan with --output-raw=<file>.)\n";
129 if (!(is_supported_architecture() or $opt_32bit or $page_offset_32bit)) {
130 printf "\nScript does not support your architecture, sorry.\n";
131 printf "\nCurrently we support: \n\n";
132 foreach(@SUPPORTED_ARCHITECTURES) {
137 printf("If you are running a 32-bit architecture you may use:\n");
138 printf("\n\t--32-bit or --page-offset-32-bit=<page offset>\n\n");
140 my $archname = `uname -m`;
141 printf("Machine hardware name (`uname -m`): %s\n", $archname);
147 open my $fh, '>', $output_raw or die "$0: $output_raw: $!\n";
158 printf(STDERR @_) if $debug;
161 sub is_supported_architecture
163 return (is_x86_64() or is_ppc64() or is_ix86_32());
168 # Allow --32-bit or --page-offset-32-bit to override
169 if ($opt_32bit or $page_offset_32bit) {
178 my $arch = `uname -m`;
181 if ($arch =~ m/i[3456]86/) {
190 my $arch = `uname -m`;
193 if ($arch eq $desc) {
201 return is_arch('x86_64');
206 return is_arch('ppc64');
209 # Gets config option value from kernel config file.
210 # Returns "" on error or if config option not found.
211 sub get_kernel_config_option
218 # Allow --kernel-config-file to override.
219 if ($kernel_config_file ne "") {
220 @config_files = ($kernel_config_file);
221 } elsif (-R "/proc/config.gz") {
222 my $tmp_file = "/tmp/tmpkconf";
224 if (system("gunzip < /proc/config.gz > $tmp_file")) {
225 dprint "$0: system(gunzip < /proc/config.gz) failed\n";
228 @config_files = ($tmp_file);
231 my $file = '/boot/config-' . `uname -r`;
233 @config_files = ($file, '/boot/config');
236 foreach my $file (@config_files) {
237 dprint("parsing config file: %s\n", $file);
238 $value = option_from_file($option, $file);
244 if ($tmp_file ne "") {
245 system("rm -f $tmp_file");
251 # Parses $file and returns kernel configuration option value.
254 my ($option, $file) = @_;
258 open(my $fh, "<", $file) or return "";
259 while (my $line = <$fh> ) {
260 if ($line =~ /^$option/) {
261 ($str, $val) = split /=/, $line;
271 sub is_false_positive
276 return is_false_positive_32bit($match);
279 # 64 bit false positives.
281 if ($match =~ '\b(0x)?(f|F){16}\b' or
282 $match =~ '\b(0x)?0{16}\b') {
286 if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
293 sub is_false_positive_32bit
296 state $page_offset = get_page_offset();
298 if ($match =~ '\b(0x)?(f|F){8}\b') {
302 if (hex($match) < $page_offset) {
309 # returns integer value
313 my $default_offset = 0xc0000000;
315 # Allow --page-offset-32bit to override.
316 if ($page_offset_32bit != 0) {
317 return $page_offset_32bit;
320 $page_offset = get_kernel_config_option('CONFIG_PAGE_OFFSET');
322 return $default_offset;
327 sub is_in_vsyscall_memory_region
331 my $hex = hex($match);
332 my $region_min = hex("0xffffffffff600000");
333 my $region_max = hex("0xffffffffff601000");
335 return ($hex >= $region_min and $hex <= $region_max);
338 # True if argument potentially contains a kernel address.
345 if ($line =~ '^SigBlk:' or
346 $line =~ '^SigIgn:' or
347 $line =~ '^SigCgt:') {
351 if ($line =~ '\bKEY=[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b' or
352 $line =~ '\b[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b') {
356 $address_re = get_address_re();
357 while (/($address_re)/g) {
358 if (!is_false_positive($1)) {
369 return '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
370 } elsif (is_32bit()) {
371 return '\b(0x)?[[:xdigit:]]{8}\b';
374 return get_x86_64_re();
379 # We handle page table levels but only if explicitly configured using
380 # CONFIG_PGTABLE_LEVELS. If config file parsing fails or config option
381 # is not found we default to using address regular expression suitable
382 # for 4 page table levels.
383 state $ptl = get_kernel_config_option('CONFIG_PGTABLE_LEVELS');
386 return '\b(0x)?ff[[:xdigit:]]{14}\b';
388 return '\b(0x)?ffff[[:xdigit:]]{12}\b';
393 open my $cmd, '-|', 'dmesg';
395 if (may_leak_address($_)) {
396 print 'dmesg: ' . $_;
402 # True if we should skip this path.
407 foreach (@skip_abs) {
408 return 1 if (/^$path$/);
411 my($filename, $dirs, $suffix) = fileparse($path);
412 foreach (@skip_any) {
413 return 1 if (/^$filename$/);
424 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required.
431 die unless $@ eq "alarm\n"; # Propagate unexpected errors.
432 printf STDERR "timed out parsing: %s\n", $file;
448 open my $fh, "<", $file or return;
450 if (may_leak_address($_)) {
451 print $file . ': ' . $_;
457 # Recursively walk directory tree.
462 while (my $pwd = shift @dirs) {
463 next if (!opendir(DIR, $pwd));
464 my @files = readdir(DIR);
467 foreach my $file (@files) {
468 next if ($file eq '.' or $file eq '..');
470 my $path = "$pwd/$file";
473 next if (skip($path));
480 dprint "parsing: $path\n";
481 timed_parse_file($path);
490 # Default is to show raw results.
491 if ($raw or (!$squash_by_path and !$squash_by_filename)) {
492 dump_raw_output($file);
496 my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
498 printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
500 if (!$suppress_dmesg) {
504 if ($squash_by_filename) {
505 squash_by($files, 'filename');
508 if ($squash_by_path) {
509 squash_by($paths, 'path');
517 open (my $fh, '<', $file) or die "$0: $file: $!\n";
519 if ($suppress_dmesg) {
520 if ("dmesg:" eq substr($_, 0, 6)) {
533 my $total = 0; # Total number of lines parsed.
534 my @dmesg; # dmesg output.
535 my %files; # Unique filenames containing leaks.
536 my %paths; # Unique paths containing leaks.
538 open (my $fh, '<', $file) or die "$0: $file: $!\n";
539 while (my $line = <$fh>) {
542 if ("dmesg:" eq substr($line, 0, 6)) {
547 cache_path(\%paths, $line);
548 cache_filename(\%files, $line);
551 return $total, \@dmesg, \%paths, \%files;
558 print "\ndmesg output:\n";
561 print "<no results>\n";
566 my $index = index($_, ': ');
567 $index += 2; # skid ': '
568 print substr($_, $index);
574 my ($ref, $desc) = @_;
576 print "\nResults squashed by $desc (excl dmesg). ";
577 print "Displaying [<number of results> <$desc>], <example result>\n";
579 if (keys %$ref == 0) {
580 print "<no results>\n";
584 foreach(keys %$ref) {
585 my $lines = $ref->{$_};
586 my $length = @$lines;
587 printf "[%d %s] %s", $length, $_, @$lines[0];
593 my ($paths, $line) = @_;
595 my $index = index($line, ': ');
596 my $path = substr($line, 0, $index);
598 $index += 2; # skip ': '
599 add_to_cache($paths, $path, substr($line, $index));
604 my ($files, $line) = @_;
606 my $index = index($line, ': ');
607 my $path = substr($line, 0, $index);
608 my $filename = basename($path);
610 $index += 2; # skip ': '
611 add_to_cache($files, $filename, substr($line, $index));
616 my ($cache, $key, $value) = @_;
618 if (!$cache->{$key}) {
621 push @{$cache->{$key}}, $value;