blob: b3ffbf8022ce30a69001ce8dcd423f029ca3e5f1 [file] [log] [blame]
Tobin C. Harding136fc5c2017-11-06 16:19:27 +11001#!/usr/bin/env perl
2#
3# (c) 2017 Tobin C. Harding <[email protected]>
4# Licensed under the terms of the GNU GPL License version 2
5#
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).
9#
Tobin C. Harding136fc5c2017-11-06 16:19:27 +110010# Use --debug to output path before parsing, this is useful to find files that
11# cause the script to choke.
Tobin C. Harding136fc5c2017-11-06 16:19:27 +110012
13use warnings;
14use strict;
15use POSIX;
16use File::Basename;
17use File::Spec;
18use Cwd 'abs_path';
19use Term::ANSIColor qw(:constants);
20use Getopt::Long qw(:config no_auto_abbrev);
Tobin C. Harding62139c12017-11-09 15:19:40 +110021use Config;
Tobin C. Harding87e37582017-12-07 12:33:21 +110022use bigint qw/hex/;
Tobin C. Harding136fc5c2017-11-06 16:19:27 +110023
24my $P = $0;
25my $V = '0.01';
26
27# Directories to scan.
28my @DIRS = ('/proc', '/sys');
29
Tobin C. Hardingdd98c252017-11-09 15:37:06 +110030# Timer for parsing each file, in seconds.
31my $TIMEOUT = 10;
32
Tobin C. Harding62139c12017-11-09 15:19:40 +110033# Script can only grep for kernel addresses on the following architectures. If
34# your architecture is not listed here and has a grep'able kernel address please
35# consider submitting a patch.
36my @SUPPORTED_ARCHITECTURES = ('x86_64', 'ppc64');
37
Tobin C. Harding136fc5c2017-11-06 16:19:27 +110038# Command line options.
39my $help = 0;
40my $debug = 0;
Tobin C. Hardingd09bd8d2017-11-09 15:07:15 +110041my $raw = 0;
42my $output_raw = ""; # Write raw results to file.
43my $input_raw = ""; # Read raw results from file instead of scanning.
Tobin C. Hardingd09bd8d2017-11-09 15:07:15 +110044my $suppress_dmesg = 0; # Don't show dmesg in output.
45my $squash_by_path = 0; # Summary report grouped by absolute path.
46my $squash_by_filename = 0; # Summary report grouped by filename.
Tobin C. Hardingf9d2a422017-12-07 13:53:41 +110047my $kernel_config_file = ""; # Kernel configuration file.
Tobin C. Harding136fc5c2017-11-06 16:19:27 +110048
49# Do not parse these files (absolute path).
50my @skip_parse_files_abs = ('/proc/kmsg',
51 '/proc/kcore',
52 '/proc/fs/ext4/sdb1/mb_groups',
53 '/proc/1/fd/3',
Tobin C. Harding1c1e3be2017-11-09 14:02:41 +110054 '/sys/firmware/devicetree',
55 '/proc/device-tree',
Tobin C. Harding136fc5c2017-11-06 16:19:27 +110056 '/sys/kernel/debug/tracing/trace_pipe',
57 '/sys/kernel/security/apparmor/revision');
58
Tobin C. Hardinga2847332017-11-09 13:28:43 +110059# Do not parse these files under any subdirectory.
Tobin C. Harding136fc5c2017-11-06 16:19:27 +110060my @skip_parse_files_any = ('0',
61 '1',
62 '2',
63 'pagemap',
64 'events',
65 'access',
66 'registers',
67 'snapshot_raw',
68 'trace_pipe_raw',
69 'ptmx',
70 'trace_pipe');
71
72# Do not walk these directories (absolute path).
73my @skip_walk_dirs_abs = ();
74
75# Do not walk these directories under any subdirectory.
76my @skip_walk_dirs_any = ('self',
77 'thread-self',
78 'cwd',
79 'fd',
Tobin C. Harding1c1e3be2017-11-09 14:02:41 +110080 'usbmon',
Tobin C. Harding136fc5c2017-11-06 16:19:27 +110081 'stderr',
82 'stdin',
83 'stdout');
84
85sub help
86{
87 my ($exitcode) = @_;
88
89 print << "EOM";
Tobin C. Hardingd09bd8d2017-11-09 15:07:15 +110090
Tobin C. Harding136fc5c2017-11-06 16:19:27 +110091Usage: $P [OPTIONS]
92Version: $V
93
94Options:
95
Tobin C. Harding15d60a32017-12-07 13:57:53 +110096 -o, --output-raw=<file> Save results for future processing.
97 -i, --input-raw=<file> Read results from file instead of scanning.
98 --raw Show raw results (default).
99 --suppress-dmesg Do not show dmesg results.
100 --squash-by-path Show one result per unique path.
101 --squash-by-filename Show one result per unique filename.
Tobin C. Hardingf9d2a422017-12-07 13:53:41 +1100102 --kernel-config-file=<file> Kernel configuration file (e.g /boot/config)
Tobin C. Harding15d60a32017-12-07 13:57:53 +1100103 -d, --debug Display debugging output.
104 -h, --help, --version Display this help and exit.
Tobin C. Hardingd09bd8d2017-11-09 15:07:15 +1100105
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100106Scans the running (64 bit) kernel for potential leaking addresses.
107
108EOM
109 exit($exitcode);
110}
111
112GetOptions(
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100113 'd|debug' => \$debug,
114 'h|help' => \$help,
Tobin C. Hardingd09bd8d2017-11-09 15:07:15 +1100115 'version' => \$help,
116 'o|output-raw=s' => \$output_raw,
117 'i|input-raw=s' => \$input_raw,
118 'suppress-dmesg' => \$suppress_dmesg,
119 'squash-by-path' => \$squash_by_path,
120 'squash-by-filename' => \$squash_by_filename,
121 'raw' => \$raw,
Tobin C. Hardingf9d2a422017-12-07 13:53:41 +1100122 'kernel-config-file=s' => \$kernel_config_file,
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100123) or help(1);
124
125help(0) if ($help);
126
Tobin C. Hardingd09bd8d2017-11-09 15:07:15 +1100127if ($input_raw) {
128 format_output($input_raw);
129 exit(0);
130}
131
132if (!$input_raw and ($squash_by_path or $squash_by_filename)) {
133 printf "\nSummary reporting only available with --input-raw=<file>\n";
134 printf "(First run scan with --output-raw=<file>.)\n";
135 exit(128);
136}
137
Tobin C. Harding62139c12017-11-09 15:19:40 +1100138if (!is_supported_architecture()) {
139 printf "\nScript does not support your architecture, sorry.\n";
140 printf "\nCurrently we support: \n\n";
141 foreach(@SUPPORTED_ARCHITECTURES) {
142 printf "\t%s\n", $_;
143 }
144
145 my $archname = $Config{archname};
146 printf "\n\$ perl -MConfig -e \'print \"\$Config{archname}\\n\"\'\n";
147 printf "%s\n", $archname;
148
149 exit(129);
150}
151
Tobin C. Hardingd09bd8d2017-11-09 15:07:15 +1100152if ($output_raw) {
153 open my $fh, '>', $output_raw or die "$0: $output_raw: $!\n";
154 select $fh;
155}
156
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100157parse_dmesg();
158walk(@DIRS);
159
160exit 0;
161
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100162sub dprint
163{
164 printf(STDERR @_) if $debug;
165}
166
Tobin C. Harding62139c12017-11-09 15:19:40 +1100167sub is_supported_architecture
168{
169 return (is_x86_64() or is_ppc64());
170}
171
172sub is_x86_64
173{
174 my $archname = $Config{archname};
175
176 if ($archname =~ m/x86_64/) {
177 return 1;
178 }
179 return 0;
180}
181
182sub is_ppc64
183{
184 my $archname = $Config{archname};
185
186 if ($archname =~ m/powerpc/ and $archname =~ m/64/) {
187 return 1;
188 }
189 return 0;
190}
191
Tobin C. Hardingf9d2a422017-12-07 13:53:41 +1100192# Gets config option value from kernel config file.
193# Returns "" on error or if config option not found.
194sub get_kernel_config_option
195{
196 my ($option) = @_;
197 my $value = "";
198 my $tmp_file = "";
199 my @config_files;
200
201 # Allow --kernel-config-file to override.
202 if ($kernel_config_file ne "") {
203 @config_files = ($kernel_config_file);
204 } elsif (-R "/proc/config.gz") {
205 my $tmp_file = "/tmp/tmpkconf";
206
207 if (system("gunzip < /proc/config.gz > $tmp_file")) {
208 dprint "$0: system(gunzip < /proc/config.gz) failed\n";
209 return "";
210 } else {
211 @config_files = ($tmp_file);
212 }
213 } else {
214 my $file = '/boot/config-' . `uname -r`;
215 chomp $file;
216 @config_files = ($file, '/boot/config');
217 }
218
219 foreach my $file (@config_files) {
220 dprint("parsing config file: %s\n", $file);
221 $value = option_from_file($option, $file);
222 if ($value ne "") {
223 last;
224 }
225 }
226
227 if ($tmp_file ne "") {
228 system("rm -f $tmp_file");
229 }
230
231 return $value;
232}
233
234# Parses $file and returns kernel configuration option value.
235sub option_from_file
236{
237 my ($option, $file) = @_;
238 my $str = "";
239 my $val = "";
240
241 open(my $fh, "<", $file) or return "";
242 while (my $line = <$fh> ) {
243 if ($line =~ /^$option/) {
244 ($str, $val) = split /=/, $line;
245 chomp $val;
246 last;
247 }
248 }
249
250 close $fh;
251 return $val;
252}
253
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100254sub is_false_positive
255{
Tobin C. Harding7e5758f2017-11-08 11:01:59 +1100256 my ($match) = @_;
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100257
Tobin C. Harding7e5758f2017-11-08 11:01:59 +1100258 if ($match =~ '\b(0x)?(f|F){16}\b' or
259 $match =~ '\b(0x)?0{16}\b') {
260 return 1;
261 }
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100262
Tobin C. Harding87e37582017-12-07 12:33:21 +1100263 if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
264 return 1;
Tobin C. Harding7e5758f2017-11-08 11:01:59 +1100265 }
266
267 return 0;
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100268}
269
Tobin C. Harding87e37582017-12-07 12:33:21 +1100270sub is_in_vsyscall_memory_region
271{
272 my ($match) = @_;
273
274 my $hex = hex($match);
275 my $region_min = hex("0xffffffffff600000");
276 my $region_max = hex("0xffffffffff601000");
277
278 return ($hex >= $region_min and $hex <= $region_max);
279}
280
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100281# True if argument potentially contains a kernel address.
282sub may_leak_address
283{
Tobin C. Harding7e5758f2017-11-08 11:01:59 +1100284 my ($line) = @_;
Tobin C. Harding62139c12017-11-09 15:19:40 +1100285 my $address_re;
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100286
Tobin C. Harding7e5758f2017-11-08 11:01:59 +1100287 # Signal masks.
288 if ($line =~ '^SigBlk:' or
Tobin C. Hardinga11949e2017-11-14 09:25:11 +1100289 $line =~ '^SigIgn:' or
Tobin C. Harding7e5758f2017-11-08 11:01:59 +1100290 $line =~ '^SigCgt:') {
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100291 return 0;
Tobin C. Harding7e5758f2017-11-08 11:01:59 +1100292 }
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100293
Tobin C. Harding7e5758f2017-11-08 11:01:59 +1100294 if ($line =~ '\bKEY=[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b' or
295 $line =~ '\b[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b') {
296 return 0;
297 }
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100298
Tobin C. Harding62139c12017-11-09 15:19:40 +1100299 # One of these is guaranteed to be true.
300 if (is_x86_64()) {
301 $address_re = '\b(0x)?ffff[[:xdigit:]]{12}\b';
302 } elsif (is_ppc64()) {
303 $address_re = '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
304 }
305
306 while (/($address_re)/g) {
Tobin C. Harding7e5758f2017-11-08 11:01:59 +1100307 if (!is_false_positive($1)) {
308 return 1;
309 }
310 }
311
312 return 0;
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100313}
314
315sub parse_dmesg
316{
317 open my $cmd, '-|', 'dmesg';
318 while (<$cmd>) {
319 if (may_leak_address($_)) {
320 print 'dmesg: ' . $_;
321 }
322 }
323 close $cmd;
324}
325
326# True if we should skip this path.
327sub skip
328{
329 my ($path, $paths_abs, $paths_any) = @_;
330
331 foreach (@$paths_abs) {
332 return 1 if (/^$path$/);
333 }
334
335 my($filename, $dirs, $suffix) = fileparse($path);
336 foreach (@$paths_any) {
337 return 1 if (/^$filename$/);
338 }
339
340 return 0;
341}
342
343sub skip_parse
344{
345 my ($path) = @_;
346 return skip($path, \@skip_parse_files_abs, \@skip_parse_files_any);
347}
348
Tobin C. Hardingdd98c252017-11-09 15:37:06 +1100349sub timed_parse_file
350{
351 my ($file) = @_;
352
353 eval {
354 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required.
355 alarm $TIMEOUT;
356 parse_file($file);
357 alarm 0;
358 };
359
360 if ($@) {
361 die unless $@ eq "alarm\n"; # Propagate unexpected errors.
362 printf STDERR "timed out parsing: %s\n", $file;
363 }
364}
365
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100366sub parse_file
367{
368 my ($file) = @_;
369
370 if (! -R $file) {
371 return;
372 }
373
374 if (skip_parse($file)) {
375 dprint "skipping file: $file\n";
376 return;
377 }
378 dprint "parsing: $file\n";
379
380 open my $fh, "<", $file or return;
381 while ( <$fh> ) {
382 if (may_leak_address($_)) {
383 print $file . ': ' . $_;
384 }
385 }
386 close $fh;
387}
388
389
390# True if we should skip walking this directory.
391sub skip_walk
392{
393 my ($path) = @_;
394 return skip($path, \@skip_walk_dirs_abs, \@skip_walk_dirs_any)
395}
396
397# Recursively walk directory tree.
398sub walk
399{
400 my @dirs = @_;
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100401
402 while (my $pwd = shift @dirs) {
403 next if (skip_walk($pwd));
404 next if (!opendir(DIR, $pwd));
405 my @files = readdir(DIR);
406 closedir(DIR);
407
408 foreach my $file (@files) {
409 next if ($file eq '.' or $file eq '..');
410
411 my $path = "$pwd/$file";
412 next if (-l $path);
413
414 if (-d $path) {
415 push @dirs, $path;
416 } else {
Tobin C. Hardingdd98c252017-11-09 15:37:06 +1100417 timed_parse_file($path);
Tobin C. Harding136fc5c2017-11-06 16:19:27 +1100418 }
419 }
420 }
421}
Tobin C. Hardingd09bd8d2017-11-09 15:07:15 +1100422
423sub format_output
424{
425 my ($file) = @_;
426
427 # Default is to show raw results.
428 if ($raw or (!$squash_by_path and !$squash_by_filename)) {
429 dump_raw_output($file);
430 return;
431 }
432
433 my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
434
435 printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
436
437 if (!$suppress_dmesg) {
438 print_dmesg($dmesg);
439 }
440
441 if ($squash_by_filename) {
442 squash_by($files, 'filename');
443 }
444
445 if ($squash_by_path) {
446 squash_by($paths, 'path');
447 }
448}
449
450sub dump_raw_output
451{
452 my ($file) = @_;
453
454 open (my $fh, '<', $file) or die "$0: $file: $!\n";
455 while (<$fh>) {
456 if ($suppress_dmesg) {
457 if ("dmesg:" eq substr($_, 0, 6)) {
458 next;
459 }
460 }
461 print $_;
462 }
463 close $fh;
464}
465
466sub parse_raw_file
467{
468 my ($file) = @_;
469
470 my $total = 0; # Total number of lines parsed.
471 my @dmesg; # dmesg output.
472 my %files; # Unique filenames containing leaks.
473 my %paths; # Unique paths containing leaks.
474
475 open (my $fh, '<', $file) or die "$0: $file: $!\n";
476 while (my $line = <$fh>) {
477 $total++;
478
479 if ("dmesg:" eq substr($line, 0, 6)) {
480 push @dmesg, $line;
481 next;
482 }
483
484 cache_path(\%paths, $line);
485 cache_filename(\%files, $line);
486 }
487
488 return $total, \@dmesg, \%paths, \%files;
489}
490
491sub print_dmesg
492{
493 my ($dmesg) = @_;
494
495 print "\ndmesg output:\n";
496
497 if (@$dmesg == 0) {
498 print "<no results>\n";
499 return;
500 }
501
502 foreach(@$dmesg) {
503 my $index = index($_, ': ');
504 $index += 2; # skid ': '
505 print substr($_, $index);
506 }
507}
508
509sub squash_by
510{
511 my ($ref, $desc) = @_;
512
513 print "\nResults squashed by $desc (excl dmesg). ";
514 print "Displaying [<number of results> <$desc>], <example result>\n";
515
516 if (keys %$ref == 0) {
517 print "<no results>\n";
518 return;
519 }
520
521 foreach(keys %$ref) {
522 my $lines = $ref->{$_};
523 my $length = @$lines;
524 printf "[%d %s] %s", $length, $_, @$lines[0];
525 }
526}
527
528sub cache_path
529{
530 my ($paths, $line) = @_;
531
532 my $index = index($line, ': ');
533 my $path = substr($line, 0, $index);
534
535 $index += 2; # skip ': '
536 add_to_cache($paths, $path, substr($line, $index));
537}
538
539sub cache_filename
540{
541 my ($files, $line) = @_;
542
543 my $index = index($line, ': ');
544 my $path = substr($line, 0, $index);
545 my $filename = basename($path);
546
547 $index += 2; # skip ': '
548 add_to_cache($files, $filename, substr($line, $index));
549}
550
551sub add_to_cache
552{
553 my ($cache, $key, $value) = @_;
554
555 if (!$cache->{$key}) {
556 $cache->{$key} = ();
557 }
558 push @{$cache->{$key}}, $value;
559}