Debian Codegraph @

samples/swtpm-create-tpmca

raw
1 #!/usr/bin/env bash
2
3 FLAG_OVERWRITE=1
4 FLAG_REGISTER_KEY=2
5 FLAG_TPMTOOL_SUPPORTS_SRK_WELL_KNOWN=4
6 FLAG_SRK_WELL_KNOWN=8
7 FLAG_TPM2=16
8
9 TSS_TCSD_HOSTNAME_DEFAULT=localhost
10 TSS_TCSD_PORT_DEFAULT=30003
11
12 logit()
13 {
14 if [ -z "$LOGFILE" ]; then
15 echo "$@" >&1
16 else
17 echo "$@" >> "$LOGFILE"
18 fi
19 }
20
21 logerr()
22 {
23 if [ -z "$LOGFILE" ]; then
24 echo "Error: $*" >&2
25 else
26 echo "Error: $*" >> "$LOGFILE"
27 fi
28 }
29
30 # Get the size of a file in bytes
31 #
32 # @1: filename
33 function get_filesize()
34 {
35 if [[ "$(uname -s)" =~ (Linux|CYGWIN_NT-) ]]; then
36 stat -c%s "$1"
37 else
38 # OpenBSD
39 stat -f%z "$1"
40 fi
41 }
42
43 # Create a config value by escaping the proper characters
44 #
45 # @param 1: The string to escape
46 function escape_pkcs11_url()
47 {
48 echo "${1//;/\\;}"
49 }
50
51 # Use expect for automating the interaction with the tpmtool
52 #
53 # @param 1...: parameters to pass to tpmtool command line
54 #
55 # TPM_SRK_PASSWORD and TPM_KEY_PASSWORD global variables are used
56 # for the SRK and key passwords respectively.
57 run_tpmtool() {
58 local prg out rc
59
60 if [ -z "$(type -P tpmtool)" ]; then
61 echo "Could not find tpmtool in PATH (${PATH})."
62 return 1
63 fi
64
65 # shellcheck disable=SC2124,SC2027
66 prg="spawn tpmtool "$@"
67 expect {
68 \"Enter SRK password:\" {
69 send \"${TPM_SRK_PASSWORD}\n\"
70 exp_continue
71 }
72 \"Enter key password:\" {
73 send \"${TPM_KEY_PASSWORD}\n\"
74 exp_continue
75 }
76 \"tpmkey:\" {
77 send_user \"\n\"
78 }
79 eof {
80 exit
81 }
82 }
83 catch wait result
84 exit [lindex \$result 3]
85 "
86 out=$(expect -c "${prg}")
87 rc=$?
88 echo "${out}"
89 return $rc
90 } #run_tpmtool
91
92 create_localca_cert() {
93 local flags=$1
94 local dir="$2"
95 local outfile="$3"
96 local owner="$4"
97 local pid="$5" # TPM2 parameter
98
99 local cakey=${dir}/swtpm-localca-rootca-privkey.pem
100 local cacert=${dir}/swtpm-localca-rootca-cert.pem
101 local tpmkey=${dir}/swtpm-localca-tpmca-privkey.pem
102 local tpmpubkey=${dir}/swtpm-localca-tpmca-pubkey.pem
103 local tpmca=${dir}/swtpm-localca-tpmca-cert.pem
104 local template=${dir}/template
105 local tpmkeyurl
106 local msg output
107
108 if ! [ -r "${cakey}" ] || ! [ -r "${cacert}" ]; then
109 if ! msg=$("${CERTTOOL}" \
110 --generate-privkey \
111 ${SWTPM_ROOTCA_PASSWORD:+--password "${SWTPM_ROOTCA_PASSWORD}"} \
112 --outfile "${cakey}" \
113 2>&1);
114 then
115 logerr "Could not create root-CA key ${cakey}."
116 logerr "${msg}"
117 return 1
118 fi
119 chmod 640 "${cakey}"
120
121 {
122 echo "cn=swtpm-localca-rootca"
123 echo "ca"
124 echo "cert_signing_key"
125 echo "expiration_days = 3650"
126 } > "${template}"
127
128 if ! msg=$(GNUTLS_PIN="${SWTPM_ROOTCA_PASSWORD}" ${CERTTOOL} \
129 --generate-self-signed \
130 --template "${template}" \
131 --outfile "${cacert}" \
132 --load-privkey "${cakey}" \
133 2>&1);
134 then
135 logerr "Could not create root CA."
136 logerr "${msg}"
137 rm -f "${cakey}" "${template}"
138 return 1
139 fi
140 else
141 logit "Reusing existing root CA"
142 fi
143
144 rm -f "${tpmkey}" "${tpmpubkey}" "${tpmca}"
145
146 if [ $((flags & FLAG_TPM2)) -ne 0 ]; then
147 local tokenurl tpmkeyurl
148 local token="swtpm-tpmca-${pid}"
149 local label="${token}" # must be same
150 local keylabel="swtpm-tpmca-key"
151 local userpin="${SWTPM_PKCS11_PIN:-swtpm-tpmca}"
152
153 tokenurl=$(p11tool --list-tokens 2>&1 | \
154 grep -E ";token=${token}\$" | \
155 sed -n "s/.*URL: //p")
156 if [ -z "${tokenurl}" ]; then
157 if [ -z "${SWTPM_PKCS11_SO_PIN}" ]; then
158 logerr "The env. variable SWTPM_PKCS11_SO_PIN must be set to create token ${label}."
159 return 1
160 fi
161 if ! msg=$(tpm2_ptool addtoken \
162 --pid "${pid}" \
163 --sopin "${SWTPM_PKCS11_SO_PIN}" \
164 --userpin "${userpin}" \
165 --label "${label}" 2>&1);
166 then
167 logerr "Error: Could not create pkcs11 token"
168 logerr "${msg}"
169 return 1
170 fi
171 tokenurl=$(p11tool --list-tokens 2>&1 | \
172 grep -E ";token=${token}\$" | \
173 sed -n "s/.*URL: //p")
174 if [ -z "${tokenurl}" ]; then
175 logerr "Error: Could not get token URL for token '${token}'"
176 logerr "${msg}"
177 return 1
178 fi
179 if ! msg=$(tpm2_ptool config \
180 --key tcti \
181 --value tabrmd \
182 --label "${label}");
183 then
184 logerr "Error: Could not set config value for tcti key"
185 logerr "${msg}"
186 return 1
187 fi
188 fi
189
190 export GNUTLS_PIN="${userpin}"
191 # GNUTLS_SO_PIN not needed at this point
192
193 if msg="$(p11tool --login --list-keys "${tokenurl}" 2>&1)"; then
194 tpmkeyurl=$(echo "${msg}" | \
195 grep ";object=${keylabel}" | \
196 sed -n "s/.*URL: //p")
197 fi
198 if [ -z "${tpmkeyurl}" ]; then
199 if ! msg=$(tpm2_ptool addkey \
200 "--label=${label}" \
201 "--userpin=${userpin}" \
202 --algorithm=rsa2048 \
203 "--key-label=${keylabel}" \
204 --id 1 2>&1);
205 then
206 logerr "Error: Could not create create key under pkcs11 token ${token}"
207 logerr "${msg}"
208 return 1
209 fi
210 if ! msg="$(p11tool --login --list-keys "${tokenurl}" 2>&1)"; then
211 logerr "Error: Could not get TPM key URL for ${tokenurl}"
212 logerr "${msg}"
213 return 1
214 fi
215 tpmkeyurl=$(echo "${msg}" | \
216 grep ";object=${keylabel}" | \
217 sed -n "s/.*URL: //p")
218 if [ -z "${tpmkeyurl}" ]; then
219 logerr "Error: Could not get TPM key URL for ${tokenurl}"
220 logerr "${msg}"
221 return 1
222 fi
223 fi
224 rm -f "${tpmpubkey}"
225
226 if ! msg=$(p11tool --export-pubkey "${tpmkeyurl}" --login --outfile "${tpmpubkey}" 2>&1) || \
227 [ ! -r "${tpmpubkey}" ] || [ "$(get_filesize "${tpmpubkey}")" -eq 0 ]; then
228 logerr "Error: Could not get TPM public key"
229 logerr "${msg}"
230 rm -f "${tpmkey}" "${tpmpubkey}"
231 return 1
232 fi
233 else
234 local params=""
235
236 if [ $((flags & FLAG_SRK_WELL_KNOWN)) -ne 0 ]; then
237 unset GNUTLS_PIN
238 params="--srk-well-known"
239 else
240 export GNUTLS_PIN="${TPM_SRK_PASSWORD}"
241 fi
242
243 if [ $((flags & FLAG_REGISTER_KEY)) -ne 0 ]; then
244 if ! msg="$(run_tpmtool --generate-rsa --signing --register ${params})"; then
245 logerr "Could not generate registered signing key with tpmtool"
246 logerr "${msg}"
247 return 1
248 fi
249 tpmkeyurl=$(echo "${msg}" | sed -n 's/\(tpmkey:uuid=[^;]*\);.*/\1/p')
250 if [ -z "${tpmkeyurl}" ]; then
251 logerr "Could not parse tpmkey URL"
252 logerr "${msg}"
253 return 1
254 fi
255 else
256 rm -f "${tpmkey}"
257 # shellcheck disable=SC2086
258 if ! msg="$(run_tpmtool --generate-rsa --signing --outfile \"${tpmkey}\" ${params})"; then
259 logerr "Could not create signing key with tpmtool"
260 logerr "${msg}"
261 rm -f "${tpmkey}"
262 return 1
263 fi
264 if [ ! -r "${tpmkey}" ] || [ "$(get_filesize "${tpmkey}")" -eq 0 ]; then
265 logerr "The TPM key file ${tpmkey} was not written properly"
266 logerr "${msg}"
267 rm -f "${tpmkey}"
268 return 1
269 fi
270 chmod 640 "${tpmkey}"
271 tpmkeyurl="tpmkey:file=${tpmkey}"
272 fi
273
274 rm -f "${tpmpubkey}"
275 # shellcheck disable=SC2086
276 if ! msg=$(run_tpmtool "--pubkey=${tpmkeyurl}" --outfile \"${tpmpubkey}\" ${params}) || \
277 [ ! -r "${tpmpubkey}" ] || [ "$(get_filesize "${tpmpubkey}")" -eq 0 ]; then
278 logerr "Error: Could not get TPM public key"
279 logerr "${msg}"
280 rm -f "${tpmkey}" "${tpmpubkey}"
281 return 1
282 fi
283 fi
284
285 {
286 echo "cn=swtpm-localca"
287 echo "ca"
288 echo "cert_signing_key"
289 echo "expiration_days = 3650"
290 } > "${template}"
291
292 if ! msg=$(${CERTTOOL} \
293 --generate-certificate \
294 --template "${template}" \
295 --outfile "${tpmca}" \
296 --load-ca-privkey "${cakey}" \
297 --load-ca-certificate "${cacert}" \
298 --load-privkey "${tpmkeyurl}" \
299 --load-pubkey "${tpmpubkey}" \
300 2>&1);
301 then
302 logerr "Could not create TPM CA"
303 logerr "${msg}"
304 rm -f "${template}"
305 return 1
306 fi
307
308 output="statedir = ${dir}
309 signingkey = $(escape_pkcs11_url "${tpmkeyurl}")
310 issuercert = ${tpmca}
311 certserial = ${dir}/certserial"
312
313 if [ $((flags & FLAG_TPM2)) -eq 0 ]; then
314 output+="$(echo -e "\nTSS_TCSD_HOSTNAME = ${TSS_TCSD_HOSTNAME}")"
315 output+="$(echo -e "\nTSS_TCSD_PORT = ${TSS_TCSD_PORT}")"
316 else
317 output+="$(echo -e "\nSWTPM_PKCS11_PIN = ${SWTPM_PKCS11_PIN}")"
318 # output+="$(echo -e "\nSWTPM_PKCS11_SO_PIN = ${SWTPM_PKCS11_SO_PIN}")"
319 fi
320 if [ -n "${TPM_KEY_PASSWORD}" ]; then
321 output+="$(echo -e "\nsigningkey_password = ${TPM_KEY_PASSWORD}")"
322 fi
323 if [ -n "${TPM_SRK_PASSWORD}" ]; then
324 output+="$(echo -e "\nparentkey_password = ${TPM_SRK_PASSWORD}")"
325 fi
326
327 if [ -n "${outfile}" ]; then
328 echo "${output}" > "${outfile}"
329 chmod 640 "${outfile}"
330 fi
331 echo "${output}"
332
333 if [ "$(id -u)" -eq 0 ]; then
334 chown "${owner}:${group}" "${dir}"
335
336 if pushd "${dir}" &>/dev/null; then
337 chown "${owner}:${group}" ./*
338 popd &>/dev/null || return 1
339 fi
340
341 if [ -n "${outfile}" ]; then
342 chown "${owner}:${group}" "${outfile}"
343 fi
344 fi
345
346 rm -f "${template}"
347
348 return 0
349 } #create_localca_cert
350
351 usage() {
352 local flags=$2
353
354 local tpmtool_note=" use 'well known' password if not
355 given"
356 [ $((flags & FLAG_TPMTOOL_SUPPORTS_SRK_WELL_KNOWN)) -eq 0 ] && \
357 tpmtool_note="
358 Note: the well known password of 20 zero bytes is not
359 supported by tpmtool"
360
361 cat << _EOF_
362 Create a TPM-based CA for signing EK and platform certificates.
363
364 Usage: $(basename "$1") [options]
365
366 THIS SCRIPT IS EXPERIMENTAL
367
368 The following options are supported:
369
370 --dir directory Directory where to write the CA files into; must not exist
371 unless --overwrite is passed
372 --overwrite Overwrite any data in an existing directory; tries to
373 reuse a root CA if one is found there
374 --register Create a registered TPM 1.2 key rather than a file that
375 contains the key; this option has no effect if --tpm2 is
376 used
377 --key-password s Password for the newly created TPM key; required if
378 --register is not passed
379 Note: use the same as the --srk-password (bug in certtool)
380 --srk-password s Password for the TPM's SRK;${tpmtool_note}
381 --outfile file File to write the configuration to; if not passed it will be
382 written to stdout only
383 --owner owner The owner of the directory and the files; only set if this
384 script is run as root; recommended to be 'tss'
385 --group group The group owning the directory and the files;
386 recommended to be 'tss'
387 --tss-tcsd-hostname hostname
388 The name of the host where tcsd (TrouSerS daemon) is running
389 on; default is '${TSS_TCSD_HOSTNAME_DEFAULT}'
390 --tss-tcsd-port p The TCP port on which tcsd is listening for connections;
391 default is ${TSS_TCSD_PORT_DEFAULT}
392 --tpm2 Setup a CA that uses a TPM 2.0
393 --pid <pid> Pimary object Id used by tpm2_ptool; only valid if --tpm2
394 is used
395 --help, -h, -? Display this help screen and exit
396
397
398 The following environment variables are supported:
399
400 SWTPM_ROOTCA_PASSWORD The root CA's private key password
401
402 _EOF_
403 } #usage
404
405 # Check whether tpmtool supports --srk-well-known
406 tpmtool_supports_srk_well_known()
407 {
408 local tmp
409
410 [ -z "$(type -P tpmtool)" ] && return 1
411
412 tmp=$(tpmtool --help | grep "srk-well-known")
413 [ -z "${tmp}" ] && return 1
414 return 0
415 }
416
417 main() {
418 local flags=0
419 local dir outfile owner group msg pid
420
421 if tpmtool_supports_srk_well_known; then
422 flags=$((flags | FLAG_TPMTOOL_SUPPORTS_SRK_WELL_KNOWN | FLAG_SRK_WELL_KNOWN))
423 fi
424
425 CERTTOOL=certtool
426 export TSS_TCSD_HOSTNAME=${TSS_TCSD_HOSTNAME_DEFAULT}
427 export TSS_TCSD_PORT=${TSS_TCSD_PORT_DEFAULT}
428
429 while [ $# -ne 0 ]; do
430 case "$1" in
431 --dir)
432 shift
433 dir="$1"
434 ;;
435 --overwrite)
436 flags=$((flags | FLAG_OVERWRITE))
437 ;;
438 --register)
439 flags=$((flags | FLAG_REGISTER_KEY))
440 ;;
441 --srk-password)
442 shift
443 TPM_SRK_PASSWORD="$1"
444 flags=$((flags & ~FLAG_SRK_WELL_KNOWN))
445 ;;
446 --key-password)
447 shift
448 TPM_KEY_PASSWORD="$1"
449 ;;
450 --outfile)
451 shift
452 outfile="$1"
453 ;;
454 --owner)
455 shift
456 owner="$1"
457 ;;
458 --group)
459 shift
460 group="$1"
461 ;;
462 --tss-tcsd-hostname)
463 shift
464 TSS_TCSD_HOSTNAME="$1"
465 ;;
466 --tss-tcsd-port)
467 shift
468 TSS_TCSD_PORT="$1"
469 ;;
470 --tpm2)
471 flags=$((flags | FLAG_TPM2))
472 ;;
473 --pid)
474 shift
475 pid="$1"
476 ;;
477 --help|-h|-?)
478 usage "$0" "${flags}"
479 exit 0
480 ;;
481 *)
482 logerr "Unsupported option $1"
483 exit 1
484 ;;
485 esac
486 shift
487 done
488 if [ -z "${dir}" ]; then
489 logerr "Missing --dir option."
490 return 1
491 fi
492 # strip trailing '/' from dir
493 dir="$(echo "${dir}" | sed -n 's|[/]*$||p')"
494
495 if [ -d "${dir}" ] && [ $((flags & FLAG_OVERWRITE)) -eq 0 ]; then
496 logerr "Refusing to overwrite existing directory ${dir}."
497 return 1
498 fi
499
500 if [ -z "${TPM_SRK_PASSWORD}" ] && [ $((flags & FLAG_TPM2)) -eq 0 ] &&
501 [ $((flags & FLAG_TPMTOOL_SUPPORTS_SRK_WELL_KNOWN)) -eq 0 ]; then
502 logerr "SRK password must be provided"
503 return 1
504 fi
505
506 if [ -z "${TPM_KEY_PASSWORD}" ] && \
507 [ $((flags & FLAG_REGISTER_KEY)) -eq 0 ] && \
508 [ $((flags & FLAG_TPM2)) -eq 0 ]; then
509 logerr "Key password is required"
510 return 1
511 fi
512
513 if [ $((flags & FLAG_TPM2)) -ne 0 ] && [ -z "${pid}" ]; then
514 logerr "--pid is required for TPM 2"
515 return 1
516 fi
517
518 if [ "$(id -u)" -eq 0 ]; then
519 if [ -n "${owner}" ]; then
520 if ! msg="$(id -u "${owner}" 2>&1)"; then
521 logerr "User ${owner} cannot be used: ${msg}"
522 return 1
523 fi
524 else
525 owner="root"
526 fi
527 if [ -n "${group}" ]; then
528 if ! msg="$(id -g "${group}" 2>&1)"; then
529 logerr "Group ${group} cannot be used: ${msg}"
530 return 1
531 fi
532 else
533 group="root"
534 fi
535 fi
536
537 if ! mkdir -p "${dir}"; then
538 logerr "Could not create directory ${dir}."
539 return 1
540 fi
541
542 create_localca_cert "${flags}" "${dir}" "${outfile}" "${owner}" "${pid}"
543 return $?
544 } #main
545
546 main "$@"
547 exit $?