mk-ca-bundle.pl 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  1. #!/usr/bin/perl -w
  2. # ***************************************************************************
  3. # * _ _ ____ _
  4. # * Project ___| | | | _ \| |
  5. # * / __| | | | |_) | |
  6. # * | (__| |_| | _ <| |___
  7. # * \___|\___/|_| \_\_____|
  8. # *
  9. # * Copyright (C) 1998 - 2016, Daniel Stenberg, <[email protected]>, 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 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);
  38. use List::Util;
  39. use Text::Wrap;
  40. my $MOD_SHA = "Digest::SHA";
  41. eval "require $MOD_SHA";
  42. if ($@) {
  43. $MOD_SHA = "Digest::SHA::PurePerl";
  44. eval "require $MOD_SHA";
  45. }
  46. eval "require LWP::UserAgent";
  47. my %urls = (
  48. 'nss' =>
  49. 'https://hg.mozilla.org/projects/nss/raw-file/tip/lib/ckfw/builtins/certdata.txt',
  50. 'central' =>
  51. 'https://hg.mozilla.org/mozilla-central/raw-file/default/security/nss/lib/ckfw/builtins/certdata.txt',
  52. 'aurora' =>
  53. 'https://hg.mozilla.org/releases/mozilla-aurora/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.27';
  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 "MIME::Base64.pm Version : ${MIME::Base64::VERSION}\n";
  126. print "LWP::UserAgent.pm Version : ${LWP::UserAgent::VERSION}\n" if($LWP::UserAgent::VERSION);
  127. print "LWP.pm Version : ${LWP::VERSION}\n" if($LWP::VERSION);
  128. print "Digest::SHA.pm Version : ${Digest::SHA::VERSION}\n" if ($Digest::SHA::VERSION);
  129. print "Digest::SHA::PurePerl.pm Version : ${Digest::SHA::PurePerl::VERSION}\n" if ($Digest::SHA::PurePerl::VERSION);
  130. print ("=" x 78 . "\n");
  131. }
  132. sub warning_message() {
  133. if ( $opt_d =~ m/^risk$/i ) { # Long Form Warning and Exit
  134. print "Warning: Use of this script may pose some risk:\n";
  135. print "\n";
  136. print " 1) If you use HTTP URLs they are subject to a man in the middle attack\n";
  137. print " 2) Default to 'release', but more recent updates may be found in other trees\n";
  138. print " 3) certdata.txt file format may change, lag time to update this script\n";
  139. print " 4) Generally unwise to blindly trust CAs without manual review & verification\n";
  140. print " 5) Mozilla apps use additional security checks aren't represented in certdata\n";
  141. print " 6) Use of this script will make a security engineer grind his teeth and\n";
  142. print " swear at you. ;)\n";
  143. exit;
  144. } else { # Short Form Warning
  145. print "Warning: Use of this script may pose some risk, -d risk for more details.\n";
  146. }
  147. }
  148. sub HELP_MESSAGE() {
  149. 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";
  150. print "\t-b\tbackup an existing version of ca-bundle.crt\n";
  151. print "\t-d\tspecify Mozilla tree to pull certdata.txt or custom URL\n";
  152. print "\t\t Valid names are:\n";
  153. print "\t\t ", join( ", ", map { ( $_ =~ m/$opt_d/ ) ? "$_ (default)" : "$_" } sort keys %urls ), "\n";
  154. print "\t-f\tforce rebuild even if certdata.txt is current\n";
  155. print "\t-i\tprint version info about used modules\n";
  156. print "\t-k\tallow URLs other than HTTPS, enable HTTP fallback (insecure)\n";
  157. print "\t-l\tprint license info about certdata.txt\n";
  158. print "\t-m\tinclude meta data in output\n";
  159. print "\t-n\tno download of certdata.txt (to use existing)\n";
  160. 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";
  161. print "\t\t Valid purposes are:\n";
  162. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_purposes ) ), "\n";
  163. print "\t\t Valid levels are:\n";
  164. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_levels ) ), "\n";
  165. print "\t-q\tbe really quiet (no progress output at all)\n";
  166. print wrap("\t","\t\t", "-s\tcomma separated list of certificate signatures/hashes to output in plain text mode. (default: $default_signature_algorithms)\n");
  167. print "\t\t Valid signature algorithms are:\n";
  168. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_signature_algorithms ) ), "\n";
  169. print "\t-t\tinclude plain text listing of certificates\n";
  170. print "\t-u\tunlink (remove) certdata.txt after processing\n";
  171. print "\t-v\tbe verbose and print out processed CAs\n";
  172. print "\t-w <l>\twrap base64 output lines after <l> chars (default: ${opt_w})\n";
  173. exit;
  174. }
  175. sub VERSION_MESSAGE() {
  176. print "${0} version ${version} running Perl ${]} on ${^O}\n";
  177. }
  178. warning_message() unless ($opt_q || $url =~ m/^(ht|f)tps:/i );
  179. HELP_MESSAGE() if ($opt_h);
  180. sub report($@) {
  181. my $output = shift;
  182. print STDERR $output . "\n" unless $opt_q;
  183. }
  184. sub is_in_list($@) {
  185. my $target = shift;
  186. return defined(List::Util::first { $target eq $_ } @_);
  187. }
  188. # Parses $param_string as a case insensitive comma separated list with optional whitespace
  189. # validates that only allowed parameters are supplied
  190. sub parse_csv_param($$@) {
  191. my $description = shift;
  192. my $param_string = shift;
  193. my @valid_values = @_;
  194. my @values = map {
  195. s/^\s+//; # strip leading spaces
  196. s/\s+$//; # strip trailing spaces
  197. uc $_ # return the modified string as upper case
  198. } split( ',', $param_string );
  199. # Find all values which are not in the list of valid values or "ALL"
  200. my @invalid = grep { !is_in_list($_,"ALL",@valid_values) } @values;
  201. if ( scalar(@invalid) > 0 ) {
  202. # Tell the user which parameters were invalid and print the standard help message which will exit
  203. print "Error: Invalid ", $description, scalar(@invalid) == 1 ? ": " : "s: ", join( ", ", map { "\"$_\"" } @invalid ), "\n";
  204. HELP_MESSAGE();
  205. }
  206. @values = @valid_values if ( is_in_list("ALL",@values) );
  207. return @values;
  208. }
  209. sub sha256 {
  210. my $result;
  211. if ($Digest::SHA::VERSION || $Digest::SHA::PurePerl::VERSION) {
  212. open(FILE, $_[0]) or die "Can't open '$_[0]': $!";
  213. binmode(FILE);
  214. $result = $MOD_SHA->new(256)->addfile(*FILE)->hexdigest;
  215. close(FILE);
  216. } else {
  217. # Use OpenSSL command if Perl Digest::SHA modules not available
  218. $result = `"$openssl" dgst -r -sha256 "$_[0]"`;
  219. $result =~ s/^([0-9a-f]{64}) .+/$1/is;
  220. }
  221. return $result;
  222. }
  223. sub oldhash {
  224. my $hash = "";
  225. open(C, "<$_[0]") || return 0;
  226. while(<C>) {
  227. chomp;
  228. if($_ =~ /^\#\# SHA256: (.*)/) {
  229. $hash = $1;
  230. last;
  231. }
  232. }
  233. close(C);
  234. return $hash;
  235. }
  236. if ( $opt_p !~ m/:/ ) {
  237. print "Error: Mozilla trust identifier list must include both purposes and levels\n";
  238. HELP_MESSAGE();
  239. }
  240. (my $included_mozilla_trust_purposes_string, my $included_mozilla_trust_levels_string) = split( ':', $opt_p );
  241. my @included_mozilla_trust_purposes = parse_csv_param( "trust purpose", $included_mozilla_trust_purposes_string, @valid_mozilla_trust_purposes );
  242. my @included_mozilla_trust_levels = parse_csv_param( "trust level", $included_mozilla_trust_levels_string, @valid_mozilla_trust_levels );
  243. my @included_signature_algorithms = parse_csv_param( "signature algorithm", $opt_s, @valid_signature_algorithms );
  244. sub should_output_cert(%) {
  245. my %trust_purposes_by_level = @_;
  246. foreach my $level (@included_mozilla_trust_levels) {
  247. # for each level we want to output, see if any of our desired purposes are included
  248. return 1 if ( defined( List::Util::first { is_in_list( $_, @included_mozilla_trust_purposes ) } @{$trust_purposes_by_level{$level}} ) );
  249. }
  250. return 0;
  251. }
  252. my $crt = $ARGV[0] || 'ca-bundle.crt';
  253. (my $txt = $url) =~ s@(.*/|\?.*)@@g;
  254. my $stdout = $crt eq '-';
  255. my $resp;
  256. my $fetched;
  257. my $oldhash = oldhash($crt);
  258. report "SHA256 of old file: $oldhash";
  259. if(!$opt_n) {
  260. report "Downloading $txt ...";
  261. # If we have an HTTPS URL then use curl
  262. if($url =~ /^https:\/\//i) {
  263. if($curl) {
  264. if($curl =~ /^Protocols:.* https( |$)/m) {
  265. report "Get certdata with curl!";
  266. my $proto = !$opt_k ? "--proto =https" : "";
  267. my $quiet = $opt_q ? "-s" : "";
  268. my @out = `curl -w %{response_code} $proto $quiet -o "$txt" "$url"`;
  269. if(@out && $out[0] == 200) {
  270. $fetched = 1;
  271. report "Downloaded $txt";
  272. }
  273. else {
  274. report "Failed downloading via HTTPS with curl";
  275. if(-e $txt && !unlink($txt)) {
  276. report "Failed to remove '$txt': $!";
  277. }
  278. }
  279. }
  280. else {
  281. report "curl lacks https support";
  282. }
  283. }
  284. else {
  285. report "curl not found";
  286. }
  287. }
  288. # If nothing was fetched then use LWP
  289. if(!$fetched) {
  290. if($url =~ /^https:\/\//i) {
  291. report "Falling back to HTTP";
  292. $url =~ s/^https:\/\//http:\/\//i;
  293. }
  294. if(!$opt_k) {
  295. report "URLs other than HTTPS are disabled by default, to enable use -k";
  296. exit 1;
  297. }
  298. report "Get certdata with LWP!";
  299. if(!defined(${LWP::UserAgent::VERSION})) {
  300. report "LWP is not available (LWP::UserAgent not found)";
  301. exit 1;
  302. }
  303. my $ua = new LWP::UserAgent(agent => "$0/$version");
  304. $ua->env_proxy();
  305. $resp = $ua->mirror($url, $txt);
  306. if($resp && $resp->code eq '304') {
  307. report "Not modified";
  308. exit 0 if -e $crt && !$opt_f;
  309. }
  310. else {
  311. $fetched = 1;
  312. report "Downloaded $txt";
  313. }
  314. if(!$resp || $resp->code !~ /^(?:200|304)$/) {
  315. report "Unable to download latest data: "
  316. . ($resp? $resp->code . ' - ' . $resp->message : "LWP failed");
  317. exit 1 if -e $crt || ! -r $txt;
  318. }
  319. }
  320. }
  321. my $filedate = $resp ? $resp->last_modified : (stat($txt))[9];
  322. my $datesrc = "as of";
  323. if(!$filedate) {
  324. # mxr.mozilla.org gave us a time, hg.mozilla.org does not!
  325. $filedate = time();
  326. $datesrc="downloaded on";
  327. }
  328. # get the hash from the download file
  329. my $newhash= sha256($txt);
  330. if(!$opt_f && $oldhash eq $newhash) {
  331. report "Downloaded file identical to previous run\'s source file. Exiting";
  332. exit;
  333. }
  334. report "SHA256 of new file: $newhash";
  335. my $currentdate = scalar gmtime($filedate);
  336. my $format = $opt_t ? "plain text and " : "";
  337. if( $stdout ) {
  338. open(CRT, '> -') or die "Couldn't open STDOUT: $!\n";
  339. } else {
  340. open(CRT,">$crt.~") or die "Couldn't open $crt.~: $!\n";
  341. }
  342. print CRT <<EOT;
  343. ##
  344. ## Bundle of CA Root Certificates
  345. ##
  346. ## Certificate data from Mozilla ${datesrc}: ${currentdate} GMT
  347. ##
  348. ## This is a bundle of X.509 certificates of public Certificate Authorities
  349. ## (CA). These were automatically extracted from Mozilla's root certificates
  350. ## file (certdata.txt). This file can be found in the mozilla source tree:
  351. ## ${url}
  352. ##
  353. ## It contains the certificates in ${format}PEM format and therefore
  354. ## can be directly used with curl / libcurl / php_curl, or with
  355. ## an Apache+mod_ssl webserver for SSL client authentication.
  356. ## Just configure this file as the SSLCACertificateFile.
  357. ##
  358. ## Conversion done with mk-ca-bundle.pl version $version.
  359. ## SHA256: $newhash
  360. ##
  361. EOT
  362. report "Processing '$txt' ...";
  363. my $caname;
  364. my $certnum = 0;
  365. my $skipnum = 0;
  366. my $start_of_cert = 0;
  367. my @precert;
  368. open(TXT,"$txt") or die "Couldn't open $txt: $!\n";
  369. while (<TXT>) {
  370. if (/\*\*\*\*\* BEGIN LICENSE BLOCK \*\*\*\*\*/) {
  371. print CRT;
  372. print if ($opt_l);
  373. while (<TXT>) {
  374. print CRT;
  375. print if ($opt_l);
  376. last if (/\*\*\*\*\* END LICENSE BLOCK \*\*\*\*\*/);
  377. }
  378. }
  379. elsif(/^# (Issuer|Serial Number|Subject|Not Valid Before|Not Valid After |Fingerprint \(MD5\)|Fingerprint \(SHA1\)):/) {
  380. push @precert, $_;
  381. next;
  382. }
  383. elsif(/^#|^\s*$/) {
  384. undef @precert;
  385. next;
  386. }
  387. chomp;
  388. # this is a match for the start of a certificate
  389. if (/^CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE/) {
  390. $start_of_cert = 1
  391. }
  392. if ($start_of_cert && /^CKA_LABEL UTF8 \"(.*)\"/) {
  393. $caname = $1;
  394. }
  395. my %trust_purposes_by_level;
  396. if ($start_of_cert && /^CKA_VALUE MULTILINE_OCTAL/) {
  397. my $data;
  398. while (<TXT>) {
  399. last if (/^END/);
  400. chomp;
  401. my @octets = split(/\\/);
  402. shift @octets;
  403. for (@octets) {
  404. $data .= chr(oct);
  405. }
  406. }
  407. # scan forwards until the trust part
  408. while (<TXT>) {
  409. last if (/^CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST/);
  410. chomp;
  411. }
  412. # now scan the trust part to determine how we should trust this cert
  413. while (<TXT>) {
  414. last if (/^#/);
  415. if (/^CKA_TRUST_([A-Z_]+)\s+CK_TRUST\s+CKT_NSS_([A-Z_]+)\s*$/) {
  416. if ( !is_in_list($1,@valid_mozilla_trust_purposes) ) {
  417. report "Warning: Unrecognized trust purpose for cert: $caname. Trust purpose: $1. Trust Level: $2";
  418. } elsif ( !is_in_list($2,@valid_mozilla_trust_levels) ) {
  419. report "Warning: Unrecognized trust level for cert: $caname. Trust purpose: $1. Trust Level: $2";
  420. } else {
  421. push @{$trust_purposes_by_level{$2}}, $1;
  422. }
  423. }
  424. }
  425. if ( !should_output_cert(%trust_purposes_by_level) ) {
  426. $skipnum ++;
  427. } else {
  428. my $encoded = MIME::Base64::encode_base64($data, '');
  429. $encoded =~ s/(.{1,${opt_w}})/$1\n/g;
  430. my $pem = "-----BEGIN CERTIFICATE-----\n"
  431. . $encoded
  432. . "-----END CERTIFICATE-----\n";
  433. print CRT "\n$caname\n";
  434. print CRT @precert if($opt_m);
  435. my $maxStringLength = length(decode('UTF-8', $caname, Encode::FB_CROAK));
  436. if ($opt_t) {
  437. foreach my $key (keys %trust_purposes_by_level) {
  438. my $string = $key . ": " . join(", ", @{$trust_purposes_by_level{$key}});
  439. $maxStringLength = List::Util::max( length($string), $maxStringLength );
  440. print CRT $string . "\n";
  441. }
  442. }
  443. print CRT ("=" x $maxStringLength . "\n");
  444. if (!$opt_t) {
  445. print CRT $pem;
  446. } else {
  447. my $pipe = "";
  448. foreach my $hash (@included_signature_algorithms) {
  449. $pipe = "|$openssl x509 -" . $hash . " -fingerprint -noout -inform PEM";
  450. if (!$stdout) {
  451. $pipe .= " >> $crt.~";
  452. close(CRT) or die "Couldn't close $crt.~: $!";
  453. }
  454. open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
  455. print TMP $pem;
  456. close(TMP) or die "Couldn't close openssl pipe: $!";
  457. if (!$stdout) {
  458. open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
  459. }
  460. }
  461. $pipe = "|$openssl x509 -text -inform PEM";
  462. if (!$stdout) {
  463. $pipe .= " >> $crt.~";
  464. close(CRT) or die "Couldn't close $crt.~: $!";
  465. }
  466. open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
  467. print TMP $pem;
  468. close(TMP) or die "Couldn't close openssl pipe: $!";
  469. if (!$stdout) {
  470. open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
  471. }
  472. }
  473. report "Parsing: $caname" if ($opt_v);
  474. $certnum ++;
  475. $start_of_cert = 0;
  476. }
  477. undef @precert;
  478. }
  479. }
  480. close(TXT) or die "Couldn't close $txt: $!\n";
  481. close(CRT) or die "Couldn't close $crt.~: $!\n";
  482. unless( $stdout ) {
  483. if ($opt_b && -e $crt) {
  484. my $bk = 1;
  485. while (-e "$crt.~${bk}~") {
  486. $bk++;
  487. }
  488. rename $crt, "$crt.~${bk}~" or die "Failed to create backup $crt.~$bk}~: $!\n";
  489. } elsif( -e $crt ) {
  490. unlink( $crt ) or die "Failed to remove $crt: $!\n";
  491. }
  492. rename "$crt.~", $crt or die "Failed to rename $crt.~ to $crt: $!\n";
  493. }
  494. if($opt_u && -e $txt && !unlink($txt)) {
  495. report "Failed to remove $txt: $!\n";
  496. }
  497. report "Done ($certnum CA certs processed, $skipnum skipped).";