ca-sign: Verify cert request before acting on it.
[clinton/scripts.git] / ca-sign
1 #!/bin/bash
2 #
3 # Sign a certificate request as a CA. Run this on deleuze as an
4 # admin. If a domain is provided, then the certificate request must
5 # apply only to that domain.
6 #
7 # Usage: ca-sign days request.csr outfile.pem [domain]
8
9 if test -n "$5" || test -z "$3"; then
10 echo "Incorrect arguments."
11 echo "Usage: ca-sign days request.csr outfile.pem [domain]"
12 exit 1
13 fi
14
15 # Make sure we run this from deleuze
16 if test "$(hostname -s)" != "deleuze"; then
17 echo "Error: This script must be run from deleuze."
18 exit 1
19 fi
20
21 DIR=/var/local/lib/ca
22 CONF=$DIR/openssl.cnf
23 POLICY=policy_anything
24
25 # Certificate revocation list
26 CRL1=$DIR/crl-v1
27 CRL2=$DIR/crl-v2
28 CA_LOC=/afs/hcoop.net/user/h/hc/hcoop/public_html/ca
29
30 # Parameters
31 DAYS=$1
32 REQUEST=$2
33 PEM=$3
34 DOMAIN=$4
35
36 # Verify request
37 STATUS=$(openssl req -noout -in "$REQUEST" -verify 2>&1)
38 if test "$STATUS" != "verify OK"; then
39 echo "Error: This is not a valid certificate request."
40 exit 1
41 fi
42 if test -n "$DOMAIN"; then
43 CN=$(openssl req -text -in "$REQUEST" | grep "Subject:" | grep "CN=." | \
44 sed -r -e 's/^.*CN=([^/=,]+).*$/\1/1')
45 if test "${CN%%${DOMAIN}}" = "${CN}"; then
46 echo "Error: Domain in cert does not match $DOMAIN."
47 exit 1
48 fi
49 fi
50
51 # Get new serial number
52 ID=$(cat -- $DIR/serial)
53
54 # Exit on error
55 set -e
56
57 # Sign.
58 echo "Signing certificate request $REQUEST ..."
59 openssl ca -config $CONF -policy $POLICY -out $PEM -in $REQUEST -days $DAYS
60 echo
61
62 # Make a copy of the request
63 cp $REQUEST $DIR/requests/$ID.csr
64
65 # Update revocation list.
66 echo "Updating certificate revocation list ..."
67 openssl ca -config $CONF -batch -gencrl -crldays 30 -out $CRL1.pem
68 openssl crl -outform DER -out $CRL1.crl -in $CRL1.pem
69 openssl ca -config $CONF -batch -gencrl -crldays 30 -crlexts crl_ext \
70 -out $CRL2.pem
71 openssl crl -outform DER -out $CRL2.crl -in $CRL2.pem
72 cp $CRL1.crl $CRL2.crl $CA_LOC
73 echo
74
75 echo "Don't forget to run ca-install to install the signed certificate!"