]> git.proxmox.com Git - mirror_ubuntu-eoan-kernel.git/blob - scripts/leaking_addresses.pl
leaking_addresses: add support for kernel config file
[mirror_ubuntu-eoan-kernel.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 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 #
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
24 my $P = $0;
25 my $V = '0.01';
26
27 # Directories to scan.
28 my @DIRS = ('/proc', '/sys');
29
30 # Timer for parsing each file, in seconds.
31 my $TIMEOUT = 10;
32
33 # 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.
36 my @SUPPORTED_ARCHITECTURES = ('x86_64', 'ppc64');
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
49 # Do not parse these files (absolute path).
50 my @skip_parse_files_abs = ('/proc/kmsg',
51 '/proc/kcore',
52 '/proc/fs/ext4/sdb1/mb_groups',
53 '/proc/1/fd/3',
54 '/sys/firmware/devicetree',
55 '/proc/device-tree',
56 '/sys/kernel/debug/tracing/trace_pipe',
57 '/sys/kernel/security/apparmor/revision');
58
59 # Do not parse these files under any subdirectory.
60 my @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).
73 my @skip_walk_dirs_abs = ();
74
75 # Do not walk these directories under any subdirectory.
76 my @skip_walk_dirs_any = ('self',
77 'thread-self',
78 'cwd',
79 'fd',
80 'usbmon',
81 'stderr',
82 'stdin',
83 'stdout');
84
85 sub help
86 {
87 my ($exitcode) = @_;
88
89 print << "EOM";
90
91 Usage: $P [OPTIONS]
92 Version: $V
93
94 Options:
95
96 -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.
102 --kernel-config-file=<file> Kernel configuration file (e.g /boot/config)
103 -d, --debug Display debugging output.
104 -h, --help, --version Display this help and exit.
105
106 Scans the running (64 bit) kernel for potential leaking addresses.
107
108 EOM
109 exit($exitcode);
110 }
111
112 GetOptions(
113 'd|debug' => \$debug,
114 'h|help' => \$help,
115 '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,
122 'kernel-config-file=s' => \$kernel_config_file,
123 ) or help(1);
124
125 help(0) if ($help);
126
127 if ($input_raw) {
128 format_output($input_raw);
129 exit(0);
130 }
131
132 if (!$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
138 if (!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
152 if ($output_raw) {
153 open my $fh, '>', $output_raw or die "$0: $output_raw: $!\n";
154 select $fh;
155 }
156
157 parse_dmesg();
158 walk(@DIRS);
159
160 exit 0;
161
162 sub dprint
163 {
164 printf(STDERR @_) if $debug;
165 }
166
167 sub is_supported_architecture
168 {
169 return (is_x86_64() or is_ppc64());
170 }
171
172 sub 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
182 sub 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
192 # Gets config option value from kernel config file.
193 # Returns "" on error or if config option not found.
194 sub 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.
235 sub 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
254 sub is_false_positive
255 {
256 my ($match) = @_;
257
258 if ($match =~ '\b(0x)?(f|F){16}\b' or
259 $match =~ '\b(0x)?0{16}\b') {
260 return 1;
261 }
262
263 if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
264 return 1;
265 }
266
267 return 0;
268 }
269
270 sub 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
281 # True if argument potentially contains a kernel address.
282 sub may_leak_address
283 {
284 my ($line) = @_;
285 my $address_re;
286
287 # Signal masks.
288 if ($line =~ '^SigBlk:' or
289 $line =~ '^SigIgn:' or
290 $line =~ '^SigCgt:') {
291 return 0;
292 }
293
294 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 }
298
299 # 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) {
307 if (!is_false_positive($1)) {
308 return 1;
309 }
310 }
311
312 return 0;
313 }
314
315 sub 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.
327 sub 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
343 sub skip_parse
344 {
345 my ($path) = @_;
346 return skip($path, \@skip_parse_files_abs, \@skip_parse_files_any);
347 }
348
349 sub 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
366 sub 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.
391 sub 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.
398 sub walk
399 {
400 my @dirs = @_;
401
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 {
417 timed_parse_file($path);
418 }
419 }
420 }
421 }
422
423 sub 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
450 sub 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
466 sub 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
491 sub 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
509 sub 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
528 sub 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
539 sub 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
551 sub add_to_cache
552 {
553 my ($cache, $key, $value) = @_;
554
555 if (!$cache->{$key}) {
556 $cache->{$key} = ();
557 }
558 push @{$cache->{$key}}, $value;
559 }