mk-ca-bundle.pl 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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. my %urls = (
  41. 'nss' =>
  42. 'http://mxr.mozilla.org/nss/source/lib/ckfw/builtins/certdata.txt?raw=1',
  43. 'central' =>
  44. 'http://mxr.mozilla.org/mozilla-central/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
  45. 'aurora' =>
  46. 'http://mxr.mozilla.org/mozilla-aurora/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
  47. 'beta' =>
  48. 'http://mxr.mozilla.org/mozilla-beta/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
  49. 'release' =>
  50. 'http://mxr.mozilla.org/mozilla-release/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1',
  51. 'mozilla' =>
  52. 'http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt?raw=1'
  53. );
  54. $opt_d = 'release';
  55. # If the OpenSSL commandline is not in search path you can configure it here!
  56. my $openssl = 'openssl';
  57. my $version = '1.21';
  58. $opt_w = 76; # default base64 encoded lines length
  59. # default cert types to include in the output (default is to include CAs which may issue SSL server certs)
  60. my $default_mozilla_trust_purposes = "SERVER_AUTH";
  61. my $default_mozilla_trust_levels = "TRUSTED_DELEGATOR";
  62. $opt_p = $default_mozilla_trust_purposes . ":" . $default_mozilla_trust_levels;
  63. my @valid_mozilla_trust_purposes = (
  64. "DIGITAL_SIGNATURE",
  65. "NON_REPUDIATION",
  66. "KEY_ENCIPHERMENT",
  67. "DATA_ENCIPHERMENT",
  68. "KEY_AGREEMENT",
  69. "KEY_CERT_SIGN",
  70. "CRL_SIGN",
  71. "SERVER_AUTH",
  72. "CLIENT_AUTH",
  73. "CODE_SIGNING",
  74. "EMAIL_PROTECTION",
  75. "IPSEC_END_SYSTEM",
  76. "IPSEC_TUNNEL",
  77. "IPSEC_USER",
  78. "TIME_STAMPING",
  79. "STEP_UP_APPROVED"
  80. );
  81. my @valid_mozilla_trust_levels = (
  82. "TRUSTED_DELEGATOR", # CAs
  83. "NOT_TRUSTED", # Don't trust these certs.
  84. "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.
  85. "TRUSTED" # This cert is trusted, but only for itself and not for delegates (i.e. it is not a CA).
  86. );
  87. my $default_signature_algorithms = $opt_s = "MD5";
  88. my @valid_signature_algorithms = (
  89. "MD5",
  90. "SHA1",
  91. "SHA256",
  92. "SHA512"
  93. );
  94. $0 =~ s@.*(/|\\)@@;
  95. $Getopt::Std::STANDARD_HELP_VERSION = 1;
  96. getopts('bd:fhilnp:qs:tuvw:');
  97. if(!defined($opt_d)) {
  98. # to make plain "-d" use not cause warnings, and actually still work
  99. $opt_d = 'release';
  100. }
  101. # Use predefined URL or else custom URL specified on command line.
  102. my $url = ( defined( $urls{$opt_d} ) ) ? $urls{$opt_d} : $opt_d;
  103. if ($opt_i) {
  104. print ("=" x 78 . "\n");
  105. print "Script Version : $version\n";
  106. print "Perl Version : $]\n";
  107. print "Operating System Name : $^O\n";
  108. print "Getopt::Std.pm Version : ${Getopt::Std::VERSION}\n";
  109. print "MIME::Base64.pm Version : ${MIME::Base64::VERSION}\n";
  110. print "LWP::UserAgent.pm Version : ${LWP::UserAgent::VERSION}\n";
  111. print "LWP.pm Version : ${LWP::VERSION}\n";
  112. print ("=" x 78 . "\n");
  113. }
  114. sub WARNING_MESSAGE() {
  115. if ( $opt_d =~ m/^risk$/i ) { # Long Form Warning and Exit
  116. print "Warning: Use of this script may pose some risk:\n";
  117. print "\n";
  118. print " 1) Using http is subject to man in the middle attack of certdata content\n";
  119. print " 2) Default to 'release', but more recent updates may be found in other trees\n";
  120. print " 3) certdata.txt file format may change, lag time to update this script\n";
  121. print " 4) Generally unwise to blindly trust CAs without manual review & verification\n";
  122. print " 5) Mozilla apps use additional security checks aren't represented in certdata\n";
  123. print " 6) Use of this script will make a security engineer grind his teeth and\n";
  124. print " swear at you. ;)\n";
  125. exit;
  126. } else { # Short Form Warning
  127. print "Warning: Use of this script may pose some risk, -d risk for more details.\n";
  128. }
  129. }
  130. sub HELP_MESSAGE() {
  131. print "Usage:\t${0} [-b] [-d<certdata>] [-f] [-i] [-l] [-n] [-p<purposes:levels>] [-q] [-s<algorithms>] [-t] [-u] [-v] [-w<l>] [<outputfile>]\n";
  132. print "\t-b\tbackup an existing version of ca-bundle.crt\n";
  133. print "\t-d\tspecify Mozilla tree to pull certdata.txt or custom URL\n";
  134. print "\t\t Valid names are:\n";
  135. print "\t\t ", join( ", ", map { ( $_ =~ m/$opt_d/ ) ? "$_ (default)" : "$_" } sort keys %urls ), "\n";
  136. print "\t-f\tforce rebuild even if certdata.txt is current\n";
  137. print "\t-i\tprint version info about used modules\n";
  138. print "\t-l\tprint license info about certdata.txt\n";
  139. print "\t-n\tno download of certdata.txt (to use existing)\n";
  140. 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";
  141. print "\t\t Valid purposes are:\n";
  142. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_purposes ) ), "\n";
  143. print "\t\t Valid levels are:\n";
  144. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_mozilla_trust_levels ) ), "\n";
  145. print "\t-q\tbe really quiet (no progress output at all)\n";
  146. print wrap("\t","\t\t", "-s\tcomma separated list of certificate signatures/hashes to output in plain text mode. (default: $default_signature_algorithms)\n");
  147. print "\t\t Valid signature algorithms are:\n";
  148. print wrap("\t\t ","\t\t ", join( ", ", "ALL", @valid_signature_algorithms ) ), "\n";
  149. print "\t-t\tinclude plain text listing of certificates\n";
  150. print "\t-u\tunlink (remove) certdata.txt after processing\n";
  151. print "\t-v\tbe verbose and print out processed CAs\n";
  152. print "\t-w <l>\twrap base64 output lines after <l> chars (default: ${opt_w})\n";
  153. exit;
  154. }
  155. sub VERSION_MESSAGE() {
  156. print "${0} version ${version} running Perl ${]} on ${^O}\n";
  157. }
  158. WARNING_MESSAGE() unless ($opt_q || $url =~ m/^(ht|f)tps:/i );
  159. HELP_MESSAGE() if ($opt_h);
  160. sub IS_IN_LIST($@) {
  161. my $target = shift;
  162. return defined(List::Util::first { $target eq $_ } @_);
  163. }
  164. # Parses $param_string as a case insensitive comma separated list with optional whitespace
  165. # validates that only allowed parameters are supplied
  166. sub PARSE_CSV_PARAM($$@) {
  167. my $description = shift;
  168. my $param_string = shift;
  169. my @valid_values = @_;
  170. my @values = map {
  171. s/^\s+//; # strip leading spaces
  172. s/\s+$//; # strip trailing spaces
  173. uc $_ # return the modified string as upper case
  174. } split( ',', $param_string );
  175. # Find all values which are not in the list of valid values or "ALL"
  176. my @invalid = grep { !IS_IN_LIST($_,"ALL",@valid_values) } @values;
  177. if ( scalar(@invalid) > 0 ) {
  178. # Tell the user which parameters were invalid and print the standard help message which will exit
  179. print "Error: Invalid ", $description, scalar(@invalid) == 1 ? ": " : "s: ", join( ", ", map { "\"$_\"" } @invalid ), "\n";
  180. HELP_MESSAGE();
  181. }
  182. @values = @valid_values if ( IS_IN_LIST("ALL",@values) );
  183. return @values;
  184. }
  185. if ( $opt_p !~ m/:/ ) {
  186. print "Error: Mozilla trust identifier list must include both purposes and levels\n";
  187. HELP_MESSAGE();
  188. }
  189. (my $included_mozilla_trust_purposes_string, my $included_mozilla_trust_levels_string) = split( ':', $opt_p );
  190. my @included_mozilla_trust_purposes = PARSE_CSV_PARAM( "trust purpose", $included_mozilla_trust_purposes_string, @valid_mozilla_trust_purposes );
  191. my @included_mozilla_trust_levels = PARSE_CSV_PARAM( "trust level", $included_mozilla_trust_levels_string, @valid_mozilla_trust_levels );
  192. my @included_signature_algorithms = PARSE_CSV_PARAM( "signature algorithm", $opt_s, @valid_signature_algorithms );
  193. sub SHOULD_OUTPUT_CERT(%) {
  194. my %trust_purposes_by_level = @_;
  195. foreach my $level (@included_mozilla_trust_levels) {
  196. # for each level we want to output, see if any of our desired purposes are included
  197. return 1 if ( defined( List::Util::first { IS_IN_LIST( $_, @included_mozilla_trust_purposes ) } @{$trust_purposes_by_level{$level}} ) );
  198. }
  199. return 0;
  200. }
  201. my $crt = $ARGV[0] || 'ca-bundle.crt';
  202. (my $txt = $url) =~ s@(.*/|\?.*)@@g;
  203. my $stdout = $crt eq '-';
  204. my $resp;
  205. my $fetched;
  206. unless ($opt_n and -e $txt) {
  207. print STDERR "Downloading '$txt' ...\n" if (!$opt_q);
  208. my $ua = new LWP::UserAgent(agent => "$0/$version");
  209. $ua->env_proxy();
  210. $resp = $ua->mirror($url, $txt);
  211. if ($resp && $resp->code eq '304') {
  212. print STDERR "Not modified\n" unless $opt_q;
  213. exit 0 if -e $crt && !$opt_f;
  214. } else {
  215. $fetched = 1;
  216. }
  217. if( !$resp || $resp->code !~ /^(?:200|304)$/ ) {
  218. print STDERR "Unable to download latest data: "
  219. . ($resp? $resp->code . ' - ' . $resp->message : "LWP failed") . "\n"
  220. unless $opt_q;
  221. exit 1 if -e $crt || ! -r $txt;
  222. }
  223. }
  224. my $currentdate = scalar gmtime($fetched ? $resp->last_modified : (stat($txt))[9]);
  225. my $format = $opt_t ? "plain text and " : "";
  226. if( $stdout ) {
  227. open(CRT, '> -') or die "Couldn't open STDOUT: $!\n";
  228. } else {
  229. open(CRT,">$crt.~") or die "Couldn't open $crt.~: $!\n";
  230. }
  231. print CRT <<EOT;
  232. ##
  233. ## $crt -- Bundle of CA Root Certificates
  234. ##
  235. ## Certificate data from Mozilla as of: ${currentdate}
  236. ##
  237. ## This is a bundle of X.509 certificates of public Certificate Authorities
  238. ## (CA). These were automatically extracted from Mozilla's root certificates
  239. ## file (certdata.txt). This file can be found in the mozilla source tree:
  240. ## ${url}
  241. ##
  242. ## It contains the certificates in ${format}PEM format and therefore
  243. ## can be directly used with curl / libcurl / php_curl, or with
  244. ## an Apache+mod_ssl webserver for SSL client authentication.
  245. ## Just configure this file as the SSLCACertificateFile.
  246. ##
  247. EOT
  248. print STDERR "Processing '$txt' ...\n" if (!$opt_q);
  249. my $caname;
  250. my $certnum = 0;
  251. my $skipnum = 0;
  252. my $start_of_cert = 0;
  253. open(TXT,"$txt") or die "Couldn't open $txt: $!\n";
  254. while (<TXT>) {
  255. if (/\*\*\*\*\* BEGIN LICENSE BLOCK \*\*\*\*\*/) {
  256. print CRT;
  257. print if ($opt_l);
  258. while (<TXT>) {
  259. print CRT;
  260. print if ($opt_l);
  261. last if (/\*\*\*\*\* END LICENSE BLOCK \*\*\*\*\*/);
  262. }
  263. }
  264. next if /^#|^\s*$/;
  265. chomp;
  266. if (/^CVS_ID\s+\"(.*)\"/) {
  267. print CRT "# $1\n";
  268. }
  269. # this is a match for the start of a certificate
  270. if (/^CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE/) {
  271. $start_of_cert = 1
  272. }
  273. if ($start_of_cert && /^CKA_LABEL UTF8 \"(.*)\"/) {
  274. $caname = $1;
  275. }
  276. my %trust_purposes_by_level;
  277. if ($start_of_cert && /^CKA_VALUE MULTILINE_OCTAL/) {
  278. my $data;
  279. while (<TXT>) {
  280. last if (/^END/);
  281. chomp;
  282. my @octets = split(/\\/);
  283. shift @octets;
  284. for (@octets) {
  285. $data .= chr(oct);
  286. }
  287. }
  288. # scan forwards until the trust part
  289. while (<TXT>) {
  290. last if (/^CKA_CLASS CK_OBJECT_CLASS CKO_NSS_TRUST/);
  291. chomp;
  292. }
  293. # now scan the trust part to determine how we should trust this cert
  294. while (<TXT>) {
  295. last if (/^#/);
  296. if (/^CKA_TRUST_([A-Z_]+)\s+CK_TRUST\s+CKT_NSS_([A-Z_]+)\s*$/) {
  297. if ( !IS_IN_LIST($1,@valid_mozilla_trust_purposes) ) {
  298. print STDERR "Warning: Unrecognized trust purpose for cert: $caname. Trust purpose: $1. Trust Level: $2\n" if (!$opt_q);
  299. } elsif ( !IS_IN_LIST($2,@valid_mozilla_trust_levels) ) {
  300. print STDERR "Warning: Unrecognized trust level for cert: $caname. Trust purpose: $1. Trust Level: $2\n" if (!$opt_q);
  301. } else {
  302. push @{$trust_purposes_by_level{$2}}, $1;
  303. }
  304. }
  305. }
  306. if ( !SHOULD_OUTPUT_CERT(%trust_purposes_by_level) ) {
  307. $skipnum ++;
  308. } else {
  309. my $encoded = MIME::Base64::encode_base64($data, '');
  310. $encoded =~ s/(.{1,${opt_w}})/$1\n/g;
  311. my $pem = "-----BEGIN CERTIFICATE-----\n"
  312. . $encoded
  313. . "-----END CERTIFICATE-----\n";
  314. print CRT "\n$caname\n";
  315. my $maxStringLength = length($caname);
  316. if ($opt_t) {
  317. foreach my $key (keys %trust_purposes_by_level) {
  318. my $string = $key . ": " . join(", ", @{$trust_purposes_by_level{$key}});
  319. $maxStringLength = List::Util::max( length($string), $maxStringLength );
  320. print CRT $string . "\n";
  321. }
  322. }
  323. print CRT ("=" x $maxStringLength . "\n");
  324. if (!$opt_t) {
  325. print CRT $pem;
  326. } else {
  327. my $pipe = "";
  328. foreach my $hash (@included_signature_algorithms) {
  329. $pipe = "|$openssl x509 -" . $hash . " -fingerprint -noout -inform PEM";
  330. if (!$stdout) {
  331. $pipe .= " >> $crt.~";
  332. close(CRT) or die "Couldn't close $crt.~: $!";
  333. }
  334. open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
  335. print TMP $pem;
  336. close(TMP) or die "Couldn't close openssl pipe: $!";
  337. if (!$stdout) {
  338. open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
  339. }
  340. }
  341. $pipe = "|$openssl x509 -text -inform PEM";
  342. if (!$stdout) {
  343. $pipe .= " >> $crt.~";
  344. close(CRT) or die "Couldn't close $crt.~: $!";
  345. }
  346. open(TMP, $pipe) or die "Couldn't open openssl pipe: $!";
  347. print TMP $pem;
  348. close(TMP) or die "Couldn't close openssl pipe: $!";
  349. if (!$stdout) {
  350. open(CRT, ">>$crt.~") or die "Couldn't open $crt.~: $!";
  351. }
  352. }
  353. print STDERR "Parsing: $caname\n" if ($opt_v);
  354. $certnum ++;
  355. $start_of_cert = 0;
  356. }
  357. }
  358. }
  359. close(TXT) or die "Couldn't close $txt: $!\n";
  360. close(CRT) or die "Couldn't close $crt.~: $!\n";
  361. unless( $stdout ) {
  362. if ($opt_b && -e $crt) {
  363. my $bk = 1;
  364. while (-e "$crt.~${bk}~") {
  365. $bk++;
  366. }
  367. rename $crt, "$crt.~${bk}~" or die "Failed to create backup $crt.~$bk}~: $!\n";
  368. } elsif( -e $crt ) {
  369. unlink( $crt ) or die "Failed to remove $crt: $!\n";
  370. }
  371. rename "$crt.~", $crt or die "Failed to rename $crt.~ to $crt: $!\n";
  372. }
  373. unlink $txt if ($opt_u);
  374. print STDERR "Done ($certnum CA certs processed, $skipnum skipped).\n" if (!$opt_q);
  375. exit;