2
0

mk-ca-bundle.pl 24 KB

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