mk-ca-bundle.pl 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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. if ($opt_i) {
  126. print ("=" x 78 . "\n");
  127. print "Script Version : $version\n";
  128. print "Perl Version : $]\n";
  129. print "Operating System Name : $^O\n";
  130. print "Getopt::Std.pm Version : ${Getopt::Std::VERSION}\n";
  131. print "Encode::Encoding.pm Version : ${Encode::Encoding::VERSION}\n";
  132. print "MIME::Base64.pm Version : ${MIME::Base64::VERSION}\n";
  133. print "LWP::UserAgent.pm Version : ${LWP::UserAgent::VERSION}\n" if($LWP::UserAgent::VERSION);
  134. print "LWP.pm Version : ${LWP::VERSION}\n" if($LWP::VERSION);
  135. print "Digest::SHA.pm Version : ${Digest::SHA::VERSION}\n" if ($Digest::SHA::VERSION);
  136. print "Digest::SHA::PurePerl.pm Version : ${Digest::SHA::PurePerl::VERSION}\n" if ($Digest::SHA::PurePerl::VERSION);
  137. print ("=" x 78 . "\n");
  138. }
  139. sub warning_message() {
  140. if ( $opt_d =~ m/^risk$/i ) { # Long Form Warning and Exit
  141. print "Warning: Use of this script may pose some risk:\n";
  142. print "\n";
  143. print " 1) If you use HTTP URLs they are subject to a man in the middle attack\n";
  144. print " 2) Default to 'release', but more recent updates may be found in other trees\n";
  145. print " 3) certdata.txt file format may change, lag time to update this script\n";
  146. print " 4) Generally unwise to blindly trust CAs without manual review & verification\n";
  147. print " 5) Mozilla apps use additional security checks aren't represented in certdata\n";
  148. print " 6) Use of this script will make a security engineer grind his teeth and\n";
  149. print " swear at you. ;)\n";
  150. exit;
  151. } else { # Short Form Warning
  152. print "Warning: Use of this script may pose some risk, -d risk for more details.\n";
  153. }
  154. }
  155. sub HELP_MESSAGE() {
  156. 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";
  157. print "\t-b\tbackup an existing version of ca-bundle.crt\n";
  158. print "\t-d\tspecify Mozilla tree to pull certdata.txt or custom URL\n";
  159. print "\t\t Valid names are:\n";
  160. print "\t\t ", join( ", ", map { ( $_ =~ m/$opt_d/ ) ? "$_ (default)" : "$_" } sort keys %urls ), "\n";
  161. print "\t-f\tforce rebuild even if certdata.txt is current\n";
  162. print "\t-i\tprint version info about used modules\n";
  163. print "\t-k\tallow URLs other than HTTPS, enable HTTP fallback (insecure)\n";
  164. print "\t-l\tprint license info about certdata.txt\n";
  165. print "\t-m\tinclude meta data in output\n";
  166. print "\t-n\tno download of certdata.txt (to use existing)\n";
  167. 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";
  168. print "\t\t Valid purposes are:\n";
  169. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_purposes ) ), "\n";
  170. print "\t\t Valid levels are:\n";
  171. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_levels ) ), "\n";
  172. print "\t-q\tbe really quiet (no progress output at all)\n";
  173. print wrap("\t","\t\t", "-s\tcomma separated list of certificate signatures/hashes to output in plain text mode. (default: $default_signature_algorithms)\n");
  174. print "\t\t Valid signature algorithms are:\n";
  175. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_signature_algorithms ) ), "\n";
  176. print "\t-t\tinclude plain text listing of certificates\n";
  177. print "\t-u\tunlink (remove) certdata.txt after processing\n";
  178. print "\t-v\tbe verbose and print out processed CAs\n";
  179. print "\t-w <l>\twrap base64 output lines after <l> chars (default: ${opt_w})\n";
  180. exit;
  181. }
  182. sub VERSION_MESSAGE() {
  183. print "${0} version ${version} running Perl ${]} on ${^O}\n";
  184. }
  185. warning_message() unless ($opt_q || $url =~ m/^(ht|f)tps:/i );
  186. HELP_MESSAGE() if ($opt_h);
  187. sub report($@) {
  188. my $output = shift;
  189. print STDERR $output . "\n" unless $opt_q;
  190. }
  191. sub is_in_list($@) {
  192. my $target = shift;
  193. return defined(List::Util::first { $target eq $_ } @_);
  194. }
  195. # Parses $param_string as a case insensitive comma separated list with optional
  196. # whitespace validates that only allowed parameters are supplied
  197. sub parse_csv_param($$@) {
  198. my $description = shift;
  199. my $param_string = shift;
  200. my @valid_values = @_;
  201. my @values = map {
  202. s/^\s+//; # strip leading spaces
  203. s/\s+$//; # strip trailing spaces
  204. uc $_ # return the modified string as upper case
  205. } split( ',', $param_string );
  206. # Find all values which are not in the list of valid values or "ALL"
  207. my @invalid = grep { !is_in_list($_,"ALL",@valid_values) } @values;
  208. if ( scalar(@invalid) > 0 ) {
  209. # Tell the user which parameters were invalid and print the standard help
  210. # message which will exit
  211. print "Error: Invalid ", $description, scalar(@invalid) == 1 ? ": " : "s: ", join( ", ", map { "\"$_\"" } @invalid ), "\n";
  212. HELP_MESSAGE();
  213. }
  214. @values = @valid_values if ( is_in_list("ALL",@values) );
  215. return @values;
  216. }
  217. sub sha256 {
  218. my $result;
  219. if ($Digest::SHA::VERSION || $Digest::SHA::PurePerl::VERSION) {
  220. open(FILE, $_[0]) or die "Can't open '$_[0]': $!";
  221. binmode(FILE);
  222. $result = $MOD_SHA->new(256)->addfile(*FILE)->hexdigest;
  223. close(FILE);
  224. } else {
  225. # Use OpenSSL command if Perl Digest::SHA modules not available
  226. $result = `"$openssl" dgst -r -sha256 "$_[0]"`;
  227. $result =~ s/^([0-9a-f]{64}) .+/$1/is;
  228. }
  229. return $result;
  230. }
  231. sub oldhash {
  232. my $hash = "";
  233. open(C, "<$_[0]") || return 0;
  234. while(<C>) {
  235. chomp;
  236. if($_ =~ /^\#\# SHA256: (.*)/) {
  237. $hash = $1;
  238. last;
  239. }
  240. }
  241. close(C);
  242. return $hash;
  243. }
  244. if ( $opt_p !~ m/:/ ) {
  245. print "Error: Mozilla trust identifier list must include both purposes and levels\n";
  246. HELP_MESSAGE();
  247. }
  248. (my $included_mozilla_trust_purposes_string, my $included_mozilla_trust_levels_string) = split( ':', $opt_p );
  249. my @included_mozilla_trust_purposes = parse_csv_param( "trust purpose", $included_mozilla_trust_purposes_string, @valid_mozilla_trust_purposes );
  250. my @included_mozilla_trust_levels = parse_csv_param( "trust level", $included_mozilla_trust_levels_string, @valid_mozilla_trust_levels );
  251. my @included_signature_algorithms = parse_csv_param( "signature algorithm", $opt_s, @valid_signature_algorithms );
  252. sub should_output_cert(%) {
  253. my %trust_purposes_by_level = @_;
  254. foreach my $level (@included_mozilla_trust_levels) {
  255. # for each level we want to output, see if any of our desired purposes are
  256. # included
  257. return 1 if ( defined( List::Util::first { is_in_list( $_, @included_mozilla_trust_purposes ) } @{$trust_purposes_by_level{$level}} ) );
  258. }
  259. return 0;
  260. }
  261. my $crt = $ARGV[0] || 'ca-bundle.crt';
  262. (my $txt = $url) =~ s@(.*/|\?.*)@@g;
  263. my $stdout = $crt eq '-';
  264. my $resp;
  265. my $fetched;
  266. my $oldhash = oldhash($crt);
  267. report "SHA256 of old file: $oldhash";
  268. if(!$opt_n) {
  269. report "Downloading $txt ...";
  270. # If we have an HTTPS URL then use curl
  271. if($url =~ /^https:\/\//i) {
  272. my $curl = `curl -V`;
  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. ## Find updated versions here: https://curl.se/docs/caextract.html
  362. ##
  363. ## This is a bundle of X.509 certificates of public Certificate Authorities
  364. ## (CA). These were automatically extracted from Mozilla's root certificates
  365. ## file (certdata.txt). This file can be found in the mozilla source tree:
  366. ## ${url}
  367. ##
  368. ## It contains the certificates in ${format}PEM format and therefore
  369. ## can be directly used with curl / libcurl / php_curl, or with
  370. ## an Apache+mod_ssl webserver for SSL client authentication.
  371. ## Just configure this file as the SSLCACertificateFile.
  372. ##
  373. ## Conversion done with mk-ca-bundle.pl version $version.
  374. ## SHA256: $newhash
  375. ##
  376. EOT
  377. report "Processing '$txt' ...";
  378. my $caname;
  379. my $certnum = 0;
  380. my $skipnum = 0;
  381. my $start_of_cert = 0;
  382. my $main_block = 0;
  383. my $main_block_name;
  384. my $trust_block = 0;
  385. my $trust_block_name;
  386. my @precert;
  387. my $cka_value;
  388. my $valid = 0;
  389. open(TXT,"$txt") or die "Couldn't open $txt: $!\n";
  390. while (<TXT>) {
  391. if (/\*\*\*\*\* BEGIN LICENSE BLOCK \*\*\*\*\*/) {
  392. print CRT;
  393. print if ($opt_l);
  394. while (<TXT>) {
  395. print CRT;
  396. print if ($opt_l);
  397. last if (/\*\*\*\*\* END LICENSE BLOCK \*\*\*\*\*/);
  398. }
  399. next;
  400. }
  401. # The input file format consists of blocks of Mozilla objects.
  402. # The blocks are separated by blank lines but may be related.
  403. elsif(/^\s*$/) {
  404. $main_block = 0;
  405. $trust_block = 0;
  406. next;
  407. }
  408. # Each certificate has a main block.
  409. elsif(/^# Certificate "(.*)"/) {
  410. (!$main_block && !$trust_block) or die "Unexpected certificate block";
  411. $main_block = 1;
  412. $main_block_name = $1;
  413. # Reset all other certificate variables.
  414. $trust_block = 0;
  415. $trust_block_name = "";
  416. $valid = 0;
  417. $start_of_cert = 0;
  418. $caname = "";
  419. $cka_value = "";
  420. undef @precert;
  421. next;
  422. }
  423. # Each certificate's main block is followed by a trust block.
  424. elsif(/^# Trust for (?:Certificate )?"(.*)"/) {
  425. (!$main_block && !$trust_block) or die "Unexpected trust block";
  426. $trust_block = 1;
  427. $trust_block_name = $1;
  428. if($main_block_name ne $trust_block_name) {
  429. die "cert name \"$main_block_name\" != trust name \"$trust_block_name\"";
  430. }
  431. next;
  432. }
  433. # Ignore other blocks.
  434. #
  435. # There is a documentation comment block, a BEGINDATA block, and a bunch of
  436. # blocks starting with "# Explicitly Distrust <certname>".
  437. #
  438. # The latter is for certificates that have already been removed and are not
  439. # included. Not all explicitly distrusted certificates are ignored at this
  440. # point, just those without an actual certificate.
  441. elsif(!$main_block && !$trust_block) {
  442. next;
  443. }
  444. elsif(/^#/) {
  445. # The commented lines in a main block are plaintext metadata that describes
  446. # the certificate. Issuer, Subject, Fingerprint, etc.
  447. if($main_block) {
  448. push @precert, $_ if not /^#$/;
  449. if(/^# Not Valid After : (.*)/) {
  450. my $stamp = $1;
  451. use Time::Piece;
  452. # Not Valid After : Thu Sep 30 14:01:15 2021
  453. my $t = Time::Piece->strptime($stamp, "%a %b %d %H:%M:%S %Y");
  454. my $delta = ($t->epoch - time()); # negative means no longer valid
  455. if($delta < 0) {
  456. $skipnum++;
  457. report "Skipping: $main_block_name is not valid anymore" if ($opt_v);
  458. $valid = 0;
  459. }
  460. else {
  461. $valid = 1;
  462. }
  463. }
  464. }
  465. next;
  466. }
  467. elsif(!$valid) {
  468. next;
  469. }
  470. chomp;
  471. if($main_block) {
  472. if(/^CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE/) {
  473. !$start_of_cert or die "Duplicate CKO_CERTIFICATE object";
  474. $start_of_cert = 1;
  475. next;
  476. }
  477. elsif(!$start_of_cert) {
  478. next;
  479. }
  480. elsif(/^CKA_LABEL UTF8 \"(.*)\"/) {
  481. ($caname eq "") or die "Duplicate CKA_LABEL attribute";
  482. $caname = $1;
  483. if($caname ne $main_block_name) {
  484. die "caname \"$caname\" != cert name \"$main_block_name\"";
  485. }
  486. next;
  487. }
  488. elsif(/^CKA_VALUE MULTILINE_OCTAL/) {
  489. ($cka_value eq "") or die "Duplicate CKA_VALUE attribute";
  490. while (<TXT>) {
  491. last if (/^END/);
  492. chomp;
  493. my @octets = split(/\\/);
  494. shift @octets;
  495. for (@octets) {
  496. $cka_value .= chr(oct);
  497. }
  498. }
  499. next;
  500. }
  501. elsif (/^CKA_NSS_SERVER_DISTRUST_AFTER (CK_BBOOL CK_FALSE|MULTILINE_OCTAL)/) {
  502. # Example:
  503. # CKA_NSS_SERVER_DISTRUST_AFTER MULTILINE_OCTAL
  504. # \062\060\060\066\061\067\060\060\060\060\060\060\132
  505. # END
  506. if($1 eq "MULTILINE_OCTAL") {
  507. my @timestamp;
  508. while (<TXT>) {
  509. last if (/^END/);
  510. chomp;
  511. my @octets = split(/\\/);
  512. shift @octets;
  513. for (@octets) {
  514. push @timestamp, chr(oct);
  515. }
  516. }
  517. scalar(@timestamp) == 13 or die "Failed parsing timestamp";
  518. # A trailing Z in the timestamp signifies UTC
  519. if($timestamp[12] ne "Z") {
  520. report "distrust date stamp is not using UTC";
  521. }
  522. # Example date: 200617000000Z
  523. # Means 2020-06-17 00:00:00 UTC
  524. my $distrustat =
  525. timegm($timestamp[10] . $timestamp[11], # second
  526. $timestamp[8] . $timestamp[9], # minute
  527. $timestamp[6] . $timestamp[7], # hour
  528. $timestamp[4] . $timestamp[5], # day
  529. ($timestamp[2] . $timestamp[3]) - 1, # month
  530. "20" . $timestamp[0] . $timestamp[1]); # year
  531. if(time >= $distrustat) {
  532. # not trusted anymore
  533. $skipnum++;
  534. report "Skipping: $main_block_name is not trusted anymore" if ($opt_v);
  535. $valid = 0;
  536. }
  537. else {
  538. # still trusted
  539. }
  540. }
  541. next;
  542. }
  543. else {
  544. next;
  545. }
  546. }
  547. if(!$trust_block || !$start_of_cert || $caname eq "" || $cka_value eq "") {
  548. die "Certificate extraction failed";
  549. }
  550. my %trust_purposes_by_level;
  551. if(/^CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST/) {
  552. # now scan the trust part to determine how we should trust this cert
  553. while (<TXT>) {
  554. if(/^\s*$/) {
  555. $trust_block = 0;
  556. last;
  557. }
  558. if (/^CKA_TRUST_([A-Z_]+)\s+CK_TRUST\s+CKT_NSS_([A-Z_]+)\s*$/) {
  559. if ( !is_in_list($1,@valid_mozilla_trust_purposes) ) {
  560. report "Warning: Unrecognized trust purpose for cert: $caname. Trust purpose: $1. Trust Level: $2";
  561. } elsif ( !is_in_list($2,@valid_mozilla_trust_levels) ) {
  562. report "Warning: Unrecognized trust level for cert: $caname. Trust purpose: $1. Trust Level: $2";
  563. } else {
  564. push @{$trust_purposes_by_level{$2}}, $1;
  565. }
  566. }
  567. }
  568. # Sanity check that an explicitly distrusted certificate only has trust
  569. # purposes with a trust level of NOT_TRUSTED.
  570. #
  571. # Certificate objects that are explicitly distrusted are in a certificate
  572. # block that starts # Certificate "Explicitly Distrust(ed) <certname>",
  573. # where "Explicitly Distrust(ed) " was prepended to the original cert name.
  574. if($caname =~ /distrust/i ||
  575. $main_block_name =~ /distrust/i ||
  576. $trust_block_name =~ /distrust/i) {
  577. my @levels = keys %trust_purposes_by_level;
  578. if(scalar(@levels) != 1 || $levels[0] ne "NOT_TRUSTED") {
  579. die "\"$caname\" must have all trust purposes at level NOT_TRUSTED.";
  580. }
  581. }
  582. if ( !should_output_cert(%trust_purposes_by_level) ) {
  583. $skipnum ++;
  584. report "Skipping: $caname lacks acceptable trust level" if ($opt_v);
  585. } else {
  586. my $encoded = MIME::Base64::encode_base64($cka_value, '');
  587. $encoded =~ s/(.{1,${opt_w}})/$1\n/g;
  588. my $pem = "-----BEGIN CERTIFICATE-----\n"
  589. . $encoded
  590. . "-----END CERTIFICATE-----\n";
  591. print CRT "\n$caname\n";
  592. my $maxStringLength = length(decode('UTF-8', $caname, Encode::FB_CROAK | Encode::LEAVE_SRC));
  593. print CRT ("=" x $maxStringLength . "\n");
  594. if ($opt_t) {
  595. foreach my $key (sort keys %trust_purposes_by_level) {
  596. my $string = $key . ": " . join(", ", @{$trust_purposes_by_level{$key}});
  597. print CRT $string . "\n";
  598. }
  599. }
  600. if($opt_m) {
  601. print CRT for @precert;
  602. }
  603. if (!$opt_t) {
  604. print CRT $pem;
  605. } else {
  606. my $pipe = "";
  607. foreach my $hash (@included_signature_algorithms) {
  608. $pipe = "|$openssl x509 -" . $hash . " -fingerprint -noout -inform PEM";
  609. if (!$stdout) {
  610. $pipe .= " >> $crt.~";
  611. close(CRT) or die "Couldn't close $crt.~: $!";
  612. }
  613. open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
  614. print TMP $pem;
  615. close(TMP) or die "Couldn't close openssl pipe: $!";
  616. if (!$stdout) {
  617. open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
  618. }
  619. }
  620. $pipe = "|$openssl x509 -text -inform PEM";
  621. if (!$stdout) {
  622. $pipe .= " >> $crt.~";
  623. close(CRT) or die "Couldn't close $crt.~: $!";
  624. }
  625. open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
  626. print TMP $pem;
  627. close(TMP) or die "Couldn't close openssl pipe: $!";
  628. if (!$stdout) {
  629. open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
  630. }
  631. }
  632. report "Processed: $caname" if ($opt_v);
  633. $certnum ++;
  634. }
  635. }
  636. }
  637. close(TXT) or die "Couldn't close $txt: $!\n";
  638. close(CRT) or die "Couldn't close $crt.~: $!\n";
  639. unless( $stdout ) {
  640. if ($opt_b && -e $crt) {
  641. my $bk = 1;
  642. while (-e "$crt.~${bk}~") {
  643. $bk++;
  644. }
  645. rename $crt, "$crt.~${bk}~" or die "Failed to create backup $crt.~$bk}~: $!\n";
  646. } elsif( -e $crt ) {
  647. unlink( $crt ) or die "Failed to remove $crt: $!\n";
  648. }
  649. rename "$crt.~", $crt or die "Failed to rename $crt.~ to $crt: $!\n";
  650. }
  651. if($opt_u && -e $txt && !unlink($txt)) {
  652. report "Failed to remove $txt: $!\n";
  653. }
  654. report "Done ($certnum CA certs processed, $skipnum skipped).";