aboutsummaryrefslogtreecommitdiff
path: root/pki
blob: 9a94121242d874bc414038e741cdd56e5ff59b08 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#!/bin/sh
#
# Utility to manage an internal certificate authority using OpenSSL.

set -eu

PROGNAME=pki
USAGE="<init|cert|client-cert|renew>"
BOXCONF_ROOT=$(dirname "$(readlink -f "$0")")

BOXCONF_CA_PASSWORD_FILE="${BOXCONF_ROOT}/.ca_password"
CA_VALID_DAYS=3650
DEFAULT_VALID_DAYS=3650
EC_CURVE=prime256v1
DIGEST=sha256
CIPHER=aes256

usage(){
  printf 'usage: %s %s\n' "$PROGNAME" "$USAGE" 2>&1
  exit 2
}

_pki_get_ca_password(){
  # Acquire the CA password.
  # If the BOXCONF_CA_PASSWORD environment variable is set, use that.
  # Next, try reading the password from the .ca_password file.
  # If all else fails, prompt interactively.
  if [ -n "${BOXCONF_CA_PASSWORD:-}" ]; then
    return
  elif [ -f "$BOXCONF_CA_PASSWORD_FILE" ]; then
    BOXCONF_CA_PASSWORD=$(cat "$BOXCONF_CA_PASSWORD_FILE")
  else
    _boxconf_read_password 'Enter CA password: ' BOXCONF_CA_PASSWORD
  fi
}

_pki_dn2cnf() {
  # Convert an LDAP DN to its OpenSSL .cnf file representation.
  echo "$1" \
    | tr ',' '\n' \
    | awk '{a[i++]=$0} END {for (j=i-1; j>=0;) print a[j--] }' \
    | sed                                        \
      -e 's/^[Cc][Nn]=/commonName=/'             \
      -e 's/^[Oo]=/organizationName=/'           \
      -e 's/^[Oo][Uu]=/organizationalUnitName=/' \
      -e 's/^[Dd][Cc]=/domainComponent=/'        \
      -e 's/^[Cc]=/countryName=/'                \
      -e 's/^[Ss][Tt]=/stateOrProvinceName=/'    \
      -e 's/^[Ll]=/locality=/'                   \
      -e 's/^[Ss][Nn]=/surName=/'                \
      -e 's/^[Gg][Nn]=/givenName=/'              \
      -e 's/^[Uu][Ii][Dd]=/userId=/'             \
    | awk '{print NR-1 "." $0}'
}

_pki_postsign(){
  # Create symlinks and delete temp files after signing a certificate.
  # $1 = certificate path

  # Create symlink with human-readable name.
  serial=$(awk 'END{print $3}' "${BOXCONF_CA_DIR}/index.txt")
  ln -sf "../certs/${serial}.pem" "${BOXCONF_CA_DIR}/${1}.crt"

  # Create fullchain certificate.
  cat "${BOXCONF_CA_DIR}/${1}.crt" "${BOXCONF_CA_DIR}/ca.crt" > "${BOXCONF_CA_DIR}/${1}.fullchain.crt"

  # Delete useless files.
  rm -f                             \
    "${BOXCONF_CA_DIR}/index.txt.old"      \
    "${BOXCONF_CA_DIR}/index.txt.attr.old" \
    "${BOXCONF_CA_DIR}/serial.old"
}

_pki_sign(){
  # Given an OpenSSL config file, generate a signed certificate keypair.
  # $1 = certificate path
  # $2 = validity time (days)

  # Generate encrypted private key for the server certificate.
  PASS="$BOXCONF_VAULT_PASSWORD" openssl genpkey     \
    -algorithm ec                            \
    -pkeyopt "ec_paramgen_curve:${EC_CURVE}" \
    "-${CIPHER}"                             \
    -pass env:PASS                           \
    -out "${BOXCONF_CA_DIR}/${1}.key"

  # Generate the CSR.
  PASS="$BOXCONF_VAULT_PASSWORD" openssl req -new \
    -key "${BOXCONF_CA_DIR}/${1}.key"         \
    "-${DIGEST}"                          \
    -passin env:PASS                      \
    -config "${BOXCONF_CA_DIR}/${1}.cnf"      \
    -out "${BOXCONF_CA_DIR}/${1}.csr"

  # Sign the certificate.
  PASS="$BOXCONF_CA_PASSWORD" openssl ca -batch \
    -config "${BOXCONF_CA_DIR}/ca.cnf"         \
    -passin env:PASS                    \
    ${2:+-days $2}                \
    -notext                             \
    -out /dev/null                      \
    -outdir "${BOXCONF_CA_DIR}/certs"          \
    -infiles "${BOXCONF_CA_DIR}/${1}.csr"

  _pki_postsign "$1"
}

