a5992bf22dff42bb92edbd0ff602c24fb00b24ad
[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 # Run this on deleuze as an admin.
8 #
9 # Usage: ca-sign days request.csr key.asc outfile.pem [domain]
10
11 if test -n "$6" || test -z "$4"; then
12 echo "Incorrect arguments."
13 echo "Usage: ca-sign days request.csr key.asc outfile.pem [domain]"
14 exit 1
15 fi
16
17 # Make sure we run this from deleuze
18 if test "$(hostname -s)" != "deleuze"; then
19 echo "Error: This script must be run from deleuze."
20 exit 1
21 fi
22
23 DIR=/var/local/lib/ca
24 CONF=$DIR/openssl.cnf
25 POLICY=policy_anything
26
27 # Certificate revocation list
28 CRL1=$DIR/crl-v1
29 CRL2=$DIR/crl-v2
30 CA_LOC=/afs/hcoop.net/user/h/hc/hcoop/public_html/ca
31
32 # Parameters
33 DAYS=$1
34 REQUEST=$2
35 KEY=$3
36 PEM=$4
37 DOMAIN=$5
38
39 # Make sure completed certificate does not already exist
40 if test -e "$PEM"; then
41 echo "Error: Refusing to overwrite existing certificate at"
42 echo " $PEM."
43 exit 1
44 fi
45
46 # Make sure that the key and request do exist
47 if test ! -f "$REQUEST"; then
48 echo "Error: The given certificate request file does not exist."
49 exit 1
50 fi
51 if test ! -f "$KEY"; then
52 echo "Error: The given key file does not exist."
53 exit 1
54 fi
55
56 # Verify request
57 STATUS=$(openssl req -noout -in "$REQUEST" -verify 2>&1)
58 if test "$STATUS" != "verify OK"; then
59 echo "Error: This is not a valid certificate request."
60 exit 1
61 fi
62 if test -n "$DOMAIN"; then
63 CN=$(openssl req -text -in "$REQUEST" | grep "Subject:" | grep "CN=." | \
64 sed -r -e 's/^.*CN=([^/=,]+).*$/\1/1')
65 if test "${CN%%${DOMAIN}}" = "${CN}"; then
66 echo "Error: Domain in cert does not match $DOMAIN."
67 exit 1
68 fi
69 fi
70
71 # Get new serial number
72 ID=$(cat -- $DIR/serial)
73
74 # Exit on error
75 set -e
76
77 # Sign
78 echo "Signing certificate request $REQUEST ..."
79 openssl ca -config $CONF -policy $POLICY -out "$PEM" -in "$REQUEST" \
80 -days "$DAYS"
81 echo
82
83 # Make a copy of the request
84 cp "$REQUEST" $DIR/requests/$ID.csr
85
86 # Append key to generated certificate
87 cat "$KEY" >> "$PEM"
88
89 # Update revocation list.
90 echo "Updating certificate revocation list ..."
91 openssl ca -config $CONF -batch -gencrl -crldays 30 -out $CRL1.pem
92 openssl crl -outform DER -out $CRL1.crl -in $CRL1.pem
93 openssl ca -config $CONF -batch -gencrl -crldays 30 -crlexts crl_ext \
94 -out $CRL2.pem
95 openssl crl -outform DER -out $CRL2.crl -in $CRL2.pem
96 cp $CRL1.crl $CRL2.crl $CA_LOC
97 echo
98
99 echo "Don't forget to run ca-install to install the signed certificate!"