Update primary code license to Apache 2.0.
[cascardo/ovs.git] / utilities / ovs-pki.in
1 #! /bin/sh
2
3 # Copyright (c) 2008, 2009 Nicira Networks, Inc.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at:
8 #
9 #     http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 set -e
18
19 pkidir='@PKIDIR@'
20 command=
21 prev=
22 force=no
23 batch=no
24 log='@LOGDIR@/ovs-pki.log'
25 keytype=rsa
26 bits=2048
27 for option; do
28     # This option-parsing mechanism borrowed from a Autoconf-generated
29     # configure script under the following license:
30
31     # Copyright (C) 1992, 1993, 1994, 1995, 1996, 1998, 1999, 2000, 2001,
32     # 2002, 2003, 2004, 2005, 2006, 2009 Free Software Foundation, Inc.
33     # This configure script is free software; the Free Software Foundation
34     # gives unlimited permission to copy, distribute and modify it.
35
36     # If the previous option needs an argument, assign it.
37     if test -n "$prev"; then
38         eval $prev=\$option
39         prev=
40         continue
41     fi
42     case $option in
43         *=*) optarg=`expr "X$option" : '[^=]*=\(.*\)'` ;;
44         *) optarg=yes ;;
45     esac
46
47     case $dashdash$option in
48         --)
49             dashdash=yes ;;
50         -h|--help)
51             cat <<EOF
52 ovs-pki, for managing a simple OpenFlow public key infrastructure 
53 usage: $0 [OPTION...] COMMAND [ARG...]
54
55 The valid stand-alone commands and their arguments are:
56   init                 Initialize the PKI
57   req NAME             Create new private key and certificate request
58                        named NAME-privkey.pem and NAME-req.pem, resp.
59   sign NAME [TYPE]     Sign switch certificate request NAME-req.pem,
60                        producing certificate NAME-cert.pem
61   req+sign NAME [TYPE] Combine the above two steps, producing all three files.
62   verify NAME [TYPE]   Checks that NAME-cert.pem is a valid TYPE certificate
63   fingerprint FILE     Prints the fingerprint for FILE
64   self-sign NAME       Sign NAME-req.pem with NAME-privkey.pem,
65                        producing self-signed certificate NAME-cert.pem
66
67 The following additional commands manage an online PKI:
68   ls [PREFIX] [TYPE]   Lists incoming requests of the given TYPE, optionally 
69                        limited to those whose fingerprint begins with PREFIX
70   flush [TYPE]         Rejects all incoming requests of the given TYPE
71   reject PREFIX [TYPE] Rejects the incoming request(s) whose fingerprint begins
72                        with PREFIX and has the given TYPE
73   approve PREFIX [TYPE] Approves the incoming request whose fingerprint begins
74                        with PREFIX and has the given TYPE
75   expire [AGE]         Rejects all incoming requests older than AGE, in
76                        one of the forms Ns, Nmin, Nh, Nday (default: 1day)
77   prompt [TYPE]        Interactively prompts to accept or reject each incoming
78                        request of the given TYPE
79
80 Each TYPE above is a certificate type: 'switch' (default) or 'controller'.
81
82 Options for 'init', 'req', and 'req+sign' only:
83   -k, --key=rsa|dsa    Type of keys to use (default: rsa)
84   -B, --bits=NBITS     Number of bits in keys (default: 2048).  For DSA keys,
85                          this has an effect only on 'init'.
86   -D, --dsaparam=FILE  File with DSA parameters (DSA only)
87                          (default: dsaparam.pem within PKI directory)
88 Options for use with the 'sign' and 'approve' commands:
89   -b, --batch          Skip fingerprint verification
90 Options that apply to any command:
91   -d, --dir=DIR        Directory where the PKI is located
92                          (default: $pkidir)
93   -f, --force          Continue even if file or directory already exists
94   -l, --log=FILE       Log openssl output to FILE (default: ovs-log.log)
95   -h, --help           Print this usage message.
96 EOF
97             exit 0
98             ;;
99         --di*=*)
100             pkidir=$optarg
101             ;;
102         --di*|-d)
103             prev=pkidir
104             ;;
105         --k*=*)
106             keytype=$optarg
107             ;;
108         --k*|-k)
109             prev=keytype
110             ;;
111         --bi*=*)
112             bits=$optarg
113             ;;
114         --bi*|-B)
115             prev=bits
116             ;;
117         --ds*=*)
118             dsaparam=$optarg
119             ;;
120         --ds*|-D)
121             prev=dsaparam
122             ;;
123         --l*=*)
124             log=$optarg
125             ;;
126         --l*|-l)
127             prev=log
128             ;;
129         --force|-f)
130             force=yes
131             ;;
132         --ba*|-b)
133             batch=yes
134             ;;
135         -*)
136             echo "unrecognized option $option" >&2
137             exit 1
138             ;;
139         *)
140             if test -z "$command"; then
141                 command=$option
142             elif test -z "${arg1+set}"; then
143                 arg1=$option
144             elif test -z "${arg2+set}"; then
145                 arg2=$option
146             else
147                 echo "$option: only two arguments may be specified" >&2
148                 exit 1
149             fi
150             ;;
151     esac
152     shift
153 done
154 if test -n "$prev"; then
155     option=--`echo $prev | sed 's/_/-/g'`
156     { echo "$as_me: error: missing argument to $option" >&2
157         { (exit 1); exit 1; }; }
158 fi
159 if test -z "$command"; then
160     echo "$0: missing command name; use --help for help" >&2
161     exit 1
162 fi
163 if test "$keytype" != rsa && test "$keytype" != dsa; then
164     echo "$0: argument to -k or --key must be rsa or dsa"
165     exit 1
166 fi
167 if test "$bits" -lt 1024; then
168     echo "$0: argument to -B or --bits must be at least 1024"
169     exit 1
170 fi
171 if test -z "$dsaparam"; then
172     dsaparam=$pkidir/dsaparam.pem
173 fi
174 case $log in
175     /*) ;;
176     *) $log="$PWD/$log" ;;
177 esac
178
179 if test "$command" = "init"; then
180     if test -e "$pkidir" && test "$force" != "yes"; then
181         echo "$0: $pkidir already exists and --force not specified" >&2
182         exit 1
183     fi
184
185     if test ! -d "$pkidir"; then
186         mkdir -p "$pkidir"
187     fi
188     cd "$pkidir"
189     exec 3>>$log
190
191     if test $keytype = dsa && test ! -e dsaparam.pem; then
192         echo "Generating DSA parameters, please wait..." >&2
193         openssl dsaparam -out dsaparam.pem $bits 1>&3 2>&3
194     fi
195
196     # Create the CAs.
197     for ca in controllerca switchca; do
198         echo "Creating $ca..." >&2
199         oldpwd=$PWD
200         mkdir -p $ca
201         cd $ca
202
203         mkdir -p certs crl newcerts
204         mkdir -p -m 0700 private
205         mkdir -p -m 0733 incoming
206         touch index.txt
207         test -e crlnumber || echo 01 > crlnumber
208         test -e serial || echo 01 > serial
209
210         # Put DSA parameters in directory.
211         if test $keytype = dsa && test ! -e dsaparam.pem; then
212             cp ../dsaparam.pem .
213         fi
214
215     # Write CA configuration file.
216         if test ! -e ca.cnf; then
217             sed "s/@ca@/$ca/g" > ca.cnf <<'EOF'
218 [ req ]
219 prompt = no
220 distinguished_name = req_distinguished_name
221
222 [ req_distinguished_name ]
223 C = US
224 ST = CA
225 L = Palo Alto
226 O = Open vSwitch
227 OU = @ca@
228 CN = Open vSwitch @ca@ CA Certificate
229
230 [ ca ]
231 default_ca = the_ca
232
233 [ the_ca ]
234 dir            = .                     # top dir
235 database       = $dir/index.txt        # index file.
236 new_certs_dir  = $dir/newcerts         # new certs dir
237 certificate    = $dir/cacert.pem       # The CA cert
238 serial         = $dir/serial           # serial no file
239 private_key    = $dir/private/cakey.pem# CA private key
240 RANDFILE       = $dir/private/.rand    # random number file
241 default_days   = 365                   # how long to certify for
242 default_crl_days= 30                   # how long before next CRL
243 default_md     = md5                   # md to use
244 policy         = policy                # default policy
245 email_in_dn    = no                    # Don't add the email into cert DN
246 name_opt       = ca_default            # Subject name display option
247 cert_opt       = ca_default            # Certificate display option
248 copy_extensions = none                 # Don't copy extensions from request
249
250 # For the CA policy
251 [ policy ]
252 countryName             = optional
253 stateOrProvinceName     = optional
254 organizationName        = match
255 organizationalUnitName  = optional
256 commonName              = supplied
257 emailAddress            = optional
258 EOF
259         fi
260
261         # Create certificate authority.
262         if test $keytype = dsa; then
263             newkey=dsa:dsaparam.pem
264         else
265             newkey=rsa:$bits
266         fi
267         openssl req -config ca.cnf -nodes \
268             -newkey $newkey -keyout private/cakey.pem -out careq.pem \
269             1>&3 2>&3
270         openssl ca -config ca.cnf -create_serial -out cacert.pem \
271             -days 1095 -batch -keyfile private/cakey.pem -selfsign \
272             -infiles careq.pem 1>&3 2>&3
273         chmod 0700 private/cakey.pem
274
275         cd "$oldpwd"
276     done
277     exit 0
278 fi
279
280 one_arg() {
281     if test -z "$arg1" || test -n "$arg2"; then
282         echo "$0: $command must have exactly one argument; use --help for help" >&2
283         exit 1
284     fi
285 }
286
287 zero_or_one_args() {
288     if test -n "$arg2"; then
289         echo "$0: $command must have zero or one arguments; use --help for help" >&2
290         exit 1
291     fi
292 }
293
294 one_or_two_args() {
295     if test -z "$arg1"; then
296         echo "$0: $command must have one or two arguments; use --help for help" >&2
297         exit 1
298     fi
299 }
300
301 must_not_exist() {
302     if test -e "$1" && test "$force" != "yes"; then
303         echo "$0: $1 already exists and --force not supplied" >&2
304         exit 1
305     fi
306 }
307
308 resolve_prefix() {
309     test -n "$type" || exit 123 # Forgot to call check_type?
310
311     case $1 in
312         ????*)
313             ;;
314         *)
315             echo "Prefix $arg1 is too short (less than 4 hex digits)"
316             exit 0
317             ;;
318     esac
319     
320     fingerprint=$(cd "$pkidir/${type}ca/incoming" && echo "$1"*-req.pem | sed 's/-req\.pem$//')
321     case $fingerprint in
322         "${1}*")
323             echo "No certificate requests matching $1"
324             exit 1
325             ;;
326         *" "*)
327             echo "$1 matches more than one certificate request:"
328             echo $fingerprint | sed 's/ /\
329 /g'
330             exit 1
331             ;;
332         *)
333             # Nothing to do.
334             ;;
335     esac
336     req="$pkidir/${type}ca/incoming/$fingerprint-req.pem"
337     cert="$pkidir/${type}ca/certs/$fingerprint-cert.pem"
338 }
339
340 make_tmpdir() {
341     TMP=/tmp/ovs-pki.tmp$$
342     rm -rf $TMP
343     trap "rm -rf $TMP" 0
344     mkdir -m 0700 $TMP
345 }
346
347 fingerprint() {
348     local file=$1
349     local name=${1-$2}
350     local date=$(date -r $file)
351     local fingerprint
352     if grep -q -e '-BEGIN CERTIFICATE-' "$file"; then
353         fingerprint=$(openssl x509 -noout -in "$file" -fingerprint |
354                       sed 's/SHA1 Fingerprint=//' | tr -d ':')
355     else
356         fingerprint=$(sha1sum "$file" | awk '{print $1}')
357     fi
358     printf "$name\\t$date\\n"
359     case $file in
360         $fingerprint*)
361             printf "\\t(correct fingerprint in filename)\\n"
362             ;;
363         *)
364             printf "\\tfingerprint $fingerprint\\n"
365             ;;
366     esac
367 }
368
369 verify_fingerprint() {
370     fingerprint "$@"
371     if test $batch != yes; then
372         echo "Does fingerprint match? (yes/no)"
373         read answer
374         if test "$answer" != yes; then 
375             echo "Match failure, aborting" >&2
376             exit 1
377         fi
378     fi
379 }
380
381 check_type() {
382     if test x = x"$1"; then
383         type=switch
384     elif test "$1" = switch || test "$1" = controller; then 
385         type=$1
386     else
387         echo "$0: type argument must be 'switch' or 'controller'" >&2
388         exit 1
389     fi
390 }
391
392 parse_age() {
393     number=$(echo $1 | sed 's/^\([0-9]\+\)\([[:alpha:]]\+\)/\1/')
394     unit=$(echo $1 | sed 's/^\([0-9]\+\)\([[:alpha:]]\+\)/\2/')
395     case $unit in
396         s)
397             factor=1
398             ;;
399         min)
400             factor=60
401             ;;
402         h)
403             factor=3600
404             ;;
405         day)
406             factor=86400
407             ;;
408         *)
409             echo "$1: age not in the form Ns, Nmin, Nh, Nday (e.g. 1day)" >&2
410             exit 1
411             ;;
412     esac
413     echo $(($number * $factor))
414 }
415
416 must_exist() {
417     if test ! -e "$1"; then
418         echo "$0: $1 does not exist" >&2
419         exit 1
420     fi
421 }
422
423 pkidir_must_exist() {
424     if test ! -e "$pkidir"; then
425         echo "$0: $pkidir does not exist (need to run 'init' or use '--dir'?)" >&2
426         exit 1
427     elif test ! -d "$pkidir"; then
428         echo "$0: $pkidir is not a directory" >&2
429         exit 1
430     fi
431 }
432
433 make_request() {
434     must_not_exist "$arg1-privkey.pem"
435     must_not_exist "$arg1-req.pem"
436     make_tmpdir
437     cat > "$TMP/req.cnf" <<EOF
438 [ req ]
439 prompt = no
440 distinguished_name = req_distinguished_name
441
442 [ req_distinguished_name ]
443 C = US
444 ST = CA
445 L = Palo Alto
446 O = Open vSwitch
447 OU = Open vSwitch certifier
448 CN = Open vSwitch certificate for $arg1
449 EOF
450     if test $keytype = rsa; then
451         newkey=rsa:$bits
452     else
453         must_exist "$dsaparam"
454         newkey=dsa:$dsaparam
455     fi
456     openssl req -config "$TMP/req.cnf" -text -nodes \
457         -newkey $newkey -keyout "$1-privkey.pem" -out "$1-req.pem" 1>&3 2>&3
458 }
459
460 sign_request() {
461     must_exist "$1"
462     must_not_exist "$2"
463     pkidir_must_exist
464
465     (cd "$pkidir/${type}ca" && 
466      openssl ca -config ca.cnf -batch -in /dev/stdin) \
467         < "$1" > "$2.tmp$$" 2>&3
468     mv "$2.tmp$$" "$2"
469 }
470
471 glob() {
472     local files=$(echo $1)
473     if test "$files" != "$1"; then
474         echo "$files"
475     fi
476 }
477
478 exec 3>>$log || true
479 if test "$command" = req; then
480     one_arg
481
482     make_request "$arg1"
483     fingerprint "$arg1-req.pem"
484 elif test "$command" = sign; then
485     one_or_two_args
486     check_type "$arg2"
487     verify_fingerprint "$arg1-req.pem"
488
489     sign_request "$arg1-req.pem" "$arg2-cert.pem"
490 elif test "$command" = req+sign; then
491     one_or_two_args
492     check_type "$arg2"
493
494     pkidir_must_exist
495     make_request "$arg1"
496     sign_request "$arg1-req.pem" "$arg1-cert.pem"
497     fingerprint "$arg1-req.pem"
498 elif test "$command" = verify; then
499     one_or_two_args
500     must_exist "$arg1-cert.pem"
501     check_type "$arg2"
502
503     pkidir_must_exist
504     openssl verify -CAfile "$pkidir/${type}ca/cacert.pem" "$arg1-cert.pem"
505 elif test "$command" = fingerprint; then
506     one_arg
507
508     fingerprint "$arg1"
509 elif test "$command" = self-sign; then
510     one_arg
511     must_exist "$arg1-req.pem"
512     must_exist "$arg1-privkey.pem"
513     must_not_exist "$arg1-cert.pem"
514
515     openssl x509 -in "$arg1-req.pem" -out "$arg1-cert.pem" \
516         -signkey "$arg1-privkey.pem" -req -text 2>&3
517 elif test "$command" = ls; then
518     check_type "$arg2"
519
520     cd "$pkidir/${type}ca/incoming"
521     for file in $(glob "$arg1*-req.pem"); do
522         fingerprint $file
523     done
524 elif test "$command" = flush; then
525     check_type "$arg1"
526
527     rm -f "$pkidir/${type}ca/incoming/"*
528 elif test "$command" = reject; then
529     one_or_two_args
530     check_type "$arg2"
531     resolve_prefix "$arg1"
532
533     rm -f "$req"
534 elif test "$command" = approve; then
535     one_or_two_args
536     check_type "$arg2"
537     resolve_prefix "$arg1"
538
539     make_tmpdir
540     cp "$req" "$TMP/$req"
541     verify_fingerprint "$TMP/$req"
542     sign_request "$TMP/$req"
543     rm -f "$req" "$TMP/$req"
544 elif test "$command" = prompt; then
545     zero_or_one_args
546     check_type "$arg1"
547
548     make_tmpdir
549     cd "$pkidir/${type}ca/incoming"
550     for req in $(glob "*-req.pem"); do
551         cp "$req" "$TMP/$req"
552
553         cert=$(echo "$pkidir/${type}ca/certs/$req" |
554                sed 's/-req.pem/-cert.pem/')
555         if test -f $cert; then
556             echo "Request $req already approved--dropping duplicate request"
557             rm -f "$req" "$TMP/$req"
558             continue
559         fi
560
561         echo
562         echo
563         fingerprint "$TMP/$req" "$req"
564         printf "Disposition for this request (skip/approve/reject)? "
565         read answer
566         case $answer in
567             approve)
568                 echo "Approving $req"
569                 sign_request "$TMP/$req" "$cert"
570                 rm -f "$req" "$TMP/$req"
571                 ;;
572             r*)
573                 echo "Rejecting $req"
574                 rm -f "$req" "$TMP/$req"
575                 ;;
576             *)
577                 echo "Skipping $req"
578                 ;;
579         esac
580     done
581 elif test "$command" = expire; then
582     zero_or_one_args
583     cutoff=$(($(date +%s) - $(parse_age ${arg1-1day})))
584     for type in switch controller; do
585         cd "$pkidir/${type}ca/incoming" || exit 1
586         for file in $(glob "*"); do
587             time=$(date -r "$file" +%s)
588             if test "$time" -lt "$cutoff"; then
589                 rm -f "$file"
590             fi
591         done
592     done
593 else
594     echo "$0: $command command unknown; use --help for help" >&2
595     exit 1
596 fi