forked from imperador/chromefy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathswtpm_setup.sh
executable file
·2235 lines (1918 loc) · 56.4 KB
/
swtpm_setup.sh
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
#
# swtpm_setup.sh
#
# Authors: Stefan Berger <[email protected]>
#
# (c) Copyright IBM Corporation 2011,2014,2015.
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# Neither the names of the IBM Corporation nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# echo "UID=$UID EUID=$EUID"
# Dependencies:
#
# - tpm_tools (tpm-tools package with NVRAM utilities)
# - tcsd (trousers package with tcsd with -c <configfile> option)
# - expect (expect package)
SWTPM=`type -P swtpm`
if [ -n "$SWTPM" ]; then
SWTPM="$SWTPM socket"
fi
SWTPM_IOCTL=`type -P swtpm_ioctl`
ECHO=`which echo`
if [ -z "$ECHO" ]; then
echo "Error: external echo program not found."
exit 1
fi
UNAME_S="$(uname -s)"
SETUP_CREATE_EK_F=1
SETUP_TAKEOWN_F=2
SETUP_EK_CERT_F=4
SETUP_PLATFORM_CERT_F=8
SETUP_LOCK_NVRAM_F=16
SETUP_SRKPASS_ZEROS_F=32
SETUP_OWNERPASS_ZEROS_F=64
SETUP_STATE_OVERWRITE_F=128
SETUP_STATE_NOT_OVERWRITE_F=256
SETUP_TPM2_F=512
SETUP_ALLOW_SIGNING_F=1024
SETUP_TPM2_ECC_F=2048
SETUP_CREATE_SPK_F=4096
SETUP_DISPLAY_RESULTS_F=8192
SETUP_DECRYPTION_F=16384
# default values for passwords
DEFAULT_OWNER_PASSWORD=ooo
DEFAULT_SRK_PASSWORD=sss
# default configuration file
DEFAULT_CONFIG_FILE="${XDG_CONFIG_HOME:-/etc}/swtpm_setup.conf"
#default PCR banks to activate for TPM 2
DEFAULT_PCR_BANKS="sha1,sha256"
# TPM constants
TPM_NV_INDEX_D_BIT=$((0x10000000))
TPM_NV_INDEX_EKCert=$((0xF000))
TPM_NV_INDEX_PlatformCert=$((0xF002))
TPM_NV_INDEX_LOCK=$((0xFFFFFFFF))
# TPM 2 constants
TPMA_NV_PLATFORMCREATE=$((0x40000000))
TPMA_NV_AUTHWRITE=$((0x4))
TPMA_NV_AUTHREAD=$((0x40000))
TPMA_NV_NO_DA=$((0x2000000))
TPMA_NV_PPWRITE=$((0x1))
TPMA_NV_PPREAD=$((0x10000))
TPMA_NV_OWNERREAD=$((0x20000))
TPMA_NV_POLICY_DELETE=$((0x400))
TPMA_NV_WRITEDEFINE=$((0x2000))
# Use standard EK Cert NVRAM, EK and SRK handles per IWG spec.
# "TCG TPM v2.0 Provisioning Guide"; Version 1.0, Rev 1.0, March 15, 2017
# Table 2
TPM2_NV_INDEX_RSA_EKCert=$((0x01c00002))
TPM2_NV_INDEX_RSA_EKTemplate=$((0x01c00004))
# For ECC follow "TCG EK Credential Profile For TPM Family 2.0; Level 0"
# Specification Version 2.1; Revision 12; 17 August 2018 (Draft)
TPM2_NV_INDEX_ECC_EKCert=$((0x01c0000a))
TPM2_NV_INDEX_ECC_EKTemplate=$((0x01c0000c))
TPM2_NV_INDEX_PlatformCert=$((0x01c08000))
TPM2_EK_HANDLE=$((0x81010001))
TPM2_SPK_HANDLE=$((0x81000001))
# Default logging goes to stderr
LOGFILE=""
TPMLIB_INFO_TPMSPECIFICATION=1
TPMLIB_INFO_TPMATTRIBUTES=2
NB16='\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
NB32=${NB16}${NB16}
NB256=${NB32}${NB32}${NB32}${NB32}${NB32}${NB32}${NB32}${NB32}
# Nonce used for EK creation; 2 bytes length + nonce
NONCE_RSA='\x01\x00'${NB256}
NONCE_RSA_SIZE=256
NONCE_ECC='\x00\x20'${NB32}
NONCE_ECC_SIZE=32
trap "cleanup" SIGTERM EXIT
logit()
{
if [ -z "$LOGFILE" ]; then
echo "$@" >&1
else
echo "$@" >> $LOGFILE
fi
}
logit_cmd()
{
if [ -z "$LOGFILE" ]; then
eval "$@" >&1
else
eval "$@" >> $LOGFILE
fi
}
logerr()
{
if [ -z "$LOGFILE" ]; then
echo "Error: $@" >&2
else
echo "Error: $@" >> $LOGFILE
fi
}
# Get the size of a file
#
# @param1: filename
get_filesize()
{
case "${UNAME_S}" in
OpenBSD|FreeBSD|NetBSD|Darwin|DragonFly)
stat -f%z $1
;;
*)
stat -c%s $1
;;
esac
}
# Get a random number given a lower and upper bound
#
# @param1: lower bound
# @param2: upper bound
get_random()
{
local lower=$1
local upper=$2
echo $(( (RANDOM % (upper - lower)) + lower))
}
# Get the TPM specification parameters from the TPM using swtpm_ioctl
get_tpm_parameters()
{
local json
local res part arr
json="$($SWTPM_IOCTL \
--info $((TPMLIB_INFO_TPMSPECIFICATION |
TPMLIB_INFO_TPMATTRIBUTES)) \
--tcp :$((TPM_PORT+1)) 2>&1)"
if [ $? -ne 0 ]; then
logerr "Error: $SWTPM_IOCTL failed: $json"
return 1
fi
for params in \
's/.*"family":\s*"\([^"]*\)".*/\1/p --tpm-spec-family' \
's/.*"level":\s*\([0-9\.]*\).*/\1/p --tpm-spec-level' \
's/.*"revision":\s*\([0-9]*\).*/\1/p --tpm-spec-revision' \
's/.*"manufacturer":\s*"\([^"]*\)".*/\1/p --tpm-manufacturer' \
's/.*"model":\s*"\([^"]*\)".*/\1/p --tpm-model' \
's/.*"version":\s*"\([^"]*\)".*/\1/p --tpm-version';
do
arr=($params)
part=$(echo "$json" | sed -n "${arr[0]}")
if [ -z "$part" ]; then
logerr "Error: Could not parse JSON output"
logerr " No result from \"echo '$json' | sed -n '${arr[0]}'\""
return 1
fi
res+="${arr[1]} ${part} "
done
echo "${res}"
return 0
}
# Call external program to create certificates
#
# @param1: flags
# @param2: the configuration file to get the external program from
# @parma3: the directory where to write the certificates to
# @param4: the EK as a sequence of hex nunbers
# @param5: the ID of the VM
call_create_certs()
{
local ret=0
local flags="$1"
local configfile="$2"
local certdir="$3"
local ek="$4"
local vmid="$5"
local logparam tmp
local params="" cmd
if [ -n "$vmid" ]; then
params="$params --vmid \"$vmid\""
fi
if [ -n "$LOGFILE" ]; then
logparam="--logfile $LOGFILE"
fi
params="${params} $(get_tpm_parameters)"
[ $? -ne 0 ] && return 1
if [ $((flags & SETUP_EK_CERT_F)) -ne 0 ] || \
[ $((flags & SETUP_PLATFORM_CERT_F)) -ne 0 ]; then
if [ -r "$configfile" ]; then
# The config file contains lines in the format:
# key = value
# or with a comment at the end started by #:
# key = value # comment
create_certs_tool="$(sed -n 's/\s*create_certs_tool\s*=\s*\([^#]*\).*/\1/p' \
"$configfile")"
create_certs_tool_config="$(sed -n 's/\s*create_certs_tool_config\s*=\s*\([^#]*\).*/\1/p' \
"$configfile")"
if [ -n "$create_certs_tool_config" ]; then
params="$params --configfile \"$create_certs_tool_config\""
fi
create_certs_tool_options="$(sed -n 's/\s*create_certs_tool_options\s*=\s*\([^#]*\).*/\1/p' \
"$configfile")"
if [ -n "$create_certs_tool_options" ]; then
params="$params --optsfile \"$create_certs_tool_options\""
fi
else
logerr "Could not access config file" \
"'$configfile' to get" \
"name of certificate tool to invoke."
return 1
fi
fi
if [ $((flags & SETUP_TPM2_F)) -ne 0 ]; then
params="$params --tpm2"
fi
if [ -n "$create_certs_tool" ]; then
local fn=$(basename "${create_certs_tool}")
if [ $((flags & SETUP_EK_CERT_F)) -ne 0 ]; then
cmd="$create_certs_tool \
--type ek \
--ek "$ek" \
--dir "$certdir" \
${logparam} ${params}"
logit " Invoking: $(echo $cmd | tr -s " ")"
tmp="$(eval $cmd 2>&1)"
ret=$?
logit "$(echo "${tmp}" | sed -e "s/^/$fn: /")"
if [ $ret -ne 0 ]; then
logerr "Error running '$cmd'."
return $ret
fi
fi
if [ $((flags & SETUP_PLATFORM_CERT_F)) -ne 0 ]; then
cmd="$create_certs_tool \
--type platform \
--ek "$ek" \
--dir "$certdir" \
${logparam} ${params}"
logit " Invoking: $(echo $cmd | tr -s " ")"
tmp="$(eval $cmd 2>&1)"
ret=$?
logit "$(echo "${tmp}" | sed -e "s/^/$fn: /")"
if [ $ret -ne 0 ]; then
logerr "Error running '$cmd'."
return $ret
fi
fi
fi
return $ret
}
# Start the TPM on a random open port
#
# @param1: full path to the TPM executable to use
# @param2: the directory where the TPM is supposed to write its state to
start_tpm()
{
local swtpm="$1"
local swtpm_state="$2"
local ctr=0 ctr2 ctr3
local pidfile="${swtpm_state}/.swtpm_setup.pidfile"
while [ $ctr -lt 100 ]; do
TPM_PORT=$(get_random 30000 65535)
rm -f $pidfile &>/dev/null
$swtpm \
--flags not-need-init \
-p $TPM_PORT \
--tpmstate dir=$swtpm_state \
--ctrl type=tcp,port=$((TPM_PORT+1)) \
--pid file=$pidfile \
2>&1 1>/dev/null &
SWTPM_PID=$!
# poll for open port (good) or the process to have
# disappeared (bad); whatever happens first
ctr3=0
while :; do
kill -0 $SWTPM_PID 2>/dev/null
if [ $? -ne 0 ]; then
# process dead; try next socket
break
fi
# pidfile needs to be there for us to know we are
# testing swtpm's port rather than some other
# process's
ctr2=0
while [ -f ${pidfile} ]; do
# test the connection to swtpm
(exec 100<>/dev/tcp/localhost/$TPM_PORT) 2>/dev/null
if [ $? -ne 0 ]; then
if [ $ctr2 -eq 40 ]; then
stop_tpm
break
fi
sleep 0.05
let ctr2=ctr2+1
continue
fi
exec 100>&-
echo "TPM is listening on TCP port $TPM_PORT."
return 0
done
sleep 0.05
let ctr3=ctr3+1
# at some point the pid file must appear...
if [ $ctr3 -eq 40 ] && [ ! -f ${pidfile} ]; then
stop_tpm
break
fi
done
let ctr=$ctr+1
done
return 1
}
# Stop the TPM by sigalling it with a SIGTERM
stop_tpm()
{
[ "$SWTPM_PID" != "" ] && kill -SIGTERM $SWTPM_PID
SWTPM_PID=
}
# Start the TSS for TPM 1.2
start_tcsd()
{
local TCSD=$1
local user=$(id -u -n)
local group=$(id -g -n)
local ctr=0 ctr2
export TSS_TCSD_PORT
TCSD_CONFIG="$(mktemp)"
TCSD_DATA_DIR="$(mktemp -d)"
TCSD_DATA_FILE="$(mktemp --tmpdir=$TCSD_DATA_DIR)"
if [ -z "$TCSD_CONFIG" ] || [ -z "$TCSD_DATA_DIR" ] || \
[ -z "$TCSD_DATA_FILE" ]; then
logerr "Could not create temporary file; TMPDIR=$TMPDIR"
return 1
fi
while [ $ctr -lt 100 ]; do
TSS_TCSD_PORT=$(get_random 30000 65535)
cat << EOF >$TCSD_CONFIG
port = $TSS_TCSD_PORT
system_ps_file = $TCSD_DATA_FILE
EOF
# tcsd requires tss:tss and 0600 on TCSD_CONFIG
# -> only root can start
chmod 600 $TCSD_CONFIG
if [ $(id -u) -eq 0 ]; then
chown tss:tss $TCSD_CONFIG 2>/dev/null
chown tss:tss $TCSD_DATA_DIR 2>/dev/null
chown tss:tss $TCSD_DATA_FILE 2>/dev/null
fi
if [ $? -ne 0 ]; then
logerr "Could not change ownership on $TCSD_CONFIG to ${user}:${group}."
ls -l $TCSD_CONFIG
return 1
fi
case "$(id -u)" in
0)
$TCSD -c $TCSD_CONFIG -e -f 2>&1 1>/dev/null &
TCSD_PID=$!
;;
*)
# for tss user, use the wrapper
$TCSD -c $TCSD_CONFIG -e -f 2>&1 1>/dev/null &
#if [ $? -ne 0]; then
# swtpm_tcsd_launcher -c $TCSD_CONFIG -e -f 2>&1 1>/dev/null &
#fi
TCSD_PID=$!
;;
esac
# poll for open port (good) or the process to have
# disappeared (bad); whatever happens first
ctr2=0
while :; do
(exec 100<>/dev/tcp/localhost/$TSS_TCSD_PORT) 2>/dev/null
if [ $? -ne 0 ]; then
if [ $ctr2 -eq 40 ]; then
stop_tcsd
break
fi
# check TCSD is still alive and we haven't
# successfully test some other process's port
kill -0 $TCSD_PID 2>/dev/null
if [ $? -ne 0 ]; then
break
fi
# process still alive
let ctr2=ctr2+1
sleep 0.05
continue
fi
exec 100>&-
echo "TSS is listening on TCP port $TSS_TCSD_PORT."
return 0
done
let ctr=$ctr+1
done
return 1
}
# Stop the TSS
stop_tcsd()
{
[ "$TCSD_PID" != "" ] && kill -SIGTERM $TCSD_PID
TCSD_PID=
}
# Cleanup everything including TPM, TSS, and files we may have created
cleanup()
{
stop_tpm
stop_tcsd
rm -rf "$TCSD_CONFIG" "$TCSD_DATA_FILE" "$TCSD_DATA_DIR"
}
# Read hex data passed to this function via a pipe and convert them to a
# string using od -t x1. The specifics require the use oif a different
# implementation on OpenBSD than on Linux/Cygwin. On the latter systems it
# can be executed more efficiently using only 'od'.
read_hex_data()
{
case "${UNAME_S}" in
OpenBSD|FreeBSD|NetBSD|Darwin|DragonFly)
od -t x1 -A n | tr -s ' ' | tr -d '\n' | sed 's/ $//'
;;
*)
od -t x1 -A n -w2048
;;
esac
}
# Send hex data written in a string with each hex number
# written in the form \x<2 hex digits>
# We have to use bash's echo on OpenBSD 6.2.
# We have to use | cat since some versions of echo otherwise
# stop writing data into a socket after the first \x0a.
#
# @param1: The string with hex numbers
send_hex_data()
{
case "${UNAME_S}" in
OpenBSD|FreeBSD|NetBSD|Darwin|DragonFly|CYGWIN*)
echo -en "$1" | cat
;;
*)
# Some Ubuntu Xenial version still needs this
$ECHO -en "$1"
;;
esac
}
# Transfer a request to the TPM and receive the response
#
# @param1: The request to send
tpm_transfer()
{
exec 100<>/dev/tcp/127.0.0.1/${TPM_PORT}
send_hex_data "$1" >&100
read_hex_data <&100
exec 100>&-
}
# Create an endorsement key
tpm_createendorsementkeypair()
{
local req rsp exp
req='\x00\xc1\x00\x00\x00\x36\x00\x00\x00\x78\x38\xf0\x30\x81\x07\x2b'
req+='\x0c\xa9\x10\x98\x08\xc0\x4B\x05\x11\xc9\x50\x23\x52\xc4\x00\x00'
req+='\x00\x01\x00\x03\x00\x02\x00\x00\x00\x0c\x00\x00\x08\x00\x00\x00'
req+='\x00\x02\x00\x00\x00\x00'
rsp="$(tpm_transfer "${req}")"
exp=' 00 c4 00 00 01 3a 00 00 00 00'
if [ "${rsp:0:30}" != "$exp" ]; then
logerr "TPM_CreateEndorsementKeyPair() failed"
logerr " expected: $exp"
logerr " received: ${rsp:0:30}"
return 1
fi
echo "${rsp:114:768}" | tr -d " "
return 0
}
# Initialize the TPM
#
# @param1: the flags
# @param2: the configuration file to get the external program from
# @parma3: the directory where the TPM is supposed to write it state to
# @param4: the TPM owner password to use
# @param5: The SRK password to use
# @param6: The ID of the VM
init_tpm()
{
local flags="$1"
local config_file="$2"
local tpm_state_path="$3"
local ownerpass="$4"
local srkpass="$5"
local vmid="$6"
# where external app writes certs into
local certsdir="$tpm_state_path"
local ek tmp output
local PLATFORM_CERT_FILE="$certsdir/platform.cert"
local EK_CERT_FILE="$certsdir/ek.cert"
local nvramauth="OWNERREAD|OWNERWRITE"
start_tpm "$SWTPM" "$tpm_state_path"
if [ $? -ne 0 ]; then
logerr "Could not start the TPM."
return 1
fi
export TCSD_USE_TCP_DEVICE=1
export TCSD_TCP_DEVICE_PORT=$TPM_PORT
output="$(swtpm_bios 2>&1)"
if [ $? -ne 0 ]; then
logerr "swtpm_bios failed: $output"
return 1
fi
# Creating EK is simple enough to do without the tcsd
if [ $((flags & $SETUP_CREATE_EK_F)) -ne 0 ]; then
ek="$(tpm_createendorsementkeypair)"
if [ $? -ne 0 ]; then
logerr "tpm_createendorsementkeypair failed."
return 1
fi
logit "Successfully created EK."
if [ $((flags & ~$SETUP_CREATE_EK_F)) -eq 0 ]; then
return 0
fi
fi
# TPM is enabled and activated upon first start
start_tcsd $TCSD
if [ $? -ne 0 ]; then
return 1
fi
# temporarily take ownership if an EK was created
if [ $((flags & $SETUP_CREATE_EK_F)) -ne 0 ] ; then
local parm_z=""
local parm_y=""
if [ $((flags & $SETUP_SRKPASS_ZEROS_F)) -ne 0 ]; then
parm_z="-z"
fi
if [ $((flags & $SETUP_OWNERPASS_ZEROS_F)) -ne 0 ]; then
parm_y="-y"
fi
if [ -n "${parm_y}" ] && [ -n "${parm_z}" ]; then
tpm_takeownership $parm_z $parm_y &>/dev/null
else
if [ -z "$(type -p expect)" ]; then
logerr "Missing 'expect' tool to take" \
"ownership with non-standard password."
return 1
fi
a=$(expect -c "
set parm_z \"$parm_z\"
set parm_y \"$parm_y\"
spawn tpm_takeownership \$parm_z \$parm_y
if { \$parm_y == \"\" } {
expect {
\"Enter owner password:\"
{ send \"$ownerpass\n\" }
}
expect {
\"Confirm password:\"
{ send \"$ownerpass\n\" }
}
}
if { \$parm_z == \"\" } {
expect {
\"Enter SRK password:\"
{ send \"$srkpass\n\" }
}
expect {
\"Confirm password:\"
{ send \"$srkpass\n\" }
}
}
expect eof
catch wait result
exit [lindex \$result 3]
")
fi
if [ $? -ne 0 ]; then
logerr "Could not take ownership of TPM."
return 1
fi
logit "Successfully took ownership of the TPM."
fi
# have external program create the certificates now
call_create_certs "$flags" "$config_file" "$certsdir" "$ek" "$vmid"
if [ $? -ne 0 ]; then
return 1
fi
# Define NVRAM are for Physical Presence Interface; unfortunately
# there are no useful write permissions...
#tpm_nvdefine \
# -i $((0x50010000)) \
# -p "PPREAD|PPWRITE|WRITEDEFINE" \
# -s 6 2>&1 > /dev/null
if [ $((flags & SETUP_EK_CERT_F)) -ne 0 ] && \
[ -r "${EK_CERT_FILE}" ]; then
output="$(tpm_nvdefine \
-i $((TPM_NV_INDEX_EKCert|TPM_NV_INDEX_D_BIT)) \
-p "${nvramauth}" \
-s $(get_filesize "${EK_CERT_FILE}") 2>&1)"
if [ $? -ne 0 ]; then
logerr "Could not create NVRAM area for EK certificate."
return 1
fi
output="$(tpm_nvwrite -i $((TPM_NV_INDEX_EKCert|TPM_NV_INDEX_D_BIT)) \
-f "${EK_CERT_FILE}" 2>&1)"
if [ $? -ne 0 ]; then
logerr "Could not write EK cert to NVRAM: $output"
return 1
fi
logit "Successfully created NVRAM area for EK certificate."
rm -f ${EK_CERT_FILE}
fi
if [ $((flags & SETUP_PLATFORM_CERT_F)) -ne 0 ] && \
[ -r "${PLATFORM_CERT_FILE}" ] ; then
output="$(tpm_nvdefine \
-i $((TPM_NV_INDEX_PlatformCert|TPM_NV_INDEX_D_BIT)) \
-p "${nvramauth}" \
-s $(get_filesize "${PLATFORM_CERT_FILE}") 2>&1)"
if [ $? -ne 0 ]; then
logerr "Could not create NVRAM area for platform" \
"certificate."
return 1
fi
output="$(tpm_nvwrite \
-i $((TPM_NV_INDEX_PlatformCert|TPM_NV_INDEX_D_BIT)) \
-f "$PLATFORM_CERT_FILE" 2>&1)"
if [ $? -ne 0 ]; then
logerr "Could not write EK cert to NVRAM: $output"
return 1
fi
logit "Successfully created NVRAM area for platform" \
"certificate."
rm -f ${PLATFORM_CERT_FILE}
fi
if [ $((flags & SETUP_DISPLAY_RESULTS_F)) -ne 0 ]; then
local nvidxs=`tpm_nvinfo -n | grep 0x | gawk '{print $1}'`
local passparam
if [ $((flags & $SETUP_OWNERPASS_ZEROS_F)) -ne 0 ]; then
passparam="-z"
else
passparam="--password=$ownerpass"
fi
for i in $nvidxs; do
logit "Content of NVRAM area $i:"
tmp="tpm_nvread -i $i $passparam"
logit_cmd "$cmd"
done
fi
# Last thing is to lock the NVRAM area
if [ $((flags & SETUP_LOCK_NVRAM_F)) -ne 0 ]; then
output="$(tpm_nvdefine -i $TPM_NV_INDEX_LOCK 2>&1)"
if [ $? -ne 0 ]; then
logerr "Could not lock NVRAM access: $output"
return 1
fi
logit "Successfully locked NVRAM access."
fi
# give up ownership if not wanted
if [ $((flags & SETUP_TAKEOWN_F)) -eq 0 -a \
$((flags & SETUP_CREATE_EK_F)) -ne 0 ] ; then
if [ $((flags & $SETUP_OWNERPASS_ZEROS_F)) -ne 0 ]; then
tpm_clear -z &>/dev/null
else
if [ -z "$(type -p expect)" ]; then
logerr "Missing 'expect' tool to take" \
"ownership with non-standard password."
return 1
fi
a=$(expect -c "
spawn tpm_clear
expect {
\"Enter owner password:\" { send \"$ownerpass\n\" }
}
expect eof
catch wait result
exit [lindex \$result 3]
")
fi
if [ $? -ne 0 ]; then
logerr "Could not give up ownership of TPM."
return 1
fi
logit "Successfully gave up ownership of the TPM."
# TPM is now disabled and deactivated; enable and activate it
stop_tpm
start_tpm "$SWTPM" "$tpm_state_path"
if [ $? -ne 0 ]; then
logerr "Could not re-start TPM."
return 1
fi
TCSD_TCP_DEVICE_PORT=$TPM_PORT
output="$(swtpm_bios -c)"
if [ $? -ne 0 ]; then
logerr "swtpm_bios -c -o failed: $output"
return 1
fi
logit "Successfully enabled and activated the TPM"
fi
return 0
}
################################# TPM 2 ##################################
# Get a couple of random numbers from the host and stir the TPM
# RNG with them
#
tpm2_stirrandom()
{
local req r rsp exp
# just the header, expecting 0x18 bytes of random data
req='\x80\x01\x00\x00\x00\x24\x00\x00\x01\x46\x00\x18'
r=$(dd if=/dev/urandom count=24 bs=1 2>/dev/null | \
read_hex_data | sed 's/ /\\x/g')
rsp="$(tpm_transfer "${req}${r}")"
exp=' 80 01 00 00 00 0a 00 00 00 00'
if [ "$rsp" != "$exp" ]; then
logerr "TPM2_Stirrandom() failed"
logerr " expected: $exp"
logerr " received: $rsp"
return 1
fi
return 0
}
tpm2_changeeps()
{
local req rsp exp
req='\x80\x02\x00\x00\x00\x1b\x00\x00\x01\x24\x40\x00\x00\x0c\x00\x00'
req+='\x00\x09\x40\x00\x00\x09\x00\x00\x00\x00\x00'
rsp="$(tpm_transfer "${req}")"
exp=' 80 02 00 00 00 13 00 00 00 00 00 00 00 00 00 00 01 00 00'
if [ "$rsp" != "$exp" ]; then
logerr "TPM2_ChangeEPS() failed"
logerr " expected: $exp"
logerr " received: $rsp"
return 1
fi
return 0
}
# Create the primary key (EK equivalent)
#
# @param1: flags
# @param2: filename for template
tpm2_createprimary_ek_rsa()
{
local flags="$1"
local templatefile="$2"
local symkeydata keyflags totlen publen off min_exp authpolicy
if [ $((flags & SETUP_ALLOW_SIGNING_F)) -ne 0 ] && \
[ $((flags & SETUP_DECRYPTION_F)) -ne 0 ]; then
# keyflags: fixedTPM, fixedParent, sensitiveDatOrigin,
# adminWithPolicy, sign, decrypt
keyflags=$((0x000600b2))
# symmetric: TPM_ALG_NULL
symkeydata='\\x00\\x10'
publen=$((0x36 + NONCE_RSA_SIZE))
totlen=$((0x5f + NONCE_RSA_SIZE))
min_exp=1506
# offset of length indicator for key
off=216
elif [ $((flags & SETUP_ALLOW_SIGNING_F)) -ne 0 ]; then
# keyflags: fixedTPM, fixedParent, sensitiveDatOrigin,
# adminWithPolicy, sign
keyflags=$((0x000400b2))
# symmetric: TPM_ALG_NULL
symkeydata='\\x00\\x10'
publen=$((0x36 + NONCE_RSA_SIZE))
totlen=$((0x5f + NONCE_RSA_SIZE))
min_exp=1506
# offset of length indicator for key
off=216
else
# keyflags: fixedTPM, fixedParent, sensitiveDatOrigin,
# adminWithPolicy, restricted, decrypt
keyflags=$((0x000300b2))
# symmetric: TPM_ALG_AES, 128bit, TPM_ALG_CFB
symkeydata='\\x00\\x06\\x00\\x80\\x00\\x43'
publen=$((0x3a + NONCE_RSA_SIZE))
totlen=$((0x63 + NONCE_RSA_SIZE))
min_exp=1518
# offset of length indicator for key
off=228
fi
authpolicy='\\x83\\x71\\x97\\x67\\x44\\x84\\xb3\\xf8\\x1a\\x90\\xcc\\x8d'
authpolicy+='\\x46\\xa5\\xd7\\x24\\xfd\\x52\\xd7\\x6e\\x06\\x52\\x0b\\x64'
authpolicy+='\\xf2\\xa1\\xda\\x1b\\x33\\x14\\x69\\xaa'
# Check the TCG EK Credential Profile doc for TPM 2 for
# parameters used here
# TPM_RH_ENDORSEMENT
tpm2_createprimary_rsa_params '\\x40\\x00\\x00\\x0b' "${keyflags}" \
"${symkeydata}" "${publen}" "${totlen}" "${min_exp}" "${off}" \
"${authpolicy}" "${templatefile}"
return $?
}
# Create a storage primary key
#
# @param1: flags
tpm2_createprimary_spk_rsa()
{
local flags="$1"
local symkeydata keyflags totlen publen off min_exp
# keyflags: fixedTPM, fixedParent, sensitiveDataOrigin,
# userWithAuth, noDA, restricted, decrypt
keyflags=$((0x00030472))
# keyflags=$((0x000300b2))
# symmetric: TPM_ALG_NULL
symkeydata='\\x00\\x06\\x00\\x80\\x00\\x43'
publen=$((0x1a + NONCE_RSA_SIZE))
totlen=$((0x43 + NONCE_RSA_SIZE))
min_exp=1470
# offset of length indicator for key
off=132
# TPM_RH_OWNER
tpm2_createprimary_rsa_params '\\x40\\x00\\x00\\x01' "${keyflags}" \
"${symkeydata}" "${publen}" "${totlen}" "${min_exp}" "${off}" "" \
""
return $?
}
function tpm2_createprimary_rsa_params()
{
local primaryhandle="$1"
local keyflags="$2"
local symkeydata="$3"
local publen="$4"
local totlen="$5"
local min_exp="$6"
local off="$7"
local authpolicy="$8"
local templatefile="$9"
local req rsp res temp
local authpolicylen=$((${#authpolicy} / 5))
req='\x80\x02@TOTLEN-4@\x00\x00\x01\x31'
req+='@KEYHANDLE-4@'
# size of buffer
req+='\x00\x00\x00\x09'
# TPM_RS_PW
req+='\x40\x00\x00\x09\x00\x00\x00\x00\x00'
req+='\x00\x04\x00\x00\x00\x00'
# Size of TPM2B_PUBLIC
req+='@PUBLEN-2@'
# TPM_ALG_RSA, TPM_ALG_SHA256
temp='\x00\x01\x00\x0b'
# fixedTPM, fixedParent, sensitiveDatOrigin, adminWithPolicy
# restricted, decrypt
temp+='@KEYFLAGS-4@'
# authPolicy;32 bytes
temp+='@AUTHPOLICYLEN-2@'
temp+='@AUTHPOLICY@'
temp+='@SYMKEYDATA@'
# scheme: TPM_ALG_NULL, keyBits: 2048bits