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