mk-ca-bundle.pl 20 KB

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