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