leaking_addresses.pl 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  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. # You may like to set kptr_restrict=2 before running script
  14. # (see Documentation/sysctl/kernel.txt).
  15. use warnings;
  16. use strict;
  17. use POSIX;
  18. use File::Basename;
  19. use File::Spec;
  20. use Cwd 'abs_path';
  21. use Term::ANSIColor qw(:constants);
  22. use Getopt::Long qw(:config no_auto_abbrev);
  23. use Config;
  24. my $P = $0;
  25. my $V = '0.01';
  26. # Directories to scan.
  27. my @DIRS = ('/proc', '/sys');
  28. # Timer for parsing each file, in seconds.
  29. my $TIMEOUT = 10;
  30. # Script can only grep for kernel addresses on the following architectures. If
  31. # your architecture is not listed here and has a grep'able kernel address please
  32. # consider submitting a patch.
  33. my @SUPPORTED_ARCHITECTURES = ('x86_64', 'ppc64');
  34. # Command line options.
  35. my $help = 0;
  36. my $debug = 0;
  37. my $raw = 0;
  38. my $output_raw = ""; # Write raw results to file.
  39. my $input_raw = ""; # Read raw results from file instead of scanning.
  40. my $suppress_dmesg = 0; # Don't show dmesg in output.
  41. my $squash_by_path = 0; # Summary report grouped by absolute path.
  42. my $squash_by_filename = 0; # Summary report grouped by filename.
  43. # Do not parse these files (absolute path).
  44. my @skip_parse_files_abs = ('/proc/kmsg',
  45. '/proc/kcore',
  46. '/proc/fs/ext4/sdb1/mb_groups',
  47. '/proc/1/fd/3',
  48. '/sys/firmware/devicetree',
  49. '/proc/device-tree',
  50. '/sys/kernel/debug/tracing/trace_pipe',
  51. '/sys/kernel/security/apparmor/revision');
  52. # Do not parse these files under any subdirectory.
  53. my @skip_parse_files_any = ('0',
  54. '1',
  55. '2',
  56. 'pagemap',
  57. 'events',
  58. 'access',
  59. 'registers',
  60. 'snapshot_raw',
  61. 'trace_pipe_raw',
  62. 'ptmx',
  63. 'trace_pipe');
  64. # Do not walk these directories (absolute path).
  65. my @skip_walk_dirs_abs = ();
  66. # Do not walk these directories under any subdirectory.
  67. my @skip_walk_dirs_any = ('self',
  68. 'thread-self',
  69. 'cwd',
  70. 'fd',
  71. 'usbmon',
  72. 'stderr',
  73. 'stdin',
  74. 'stdout');
  75. sub help
  76. {
  77. my ($exitcode) = @_;
  78. print << "EOM";
  79. Usage: $P [OPTIONS]
  80. Version: $V
  81. Options:
  82. -o, --output-raw=<file> Save results for future processing.
  83. -i, --input-raw=<file> Read results from file instead of scanning.
  84. --raw Show raw results (default).
  85. --suppress-dmesg Do not show dmesg results.
  86. --squash-by-path Show one result per unique path.
  87. --squash-by-filename Show one result per unique filename.
  88. -d, --debug Display debugging output.
  89. -h, --help, --version Display this help and exit.
  90. Examples:
  91. # Scan kernel and dump raw results.
  92. $0
  93. # Scan kernel and save results to file.
  94. $0 --output-raw scan.out
  95. # View summary report.
  96. $0 --input-raw scan.out --squash-by-filename
  97. Scans the running (64 bit) kernel for potential leaking addresses.
  98. EOM
  99. exit($exitcode);
  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. ) or help(1);
  112. help(0) if ($help);
  113. if ($input_raw) {
  114. format_output($input_raw);
  115. exit(0);
  116. }
  117. if (!$input_raw and ($squash_by_path or $squash_by_filename)) {
  118. printf "\nSummary reporting only available with --input-raw=<file>\n";
  119. printf "(First run scan with --output-raw=<file>.)\n";
  120. exit(128);
  121. }
  122. if (!is_supported_architecture()) {
  123. printf "\nScript does not support your architecture, sorry.\n";
  124. printf "\nCurrently we support: \n\n";
  125. foreach(@SUPPORTED_ARCHITECTURES) {
  126. printf "\t%s\n", $_;
  127. }
  128. my $archname = $Config{archname};
  129. printf "\n\$ perl -MConfig -e \'print \"\$Config{archname}\\n\"\'\n";
  130. printf "%s\n", $archname;
  131. exit(129);
  132. }
  133. if ($output_raw) {
  134. open my $fh, '>', $output_raw or die "$0: $output_raw: $!\n";
  135. select $fh;
  136. }
  137. parse_dmesg();
  138. walk(@DIRS);
  139. exit 0;
  140. sub dprint
  141. {
  142. printf(STDERR @_) if $debug;
  143. }
  144. sub is_supported_architecture
  145. {
  146. return (is_x86_64() or is_ppc64());
  147. }
  148. sub is_x86_64
  149. {
  150. my $archname = $Config{archname};
  151. if ($archname =~ m/x86_64/) {
  152. return 1;
  153. }
  154. return 0;
  155. }
  156. sub is_ppc64
  157. {
  158. my $archname = $Config{archname};
  159. if ($archname =~ m/powerpc/ and $archname =~ m/64/) {
  160. return 1;
  161. }
  162. return 0;
  163. }
  164. sub is_false_positive
  165. {
  166. my ($match) = @_;
  167. if ($match =~ '\b(0x)?(f|F){16}\b' or
  168. $match =~ '\b(0x)?0{16}\b') {
  169. return 1;
  170. }
  171. if (is_x86_64) {
  172. # vsyscall memory region, we should probably check against a range here.
  173. if ($match =~ '\bf{10}600000\b' or
  174. $match =~ '\bf{10}601000\b') {
  175. return 1;
  176. }
  177. }
  178. return 0;
  179. }
  180. # True if argument potentially contains a kernel address.
  181. sub may_leak_address
  182. {
  183. my ($line) = @_;
  184. my $address_re;
  185. # Signal masks.
  186. if ($line =~ '^SigBlk:' or
  187. $line =~ '^SigIgn:' or
  188. $line =~ '^SigCgt:') {
  189. return 0;
  190. }
  191. if ($line =~ '\bKEY=[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b' or
  192. $line =~ '\b[[:xdigit:]]{14} [[:xdigit:]]{16} [[:xdigit:]]{16}\b') {
  193. return 0;
  194. }
  195. # One of these is guaranteed to be true.
  196. if (is_x86_64()) {
  197. $address_re = '\b(0x)?ffff[[:xdigit:]]{12}\b';
  198. } elsif (is_ppc64()) {
  199. $address_re = '\b(0x)?[89abcdef]00[[:xdigit:]]{13}\b';
  200. }
  201. while (/($address_re)/g) {
  202. if (!is_false_positive($1)) {
  203. return 1;
  204. }
  205. }
  206. return 0;
  207. }
  208. sub parse_dmesg
  209. {
  210. open my $cmd, '-|', 'dmesg';
  211. while (<$cmd>) {
  212. if (may_leak_address($_)) {
  213. print 'dmesg: ' . $_;
  214. }
  215. }
  216. close $cmd;
  217. }
  218. # True if we should skip this path.
  219. sub skip
  220. {
  221. my ($path, $paths_abs, $paths_any) = @_;
  222. foreach (@$paths_abs) {
  223. return 1 if (/^$path$/);
  224. }
  225. my($filename, $dirs, $suffix) = fileparse($path);
  226. foreach (@$paths_any) {
  227. return 1 if (/^$filename$/);
  228. }
  229. return 0;
  230. }
  231. sub skip_parse
  232. {
  233. my ($path) = @_;
  234. return skip($path, \@skip_parse_files_abs, \@skip_parse_files_any);
  235. }
  236. sub timed_parse_file
  237. {
  238. my ($file) = @_;
  239. eval {
  240. local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required.
  241. alarm $TIMEOUT;
  242. parse_file($file);
  243. alarm 0;
  244. };
  245. if ($@) {
  246. die unless $@ eq "alarm\n"; # Propagate unexpected errors.
  247. printf STDERR "timed out parsing: %s\n", $file;
  248. }
  249. }
  250. sub parse_file
  251. {
  252. my ($file) = @_;
  253. if (! -R $file) {
  254. return;
  255. }
  256. if (skip_parse($file)) {
  257. dprint "skipping file: $file\n";
  258. return;
  259. }
  260. dprint "parsing: $file\n";
  261. open my $fh, "<", $file or return;
  262. while ( <$fh> ) {
  263. if (may_leak_address($_)) {
  264. print $file . ': ' . $_;
  265. }
  266. }
  267. close $fh;
  268. }
  269. # True if we should skip walking this directory.
  270. sub skip_walk
  271. {
  272. my ($path) = @_;
  273. return skip($path, \@skip_walk_dirs_abs, \@skip_walk_dirs_any)
  274. }
  275. # Recursively walk directory tree.
  276. sub walk
  277. {
  278. my @dirs = @_;
  279. while (my $pwd = shift @dirs) {
  280. next if (skip_walk($pwd));
  281. next if (!opendir(DIR, $pwd));
  282. my @files = readdir(DIR);
  283. closedir(DIR);
  284. foreach my $file (@files) {
  285. next if ($file eq '.' or $file eq '..');
  286. my $path = "$pwd/$file";
  287. next if (-l $path);
  288. if (-d $path) {
  289. push @dirs, $path;
  290. } else {
  291. timed_parse_file($path);
  292. }
  293. }
  294. }
  295. }
  296. sub format_output
  297. {
  298. my ($file) = @_;
  299. # Default is to show raw results.
  300. if ($raw or (!$squash_by_path and !$squash_by_filename)) {
  301. dump_raw_output($file);
  302. return;
  303. }
  304. my ($total, $dmesg, $paths, $files) = parse_raw_file($file);
  305. printf "\nTotal number of results from scan (incl dmesg): %d\n", $total;
  306. if (!$suppress_dmesg) {
  307. print_dmesg($dmesg);
  308. }
  309. if ($squash_by_filename) {
  310. squash_by($files, 'filename');
  311. }
  312. if ($squash_by_path) {
  313. squash_by($paths, 'path');
  314. }
  315. }
  316. sub dump_raw_output
  317. {
  318. my ($file) = @_;
  319. open (my $fh, '<', $file) or die "$0: $file: $!\n";
  320. while (<$fh>) {
  321. if ($suppress_dmesg) {
  322. if ("dmesg:" eq substr($_, 0, 6)) {
  323. next;
  324. }
  325. }
  326. print $_;
  327. }
  328. close $fh;
  329. }
  330. sub parse_raw_file
  331. {
  332. my ($file) = @_;
  333. my $total = 0; # Total number of lines parsed.
  334. my @dmesg; # dmesg output.
  335. my %files; # Unique filenames containing leaks.
  336. my %paths; # Unique paths containing leaks.
  337. open (my $fh, '<', $file) or die "$0: $file: $!\n";
  338. while (my $line = <$fh>) {
  339. $total++;
  340. if ("dmesg:" eq substr($line, 0, 6)) {
  341. push @dmesg, $line;
  342. next;
  343. }
  344. cache_path(\%paths, $line);
  345. cache_filename(\%files, $line);
  346. }
  347. return $total, \@dmesg, \%paths, \%files;
  348. }
  349. sub print_dmesg
  350. {
  351. my ($dmesg) = @_;
  352. print "\ndmesg output:\n";
  353. if (@$dmesg == 0) {
  354. print "<no results>\n";
  355. return;
  356. }
  357. foreach(@$dmesg) {
  358. my $index = index($_, ': ');
  359. $index += 2; # skid ': '
  360. print substr($_, $index);
  361. }
  362. }
  363. sub squash_by
  364. {
  365. my ($ref, $desc) = @_;
  366. print "\nResults squashed by $desc (excl dmesg). ";
  367. print "Displaying [<number of results> <$desc>], <example result>\n";
  368. if (keys %$ref == 0) {
  369. print "<no results>\n";
  370. return;
  371. }
  372. foreach(keys %$ref) {
  373. my $lines = $ref->{$_};
  374. my $length = @$lines;
  375. printf "[%d %s] %s", $length, $_, @$lines[0];
  376. }
  377. }
  378. sub cache_path
  379. {
  380. my ($paths, $line) = @_;
  381. my $index = index($line, ': ');
  382. my $path = substr($line, 0, $index);
  383. $index += 2; # skip ': '
  384. add_to_cache($paths, $path, substr($line, $index));
  385. }
  386. sub cache_filename
  387. {
  388. my ($files, $line) = @_;
  389. my $index = index($line, ': ');
  390. my $path = substr($line, 0, $index);
  391. my $filename = basename($path);
  392. $index += 2; # skip ': '
  393. add_to_cache($files, $filename, substr($line, $index));
  394. }
  395. sub add_to_cache
  396. {
  397. my ($cache, $key, $value) = @_;
  398. if (!$cache->{$key}) {
  399. $cache->{$key} = ();
  400. }
  401. push @{$cache->{$key}}, $value;
  402. }