mk-ca-bundle.pl 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. #!/usr/bin/env perl
  2. # ***************************************************************************
  3. # * _ _ ____ _
  4. # * Project ___| | | | _ \| |
  5. # * / __| | | | |_) | |
  6. # * | (__| |_| | _ <| |___
  7. # * \___|\___/|_| \_\_____|
  8. # *
  9. # * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.
  10. # *
  11. # * This software is licensed as described in the file COPYING, which
  12. # * you should have received as part of this distribution. The terms
  13. # * are also available at https://curl.se/docs/copyright.html.
  14. # *
  15. # * You may opt to use, copy, modify, merge, publish, distribute and/or sell
  16. # * copies of the Software, and permit persons to whom the Software is
  17. # * furnished to do so, under the terms of the COPYING file.
  18. # *
  19. # * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
  20. # * KIND, either express or implied.
  21. # *
  22. # ***************************************************************************
  23. # This Perl script creates a fresh ca-bundle.crt file for use with libcurl.
  24. # It downloads certdata.txt from Mozilla's source tree (see URL below),
  25. # then parses certdata.txt and extracts CA Root Certificates into PEM format.
  26. # These are then processed with the OpenSSL commandline tool to produce the
  27. # final ca-bundle.crt file.
  28. # The script is based on the parse-certs script written by Roland Krikava.
  29. # This Perl script works on almost any platform since its only external
  30. # dependency is the OpenSSL commandline tool for optional text listing.
  31. # Hacked by Guenter Knauf.
  32. #
  33. use Encode;
  34. use Getopt::Std;
  35. use MIME::Base64;
  36. use strict;
  37. use warnings;
  38. use vars qw($opt_b $opt_d $opt_f $opt_h $opt_i $opt_k $opt_l $opt_m $opt_n $opt_p $opt_q $opt_s $opt_t $opt_u $opt_v $opt_w);
  39. use List::Util;
  40. use Text::Wrap;
  41. use Time::Local;
  42. my $MOD_SHA = "Digest::SHA";
  43. eval "require $MOD_SHA";
  44. if ($@) {
  45. $MOD_SHA = "Digest::SHA::PurePerl";
  46. eval "require $MOD_SHA";
  47. }
  48. eval "require LWP::UserAgent";
  49. my %urls = (
  50. 'nss' =>
  51. 'https://hg.mozilla.org/projects/nss/raw-file/default/lib/ckfw/builtins/certdata.txt',
  52. 'central' =>
  53. 'https://hg.mozilla.org/mozilla-central/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt',
  54. 'beta' =>
  55. 'https://hg.mozilla.org/releases/mozilla-beta/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt',
  56. 'release' =>
  57. 'https://hg.mozilla.org/releases/mozilla-release/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt',
  58. );
  59. $opt_d = 'release';
  60. # If the OpenSSL commandline is not in search path you can configure it here!
  61. my $openssl = 'openssl';
  62. my $version = '1.29';
  63. $opt_w = 76; # default base64 encoded lines length
  64. # default cert types to include in the output (default is to include CAs which
  65. # may issue SSL server certs)
  66. my $default_mozilla_trust_purposes = "SERVER_AUTH";
  67. my $default_mozilla_trust_levels = "TRUSTED_DELEGATOR";
  68. $opt_p = $default_mozilla_trust_purposes . ":" . $default_mozilla_trust_levels;
  69. my @valid_mozilla_trust_purposes = (
  70. "DIGITAL_SIGNATURE",
  71. "NON_REPUDIATION",
  72. "KEY_ENCIPHERMENT",
  73. "DATA_ENCIPHERMENT",
  74. "KEY_AGREEMENT",
  75. "KEY_CERT_SIGN",
  76. "CRL_SIGN",
  77. "SERVER_AUTH",
  78. "CLIENT_AUTH",
  79. "CODE_SIGNING",
  80. "EMAIL_PROTECTION",
  81. "IPSEC_END_SYSTEM",
  82. "IPSEC_TUNNEL",
  83. "IPSEC_USER",
  84. "TIME_STAMPING",
  85. "STEP_UP_APPROVED"
  86. );
  87. my @valid_mozilla_trust_levels = (
  88. "TRUSTED_DELEGATOR", # CAs
  89. "NOT_TRUSTED", # Don't trust these certs.
  90. "MUST_VERIFY_TRUST", # This explicitly tells us that it ISN'T a CA but is
  91. # otherwise ok. In other words, this should tell the
  92. # app to ignore any other sources that claim this is
  93. # a CA.
  94. "TRUSTED" # This cert is trusted, but only for itself and not
  95. # for delegates (i.e. it is not a CA).
  96. );
  97. my $default_signature_algorithms = $opt_s = "MD5";
  98. my @valid_signature_algorithms = (
  99. "MD5",
  100. "SHA1",
  101. "SHA256",
  102. "SHA384",
  103. "SHA512"
  104. );
  105. $0 =~ s@.*(/|\\)@@;
  106. $Getopt::Std::STANDARD_HELP_VERSION = 1;
  107. getopts('bd:fhiklmnp:qs:tuvw:');
  108. if(!defined($opt_d)) {
  109. # to make plain "-d" use not cause warnings, and actually still work
  110. $opt_d = 'release';
  111. }
  112. # Use predefined URL or else custom URL specified on command line.
  113. my $url;
  114. if(defined($urls{$opt_d})) {
  115. $url = $urls{$opt_d};
  116. if(!$opt_k && $url !~ /^https:\/\//i) {
  117. die "The URL for '$opt_d' is not HTTPS. Use -k to override (insecure).\n";
  118. }
  119. }
  120. else {
  121. $url = $opt_d;
  122. }
  123. my $curl = `curl -V`;
  124. if ($opt_i) {
  125. print ("=" x 78 . "\n");
  126. print "Script Version : $version\n";
  127. print "Perl Version : $]\n";
  128. print "Operating System Name : $^O\n";
  129. print "Getopt::Std.pm Version : ${Getopt::Std::VERSION}\n";
  130. print "Encode::Encoding.pm Version : ${Encode::Encoding::VERSION}\n";
  131. print "MIME::Base64.pm Version : ${MIME::Base64::VERSION}\n";
  132. print "LWP::UserAgent.pm Version : ${LWP::UserAgent::VERSION}\n" if($LWP::UserAgent::VERSION);
  133. print "LWP.pm Version : ${LWP::VERSION}\n" if($LWP::VERSION);
  134. print "Digest::SHA.pm Version : ${Digest::SHA::VERSION}\n" if ($Digest::SHA::VERSION);
  135. print "Digest::SHA::PurePerl.pm Version : ${Digest::SHA::PurePerl::VERSION}\n" if ($Digest::SHA::PurePerl::VERSION);
  136. print ("=" x 78 . "\n");
  137. }
  138. sub warning_message() {
  139. if ( $opt_d =~ m/^risk$/i ) { # Long Form Warning and Exit
  140. print "Warning: Use of this script may pose some risk:\n";
  141. print "\n";
  142. print " 1) If you use HTTP URLs they are subject to a man in the middle attack\n";
  143. print " 2) Default to 'release', but more recent updates may be found in other trees\n";
  144. print " 3) certdata.txt file format may change, lag time to update this script\n";
  145. print " 4) Generally unwise to blindly trust CAs without manual review & verification\n";
  146. print " 5) Mozilla apps use additional security checks aren't represented in certdata\n";
  147. print " 6) Use of this script will make a security engineer grind his teeth and\n";
  148. print " swear at you. ;)\n";
  149. exit;
  150. } else { # Short Form Warning
  151. print "Warning: Use of this script may pose some risk, -d risk for more details.\n";
  152. }
  153. }
  154. sub HELP_MESSAGE() {
  155. print "Usage:\t${0} [-b] [-d<certdata>] [-f] [-i] [-k] [-l] [-n] [-p<purposes:levels>] [-q] [-s<algorithms>] [-t] [-u] [-v] [-w<l>] [<outputfile>]\n";
  156. print "\t-b\tbackup an existing version of ca-bundle.crt\n";
  157. print "\t-d\tspecify Mozilla tree to pull certdata.txt or custom URL\n";
  158. print "\t\t Valid names are:\n";
  159. print "\t\t ", join( ", ", map { ( $_ =~ m/$opt_d/ ) ? "$_ (default)" : "$_" } sort keys %urls ), "\n";
  160. print "\t-f\tforce rebuild even if certdata.txt is current\n";
  161. print "\t-i\tprint version info about used modules\n";
  162. print "\t-k\tallow URLs other than HTTPS, enable HTTP fallback (insecure)\n";
  163. print "\t-l\tprint license info about certdata.txt\n";
  164. print "\t-m\tinclude meta data in output\n";
  165. print "\t-n\tno download of certdata.txt (to use existing)\n";
  166. print wrap("\t","\t\t", "-p\tlist of Mozilla trust purposes and levels for certificates to include in output. Takes the form of a comma separated list of purposes, a colon, and a comma separated list of levels. (default: $default_mozilla_trust_purposes:$default_mozilla_trust_levels)"), "\n";
  167. print "\t\t Valid purposes are:\n";
  168. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_purposes ) ), "\n";
  169. print "\t\t Valid levels are:\n";
  170. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_levels ) ), "\n";
  171. print "\t-q\tbe really quiet (no progress output at all)\n";
  172. print wrap("\t","\t\t", "-s\tcomma separated list of certificate signatures/hashes to output in plain text mode. (default: $default_signature_algorithms)\n");
  173. print "\t\t Valid signature algorithms are:\n";
  174. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_signature_algorithms ) ), "\n";
  175. print "\t-t\tinclude plain text listing of certificates\n";
  176. print "\t-u\tunlink (remove) certdata.txt after processing\n";
  177. print "\t-v\tbe verbose and print out processed CAs\n";
  178. print "\t-w <l>\twrap base64 output lines after <l> chars (default: ${opt_w})\n";
  179. exit;
  180. }
  181. sub VERSION_MESSAGE() {
  182. print "${0} version ${version} running Perl ${]} on ${^O}\n";
  183. }
  184. warning_message() unless ($opt_q || $url =~ m/^(ht|f)tps:/i );
  185. HELP_MESSAGE() if ($opt_h);
  186. sub report($@) {
  187. my $output = shift;
  188. print STDERR $output . "\n" unless $opt_q;
  189. }
  190. sub is_in_list($@) {
  191. my $target = shift;
  192. return defined(List::Util::first { $target eq $_ } @_);
  193. }
  194. # Parses $param_string as a case insensitive comma separated list with optional
  195. # whitespace validates that only allowed parameters are supplied
  196. sub parse_csv_param($$@) {
  197. my $description = shift;
  198. my $param_string = shift;
  199. my @valid_values = @_;
  200. my @values = map {
  201. s/^\s+//; # strip leading spaces
  202. s/\s+$//; # strip trailing spaces
  203. uc $_ # return the modified string as upper case
  204. } split( ',', $param_string );
  205. # Find all values which are not in the list of valid values or "ALL"
  206. my @invalid = grep { !is_in_list($_,"ALL",@valid_values) } @values;
  207. if ( scalar(@invalid) > 0 ) {
  208. # Tell the user which parameters were invalid and print the standard help
  209. # message which will exit
  210. print "Error: Invalid ", $description, scalar(@invalid) == 1 ? ": " : "s: ", join( ", ", map { "\"$_\"" } @invalid ), "\n";
  211. HELP_MESSAGE();
  212. }
  213. @values = @valid_values if ( is_in_list("ALL",@values) );
  214. return @values;
  215. }
  216. sub sha256 {
  217. my $result;
  218. if ($Digest::SHA::VERSION || $Digest::SHA::PurePerl::VERSION) {
  219. open(FILE, $_[0]) or die "Can't open '$_[0]': $!";
  220. binmode(FILE);
  221. $result = $MOD_SHA->new(256)->addfile(*FILE)->hexdigest;
  222. close(FILE);
  223. } else {
  224. # Use OpenSSL command if Perl Digest::SHA modules not available
  225. $result = `"$openssl" dgst -r -sha256 "$_[0]"`;
  226. $result =~ s/^([0-9a-f]{64}) .+/$1/is;
  227. }
  228. return $result;
  229. }
  230. sub oldhash {
  231. my $hash = "";
  232. open(C, "<$_[0]") || return 0;
  233. while(<C>) {
  234. chomp;
  235. if($_ =~ /^\#\# SHA256: (.*)/) {
  236. $hash = $1;
  237. last;
  238. }
  239. }
  240. close(C);
  241. return $hash;
  242. }
  243. if ( $opt_p !~ m/:/ ) {
  244. print "Error: Mozilla trust identifier list must include both purposes and levels\n";
  245. HELP_MESSAGE();
  246. }
  247. (my $included_mozilla_trust_purposes_string, my $included_mozilla_trust_levels_string) = split( ':', $opt_p );
  248. my @included_mozilla_trust_purposes = parse_csv_param( "trust purpose", $included_mozilla_trust_purposes_string, @valid_mozilla_trust_purposes );
  249. my @included_mozilla_trust_levels = parse_csv_param( "trust level", $included_mozilla_trust_levels_string, @valid_mozilla_trust_levels );
  250. my @included_signature_algorithms = parse_csv_param( "signature algorithm", $opt_s, @valid_signature_algorithms );
  251. sub should_output_cert(%) {
  252. my %trust_purposes_by_level = @_;
  253. foreach my $level (@included_mozilla_trust_levels) {
  254. # for each level we want to output, see if any of our desired purposes are
  255. # included
  256. return 1 if ( defined( List::Util::first { is_in_list( $_, @included_mozilla_trust_purposes ) } @{$trust_purposes_by_level{$level}} ) );
  257. }
  258. return 0;
  259. }
  260. my $crt = $ARGV[0] || 'ca-bundle.crt';
  261. (my $txt = $url) =~ s@(.*/|\?.*)@@g;
  262. my $stdout = $crt eq '-';
  263. my $resp;
  264. my $fetched;
  265. my $oldhash = oldhash($crt);
  266. report "SHA256 of old file: $oldhash";
  267. if(!$opt_n) {
  268. report "Downloading $txt ...";
  269. # If we have an HTTPS URL then use curl
  270. if($url =~ /^https:\/\//i) {
  271. if($curl) {
  272. if($curl =~ /^Protocols:.* https( |$)/m) {
  273. report "Get certdata with curl!";
  274. my $proto = !$opt_k ? "--proto =https" : "";
  275. my $quiet = $opt_q ? "-s" : "";
  276. my @out = `curl -w %{response_code} $proto $quiet -o "$txt" "$url"`;
  277. if(!$? && @out && $out[0] == 200) {
  278. $fetched = 1;
  279. report "Downloaded $txt";
  280. }
  281. else {
  282. report "Failed downloading via HTTPS with curl";
  283. if(-e $txt && !unlink($txt)) {
  284. report "Failed to remove '$txt': $!";
  285. }
  286. }
  287. }
  288. else {
  289. report "curl lacks https support";
  290. }
  291. }
  292. else {
  293. report "curl not found";
  294. }
  295. }
  296. # If nothing was fetched then use LWP
  297. if(!$fetched) {
  298. if($url =~ /^https:\/\//i) {
  299. report "Falling back to HTTP";
  300. $url =~ s/^https:\/\//http:\/\//i;
  301. }
  302. if(!$opt_k) {
  303. report "URLs other than HTTPS are disabled by default, to enable use -k";
  304. exit 1;
  305. }
  306. report "Get certdata with LWP!";
  307. if(!defined(${LWP::UserAgent::VERSION})) {
  308. report "LWP is not available (LWP::UserAgent not found)";
  309. exit 1;
  310. }
  311. my $ua = new LWP::UserAgent(agent => "$0/$version");
  312. $ua->env_proxy();
  313. $resp = $ua->mirror($url, $txt);
  314. if($resp && $resp->code eq '304') {
  315. report "Not modified";
  316. exit 0 if -e $crt && !$opt_f;
  317. }
  318. else {
  319. $fetched = 1;
  320. report "Downloaded $txt";
  321. }
  322. if(!$resp || $resp->code !~ /^(?:200|304)$/) {
  323. report "Unable to download latest data: "
  324. . ($resp? $resp->code . ' - ' . $resp->message : "LWP failed");
  325. exit 1 if -e $crt || ! -r $txt;
  326. }
  327. }
  328. }
  329. my $filedate = $resp ? $resp->last_modified : (stat($txt))[9];
  330. my $datesrc = "as of";
  331. if(!$filedate) {
  332. # mxr.mozilla.org gave us a time, hg.mozilla.org does not!
  333. $filedate = time();
  334. $datesrc="downloaded on";
  335. }
  336. # get the hash from the download file
  337. my $newhash= sha256($txt);
  338. if(!$opt_f && $oldhash eq $newhash) {
  339. report "Downloaded file identical to previous run\'s source file. Exiting";
  340. if($opt_u && -e $txt && !unlink($txt)) {
  341. report "Failed to remove $txt: $!\n";
  342. }
  343. exit;
  344. }
  345. report "SHA256 of new file: $newhash";
  346. my $currentdate = scalar gmtime($filedate);
  347. my $format = $opt_t ? "plain text and " : "";
  348. if( $stdout ) {
  349. open(CRT, '> -') or die "Couldn't open STDOUT: $!\n";
  350. } else {
  351. open(CRT,">$crt.~") or die "Couldn't open $crt.~: $!\n";
  352. }
  353. print CRT <<EOT;
  354. ##
  355. ## Bundle of CA Root Certificates
  356. ##
  357. ## Certificate data from Mozilla ${datesrc}: ${currentdate} GMT
  358. ##
  359. ## This is a bundle of X.509 certificates of public Certificate Authorities
  360. ## (CA). These were automatically extracted from Mozilla's root certificates
  361. ## file (certdata.txt). This file can be found in the mozilla source tree:
  362. ## ${url}
  363. ##
  364. ## It contains the certificates in ${format}PEM format and therefore
  365. ## can be directly used with curl / libcurl / php_curl, or with
  366. ## an Apache+mod_ssl webserver for SSL client authentication.
  367. ## Just configure this file as the SSLCACertificateFile.
  368. ##
  369. ## Conversion done with mk-ca-bundle.pl version $version.
  370. ## SHA256: $newhash
  371. ##
  372. EOT
  373. report "Processing '$txt' ...";
  374. my $caname;
  375. my $certnum = 0;
  376. my $skipnum = 0;
  377. my $start_of_cert = 0;
  378. my $main_block = 0;
  379. my $main_block_name;
  380. my $trust_block = 0;
  381. my $trust_block_name;
  382. my @precert;
  383. my $cka_value;
  384. my $valid = 0;
  385. open(TXT,"$txt") or die "Couldn't open $txt: $!\n";
  386. while (<TXT>) {
  387. if (/\*\*\*\*\* BEGIN LICENSE BLOCK \*\*\*\*\*/) {
  388. print CRT;
  389. print if ($opt_l);
  390. while (<TXT>) {
  391. print CRT;
  392. print if ($opt_l);
  393. last if (/\*\*\*\*\* END LICENSE BLOCK \*\*\*\*\*/);
  394. }
  395. next;
  396. }
  397. # The input file format consists of blocks of Mozilla objects.
  398. # The blocks are separated by blank lines but may be related.
  399. elsif(/^\s*$/) {
  400. $main_block = 0;
  401. $trust_block = 0;
  402. next;
  403. }
  404. # Each certificate has a main block.
  405. elsif(/^# Certificate "(.*)"/) {
  406. (!$main_block && !$trust_block) or die "Unexpected certificate block";
  407. $main_block = 1;
  408. $main_block_name = $1;
  409. # Reset all other certificate variables.
  410. $trust_block = 0;
  411. $trust_block_name = "";
  412. $valid = 0;
  413. $start_of_cert = 0;
  414. $caname = "";
  415. $cka_value = "";
  416. undef @precert;
  417. next;
  418. }
  419. # Each certificate's main block is followed by a trust block.
  420. elsif(/^# Trust for (?:Certificate )?"(.*)"/) {
  421. (!$main_block && !$trust_block) or die "Unexpected trust block";
  422. $trust_block = 1;
  423. $trust_block_name = $1;
  424. if($main_block_name ne $trust_block_name) {
  425. die "cert name \"$main_block_name\" != trust name \"$trust_block_name\"";
  426. }
  427. next;
  428. }
  429. # Ignore other blocks.
  430. #
  431. # There is a documentation comment block, a BEGINDATA block, and a bunch of
  432. # blocks starting with "# Explicitly Distrust <certname>".
  433. #
  434. # The latter is for certificates that have already been removed and are not
  435. # included. Not all explicitly distrusted certificates are ignored at this
  436. # point, just those without an actual certificate.
  437. elsif(!$main_block && !$trust_block) {
  438. next;
  439. }
  440. elsif(/^#/) {
  441. # The commented lines in a main block are plaintext metadata that describes
  442. # the certificate. Issuer, Subject, Fingerprint, etc.
  443. if($main_block) {
  444. push @precert, $_ if not /^#$/;
  445. if(/^# Not Valid After : (.*)/) {
  446. my $stamp = $1;
  447. use Time::Piece;
  448. # Not Valid After : Thu Sep 30 14:01:15 2021
  449. my $t = Time::Piece->strptime($stamp, "%a %b %d %H:%M:%S %Y");
  450. my $delta = ($t->epoch - time()); # negative means no longer valid
  451. if($delta < 0) {
  452. $skipnum++;
  453. report "Skipping: $main_block_name is not valid anymore" if ($opt_v);
  454. $valid = 0;
  455. }
  456. else {
  457. $valid = 1;
  458. }
  459. }
  460. }
  461. next;
  462. }
  463. elsif(!$valid) {
  464. next;
  465. }
  466. chomp;
  467. if($main_block) {
  468. if(/^CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE/) {
  469. !$start_of_cert or die "Duplicate CKO_CERTIFICATE object";
  470. $start_of_cert = 1;
  471. next;
  472. }
  473. elsif(!$start_of_cert) {
  474. next;
  475. }
  476. elsif(/^CKA_LABEL UTF8 \"(.*)\"/) {
  477. ($caname eq "") or die "Duplicate CKA_LABEL attribute";
  478. $caname = $1;
  479. if($caname ne $main_block_name) {
  480. die "caname \"$caname\" != cert name \"$main_block_name\"";
  481. }
  482. next;
  483. }
  484. elsif(/^CKA_VALUE MULTILINE_OCTAL/) {
  485. ($cka_value eq "") or die "Duplicate CKA_VALUE attribute";
  486. while (<TXT>) {
  487. last if (/^END/);
  488. chomp;
  489. my @octets = split(/\\/);
  490. shift @octets;
  491. for (@octets) {
  492. $cka_value .= chr(oct);
  493. }
  494. }
  495. next;
  496. }
  497. elsif (/^CKA_NSS_SERVER_DISTRUST_AFTER (CK_BBOOL CK_FALSE|MULTILINE_OCTAL)/) {
  498. # Example:
  499. # CKA_NSS_SERVER_DISTRUST_AFTER MULTILINE_OCTAL
  500. # \062\060\060\066\061\067\060\060\060\060\060\060\132
  501. # END
  502. if($1 eq "MULTILINE_OCTAL") {
  503. my @timestamp;
  504. while (<TXT>) {
  505. last if (/^END/);
  506. chomp;
  507. my @octets = split(/\\/);
  508. shift @octets;
  509. for (@octets) {
  510. push @timestamp, chr(oct);
  511. }
  512. }
  513. scalar(@timestamp) == 13 or die "Failed parsing timestamp";
  514. # A trailing Z in the timestamp signifies UTC
  515. if($timestamp[12] ne "Z") {
  516. report "distrust date stamp is not using UTC";
  517. }
  518. # Example date: 200617000000Z
  519. # Means 2020-06-17 00:00:00 UTC
  520. my $distrustat =
  521. timegm($timestamp[10] . $timestamp[11], # second
  522. $timestamp[8] . $timestamp[9], # minute
  523. $timestamp[6] . $timestamp[7], # hour
  524. $timestamp[4] . $timestamp[5], # day
  525. ($timestamp[2] . $timestamp[3]) - 1, # month
  526. "20" . $timestamp[0] . $timestamp[1]); # year
  527. if(time >= $distrustat) {
  528. # not trusted anymore
  529. $skipnum++;
  530. report "Skipping: $main_block_name is not trusted anymore" if ($opt_v);
  531. $valid = 0;
  532. }
  533. else {
  534. # still trusted
  535. }
  536. }
  537. next;
  538. }
  539. else {
  540. next;
  541. }
  542. }
  543. if(!$trust_block || !$start_of_cert || $caname eq "" || $cka_value eq "") {
  544. die "Certificate extraction failed";
  545. }
  546. my %trust_purposes_by_level;
  547. if(/^CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST/) {
  548. # now scan the trust part to determine how we should trust this cert
  549. while (<TXT>) {
  550. if(/^\s*$/) {
  551. $trust_block = 0;
  552. last;
  553. }
  554. if (/^CKA_TRUST_([A-Z_]+)\s+CK_TRUST\s+CKT_NSS_([A-Z_]+)\s*$/) {
  555. if ( !is_in_list($1,@valid_mozilla_trust_purposes) ) {
  556. report "Warning: Unrecognized trust purpose for cert: $caname. Trust purpose: $1. Trust Level: $2";
  557. } elsif ( !is_in_list($2,@valid_mozilla_trust_levels) ) {
  558. report "Warning: Unrecognized trust level for cert: $caname. Trust purpose: $1. Trust Level: $2";
  559. } else {
  560. push @{$trust_purposes_by_level{$2}}, $1;
  561. }
  562. }
  563. }
  564. # Sanity check that an explicitly distrusted certificate only has trust
  565. # purposes with a trust level of NOT_TRUSTED.
  566. #
  567. # Certificate objects that are explicitly distrusted are in a certificate
  568. # block that starts # Certificate "Explicitly Distrust(ed) <certname>",
  569. # where "Explicitly Distrust(ed) " was prepended to the original cert name.
  570. if($caname =~ /distrust/i ||
  571. $main_block_name =~ /distrust/i ||
  572. $trust_block_name =~ /distrust/i) {
  573. my @levels = keys %trust_purposes_by_level;
  574. if(scalar(@levels) != 1 || $levels[0] ne "NOT_TRUSTED") {
  575. die "\"$caname\" must have all trust purposes at level NOT_TRUSTED.";
  576. }
  577. }
  578. if ( !should_output_cert(%trust_purposes_by_level) ) {
  579. $skipnum ++;
  580. report "Skipping: $caname lacks acceptable trust level" if ($opt_v);
  581. } else {
  582. my $encoded = MIME::Base64::encode_base64($cka_value, '');
  583. $encoded =~ s/(.{1,${opt_w}})/$1\n/g;
  584. my $pem = "-----BEGIN CERTIFICATE-----\n"
  585. . $encoded
  586. . "-----END CERTIFICATE-----\n";
  587. print CRT "\n$caname\n";
  588. my $maxStringLength = length(decode('UTF-8', $caname, Encode::FB_CROAK | Encode::LEAVE_SRC));
  589. print CRT ("=" x $maxStringLength . "\n");
  590. if ($opt_t) {
  591. foreach my $key (sort keys %trust_purposes_by_level) {
  592. my $string = $key . ": " . join(", ", @{$trust_purposes_by_level{$key}});
  593. print CRT $string . "\n";
  594. }
  595. }
  596. if($opt_m) {
  597. print CRT for @precert;
  598. }
  599. if (!$opt_t) {
  600. print CRT $pem;
  601. } else {
  602. my $pipe = "";
  603. foreach my $hash (@included_signature_algorithms) {
  604. $pipe = "|$openssl x509 -" . $hash . " -fingerprint -noout -inform PEM";
  605. if (!$stdout) {
  606. $pipe .= " >> $crt.~";
  607. close(CRT) or die "Couldn't close $crt.~: $!";
  608. }
  609. open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
  610. print TMP $pem;
  611. close(TMP) or die "Couldn't close openssl pipe: $!";
  612. if (!$stdout) {
  613. open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
  614. }
  615. }
  616. $pipe = "|$openssl x509 -text -inform PEM";
  617. if (!$stdout) {
  618. $pipe .= " >> $crt.~";
  619. close(CRT) or die "Couldn't close $crt.~: $!";
  620. }
  621. open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
  622. print TMP $pem;
  623. close(TMP) or die "Couldn't close openssl pipe: $!";
  624. if (!$stdout) {
  625. open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
  626. }
  627. }
  628. report "Processed: $caname" if ($opt_v);
  629. $certnum ++;
  630. }
  631. }
  632. }
  633. close(TXT) or die "Couldn't close $txt: $!\n";
  634. close(CRT) or die "Couldn't close $crt.~: $!\n";
  635. unless( $stdout ) {
  636. if ($opt_b && -e $crt) {
  637. my $bk = 1;
  638. while (-e "$crt.~${bk}~") {
  639. $bk++;
  640. }
  641. rename $crt, "$crt.~${bk}~" or die "Failed to create backup $crt.~$bk}~: $!\n";
  642. } elsif( -e $crt ) {
  643. unlink( $crt ) or die "Failed to remove $crt: $!\n";
  644. }
  645. rename "$crt.~", $crt or die "Failed to rename $crt.~ to $crt: $!\n";
  646. }
  647. if($opt_u && -e $txt && !unlink($txt)) {
  648. report "Failed to remove $txt: $!\n";
  649. }
  650. report "Done ($certnum CA certs processed, $skipnum skipped).";