leaking_addresses.pl 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. #!/usr/bin/env perl
  2. # SPDX-License-Identifier: GPL-2.0-only
  3. #
  4. # (c) 2017 Tobin C. Harding <me@tobin.cc>
  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. # When the system is idle it is likely that most files under /proc/PID will be
  14. # identical for various processes. Scanning _all_ the PIDs under /proc is
  15. # unnecessary and implies that we are thoroughly scanning /proc. This is _not_
  16. # the case because there may be ways userspace can trigger creation of /proc
  17. # files that leak addresses but were not present during a scan. For these two
  18. # reasons we exclude all PID directories under /proc except '1/'
  19. use warnings;
  20. use strict;
  21. use POSIX;
  22. use File::Basename;
  23. use File::Spec;
  24. use Cwd 'abs_path';
  25. use Term::ANSIColor qw(:constants);
  26. use Getopt::Long qw(:config no_auto_abbrev);
  27. use Config;
  28. use bigint qw/hex/;
  29. use feature 'state';
  30. my $P = $0;
  31. # Directories to scan.
  32. my @DIRS = ('/proc', '/sys');
  33. # Timer for parsing each file, in seconds.
  34. my $TIMEOUT = 10;
  35. # Kernel addresses vary by architecture. We can only auto-detect the following
  36. # architectures (using `uname -m`). (flag --32-bit overrides auto-detection.)
  37. my @SUPPORTED_ARCHITECTURES = ('x86_64', 'ppc64', 'x86');
  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. # Skip these absolute paths.
  51. my @skip_abs = (
  52. '/proc/kmsg',
  53. '/proc/device-tree',
  54. '/proc/1/syscall',
  55. '/sys/firmware/devicetree',
  56. '/sys/kernel/debug/tracing/trace_pipe',
  57. '/sys/kernel/security/apparmor/revision');
  58. # Skip these under any subdirectory.
  59. my @skip_any = (
  60. 'pagemap',
  61. 'events',
  62. 'access',
  63. 'registers',
  64. 'snapshot_raw',
  65. 'trace_pipe_raw',
  66. 'ptmx',
  67. 'trace_pipe',
  68. 'fd',
  69. 'usbmon');
  70. sub help
  71. {
  72. my ($exitcode) = @_;
  73. print << "EOM";
  74. Usage: $P [OPTIONS]
  75. Options:
  76. -o, --output-raw=<file> Save results for future processing.
  77. -i, --input-raw=<file> Read results from file instead of scanning.
  78. --raw Show raw results (default).
  79. --suppress-dmesg Do not show dmesg results.
  80. --squash-by-path Show one result per unique path.
  81. --squash-by-filename Show one result per unique filename.
  82. --kernel-config-file=<file> Kernel configuration file (e.g /boot/config)
  83. --32-bit Scan 32-bit kernel.
  84. --page-offset-32-bit=o Page offset (for 32-bit kernel 0xABCD1234).
  85. -d, --debug Display debugging output.
  86. -h, --help Display this help and exit.
  87. Scans the running kernel for potential leaking addresses.
  88. EOM
  89. exit($exitcode);
  90. }
  91. GetOptions(
  92. 'd|debug' => \$debug,
  93. 'h|help' => \$help,
  94. 'o|output-raw=s' => \$output_raw,
  95. 'i|input-raw=s' => \$input_raw,
  96. 'suppress-dmesg' => \$suppress_dmesg,
  97. 'squash-by-path' => \$squash_by_path,
  98. 'squash-by-filename' => \$squash_by_filename,
  99. 'raw' => \$raw,
  100. 'kernel-config-file=s' => \$kernel_config_file,
  101. '32-bit' => \$opt_32bit,
  102. 'page-offset-32-bit=o' => \$page_offset_32bit,
  103. ) or help(1);
  104. help(0) if ($help);
  105. if ($input_raw) {
  106. format_output($input_raw);
  107. exit(0);
  108. }
  109. if (!$input_raw and ($squash_by_path or $squash_by_filename)) {
  110. printf "\nSummary reporting only available with --input-raw=<file>\n";
  111. printf "(First run scan with --output-raw=<file>.)\n";
  112. exit(128);
  113. }
  114. if (!(is_supported_architecture() or $opt_32bit or $page_offset_32bit)) {
  115. printf "\nScript does not support your architecture, sorry.\n";
  116. printf "\nCurrently we support: \n\n";
  117. foreach(@SUPPORTED_ARCHITECTURES) {
  118. printf "\t%s\n", $_;
  119. }
  120. printf("\n");
  121. printf("If you are running a 32-bit architecture you may use:\n");
  122. printf("\n\t--32-bit or --page-offset-32-bit=<page offset>\n\n");
  123. my $archname = `uname -m`;
  124. printf("Machine hardware name (`uname -m`): %s\n", $archname);
  125. exit(129);
  126. }
  127. if ($output_raw) {
  128. open my $fh, '>', $output_raw or die "$0: $output_raw: $!\n";
  129. select $fh;
  130. }
  131. parse_dmesg();
  132. walk(@DIRS);
  133. exit 0;
  134. sub dprint
  135. {
  136. printf(STDERR @_) if $debug;
  137. }
  138. sub is_supported_architecture
  139. {
  140. return (is_x86_64() or is_ppc64() or is_ix86_32());
  141. }
  142. sub is_32bit
  143. {
  144. # Allow --32-bit or --page-offset-32-bit to override
  145. if ($opt_32bit or $page_offset_32bit) {
  146. return 1;
  147. }
  148. return is_ix86_32();
  149. }
  150. sub is_ix86_32
  151. {
  152. state $arch = `uname -m`;
  153. chomp $arch;
  154. if ($arch =~ m/i[3456]86/) {
  155. return 1;
  156. }
  157. return 0;
  158. }
  159. sub is_arch
  160. {
  161. my ($desc) = @_;
  162. my $arch = `uname -m`;
  163. chomp $arch;
  164. if ($arch eq $desc) {
  165. return 1;
  166. }
  167. return 0;
  168. }
  169. sub is_x86_64
  170. {
  171. state $is = is_arch('x86_64');
  172. return $is;
  173. }
  174. sub is_ppc64
  175. {
  176. state $is = is_arch('ppc64');
  177. return $is;
  178. }
  179. # Gets config option value from kernel config file.
  180. # Returns "" on error or if config option not found.
  181. sub get_kernel_config_option
  182. {
  183. my ($option) = @_;
  184. my $value = "";
  185. my $tmp_file = "";
  186. my @config_files;
  187. # Allow --kernel-config-file to override.
  188. if ($kernel_config_file ne "") {
  189. @config_files = ($kernel_config_file);
  190. } elsif (-R "/proc/config.gz") {
  191. my $tmp_file = "/tmp/tmpkconf";
  192. if (system("gunzip < /proc/config.gz > $tmp_file")) {
  193. dprint("system(gunzip < /proc/config.gz) failed\n");
  194. return "";
  195. } else {
  196. @config_files = ($tmp_file);
  197. }
  198. } else {
  199. my $file = '/boot/config-' . `uname -r`;
  200. chomp $file;
  201. @config_files = ($file, '/boot/config');
  202. }
  203. foreach my $file (@config_files) {
  204. dprint("parsing config file: $file\n");
  205. $value = option_from_file($option, $file);
  206. if ($value ne "") {
  207. last;
  208. }
  209. }
  210. if ($tmp_file ne "") {
  211. system("rm -f $tmp_file");
  212. }
  213. return $value;
  214. }
  215. # Parses $file and returns kernel configuration option value.
  216. sub option_from_file
  217. {
  218. my ($option, $file) = @_;
  219. my $str = "";
  220. my $val = "";
  221. open(my $fh, "<", $file) or return "";
  222. while (my $line = <$fh> ) {
  223. if ($line =~ /^$option/) {
  224. ($str, $val) = split /=/, $line;
  225. chomp $val;
  226. last;
  227. }
  228. }
  229. close $fh;
  230. return $val;
  231. }
  232. sub is_false_positive
  233. {
  234. my ($match) = @_;
  235. if (is_32bit()) {
  236. return is_false_positive_32bit($match);
  237. }
  238. # 64 bit false positives.
  239. if ($match =~ '\b(0x)?(f|F){16}\b' or
  240. $match =~ '\b(0x)?0{16}\b') {
  241. return 1;
  242. }
  243. if (is_x86_64() and is_in_vsyscall_memory_region($match)) {
  244. return 1;
  245. }
  246. return 0;
  247. }
  248. sub is_false_positive_32bit
  249. {
  250. my ($match) = @_;
  251. state $page_offset = get_page_offset();
  252. if ($match =~ '\b(0x)?(f|F){8}\b') {
  253. return 1;
  254. }
  255. if (hex($match) < $page_offset) {
  256. return 1;
  257. }
  258. return 0;
  259. }
  260. # returns integer value
  261. sub get_page_offset
  262. {
  263. my $page_offset;
  264. my $default_offset = 0xc0000000;
  265. # Allow --page-offset-32bit to override.
  266. if ($page_offset_32bit != 0) {
  267. return $page_offset_32bit;
  268. }
  269. $page_offset = get_kernel_config_option('CONFIG_PAGE_OFFSET');
  270. if (!$page_offset) {
  271. return $default_offset;
  272. }
  273. return $page_offset;
  274. }
  275. sub is_in_vsyscall_memory_region
  276. {
  277. my ($match) = @_;
  278. my $hex = hex($match);
  279. my $region_min = hex("0xffffffffff600000");
  280. my $region_max = hex("0xffffffffff601000");
  281. return ($hex >= $region_min and $hex <= $region_max);
  282. }
  283. # True if argument potentially contains a kernel address.
  284. sub may_leak_address
  285. {
  286. my ($line) = @_;
  287. my $address_re;
  288. # Signal masks.
  289. if ($line =~ '^SigBlk:' or
  290. $line =~ '^SigIgn:' or
  291. $line =~ '^SigCgt:') {
  292. return 0;
  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. $address_re = get_address_re();
  299. while ($line =~ /($address_re)/g) {
  300. if (!is_false_positive($1)) {
  301. return 1;
  302. }
  303. }
  304. return 0;
  305. }
  306. sub get_address_re
  307. {
  308. if (is_ppc64()) {
  309. return '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
  310. } elsif (is_32bit()) {
  311. return '\b(0x)?[[:xdigit:]]{8}\b';
  312. }
  313. return get_x86_64_re();
  314. }
  315. sub get_x86_64_re
  316. {
  317. # We handle page table levels but only if explicitly configured using
  318. # CONFIG_PGTABLE_LEVELS. If config file parsing fails or config option
  319. # is not found we default to using address regular expression suitable
  320. # for 4 page table levels.
  321. state $ptl = get_kernel_config_option('CONFIG_PGTABLE_LEVELS');
  322. if ($ptl == 5) {
  323. return '\b(0x)?ff[[:xdigit:]]{14}\b';
  324. }
  325. return '\b(0x)?ffff[[:xdigit:]]{12}\b';
  326. }
  327. sub parse_dmesg
  328. {
  329. open my $cmd, '-|', 'dmesg';
  330. while (<$cmd>) {
  331. if (may_leak_address($_)) {
  332. print 'dmesg: ' . $_;
  333. }
  334. }
  335. close $cmd;
  336. }
  337. # True if we should skip this path.
  338. sub skip
  339. {
  340. my ($path) = @_;
  341. foreach (@skip_abs) {
  342. return 1 if (/^$path$/);
  343. }
  344. my($filename, $dirs, $suffix) = fileparse($path);
  345. foreach (@skip_any) {
  346. return 1 if (/^$filename$/);
  347. }
  348. return 0;
  349. }
  350. sub timed_parse_file
  351. {
  352. my ($file) = @_;
  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. if ($@) {
  360. die unless $@ eq "alarm\n"; # Propagate unexpected errors.
  361. printf STDERR "timed out parsing: %s\n", $file;
  362. }
  363. }
  364. sub parse_file
  365. {
  366. my ($file) = @_;
  367. if (! -R $file) {
  368. return;
  369. }
  370. if (! -T $file) {
  371. return;
  372. }
  373. open my $fh, "<", $file or return;
  374. while ( <$fh> ) {
  375. chomp;
  376. if (may_leak_address($_)) {
  377. printf("$file: $_\n");
  378. }
  379. }
  380. close $fh;
  381. }
  382. # Checks if the actual path name is leaking a kernel address.
  383. sub check_path_for_leaks
  384. {
  385. my ($path) = @_;
  386. if (may_leak_address($path)) {
  387. printf("Path name may contain address: $path\n");
  388. }
  389. }
  390. # Recursively walk directory tree.
  391. sub walk
  392. {
  393. my @dirs = @_;
  394. while (my $pwd = shift @dirs) {
  395. next if (!opendir(DIR, $pwd));
  396. my @files = readdir(DIR);
  397. closedir(DIR);
  398. foreach my $file (@files) {
  399. next if ($file eq '.' or $file eq '..');
  400. my $path = "$pwd/$file";
  401. next if (-l $path);
  402. # skip /proc/PID except /proc/1
  403. next if (($path =~ /^\/proc\/[0-9]+$/) &&
  404. ($path !~ /^\/proc\/1$/));
  405. next if (skip($path));
  406. check_path_for_leaks($path);
  407. if (-d $path) {
  408. push @dirs, $path;
  409. next;
  410. }
  411. dprint("parsing: $path\n");
  412. timed_parse_file($path);
  413. }
  414. }
  415. }
  416. sub format_output
  417. {
  418. my ($file) = @_;
  419. # Default is to show raw results.
  420. if ($raw or (!$squash_by_path and !$squash_by_filename)) {
  421. dump_raw_output($file);
  422. return;
  423. }
  424. my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
  425. printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
  426. if (!$suppress_dmesg) {
  427. print_dmesg($dmesg);
  428. }
  429. if ($squash_by_filename) {
  430. squash_by($files, 'filename');
  431. }
  432. if ($squash_by_path) {
  433. squash_by($paths, 'path');
  434. }
  435. }
  436. sub dump_raw_output
  437. {
  438. my ($file) = @_;
  439. open (my $fh, '<', $file) or die "$0: $file: $!\n";
  440. while (<$fh>) {
  441. if ($suppress_dmesg) {
  442. if ("dmesg:" eq substr($_, 0, 6)) {
  443. next;
  444. }
  445. }
  446. print $_;
  447. }
  448. close $fh;
  449. }
  450. sub parse_raw_file
  451. {
  452. my ($file) = @_;
  453. my $total = 0; # Total number of lines parsed.
  454. my @dmesg; # dmesg output.
  455. my %files; # Unique filenames containing leaks.
  456. my %paths; # Unique paths containing leaks.
  457. open (my $fh, '<', $file) or die "$0: $file: $!\n";
  458. while (my $line = <$fh>) {
  459. $total++;
  460. if ("dmesg:" eq substr($line, 0, 6)) {
  461. push @dmesg, $line;
  462. next;
  463. }
  464. cache_path(\%paths, $line);
  465. cache_filename(\%files, $line);
  466. }
  467. return $total, \@dmesg, \%paths, \%files;
  468. }
  469. sub print_dmesg
  470. {
  471. my ($dmesg) = @_;
  472. print "\ndmesg output:\n";
  473. if (@$dmesg == 0) {
  474. print "<no results>\n";
  475. return;
  476. }
  477. foreach(@$dmesg) {
  478. my $index = index($_, ': ');
  479. $index += 2; # skid ': '
  480. print substr($_, $index);
  481. }
  482. }
  483. sub squash_by
  484. {
  485. my ($ref, $desc) = @_;
  486. print "\nResults squashed by $desc (excl dmesg). ";
  487. print "Displaying [<number of results> <$desc>], <example result>\n";
  488. if (keys %$ref == 0) {
  489. print "<no results>\n";
  490. return;
  491. }
  492. foreach(keys %$ref) {
  493. my $lines = $ref->{$_};
  494. my $length = @$lines;
  495. printf "[%d %s] %s", $length, $_, @$lines[0];
  496. }
  497. }
  498. sub cache_path
  499. {
  500. my ($paths, $line) = @_;
  501. my $index = index($line, ': ');
  502. my $path = substr($line, 0, $index);
  503. $index += 2; # skip ': '
  504. add_to_cache($paths, $path, substr($line, $index));
  505. }
  506. sub cache_filename
  507. {
  508. my ($files, $line) = @_;
  509. my $index = index($line, ': ');
  510. my $path = substr($line, 0, $index);
  511. my $filename = basename($path);
  512. $index += 2; # skip ': '
  513. add_to_cache($files, $filename, substr($line, $index));
  514. }
  515. sub add_to_cache
  516. {
  517. my ($cache, $key, $value) = @_;
  518. if (!$cache->{$key}) {
  519. $cache->{$key} = ();
  520. }
  521. push @{$cache->{$key}}, $value;
  522. }