mk-ca-bundle.pl 17 KB

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