acmecert: Fix cryptography bugs.
[utils.git] / certreq
1 #!/bin/bash
2
3 commajoin() {
4     f=y
5     for arg in "$@"; do
6         if [ -z "$f" ]; then echo -n ,; fi
7         echo -n "$arg"
8         f=
9     done
10 }
11
12 usage() {
13     echo "usage: certreq [-h] [-a ALTNAMES] [-C] SUBJECT KEYFILE"
14     echo '        SUBJECT is of the form `/PART1=VALUE1/PART2=VALUE2/...'\'
15     echo '        ALTNAMES is of the form `DNS:name1,DNS:name,...'\'
16 }
17
18 declare -A reqexts config
19 while getopts hCa: OPT; do
20     case "$OPT" in
21         h)
22             usage
23             exit 0
24             ;;
25         a)
26             reqexts[SAN]=1
27             config[SAN]=1
28             config_SAN=("${config_SAN[@]}" "subjectAltName=$OPTARG")
29             ;;
30         C)
31             reqexts[NON_SELF_CA]=1
32             config[NON_SELF_CA]=1
33             config_NON_SELF_CA=("${config_NONE_SELF_CA[@]}"
34                                 "basicConstraints = critical,CA:true"
35                                 "keyUsage = cRLSign, keyCertSign")
36             ;;
37     esac
38 done
39 shift $((OPTIND - 1))
40 if [ $# -lt 2 ]; then
41     usage >&2
42     exit 1
43 fi
44
45 args=(openssl req -new)
46 if [ -n "${!reqexts[*]}" ]; then
47     for reqext in "${!reqexts[@]}"; do
48         args=("${args[@]}" -reqexts "$reqext")
49     done
50 fi
51 if [ -n "${!config[*]}" ]; then
52     confpath="$(mktemp /tmp/certreq-XXXXXX)"
53     cat /etc/ssl/openssl.cnf >>"$confpath"
54     for section in "${!config[@]}"; do
55         echo "[${section}]" >>"$confpath"
56         var="config_${section}[@]"
57         for confopt in "${!var}"; do
58             echo "$confopt" >>"$confpath"
59         done
60         echo >>"$confpath"
61     done
62     trap 'rm -f "$confpath"' EXIT
63     args=("${args[@]}" -config "$confpath")
64 fi
65 args=("${args[@]}" -subj "$1" -key "$2")
66
67 "${args[@]}"