Revert "Update to 7.40.1"
[platform/upstream/curl.git] / lib / mk-ca-bundle.pl
1 #!/usr/bin/perl -w
2 # ***************************************************************************
3 # *                                  _   _ ____  _
4 # *  Project                     ___| | | |  _ \| |
5 # *                             / __| | | | |_) | |
6 # *                            | (__| |_| |  _ <| |___
7 # *                             \___|\___/|_| \_\_____|
8 # *
9 # * Copyright (C) 1998 - 2014, 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 http://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 Getopt::Std;
34 use MIME::Base64;
35 use LWP::UserAgent;
36 use strict;
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);
38 use List::Util;
39 use Text::Wrap;
40
41 my %urls = (
42   'nss' =>
43     'http://mxr.mozilla.org/nss/source/lib/ckfw/builtins/certdata.txt?raw=1',
44   'central' =>
45     'http://mxr.mozilla.org/mozilla-central/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
46   'aurora' =>
47     'http://mxr.mozilla.org/mozilla-aurora/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
48   'beta' =>
49     'http://mxr.mozilla.org/mozilla-beta/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
50   'release' =>
51     'http://mxr.mozilla.org/mozilla-release/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
52   'mozilla' =>
53     'http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1'
54 );
55
56 $opt_d = 'release';
57
58 # If the OpenSSL commandline is not in search path you can configure it here!
59 my $openssl = 'openssl';
60
61 my $version = '1.21';
62
63 $opt_w = 76; # default base64 encoded lines length
64
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;
69
70 my @valid_mozilla_trust_purposes = (
71   "DIGITAL_SIGNATURE",
72   "NON_REPUDIATION",
73   "KEY_ENCIPHERMENT",
74   "DATA_ENCIPHERMENT",
75   "KEY_AGREEMENT",
76   "KEY_CERT_SIGN",
77   "CRL_SIGN",
78   "SERVER_AUTH",
79   "CLIENT_AUTH",
80   "CODE_SIGNING",
81   "EMAIL_PROTECTION",
82   "IPSEC_END_SYSTEM",
83   "IPSEC_TUNNEL",
84   "IPSEC_USER",
85   "TIME_STAMPING",
86   "STEP_UP_APPROVED"
87 );
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 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).
94 );
95
96 my $default_signature_algorithms = $opt_s = "MD5";
97
98 my @valid_signature_algorithms = (
99   "MD5",
100   "SHA1",
101   "SHA256",
102   "SHA512"  
103 );
104
105 $0 =~ s@.*(/|\\)@@;
106 $Getopt::Std::STANDARD_HELP_VERSION = 1;
107 getopts('bd:fhilnp:qs:tuvw:');
108
109 if(!defined($opt_d)) {
110     # to make plain "-d" use not cause warnings, and actually still work
111     $opt_d = 'release';
112 }
113
114 # Use predefined URL or else custom URL specified on command line.
115 my $url = ( defined( $urls{$opt_d} ) ) ? $urls{$opt_d} : $opt_d;
116
117 if ($opt_i) {
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");
127 }
128
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";
132         print "\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";
140     exit;
141   } else { # Short Form Warning
142     print "Warning: Use of this script may pose some risk, -d risk for more details.\n";
143   }
144 }
145
146 sub HELP_MESSAGE() {
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";
169   exit;
170 }
171
172 sub VERSION_MESSAGE() {
173   print "${0} version ${version} running Perl ${]} on ${^O}\n";
174 }
175
176 WARNING_MESSAGE() unless ($opt_q || $url =~ m/^(ht|f)tps:/i );
177 HELP_MESSAGE() if ($opt_h);
178
179 sub IS_IN_LIST($@) {
180   my $target = shift;
181
182   return defined(List::Util::first { $target eq $_ } @_);
183 }
184
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 = @_;
191
192   my @values = map {
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 );
197
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;
200
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   
207   @values = @valid_values if ( IS_IN_LIST("ALL",@values) );
208   
209   return @values;
210 }
211
212 if ( $opt_p !~ m/:/ ) {
213   print "Error: Mozilla trust identifier list must include both purposes and levels\n";
214   HELP_MESSAGE();
215 }
216
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 );
220
221 my @included_signature_algorithms = PARSE_CSV_PARAM( "signature algorithm", $opt_s, @valid_signature_algorithms );
222
223 sub SHOULD_OUTPUT_CERT(%) {
224   my %trust_purposes_by_level = @_;
225   
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}} ) );
229   }
230   
231   return 0;
232 }
233
234 my $crt = $ARGV[0] || 'ca-bundle.crt';
235 (my $txt = $url) =~ s@(.*/|\?.*)@@g;
236
237 my $stdout = $crt eq '-';
238 my $resp;
239 my $fetched;
240
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");
244   $ua->env_proxy();
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;
249   } else {
250       $fetched = 1;
251   }
252   if( !$resp || $resp->code !~ /^(?:200|304)$/ ) {
253       print STDERR "Unable to download latest data: "
254         . ($resp? $resp->code . ' - ' . $resp->message : "LWP failed") . "\n"
255         unless $opt_q;
256       exit 1 if -e $crt || ! -r $txt;
257   }
258 }
259
260 my $currentdate = scalar gmtime($fetched ? $resp->last_modified : (stat($txt))[9]);
261
262 my $format = $opt_t ? "plain text and " : "";
263 if( $stdout ) {
264     open(CRT, '> -') or die "Couldn't open STDOUT: $!\n";
265 } else {
266     open(CRT,">$crt.~") or die "Couldn't open $crt.~: $!\n";
267 }
268 print CRT <<EOT;
269 ##
270 ## $crt -- Bundle of CA Root Certificates
271 ##
272 ## Certificate data from Mozilla as of: ${currentdate}
273 ##
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:
277 ## ${url}
278 ##
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.
283 ##
284
285 EOT
286
287 print STDERR "Processing  '$txt' ...\n" if (!$opt_q);
288 my $caname;
289 my $certnum = 0;
290 my $skipnum = 0;
291 my $start_of_cert = 0;
292
293 open(TXT,"$txt") or die "Couldn't open $txt: $!\n";
294 while (<TXT>) {
295   if (/\*\*\*\*\* BEGIN LICENSE BLOCK \*\*\*\*\*/) {
296     print CRT;
297     print if ($opt_l);
298     while (<TXT>) {
299       print CRT;
300       print if ($opt_l);
301       last if (/\*\*\*\*\* END LICENSE BLOCK \*\*\*\*\*/);
302     }
303   }
304   next if /^#|^\s*$/;
305   chomp;
306   if (/^CVS_ID\s+\"(.*)\"/) {
307     print CRT "# $1\n";
308   }
309
310   # this is a match for the start of a certificate
311   if (/^CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE/) {
312     $start_of_cert = 1
313   }
314   if ($start_of_cert && /^CKA_LABEL UTF8 \"(.*)\"/) {
315     $caname = $1;
316   }
317   my %trust_purposes_by_level;
318   if ($start_of_cert && /^CKA_VALUE MULTILINE_OCTAL/) {
319     my $data;
320     while (<TXT>) {
321       last if (/^END/);
322       chomp;
323       my @octets = split(/\\/);
324       shift @octets;
325       for (@octets) {
326         $data .= chr(oct);
327       }
328     }
329     # scan forwards until the trust part
330     while (<TXT>) {
331       last if (/^CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST/);
332       chomp;
333     }
334     # now scan the trust part to determine how we should trust this cert
335     while (<TXT>) {
336       last if (/^#/);
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);
342         } else {
343           push @{$trust_purposes_by_level{$2}}, $1;
344         }
345       }
346     }
347
348     if ( !SHOULD_OUTPUT_CERT(%trust_purposes_by_level) ) {
349       $skipnum ++;
350     } else {
351       my $encoded = MIME::Base64::encode_base64($data, '');
352       $encoded =~ s/(.{1,${opt_w}})/$1\n/g;
353       my $pem = "-----BEGIN CERTIFICATE-----\n"
354               . $encoded
355               . "-----END CERTIFICATE-----\n";
356       print CRT "\n$caname\n";
357
358       my $maxStringLength = length($caname);
359       if ($opt_t) {
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";
364         }
365       }
366       print CRT ("=" x $maxStringLength . "\n");
367       if (!$opt_t) {
368         print CRT $pem;
369       } else {
370         my $pipe = "";
371         foreach my $hash (@included_signature_algorithms) {
372           $pipe = "|$openssl x509 -" . $hash . " -fingerprint -noout -inform PEM";
373           if (!$stdout) {
374             $pipe .= " >> $crt.~";
375             close(CRT) or die "Couldn't close $crt.~: $!";
376           }
377           open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
378           print TMP $pem;
379           close(TMP) or die "Couldn't close openssl pipe: $!";
380           if (!$stdout) {
381             open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
382           }
383         }
384         $pipe = "|$openssl x509 -text -inform PEM";
385         if (!$stdout) {
386           $pipe .= " >> $crt.~";
387           close(CRT) or die "Couldn't close $crt.~: $!";
388         }
389         open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
390         print TMP $pem;
391         close(TMP) or die "Couldn't close openssl pipe: $!";
392         if (!$stdout) {
393           open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
394         }
395       }
396       print STDERR "Parsing: $caname\n" if ($opt_v);
397       $certnum ++;
398       $start_of_cert = 0;
399     }
400   }
401 }
402 close(TXT) or die "Couldn't close $txt: $!\n";
403 close(CRT) or die "Couldn't close $crt.~: $!\n";
404 unless( $stdout ) {
405     if ($opt_b && -e $crt) {
406         my $bk = 1;
407         while (-e "$crt.~${bk}~") {
408             $bk++;
409         }
410         rename $crt, "$crt.~${bk}~" or die "Failed to create backup $crt.~$bk}~: $!\n";
411     } elsif( -e $crt ) {
412         unlink( $crt ) or die "Failed to remove $crt: $!\n";
413     }
414     rename "$crt.~", $crt or die "Failed to rename $crt.~ to $crt: $!\n";
415 }
416 unlink $txt if ($opt_u);
417 print STDERR "Done ($certnum CA certs processed, $skipnum skipped).\n" if (!$opt_q);
418
419 exit;
420
421