_pki_renew(){
  # Re-sign an existing certificate.
  # $1 = certificate path
  # $2 = validity time (time)
  _pki_get_ca_password

  # Sign the certificate.
  PASS="$BOXCONF_CA_PASSWORD" openssl ca -batch \
    -config "${BOXCONF_CA_DIR}/ca.cnf"         \
    -passin env:PASS                    \
    ${2:+-days $2}                \
    -notext                             \
    -out /dev/null                      \
    -outdir "${BOXCONF_CA_DIR}/certs"          \
    -infiles "${BOXCONF_CA_DIR}/${1}.csr"

  _pki_postsign "$1"
}

pki_init(){
  # Initialize the CA. Create CA cert, private key, and OpenSSL configuration.
  USAGE='init [-c CONSTRAINT]... DOMAIN'

  constraints=''
  while getopts :c: opt; do
    case $opt in
      c) constraints="${constraints}, permitted;${OPTARG}" ;;
      :) usage ;;
      ?) usage ;;
    esac
  done
  shift $((OPTIND - 1 ))

  [ $# -eq 1 ] || usage
  domain=$1

  [ -d "$BOXCONF_CA_DIR" ] && die 'CA already exists'
  _pki_get_ca_password
  mkdir -p "${BOXCONF_CA_DIR}/certs"

  # Generate encrypted private key for CA.
  PASS="$BOXCONF_CA_PASSWORD" openssl genpkey        \
    -algorithm ec                            \
    -pkeyopt "ec_paramgen_curve:${EC_CURVE}" \
    "-${CIPHER}"                             \
    -pass env:PASS                           \
    -out "${BOXCONF_CA_DIR}/ca.key"

  # Create a config file for the CA certificate.
  cat > "${BOXCONF_CA_DIR}/ca.cnf" <<EOF
[ req ]
x509_extensions = v3_req
distinguished_name = req_distinguished_name
prompt = no

[ v3_req ]
basicConstraints = critical, CA:TRUE, pathlen:0
keyUsage = critical, keyCertSign, cRLSign
nameConstraints = permitted;DNS:${domain}, permitted;DNS:.${domain}, permitted;email:.${domain}${constraints}

[ req_distinguished_name ]
O = ${domain}
CN = Certificate Authority

[ ca ]
preserve   = yes
default_ca = CA_own

[ CA_own ]
dir              = .${BOXCONF_CA_DIR#${BOXCONF_ROOT}}
new_certs_dir    = \$dir/certs
database         = \$dir/index.txt
rand_serial      = yes
unique_subject   = no
certificate      = \$dir/ca.crt
private_key      = \$dir/ca.key
default_days     = ${DEFAULT_VALID_DAYS}
default_crl_days = 30
default_md       = ${DIGEST}
preserve         = yes
policy           = policy_anything
copy_extensions  = copy
x509_extensions  = v3

[ v3 ]
basicConstraints = critical, CA:FALSE

[ policy_anything ]
countryName            = optional
stateOrProvinceName    = optional
localityName           = optional
organizationName       = optional
organizationalUnitName = optional
commonName             = optional
emailAddress           = optional
EOF

  # Self-sign the CA certificate.
  PASS="$BOXCONF_CA_PASSWORD" openssl req -new -x509 \
    -days "$CA_VALID_DAYS"                               \
    "-${DIGEST}"                             \
    -passin env:PASS                         \
    -config "${BOXCONF_CA_DIR}/ca.cnf"              \
    -key "${BOXCONF_CA_DIR}/ca.key"                 \
    -out "${BOXCONF_CA_DIR}/ca.crt"

  # Create empty index db.
  [ -f "${BOXCONF_CA_DIR}/index.txt" ] || touch "${BOXCONF_CA_DIR}/index.txt"
}

pki_server(){
  # Create a server certificate keypair.
  USAGE='server-cert [-d DAYS] HOSTNAME CERTNAME SAN...'

  while getopts :d: opt; do
    case $opt in
      d)   days=$OPTARG ;;
      :|?) usage ;;
    esac
  done
  shift $((OPTIND - 1 ))

  [ $# -ge 3 ] || usage
  hostname=$1; certname=$2; cn=${3#*:}
  shift 2

  [ -e "${BOXCONF_CA_DIR}/${hostname}/${certname}.cnf" ] && die "certificate already exists: ${hostname}/${certname}"

  _pki_get_ca_password
  _boxconf_get_vault_password

  # Generate the SAN list. If the arg contains a ':', pass along as-is.
  # If no ':' is present, assume type 'DNS:'.
  while [ $# -gt 0 ]; do
    if [ "${1#*:}" = "$1" ]; then
      sans="${sans:+${sans},}DNS:${1}"
    else
      sans="${sans:+${sans},}${1}"
    fi
    shift
  done

  # Create host directory.
  mkdir -p "${BOXCONF_CA_DIR}/${hostname}"

  # Create a config file for the server certificate.
  cat > "${BOXCONF_CA_DIR}/${hostname}/${certname}.cnf" <<EOF
[ req ]
req_extensions = v3_req
distinguished_name = req_distinguished_name
prompt = no

[ v3_req ]
basicConstraints = critical,CA:FALSE
extendedKeyUsage = serverAuth
subjectAltName = ${sans}

[ req_distinguished_name ]
CN = ${cn}
EOF

  # Generate and sign the certificate.
  _pki_sign "${hostname}/${certname}" "${days:-}"
}

pki_client(){
  # Create a client certificate keypair.
  USAGE='client-cert HOSTNAME CERTNAME DN [SAN...]'

  while getopts :d: opt; do
    case $opt in
      d)   days=$OPTARG ;;
      :|?) usage ;;
    esac
  done
  shift $((OPTIND - 1 ))

  [ $# -ge 3 ] || usage
  hostname=$1; certname=$2; dn=$3
  shift 3

  [ -e "${BOXCONF_CA_DIR}/${hostname}/${certname}.cnf" ] && die "certificate already exists: ${hostname}/${certname}"

  _pki_get_ca_password
  _boxconf_get_vault_password

  # Generate the SAN list.
  if [ $# -gt 0 ]; then
    sans=$1; shift
    while [ $# -gt 0 ]; do
      sans="${sans}, ${1}"
      shift
    done
  fi

  # Create host directory.
  mkdir -p "${BOXCONF_CA_DIR}/${hostname}"

  # Create a config file for the client certificate.
  cat > "${BOXCONF_CA_DIR}/${hostname}/${certname}.cnf" <<EOF
[ req ]
req_extensions = v3_req
distinguished_name = req_distinguished_name
prompt = no

[ v3_req ]
basicConstraints = critical,CA:FALSE
extendedKeyUsage = clientAuth
${sans:+subjectAltName = $sans}

[ req_distinguished_name ]
$(_pki_dn2cnf "$dn")
EOF

  # Generate and sign the certificate.
  _pki_sign "${hostname}/${certname}" "${days:-}"
}


pki_renew(){
  # Renew an existing certificate.
  USAGE='renew [-d DAYS] HOSTNAME CERTNAME'

  while getopts :d: opt; do
    case $opt in
      d)   days=$OPTARG ;;
      :|?) usage ;;
    esac
  done
  shift $((OPTIND - 1 ))
  [ $# -eq 2 ] || usage

  [ -f "${BOXCONF_CA_DIR}/${1}/${2}.csr" ] || die "CSR does not exist: ${1}/${2}.csr"

  _pki_renew "${1}/${2}" "${days:-}"
}

[ $# -ge 1 ] || usage
action=$1; shift

for _bc_lib in "${BOXCONF_ROOT}/lib"/*; do
  . "$_bc_lib"
done

case $action in
  init)                    pki_init "$@" ;;
  server-cert|server|cert) pki_server "$@" ;;
  client-cert|client)      pki_client "$@" ;;
  renew)                   pki_renew "$@" ;;
  *)                       usage ;;
esac