2 # ***************************************************************************
4 # * Project ___| | | | _ \| |
5 # * / __| | | | |_) | |
6 # * | (__| |_| | _ <| |___
7 # * \___|\___/|_| \_\_____|
9 # * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
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 http://curl.haxx.se/docs/copyright.html.
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.
19 # * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
20 # * KIND, either express or implied.
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.
37 use vars qw($opt_b $opt_d $opt_f $opt_h $opt_i $opt_l $opt_n $opt_p $opt_q $opt_s $opt_t $opt_u $opt_v $opt_w);
43 'http://mxr.mozilla.org/nss/source/lib/ckfw/builtins/certdata.txt?raw=1',
45 'http://mxr.mozilla.org/mozilla-central/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
47 'http://mxr.mozilla.org/mozilla-aurora/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
49 'http://mxr.mozilla.org/mozilla-beta/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
51 'http://mxr.mozilla.org/mozilla-release/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
53 'http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1'
58 # If the OpenSSL commandline is not in search path you can configure it here!
59 my $openssl = 'openssl';
63 $opt_w = 76; # default base64 encoded lines length
65 # default cert types to include in the output (default is to include CAs which may issue SSL server certs)
66 my $default_mozilla_trust_purposes = "SERVER_AUTH";
67 my $default_mozilla_trust_levels = "TRUSTED_DELEGATOR";
68 $opt_p = $default_mozilla_trust_purposes . ":" . $default_mozilla_trust_levels;
70 my @valid_mozilla_trust_purposes = (
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 otherwise ok. In other words, this should tell the app to ignore any other sources that claim this is a CA.
93 "TRUSTED" # This cert is trusted, but only for itself and not for delegates (i.e. it is not a CA).
96 my $default_signature_algorithms = $opt_s = "MD5";
98 my @valid_signature_algorithms = (
106 $Getopt::Std::STANDARD_HELP_VERSION = 1;
107 getopts('bd:fhilnp:qs:tuvw:');
109 if(!defined($opt_d)) {
110 # to make plain "-d" use not cause warnings, and actually still work
114 # Use predefined URL or else custom URL specified on command line.
115 my $url = ( defined( $urls{$opt_d} ) ) ? $urls{$opt_d} : $opt_d;
118 print ("=" x 78 . "\n");
119 print "Script Version : $version\n";
120 print "Perl Version : $]\n";
121 print "Operating System Name : $^O\n";
122 print "Getopt::Std.pm Version : ${Getopt::Std::VERSION}\n";
123 print "MIME::Base64.pm Version : ${MIME::Base64::VERSION}\n";
124 print "LWP::UserAgent.pm Version : ${LWP::UserAgent::VERSION}\n";
125 print "LWP.pm Version : ${LWP::VERSION}\n";
126 print ("=" x 78 . "\n");
129 sub WARNING_MESSAGE() {
130 if ( $opt_d =~ m/^risk$/i ) { # Long Form Warning and Exit
131 print "Warning: Use of this script may pose some risk:\n";
133 print " 1) Using http is subject to man in the middle attack of certdata content\n";
134 print " 2) Default to 'release', but more recent updates may be found in other trees\n";
135 print " 3) certdata.txt file format may change, lag time to update this script\n";
136 print " 4) Generally unwise to blindly trust CAs without manual review & verification\n";
137 print " 5) Mozilla apps use additional security checks aren't represented in certdata\n";
138 print " 6) Use of this script will make a security engineer grind his teeth and\n";
139 print " swear at you. ;)\n";
141 } else { # Short Form Warning
142 print "Warning: Use of this script may pose some risk, -d risk for more details.\n";
147 print "Usage:\t${0} [-b] [-d<certdata>] [-f] [-i] [-l] [-n] [-p<purposes:levels>] [-q] [-s<algorithms>] [-t] [-u] [-v] [-w<l>] [<outputfile>]\n";
148 print "\t-b\tbackup an existing version of ca-bundle.crt\n";
149 print "\t-d\tspecify Mozilla tree to pull certdata.txt or custom URL\n";
150 print "\t\t Valid names are:\n";
151 print "\t\t ", join( ", ", map { ( $_ =~ m/$opt_d/ ) ? "$_ (default)" : "$_" } sort keys %urls ), "\n";
152 print "\t-f\tforce rebuild even if certdata.txt is current\n";
153 print "\t-i\tprint version info about used modules\n";
154 print "\t-l\tprint license info about certdata.txt\n";
155 print "\t-n\tno download of certdata.txt (to use existing)\n";
156 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";
157 print "\t\t Valid purposes are:\n";
158 print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_purposes ) ), "\n";
159 print "\t\t Valid levels are:\n";
160 print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_levels ) ), "\n";
161 print "\t-q\tbe really quiet (no progress output at all)\n";
162 print wrap("\t","\t\t", "-s\tcomma separated list of certificate signatures/hashes to output in plain text mode. (default: $default_signature_algorithms)\n");
163 print "\t\t Valid signature algorithms are:\n";
164 print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_signature_algorithms ) ), "\n";
165 print "\t-t\tinclude plain text listing of certificates\n";
166 print "\t-u\tunlink (remove) certdata.txt after processing\n";
167 print "\t-v\tbe verbose and print out processed CAs\n";
168 print "\t-w <l>\twrap base64 output lines after <l> chars (default: ${opt_w})\n";
172 sub VERSION_MESSAGE() {
173 print "${0} version ${version} running Perl ${]} on ${^O}\n";
176 WARNING_MESSAGE() unless ($opt_q || $url =~ m/^(ht|f)tps:/i );
177 HELP_MESSAGE() if ($opt_h);
182 return defined(List::Util::first { $target eq $_ } @_);
185 # Parses $param_string as a case insensitive comma separated list with optional whitespace
186 # validates that only allowed parameters are supplied
187 sub PARSE_CSV_PARAM($$@) {
188 my $description = shift;
189 my $param_string = shift;
190 my @valid_values = @_;
193 s/^\s+//; # strip leading spaces
194 s/\s+$//; # strip trailing spaces
195 uc $_ # return the modified string as upper case
196 } split( ',', $param_string );
198 # Find all values which are not in the list of valid values or "ALL"
199 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";
207 @values = @valid_values if ( IS_IN_LIST("ALL",@values) );
212 if ( $opt_p !~ m/:/ ) {
213 print "Error: Mozilla trust identifier list must include both purposes and levels\n";
217 (my $included_mozilla_trust_purposes_string, my $included_mozilla_trust_levels_string) = split( ':', $opt_p );
218 my @included_mozilla_trust_purposes = PARSE_CSV_PARAM( "trust purpose", $included_mozilla_trust_purposes_string, @valid_mozilla_trust_purposes );
219 my @included_mozilla_trust_levels = PARSE_CSV_PARAM( "trust level", $included_mozilla_trust_levels_string, @valid_mozilla_trust_levels );
221 my @included_signature_algorithms = PARSE_CSV_PARAM( "signature algorithm", $opt_s, @valid_signature_algorithms );
223 sub SHOULD_OUTPUT_CERT(%) {
224 my %trust_purposes_by_level = @_;
226 foreach my $level (@included_mozilla_trust_levels) {
227 # for each level we want to output, see if any of our desired purposes are included
228 return 1 if ( defined( List::Util::first { IS_IN_LIST( $_, @included_mozilla_trust_purposes ) } @{$trust_purposes_by_level{$level}} ) );
234 my $crt = $ARGV[0] || 'ca-bundle.crt';
235 (my $txt = $url) =~ s@(.*/|\?.*)@@g;
237 my $stdout = $crt eq '-';
241 unless ($opt_n and -e $txt) {
242 print STDERR "Downloading '$txt' ...\n" if (!$opt_q);
243 my $ua = new LWP::UserAgent(agent => "$0/$version");
245 $resp = $ua->mirror($url, $txt);
246 if ($resp && $resp->code eq '304') {
247 print STDERR "Not modified\n" unless $opt_q;
248 exit 0 if -e $crt && !$opt_f;
252 if( !$resp || $resp->code !~ /^(?:200|304)$/ ) {
253 print STDERR "Unable to download latest data: "
254 . ($resp? $resp->code . ' - ' . $resp->message : "LWP failed") . "\n"
256 exit 1 if -e $crt || ! -r $txt;
260 my $currentdate = scalar gmtime($fetched ? $resp->last_modified : (stat($txt))[9]);
262 my $format = $opt_t ? "plain text and " : "";
264 open(CRT, '> -') or die "Couldn't open STDOUT: $!\n";
266 open(CRT,">$crt.~") or die "Couldn't open $crt.~: $!\n";
270 ## $crt -- Bundle of CA Root Certificates
272 ## Certificate data from Mozilla as of: ${currentdate}
274 ## This is a bundle of X.509 certificates of public Certificate Authorities
275 ## (CA). These were automatically extracted from Mozilla's root certificates
276 ## file (certdata.txt). This file can be found in the mozilla source tree:
279 ## It contains the certificates in ${format}PEM format and therefore
280 ## can be directly used with curl / libcurl / php_curl, or with
281 ## an Apache+mod_ssl webserver for SSL client authentication.
282 ## Just configure this file as the SSLCACertificateFile.
287 print STDERR "Processing '$txt' ...\n" if (!$opt_q);
291 my $start_of_cert = 0;
293 open(TXT,"$txt") or die "Couldn't open $txt: $!\n";
295 if (/\*\*\*\*\* BEGIN LICENSE BLOCK \*\*\*\*\*/) {
301 last if (/\*\*\*\*\* END LICENSE BLOCK \*\*\*\*\*/);
306 if (/^CVS_ID\s+\"(.*)\"/) {
310 # this is a match for the start of a certificate
311 if (/^CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE/) {
314 if ($start_of_cert && /^CKA_LABEL UTF8 \"(.*)\"/) {
317 my %trust_purposes_by_level;
318 if ($start_of_cert && /^CKA_VALUE MULTILINE_OCTAL/) {
323 my @octets = split(/\\/);
329 # scan forwards until the trust part
331 last if (/^CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST/);
334 # now scan the trust part to determine how we should trust this cert
337 if (/^CKA_TRUST_([A-Z_]+)\s+CK_TRUST\s+CKT_NSS_([A-Z_]+)\s*$/) {
338 if ( !IS_IN_LIST($1,@valid_mozilla_trust_purposes) ) {
339 print STDERR "Warning: Unrecognized trust purpose for cert: $caname. Trust purpose: $1. Trust Level: $2\n" if (!$opt_q);
340 } elsif ( !IS_IN_LIST($2,@valid_mozilla_trust_levels) ) {
341 print STDERR "Warning: Unrecognized trust level for cert: $caname. Trust purpose: $1. Trust Level: $2\n" if (!$opt_q);
343 push @{$trust_purposes_by_level{$2}}, $1;
348 if ( !SHOULD_OUTPUT_CERT(%trust_purposes_by_level) ) {
351 my $encoded = MIME::Base64::encode_base64($data, '');
352 $encoded =~ s/(.{1,${opt_w}})/$1\n/g;
353 my $pem = "-----BEGIN CERTIFICATE-----\n"
355 . "-----END CERTIFICATE-----\n";
356 print CRT "\n$caname\n";
358 my $maxStringLength = length($caname);
360 foreach my $key (keys %trust_purposes_by_level) {
361 my $string = $key . ": " . join(", ", @{$trust_purposes_by_level{$key}});
362 $maxStringLength = List::Util::max( length($string), $maxStringLength );
363 print CRT $string . "\n";
366 print CRT ("=" x $maxStringLength . "\n");
371 foreach my $hash (@included_signature_algorithms) {
372 $pipe = "|$openssl x509 -" . $hash . " -fingerprint -noout -inform PEM";
374 $pipe .= " >> $crt.~";
375 close(CRT) or die "Couldn't close $crt.~: $!";
377 open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
379 close(TMP) or die "Couldn't close openssl pipe: $!";
381 open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
384 $pipe = "|$openssl x509 -text -inform PEM";
386 $pipe .= " >> $crt.~";
387 close(CRT) or die "Couldn't close $crt.~: $!";
389 open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
391 close(TMP) or die "Couldn't close openssl pipe: $!";
393 open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
396 print STDERR "Parsing: $caname\n" if ($opt_v);
402 close(TXT) or die "Couldn't close $txt: $!\n";
403 close(CRT) or die "Couldn't close $crt.~: $!\n";
405 if ($opt_b && -e $crt) {
407 while (-e "$crt.~${bk}~") {
410 rename $crt, "$crt.~${bk}~" or die "Failed to create backup $crt.~$bk}~: $!\n";
412 unlink( $crt ) or die "Failed to remove $crt: $!\n";
414 rename "$crt.~", $crt or die "Failed to rename $crt.~ to $crt: $!\n";
416 unlink $txt if ($opt_u);
417 print STDERR "Done ($certnum CA certs processed, $skipnum skipped).\n" if (!$opt_q);