xref: /openssl/apps/CA.pl.in (revision 3066cf26)
1#!{- $config{HASHBANGPERL} -}
2# Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
3#
4# Licensed under the Apache License 2.0 (the "License").  You may not use
5# this file except in compliance with the License.  You can obtain a copy
6# in the file LICENSE in the source distribution or at
7# https://www.openssl.org/source/license.html
8
9#
10# Wrapper around the ca to make it easier to use
11#
12# {- join("\n# ", @autowarntext) -}
13
14use strict;
15use warnings;
16
17my $verbose = 1;
18my @OPENSSL_CMDS = ("req", "ca", "pkcs12", "x509", "verify");
19
20my $openssl = $ENV{'OPENSSL'} // "openssl";
21$ENV{'OPENSSL'} = $openssl;
22my $OPENSSL_CONFIG = $ENV{"OPENSSL_CONFIG"} // "";
23
24# Command invocations.
25my $REQ = "$openssl req $OPENSSL_CONFIG";
26my $CA = "$openssl ca $OPENSSL_CONFIG";
27my $VERIFY = "$openssl verify";
28my $X509 = "$openssl x509";
29my $PKCS12 = "$openssl pkcs12";
30
31# Default values for various configuration settings.
32my $CATOP = "./demoCA";
33my $CAKEY = "cakey.pem";
34my $CAREQ = "careq.pem";
35my $CACERT = "cacert.pem";
36my $CACRL = "crl.pem";
37my $DAYS = "-days 365";
38my $CADAYS = "-days 1095";	# 3 years
39my $EXTENSIONS = "-extensions v3_ca";
40my $POLICY = "-policy policy_anything";
41my $NEWKEY = "newkey.pem";
42my $NEWREQ = "newreq.pem";
43my $NEWCERT = "newcert.pem";
44my $NEWP12 = "newcert.p12";
45
46# Commandline parsing
47my %EXTRA;
48my $WHAT = shift @ARGV || "";
49@ARGV = parse_extra(@ARGV);
50my $RET = 0;
51
52# Split out "-extra-CMD value", and return new |@ARGV|. Fill in
53# |EXTRA{CMD}| with list of values.
54sub parse_extra
55{
56    foreach ( @OPENSSL_CMDS ) {
57        $EXTRA{$_} = '';
58    }
59
60    my @result;
61    while ( scalar(@_) > 0 ) {
62        my $arg = shift;
63        if ( $arg !~ m/-extra-([a-z0-9]+)/ ) {
64            push @result, $arg;
65            next;
66        }
67        $arg =~ s/-extra-//;
68        die("Unknown \"-${arg}-extra\" option, exiting")
69            unless scalar grep { $arg eq $_ } @OPENSSL_CMDS;
70        $EXTRA{$arg} .= " " . shift;
71    }
72    return @result;
73}
74
75
76# See if reason for a CRL entry is valid; exit if not.
77sub crl_reason_ok
78{
79    my $r = shift;
80
81    if ($r eq 'unspecified' || $r eq 'keyCompromise'
82        || $r eq 'CACompromise' || $r eq 'affiliationChanged'
83        || $r eq 'superseded' || $r eq 'cessationOfOperation'
84        || $r eq 'certificateHold' || $r eq 'removeFromCRL') {
85        return 1;
86    }
87    print STDERR "Invalid CRL reason; must be one of:\n";
88    print STDERR "    unspecified, keyCompromise, CACompromise,\n";
89    print STDERR "    affiliationChanged, superseded, cessationOfOperation\n";
90    print STDERR "    certificateHold, removeFromCRL";
91    exit 1;
92}
93
94# Copy a PEM-format file; return like exit status (zero means ok)
95sub copy_pemfile
96{
97    my ($infile, $outfile, $bound) = @_;
98    my $found = 0;
99
100    open IN, $infile || die "Cannot open $infile, $!";
101    open OUT, ">$outfile" || die "Cannot write to $outfile, $!";
102    while (<IN>) {
103        $found = 1 if /^-----BEGIN.*$bound/;
104        print OUT $_ if $found;
105        $found = 2, last if /^-----END.*$bound/;
106    }
107    close IN;
108    close OUT;
109    return $found == 2 ? 0 : 1;
110}
111
112# Wrapper around system; useful for debugging.  Returns just the exit status
113sub run
114{
115    my $cmd = shift;
116    print "====\n$cmd\n" if $verbose;
117    my $status = system($cmd);
118    print "==> $status\n====\n" if $verbose;
119    return $status >> 8;
120}
121
122
123if ( $WHAT =~ /^(-\?|-h|-help)$/ ) {
124    print STDERR <<EOF;
125Usage:
126    CA.pl -newcert | -newreq | -newreq-nodes | -xsign | -sign | -signCA | -signcert | -crl | -newca [-extra-cmd parameter]
127    CA.pl -pkcs12 [certname]
128    CA.pl -verify certfile ...
129    CA.pl -revoke certfile [reason]
130EOF
131    exit 0;
132}
133
134if ($WHAT eq '-newcert' ) {
135    # create a certificate
136    $RET = run("$REQ -new -x509 -keyout $NEWKEY -out $NEWCERT $DAYS"
137            . " $EXTRA{req}");
138    print "Cert is in $NEWCERT, private key is in $NEWKEY\n" if $RET == 0;
139} elsif ($WHAT eq '-precert' ) {
140    # create a pre-certificate
141    $RET = run("$REQ -x509 -precert -keyout $NEWKEY -out $NEWCERT $DAYS"
142            . " $EXTRA{req}");
143    print "Pre-cert is in $NEWCERT, private key is in $NEWKEY\n" if $RET == 0;
144} elsif ($WHAT =~ /^\-newreq(\-nodes)?$/ ) {
145    # create a certificate request
146    $RET = run("$REQ -new $1 -keyout $NEWKEY -out $NEWREQ $DAYS $EXTRA{req}");
147    print "Request is in $NEWREQ, private key is in $NEWKEY\n" if $RET == 0;
148} elsif ($WHAT eq '-newca' ) {
149    # create the directory hierarchy
150    my @dirs = ( "${CATOP}", "${CATOP}/certs", "${CATOP}/crl",
151                "${CATOP}/newcerts", "${CATOP}/private" );
152    die "${CATOP}/index.txt exists.\nRemove old sub-tree to proceed,"
153        if -f "${CATOP}/index.txt";
154    die "${CATOP}/serial exists.\nRemove old sub-tree to proceed,"
155        if -f "${CATOP}/serial";
156    foreach my $d ( @dirs ) {
157        if ( -d $d ) {
158            warn "Directory $d exists" if -d $d;
159        } else {
160            mkdir $d or die "Can't mkdir $d, $!";
161        }
162    }
163
164    open OUT, ">${CATOP}/index.txt";
165    close OUT;
166    open OUT, ">${CATOP}/crlnumber";
167    print OUT "01\n";
168    close OUT;
169    # ask user for existing CA certificate
170    print "CA certificate filename (or enter to create)\n";
171    my $FILE;
172    $FILE = "" unless defined($FILE = <STDIN>);
173    $FILE =~ s{\R$}{};
174    if ($FILE ne "") {
175        copy_pemfile($FILE,"${CATOP}/private/$CAKEY", "PRIVATE");
176        copy_pemfile($FILE,"${CATOP}/$CACERT", "CERTIFICATE");
177    } else {
178        print "Making CA certificate ...\n";
179        $RET = run("$REQ -new -keyout ${CATOP}/private/$CAKEY"
180                . " -out ${CATOP}/$CAREQ $EXTRA{req}");
181        $RET = run("$CA -create_serial"
182                . " -out ${CATOP}/$CACERT $CADAYS -batch"
183                . " -keyfile ${CATOP}/private/$CAKEY -selfsign"
184                . " $EXTENSIONS"
185                . " -infiles ${CATOP}/$CAREQ $EXTRA{ca}") if $RET == 0;
186        print "CA certificate is in ${CATOP}/$CACERT\n" if $RET == 0;
187    }
188} elsif ($WHAT eq '-pkcs12' ) {
189    my $cname = $ARGV[0];
190    $cname = "My Certificate" unless defined $cname;
191    $RET = run("$PKCS12 -in $NEWCERT -inkey $NEWKEY"
192            . " -certfile ${CATOP}/$CACERT -out $NEWP12"
193            . " -export -name \"$cname\" $EXTRA{pkcs12}");
194    print "PKCS #12 file is in $NEWP12\n" if $RET == 0;
195} elsif ($WHAT eq '-xsign' ) {
196    $RET = run("$CA $POLICY -infiles $NEWREQ $EXTRA{ca}");
197} elsif ($WHAT eq '-sign' ) {
198    $RET = run("$CA $POLICY -out $NEWCERT"
199            . " -infiles $NEWREQ $EXTRA{ca}");
200    print "Signed certificate is in $NEWCERT\n" if $RET == 0;
201} elsif ($WHAT eq '-signCA' ) {
202    $RET = run("$CA $POLICY -out $NEWCERT"
203            . " $EXTENSIONS -infiles $NEWREQ $EXTRA{ca}");
204    print "Signed CA certificate is in $NEWCERT\n" if $RET == 0;
205} elsif ($WHAT eq '-signcert' ) {
206    $RET = run("$X509 -x509toreq -in $NEWREQ -signkey $NEWREQ"
207            . " -out tmp.pem $EXTRA{x509}");
208    $RET = run("$CA $POLICY -out $NEWCERT"
209            .  "-infiles tmp.pem $EXTRA{ca}") if $RET == 0;
210    print "Signed certificate is in $NEWCERT\n" if $RET == 0;
211} elsif ($WHAT eq '-verify' ) {
212    my @files = @ARGV ? @ARGV : ( $NEWCERT );
213    foreach my $file (@files) {
214        # -CAfile quoted for VMS, since the C RTL downcases all unquoted
215        # arguments to C programs
216        my $status = run("$VERIFY \"-CAfile\" ${CATOP}/$CACERT $file $EXTRA{verify}");
217        $RET = $status if $status != 0;
218    }
219} elsif ($WHAT eq '-crl' ) {
220    $RET = run("$CA -gencrl -out ${CATOP}/crl/$CACRL $EXTRA{ca}");
221    print "Generated CRL is in ${CATOP}/crl/$CACRL\n" if $RET == 0;
222} elsif ($WHAT eq '-revoke' ) {
223    my $cname = $ARGV[0];
224    if (!defined $cname) {
225        print "Certificate filename is required; reason optional.\n";
226        exit 1;
227    }
228    my $reason = $ARGV[1];
229    $reason = " -crl_reason $reason"
230        if defined $reason && crl_reason_ok($reason);
231    $RET = run("$CA -revoke \"$cname\"" . $reason . $EXTRA{ca});
232} else {
233    print STDERR "Unknown arg \"$WHAT\"\n";
234    print STDERR "Use -help for help.\n";
235    exit 1;
236}
237
238exit $RET;
239