OSDN Git Service

leaking_addresses: simplify path skipping
[uclinux-h8/linux.git] / scripts / leaking_addresses.pl
1 #!/usr/bin/env perl
2 #
3 # (c) 2017 Tobin C. Harding <me@tobin.cc>
4 # Licensed under the terms of the GNU GPL License version 2
5 #
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).
9 #
10 # Use --debug to output path before parsing, this is useful to find files that
11 # cause the script to choke.
12
13 use warnings;
14 use strict;
15 use POSIX;
16 use File::Basename;
17 use File::Spec;
18 use Cwd 'abs_path';
19 use Term::ANSIColor qw(:constants);
20 use Getopt::Long qw(:config no_auto_abbrev);
21 use Config;
22 use bigint qw/hex/;
23 use feature 'state';
24
25 my $P = $0;
26 my $V = '0.01';
27
28 # Directories to scan.
29 my @DIRS = ('/proc', '/sys');
30
31 # Timer for parsing each file, in seconds.
32 my $TIMEOUT = 10;
33
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');
37
38 # Command line options.
39 my $help = 0;
40 my $debug = 0;
41 my $raw = 0;
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.
50
51 # Skip these absolute paths.
52 my @skip_abs = (
53         '/proc/kmsg',
54         '/proc/device-tree',
55         '/sys/firmware/devicetree',
56         '/sys/kernel/debug/tracing/trace_pipe',
57         '/sys/kernel/security/apparmor/revision');
58
59 # Skip these under any subdirectory.
60 my @skip_any = (
61         'pagemap',
62         'events',
63         'access',
64         'registers',
65         'snapshot_raw',
66         'trace_pipe_raw',
67         'ptmx',
68         'trace_pipe',
69         'fd',
70         'usbmon');
71
72 sub help
73 {
74         my ($exitcode) = @_;
75
76         print << "EOM";
77
78 Usage: $P [OPTIONS]
79 Version: $V
80
81 Options:
82
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.
94
95 Scans the running kernel for potential leaking addresses.
96
97 EOM
98         exit($exitcode);
99 }
100
101 GetOptions(
102         'd|debug'               => \$debug,
103         'h|help'                => \$help,
104         'version'               => \$help,
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,
110         'raw'                   => \$raw,
111         'kernel-config-file=s'  => \$kernel_config_file,
112         '32-bit'                => \$opt_32bit,
113         'page-offset-32-bit=o'  => \$page_offset_32bit,
114 ) or help(1);
115
116 help(0) if ($help);
117
118 if ($input_raw) {
119         format_output($input_raw);
120         exit(0);
121 }
122
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";
126         exit(128);
127 }
128
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) {
133                 printf "\t%s\n", $_;
134         }
135         printf("\n");
136
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");
139
140         my $archname = `uname -m`;
141         printf("Machine hardware name (`uname -m`): %s\n", $archname);
142
143         exit(129);
144 }
145
146 if ($output_raw) {
147         open my $fh, '>', $output_raw or die "$0: $output_raw: $!\n";
148         select $fh;
149 }
150
151 parse_dmesg();
152 walk(@DIRS);
153
154 exit 0;
155
156 sub dprint
157 {
158         printf(STDERR @_) if $debug;
159 }
160
161 sub is_supported_architecture
162 {
163         return (is_x86_64() or is_ppc64() or is_ix86_32());
164 }
165
166 sub is_32bit
167 {
168         # Allow --32-bit or --page-offset-32-bit to override
169         if ($opt_32bit or $page_offset_32bit) {
170                 return 1;
171         }
172
173         return is_ix86_32();
174 }
175
176 sub is_ix86_32
177 {
178        my $arch = `uname -m`;
179
180        chomp $arch;
181        if ($arch =~ m/i[3456]86/) {
182                return 1;
183        }
184        return 0;
185 }
186
187 sub is_arch
188 {
189        my ($desc) = @_;
190        my $arch = `uname -m`;
191
192        chomp $arch;
193        if ($arch eq $desc) {
194                return 1;
195        }
196        return 0;
197 }
198
199 sub is_x86_64
200 {
201         return is_arch('x86_64');
202 }
203
204 sub is_ppc64
205 {
206         return is_arch('ppc64');
207 }
208
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
212 {
213         my ($option) = @_;
214         my $value = "";
215         my $tmp_file = "";
216         my @config_files;
217
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";
223
224                 if (system("gunzip < /proc/config.gz > $tmp_file")) {
225                         dprint "$0: system(gunzip < /proc/config.gz) failed\n";
226                         return "";
227                 } else {
228                         @config_files = ($tmp_file);
229                 }
230         } else {
231                 my $file = '/boot/config-' . `uname -r`;
232                 chomp $file;
233                 @config_files = ($file, '/boot/config');
234         }
235
236         foreach my $file (@config_files) {
237                 dprint("parsing config file: %s\n", $file);
238                 $value = option_from_file($option, $file);
239                 if ($value ne "") {
240                         last;
241                 }
242         }
243
244         if ($tmp_file ne "") {
245                 system("rm -f $tmp_file");
246         }
247
248         return $value;
249 }
250
251 # Parses $file and returns kernel configuration option value.
252 sub option_from_file
253 {
254         my ($option, $file) = @_;
255         my $str = "";
256         my $val = "";
257
258         open(my $fh, "<", $file) or return "";
259         while (my $line = <$fh> ) {
260                 if ($line =~ /^$option/) {
261                         ($str, $val) = split /=/, $line;
262                         chomp $val;
263                         last;
264                 }
265         }
266
267         close $fh;
268         return $val;
269 }
270
271 sub is_false_positive
272 {
273         my ($match) = @_;
274
275         if (is_32bit()) {
276                 return is_false_positive_32bit($match);
277         }
278
279         # 64 bit false positives.
280
281         if ($match =~ '\b(0x)?(f|F){16}\b' or
282             $match =~ '\b(0x)?0{16}\b') {
283                 return 1;
284         }
285
286         if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
287                 return 1;
288         }
289
290         return 0;
291 }
292
293 sub is_false_positive_32bit
294 {
295        my ($match) = @_;
296        state $page_offset = get_page_offset();
297
298        if ($match =~ '\b(0x)?(f|F){8}\b') {
299                return 1;
300        }
301
302        if (hex($match) < $page_offset) {
303                return 1;
304        }
305
306        return 0;
307 }
308
309 # returns integer value
310 sub get_page_offset
311 {
312        my $page_offset;
313        my $default_offset = 0xc0000000;
314
315        # Allow --page-offset-32bit to override.
316        if ($page_offset_32bit != 0) {
317                return $page_offset_32bit;
318        }
319
320        $page_offset = get_kernel_config_option('CONFIG_PAGE_OFFSET');
321        if (!$page_offset) {
322                return $default_offset;
323        }
324        return $page_offset;
325 }
326
327 sub is_in_vsyscall_memory_region
328 {
329         my ($match) = @_;
330
331         my $hex = hex($match);
332         my $region_min = hex("0xffffffffff600000");
333         my $region_max = hex("0xffffffffff601000");
334
335         return ($hex >= $region_min and $hex <= $region_max);
336 }
337
338 # True if argument potentially contains a kernel address.
339 sub may_leak_address
340 {
341         my ($line) = @_;
342         my $address_re;
343
344         # Signal masks.
345         if ($line =~ '^SigBlk:' or
346             $line =~ '^SigIgn:' or
347             $line =~ '^SigCgt:') {
348                 return 0;
349         }
350
351         if ($line =~ '\bKEY=[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b' or
352             $line =~ '\b[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b') {
353                 return 0;
354         }
355
356         $address_re = get_address_re();
357         while (/($address_re)/g) {
358                 if (!is_false_positive($1)) {
359                         return 1;
360                 }
361         }
362
363         return 0;
364 }
365
366 sub get_address_re
367 {
368         if (is_ppc64()) {
369                 return '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
370         } elsif (is_32bit()) {
371                 return '\b(0x)?[[:xdigit:]]{8}\b';
372         }
373
374         return get_x86_64_re();
375 }
376
377 sub get_x86_64_re
378 {
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');
384
385         if ($ptl == 5) {
386                 return '\b(0x)?ff[[:xdigit:]]{14}\b';
387         }
388         return '\b(0x)?ffff[[:xdigit:]]{12}\b';
389 }
390
391 sub parse_dmesg
392 {
393         open my $cmd, '-|', 'dmesg';
394         while (<$cmd>) {
395                 if (may_leak_address($_)) {
396                         print 'dmesg: ' . $_;
397                 }
398         }
399         close $cmd;
400 }
401
402 # True if we should skip this path.
403 sub skip
404 {
405         my ($path) = @_;
406
407         foreach (@skip_abs) {
408                 return 1 if (/^$path$/);
409         }
410
411         my($filename, $dirs, $suffix) = fileparse($path);
412         foreach (@skip_any) {
413                 return 1 if (/^$filename$/);
414         }
415
416         return 0;
417 }
418
419 sub timed_parse_file
420 {
421         my ($file) = @_;
422
423         eval {
424                 local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required.
425                 alarm $TIMEOUT;
426                 parse_file($file);
427                 alarm 0;
428         };
429
430         if ($@) {
431                 die unless $@ eq "alarm\n";     # Propagate unexpected errors.
432                 printf STDERR "timed out parsing: %s\n", $file;
433         }
434 }
435
436 sub parse_file
437 {
438         my ($file) = @_;
439
440         if (! -R $file) {
441                 return;
442         }
443
444         if (! -T $file) {
445                 return;
446         }
447
448         open my $fh, "<", $file or return;
449         while ( <$fh> ) {
450                 if (may_leak_address($_)) {
451                         print $file . ': ' . $_;
452                 }
453         }
454         close $fh;
455 }
456
457 # Recursively walk directory tree.
458 sub walk
459 {
460         my @dirs = @_;
461
462         while (my $pwd = shift @dirs) {
463                 next if (!opendir(DIR, $pwd));
464                 my @files = readdir(DIR);
465                 closedir(DIR);
466
467                 foreach my $file (@files) {
468                         next if ($file eq '.' or $file eq '..');
469
470                         my $path = "$pwd/$file";
471                         next if (-l $path);
472
473                         next if (skip($path));
474
475                         if (-d $path) {
476                                 push @dirs, $path;
477                                 next;
478                         }
479
480                         dprint "parsing: $path\n";
481                         timed_parse_file($path);
482                 }
483         }
484 }
485
486 sub format_output
487 {
488         my ($file) = @_;
489
490         # Default is to show raw results.
491         if ($raw or (!$squash_by_path and !$squash_by_filename)) {
492                 dump_raw_output($file);
493                 return;
494         }
495
496         my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
497
498         printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
499
500         if (!$suppress_dmesg) {
501                 print_dmesg($dmesg);
502         }
503
504         if ($squash_by_filename) {
505                 squash_by($files, 'filename');
506         }
507
508         if ($squash_by_path) {
509                 squash_by($paths, 'path');
510         }
511 }
512
513 sub dump_raw_output
514 {
515         my ($file) = @_;
516
517         open (my $fh, '<', $file) or die "$0: $file: $!\n";
518         while (<$fh>) {
519                 if ($suppress_dmesg) {
520                         if ("dmesg:" eq substr($_, 0, 6)) {
521                                 next;
522                         }
523                 }
524                 print $_;
525         }
526         close $fh;
527 }
528
529 sub parse_raw_file
530 {
531         my ($file) = @_;
532
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.
537
538         open (my $fh, '<', $file) or die "$0: $file: $!\n";
539         while (my $line = <$fh>) {
540                 $total++;
541
542                 if ("dmesg:" eq substr($line, 0, 6)) {
543                         push @dmesg, $line;
544                         next;
545                 }
546
547                 cache_path(\%paths, $line);
548                 cache_filename(\%files, $line);
549         }
550
551         return $total, \@dmesg, \%paths, \%files;
552 }
553
554 sub print_dmesg
555 {
556         my ($dmesg) = @_;
557
558         print "\ndmesg output:\n";
559
560         if (@$dmesg == 0) {
561                 print "<no results>\n";
562                 return;
563         }
564
565         foreach(@$dmesg) {
566                 my $index = index($_, ': ');
567                 $index += 2;    # skid ': '
568                 print substr($_, $index);
569         }
570 }
571
572 sub squash_by
573 {
574         my ($ref, $desc) = @_;
575
576         print "\nResults squashed by $desc (excl dmesg). ";
577         print "Displaying [<number of results> <$desc>], <example result>\n";
578
579         if (keys %$ref == 0) {
580                 print "<no results>\n";
581                 return;
582         }
583
584         foreach(keys %$ref) {
585                 my $lines = $ref->{$_};
586                 my $length = @$lines;
587                 printf "[%d %s] %s", $length, $_, @$lines[0];
588         }
589 }
590
591 sub cache_path
592 {
593         my ($paths, $line) = @_;
594
595         my $index = index($line, ': ');
596         my $path = substr($line, 0, $index);
597
598         $index += 2;            # skip ': '
599         add_to_cache($paths, $path, substr($line, $index));
600 }
601
602 sub cache_filename
603 {
604         my ($files, $line) = @_;
605
606         my $index = index($line, ': ');
607         my $path = substr($line, 0, $index);
608         my $filename = basename($path);
609
610         $index += 2;            # skip ': '
611         add_to_cache($files, $filename, substr($line, $index));
612 }
613
614 sub add_to_cache
615 {
616         my ($cache, $key, $value) = @_;
617
618         if (!$cache->{$key}) {
619                 $cache->{$key} = ();
620         }
621         push @{$cache->{$key}}, $value;
622 }