File: tpmkms.go

package info (click to toggle)
golang-github-smallstep-crypto 0.63.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,800 kB
  • sloc: sh: 66; makefile: 50
file content (1411 lines) | stat: -rw-r--r-- 48,065 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
//go:build !notpmkms
// +build !notpmkms

package tpmkms

import (
	"bytes"
	"context"
	"crypto"
	"crypto/rsa"
	"crypto/sha1" //nolint:gosec // required for Windows key ID calculation
	"crypto/sha256"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/asn1"
	"encoding/base64"
	"encoding/hex"
	"encoding/pem"
	"errors"
	"fmt"
	"net/url"
	"os"
	"path/filepath"
	"runtime"
	"time"

	"go.step.sm/crypto/fingerprint"
	"go.step.sm/crypto/kms/apiv1"
	"go.step.sm/crypto/kms/uri"
	"go.step.sm/crypto/tpm"
	"go.step.sm/crypto/tpm/algorithm"
	"go.step.sm/crypto/tpm/attestation"
	"go.step.sm/crypto/tpm/storage"
	"go.step.sm/crypto/tpm/tss2"
)

func init() {
	apiv1.Register(apiv1.TPMKMS, func(ctx context.Context, opts apiv1.Options) (apiv1.KeyManager, error) {
		return New(ctx, opts)
	})
}

// PreferredSignatureAlgorithms indicates the preferred selection of signature
// algorithms when an explicit value is omitted in CreateKeyRequest
var preferredSignatureAlgorithms []apiv1.SignatureAlgorithm

// SetPreferredSignatureAlgorithms sets the preferred signature algorithms
// to select from when explicit values are omitted in CreateKeyRequest
//
// # Experimental
//
// Notice: This method is EXPERIMENTAL and may be changed or removed in a later
// release.
func SetPreferredSignatureAlgorithms(algs []apiv1.SignatureAlgorithm) {
	preferredSignatureAlgorithms = algs
}

// PreferredSignatureAlgorithms returns the preferred signature algorithms
// to select from when explicit values are omitted in CreateKeyRequest
//
// # Experimental
//
// Notice: This method is EXPERIMENTAL and may be changed or removed in a later
// release.
func PreferredSignatureAlgorithms() []apiv1.SignatureAlgorithm {
	return preferredSignatureAlgorithms
}

// Scheme is the scheme used in TPM KMS URIs, the string "tpmkms".
const Scheme = string(apiv1.TPMKMS)

const (
	// DefaultRSASize is the number of bits of a new RSA key if no size has been
	// specified. Whereas we're generally defaulting to 3072 bits for new RSA keys,
	// 2048 is used as the default for the TPMKMS, because we've observed the TPMs
	// we're testing with to be supporting this as the maximum RSA key size. We might
	// increase the default in the (near) future, but we want to be more confident
	// about the supported size for a specific TPM (model) in that case.
	DefaultRSASize = 2048
	// defaultRSAAKSize is the default number of bits for a new RSA Attestation
	// Key. It is currently set to 2048, because that's what's mentioned in the
	// TCG TPM specification and is used by the AK template in `go-attestation`.
	defaultRSAAKSize = 2048
)

// TPMKMS is a KMS implementation backed by a TPM.
type TPMKMS struct {
	tpm                              *tpm.TPM
	windowsCertificateManager        apiv1.CertificateManager
	windowsCertificateStoreLocation  string
	windowsCertificateStore          string
	windowsIntermediateStoreLocation string
	windowsIntermediateStore         string
	attestationCABaseURL             string
	attestationCARootFile            string
	attestationCAInsecure            bool
	permanentIdentifier              string
	identityRenewalPeriodPercentage  int64
	identityEarlyRenewalEnabled      bool
}

type algorithmAttributes struct {
	Type     string
	Curve    int
	Requires []algorithm.Algorithm
}

var signatureAlgorithmMapping = map[apiv1.SignatureAlgorithm]algorithmAttributes{
	apiv1.UnspecifiedSignAlgorithm: {"RSA", -1, []algorithm.Algorithm{algorithm.AlgorithmRSA}},
	apiv1.SHA256WithRSA:            {"RSA", -1, []algorithm.Algorithm{algorithm.AlgorithmRSA, algorithm.AlgorithmSHA256}},
	apiv1.SHA384WithRSA:            {"RSA", -1, []algorithm.Algorithm{algorithm.AlgorithmRSA, algorithm.AlgorithmSHA384}},
	apiv1.SHA512WithRSA:            {"RSA", -1, []algorithm.Algorithm{algorithm.AlgorithmRSA, algorithm.AlgorithmSHA512}},
	apiv1.SHA256WithRSAPSS:         {"RSA", -1, []algorithm.Algorithm{algorithm.AlgorithmRSAPSS, algorithm.AlgorithmSHA256}},
	apiv1.SHA384WithRSAPSS:         {"RSA", -1, []algorithm.Algorithm{algorithm.AlgorithmRSAPSS, algorithm.AlgorithmSHA384}},
	apiv1.SHA512WithRSAPSS:         {"RSA", -1, []algorithm.Algorithm{algorithm.AlgorithmRSAPSS, algorithm.AlgorithmSHA512}},
	apiv1.ECDSAWithSHA256:          {"ECDSA", 256, []algorithm.Algorithm{algorithm.AlgorithmECDSA, algorithm.AlgorithmSHA256}},
	apiv1.ECDSAWithSHA384:          {"ECDSA", 384, []algorithm.Algorithm{algorithm.AlgorithmECDSA, algorithm.AlgorithmSHA384}},
	apiv1.ECDSAWithSHA512:          {"ECDSA", 521, []algorithm.Algorithm{algorithm.AlgorithmECDSA, algorithm.AlgorithmSHA512}},
}

const (
	microsoftPCP                     = "Microsoft Platform Crypto Provider"
	defaultStoreLocation             = "user"
	defaultStore                     = "My"
	defaultIntermediateStoreLocation = "user"
	defaultIntermediateStore         = "CA" // TODO(hs): verify "CA" works for "machine" certs too
)

// New initializes a new KMS backed by a TPM.
//
// A new TPMKMS can be initialized with a configuration by providing
// a URI in the options:
//
//	New(ctx, &apiv1.Options{
//	    URI: tpmkms:device=/dev/tpmrm0;storage-directory=/path/to/tpmstorage/directory
//	})
//
// It's also possible to set the storage directory as follows:
//
//	New(ctx, &apiv1.Options{
//	    URI: tpmkms:device=/dev/tpmrm0
//		StorageDirectory: /path/to/tpmstorage/directory
//	})
//
// The default storage location for serialized TPM objects when
// an instance of TPMKMS is created, is the relative path "tpm".
//
// The system default TPM device will be used when not configured. A
// specific TPM device can be selected by setting the device:
//
//	tpmkms:device=/dev/tpmrm0
//
// By default newly created TPM objects won't be persisted, so can't
// be readily used. The location for storage can be set using
// storage-directory:
//
//	tpmkms:storage-directory=/path/to/tpmstorage/directory
//
// On Windows the TPMKMS implementation has an option to use the native
// certificate stores for certificate storage and retrieval instead of
// using the storage directory for those. TPM keys will still be persisted
// to the storage directory, because that's how the KMS keeps track of which
// keys it manages, but it'll use the Windows certificate stores for
// operations that involve certificates for TPM keys. Use the "enable-cng"
// option to enable this optional integration:
//
//	tpmkms:enable-cng=true
//
// If the CryptoAPI Next Generation (CNG) integration is enabled, the TPMKMS
// will use an instance of the CAPIKMS to manage certificates. It'll use the
// the "Personal" ("My") user certificate store by default. A different location
// and store to be used for all operations against the TPMKMS can be defined as
// follows:
//
//	tpmkms:store-location=machine;store=CA
//
// The location and store to use can be overridden for a specific operation
// against a TPMKMS instance, if required. It's not possible to change the crypto
// provider to user; that will always be the "Microsoft Platform Crypto Provider"
//
// For operations that involve certificate chains, it's possible to set the
// intermediate CA store location and store name at initialization time. The
// same options can be used for a specific operation, if needed. By default the
// "CA" user certificate store is used.
//
// tpmkms:intermediate-store-location=machine;intermediate-store=CustomCAStore
//
// For attestation use cases that involve the Smallstep Attestation CA
// or a compatible one, several properties can be set. The following
// specify the Attestation CA base URL, the path to a bundle of root CAs
// to trust when setting up a TLS connection to the Attestation CA and
// disable TLS certificate validation, respectively.
//
//	tpmkms:attestation-ca-url=https://my.attestation.ca
//	tpmkms:attestation-ca-root=/path/to/trusted/roots.pem
//	tpmkms:attestation-ca-insecure=true
//
// The system may not always have a PermanentIdentifier assigned, so
// when initializing the TPMKMS, it's possible to set this value:
//
//	tpmkms:permanent-identifier=<some-unique-identifier>
//
// By default, an AK (identity) certificate will be renewed early
// if it's expiring soon. The default certificate lifetime is 60%,
// meaning that the renewal for the AK certificate will be kicked
// off when it's past 60% of its lifetime. It's possible to disable
// early renewal by setting disable-early-renewal to true:
//
//	tpmkms:disable-early-renewal=true
//
// The default lifetime percentage can be changed by setting
// renewal-percentage:
//
//	tpmkms:renewal-percentage=70
//
// Attestation support in the TPMKMS is considered EXPERIMENTAL. It
// is expected that there will be changes to the configuration that
// be provided and the attestation flow.
//
// The TPMKMS implementation is backed by an instance of the TPM from
// the `tpm` package. If the TPMKMS operations aren't sufficient for
// your use case, use a tpm.TPM instance instead.
func New(ctx context.Context, opts apiv1.Options) (kms *TPMKMS, err error) {
	kms = &TPMKMS{
		identityEarlyRenewalEnabled:     true,
		identityRenewalPeriodPercentage: 60, // default to AK certificate renewal at 60% of lifetime
	}
	storageDirectory := "tpm" // store TPM objects in a relative tpm directory by default.
	if opts.StorageDirectory != "" {
		storageDirectory = opts.StorageDirectory
	}
	tpmOpts := []tpm.NewTPMOption{tpm.WithStore(storage.NewDirstore(storageDirectory))}
	if opts.URI != "" {
		u, err := uri.ParseWithScheme(Scheme, opts.URI)
		if err != nil {
			return nil, fmt.Errorf("failed parsing %q as URI: %w", opts.URI, err)
		}
		if device := u.Get("device"); device != "" {
			tpmOpts = append(tpmOpts, tpm.WithDeviceName(device))
		}
		if storageDirectory := u.Get("storage-directory"); storageDirectory != "" {
			tpmOpts = append(tpmOpts, tpm.WithStore(storage.NewDirstore(storageDirectory)))
		}
		kms.attestationCABaseURL = u.Get("attestation-ca-url")
		kms.attestationCARootFile = u.Get("attestation-ca-root")
		kms.attestationCAInsecure = u.GetBool("attestation-ca-insecure")
		kms.permanentIdentifier = u.Get("permanent-identifier") // TODO(hs): determine if this is needed
		kms.identityEarlyRenewalEnabled = !u.GetBool("disable-early-renewal")
		if percentage := u.GetInt("renewal-percentage"); percentage != nil {
			if *percentage < 1 || *percentage > 100 {
				return nil, fmt.Errorf("renewal percentage must be between 1 and 100; got %d", *percentage)
			}
			kms.identityRenewalPeriodPercentage = *percentage
		}

		// opt-in for enabling CAPI integration on Windows for certificate
		// management. This will result in certificates being stored to or
		// retrieved from the Windows certificate stores.
		enableCNG := u.GetBool("enable-cng") // TODO(hs): maybe change the option flag or make this the default on Windows
		if enableCNG && runtime.GOOS != "windows" {
			return nil, fmt.Errorf(`"enable-cng" is not supported on %s`, runtime.GOOS)
		}

		if enableCNG {
			fn, ok := apiv1.LoadKeyManagerNewFunc(apiv1.CAPIKMS)
			if !ok {
				name := filepath.Base(os.Args[0])
				return nil, fmt.Errorf(`unsupported KMS type "capi": %s is compiled without Microsoft CryptoAPI Next Generation (CNG) support`, name)
			}
			km, err := fn(ctx, apiv1.Options{
				Type: apiv1.CAPIKMS,
				URI:  uri.New("capi", url.Values{"provider": []string{microsoftPCP}}).String(),
			})
			if err != nil {
				return nil, fmt.Errorf("failed creating CAPIKMS instance: %w", err)
			}
			kms.windowsCertificateManager, ok = km.(apiv1.CertificateManager)
			if !ok {
				return nil, fmt.Errorf("unexpected type %T; expected apiv1.CertificateManager", km)
			}
			kms.windowsCertificateStoreLocation = defaultStoreLocation
			if storeLocation := u.Get("store-location"); storeLocation != "" {
				kms.windowsCertificateStoreLocation = storeLocation
			}
			kms.windowsCertificateStore = defaultStore
			if store := u.Get("store"); store != "" {
				kms.windowsCertificateStore = store
			}
			kms.windowsIntermediateStoreLocation = defaultIntermediateStoreLocation
			if intermediateStoreLocation := u.Get("intermediate-store-location"); intermediateStoreLocation != "" {
				kms.windowsIntermediateStoreLocation = intermediateStoreLocation
			}
			kms.windowsIntermediateStore = defaultIntermediateStore
			if intermediateStore := u.Get("intermediate-store"); intermediateStore != "" {
				kms.windowsIntermediateStore = intermediateStore
			}
		}

		// TODO(hs): support a mode in which the TPM storage doesn't rely on JSON on Windows
		// at all, but directly feeds into OS native storage? Some operations can be NOOPs, such
		// as the ones that create AKs and keys. Is all of the data available in the keys stored
		// with Windows, incl. the attestation certification?
	}

	kms.tpm, err = tpm.New(tpmOpts...)
	if err != nil {
		return nil, fmt.Errorf("failed creating new TPM: %w", err)
	}

	return
}

// usesWindowsCertificateStore is a helper method that indicates whether
// the TPMKMS should use the Windows certificate stores for certificate
// operations.
func (k *TPMKMS) usesWindowsCertificateStore() bool {
	return k.windowsCertificateManager != nil
}

// CreateKey generates a new key in the TPM KMS and returns the public key.
//
// The `name` in the [apiv1.CreateKeyRequest] can be used to specify
// some key properties. These are as follows:
//
//   - name=<name>: specify the name to identify the key with
//   - ak=true: if set to true, an Attestation Key (AK) will be created instead of an application key
//   - tss2=true: is set to true, the PrivateKey response will contain a [tss2.TPMKey].
//   - attest-by=<akName>: attest an application key at creation time with the AK identified by `akName`
//   - qualifying-data=<random>: hexadecimal coded binary data that can be used to guarantee freshness when attesting creation of a key
//
// Some examples usages:
//
// Create an application key, without attesting it:
//
//	tpmkms:name=my-key
//
// Create an Attestation Key (AK):
//
//	tpmkms:name=my-ak;ak=true
//
// Create an application key, attested by `my-ak` with "1234" as the Qualifying Data:
//
//	tpmkms:name=my-attested-key;attest-by=my-ak;qualifying-data=61626364
func (k *TPMKMS) CreateKey(req *apiv1.CreateKeyRequest) (*apiv1.CreateKeyResponse, error) {
	switch {
	case req.Name == "":
		return nil, errors.New("createKeyRequest 'name' cannot be empty")
	case req.Bits < 0:
		return nil, errors.New("createKeyRequest 'bits' cannot be negative")
	}

	properties, err := parseNameURI(req.Name)
	if err != nil {
		return nil, fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	ctx := context.Background()
	caps, err := k.tpm.GetCapabilities(ctx)
	if err != nil {
		return nil, fmt.Errorf("could not get TPM capabilities: %w", err)
	}

	var (
		v  algorithmAttributes
		ok bool
	)
	if !properties.ak && req.SignatureAlgorithm == apiv1.UnspecifiedSignAlgorithm && len(preferredSignatureAlgorithms) > 0 {
		for _, alg := range preferredSignatureAlgorithms {
			v, ok = signatureAlgorithmMapping[alg]
			if !ok {
				return nil, fmt.Errorf("TPMKMS does not support signature algorithm %q", alg)
			}

			if caps.SupportsAlgorithms(v.Requires) {
				break
			}
		}
	} else {
		v, ok = signatureAlgorithmMapping[req.SignatureAlgorithm]
		if !ok {
			return nil, fmt.Errorf("TPMKMS does not support signature algorithm %q", req.SignatureAlgorithm)
		}

		if !caps.SupportsAlgorithms(v.Requires) {
			return nil, fmt.Errorf("signature algorithm %q not supported by the TPM device", req.SignatureAlgorithm)
		}
	}

	if properties.ak && v.Type == "ECDSA" {
		return nil, errors.New("AKs must be RSA keys")
	}

	if properties.ak && req.Bits != 0 && req.Bits != defaultRSAAKSize { // 2048
		return nil, fmt.Errorf("creating %d bit AKs is not supported; AKs must be RSA 2048 bits", req.Bits)
	}

	size := DefaultRSASize // defaults to 2048
	if req.Bits > 0 {
		size = req.Bits
	}

	if v.Type == "ECDSA" {
		size = v.Curve
	}

	var privateKey any
	if properties.ak {
		ak, err := k.tpm.CreateAK(ctx, properties.name) // NOTE: size is never passed for AKs; it's hardcoded to 2048 in lower levels.
		if err != nil {
			if errors.Is(err, tpm.ErrExists) {
				return nil, apiv1.AlreadyExistsError{Message: err.Error()}
			}
			return nil, fmt.Errorf("failed creating AK: %w", err)
		}

		if properties.tss2 {
			tpmKey, err := ak.ToTSS2(ctx)
			if err != nil {
				return nil, fmt.Errorf("failed exporting AK to TSS2: %w", err)
			}
			privateKey = tpmKey
		}

		createdAKURI := fmt.Sprintf("tpmkms:name=%s;ak=true", ak.Name())
		return &apiv1.CreateKeyResponse{
			Name:       createdAKURI,
			PublicKey:  ak.Public(),
			PrivateKey: privateKey,
		}, nil
	}

	var key *tpm.Key
	if properties.attestBy != "" {
		config := tpm.AttestKeyConfig{
			Algorithm:      v.Type,
			Size:           size,
			QualifyingData: properties.qualifyingData,
		}
		key, err = k.tpm.AttestKey(ctx, properties.attestBy, properties.name, config)
		if err != nil {
			if errors.Is(err, tpm.ErrExists) {
				return nil, apiv1.AlreadyExistsError{Message: err.Error()}
			}
			return nil, fmt.Errorf("failed creating attested key: %w", err)
		}
	} else {
		config := tpm.CreateKeyConfig{
			Algorithm: v.Type,
			Size:      size,
		}
		key, err = k.tpm.CreateKey(ctx, properties.name, config)
		if err != nil {
			if errors.Is(err, tpm.ErrExists) {
				return nil, apiv1.AlreadyExistsError{Message: err.Error()}
			}
			return nil, fmt.Errorf("failed creating key: %w", err)
		}
	}

	if properties.tss2 {
		tpmKey, err := key.ToTSS2(ctx)
		if err != nil {
			return nil, fmt.Errorf("failed exporting key to TSS2: %w", err)
		}
		privateKey = tpmKey
	}

	signer, err := key.Signer(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed getting signer for key: %w", err)
	}

	createdKeyURI := fmt.Sprintf("tpmkms:name=%s", key.Name())
	if properties.attestBy != "" {
		createdKeyURI = fmt.Sprintf("%s;attest-by=%s", createdKeyURI, key.AttestedBy())
	}

	return &apiv1.CreateKeyResponse{
		Name:       createdKeyURI,
		PublicKey:  signer.Public(),
		PrivateKey: privateKey,
		CreateSignerRequest: apiv1.CreateSignerRequest{
			SigningKey: createdKeyURI,
			Signer:     signer,
		},
	}, nil
}

// DeleteKey deletes a key identified by name from the TPMKMS.
//
// # Experimental
//
// Notice: This method is EXPERIMENTAL and may be changed or removed in a later
// release.
func (k *TPMKMS) DeleteKey(req *apiv1.DeleteKeyRequest) error {
	if req.Name == "" {
		return fmt.Errorf("deleteKeyRequest 'name' cannot be empty")
	}
	properties, err := parseNameURI(req.Name)
	if err != nil {
		return fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	ctx := context.Background()
	if properties.ak {
		if err := k.tpm.DeleteAK(ctx, properties.name); err != nil {
			return notFoundError(err)
		}
	} else {
		if err := k.tpm.DeleteKey(ctx, properties.name); err != nil {
			return notFoundError(err)
		}
	}

	return nil
}

// CreateSigner creates a signer using a key present in the TPM KMS.
//
// The `signingKey` in the [apiv1.CreateSignerRequest] can be used to specify
// some key properties. These are as follows:
//
//   - name=<name>: specify the name to identify the key with
//   - path=<file>: specify the TSS2 PEM file to use
func (k *TPMKMS) CreateSigner(req *apiv1.CreateSignerRequest) (crypto.Signer, error) {
	if req.Signer != nil {
		return req.Signer, nil
	}

	var pemBytes []byte

	switch {
	case req.SigningKey != "":
		properties, err := parseNameURI(req.SigningKey)
		if err != nil {
			return nil, fmt.Errorf("failed parsing %q: %w", req.SigningKey, err)
		}
		if properties.ak {
			return nil, fmt.Errorf("signing with an AK currently not supported")
		}

		switch {
		case properties.name != "":
			ctx := context.Background()
			key, err := k.getKey(ctx, properties.name)
			if err != nil {
				return nil, err
			}
			signer, err := key.Signer(ctx)
			if err != nil {
				return nil, fmt.Errorf("failed getting signer for key %q: %w", properties.name, err)
			}
			return signer, nil
		case properties.path != "":
			if pemBytes, err = os.ReadFile(properties.path); err != nil {
				return nil, fmt.Errorf("failed reading key from %q: %w", properties.path, err)
			}
		default:
			return nil, fmt.Errorf("failed parsing %q: name and path cannot be empty", req.SigningKey)
		}
	case len(req.SigningKeyPEM) > 0:
		pemBytes = req.SigningKeyPEM
	default:
		return nil, errors.New("createSignerRequest 'signingKey' and 'signingKeyPEM' cannot be empty")
	}

	// Create a signer from a TSS2 PEM block
	key, err := parseTSS2(pemBytes)
	if err != nil {
		return nil, err
	}

	ctx := context.Background()
	signer, err := tpm.CreateTSS2Signer(ctx, k.tpm, key)
	if err != nil {
		return nil, fmt.Errorf("failed getting signer for TSS2 PEM: %w", err)
	}
	return signer, nil
}

// GetPublicKey returns the public key present in the TPM KMS.
//
// The `name` in the [apiv1.GetPublicKeyRequest] can be used to specify some key
// properties. These are as follows:
//
//   - name=<name>: specify the name to identify the key with
//   - ak=true: if set to true, an Attestation Key (AK) will be read instead of an application key
//   - path=<file>: specify the TSS2 PEM file to read from
func (k *TPMKMS) GetPublicKey(req *apiv1.GetPublicKeyRequest) (crypto.PublicKey, error) {
	if req.Name == "" {
		return nil, errors.New("getPublicKeyRequest 'name' cannot be empty")
	}

	properties, err := parseNameURI(req.Name)
	if err != nil {
		return nil, fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	ctx := context.Background()
	switch {
	case properties.name != "":
		if properties.ak {
			ak, err := k.getAK(ctx, properties.name)
			if err != nil {
				return nil, err
			}
			akPub := ak.Public()
			if akPub == nil {
				return nil, errors.New("failed getting AK public key")
			}
			return akPub, nil
		}

		key, err := k.getKey(ctx, properties.name)
		if err != nil {
			return nil, err
		}

		signer, err := key.Signer(ctx)
		if err != nil {
			return nil, fmt.Errorf("failed getting signer for key %q: %w", properties.name, err)
		}

		return signer.Public(), nil
	case properties.path != "":
		pemBytes, err := os.ReadFile(properties.path)
		if err != nil {
			return nil, fmt.Errorf("failed reading key from %q: %w", properties.path, err)
		}
		key, err := parseTSS2(pemBytes)
		if err != nil {
			return nil, err
		}
		pub, err := key.Public()
		if err != nil {
			return nil, fmt.Errorf("error decoding public key from %q: %w", properties.path, err)
		}
		return pub, nil
	default:
		return nil, fmt.Errorf("failed parsing %q: name and path cannot be empty", req.Name)
	}
}

// LoadCertificate loads the certificate for the key identified by name from the TPMKMS.
func (k *TPMKMS) LoadCertificate(req *apiv1.LoadCertificateRequest) (cert *x509.Certificate, err error) {
	if req.Name == "" {
		return nil, errors.New("loadCertificateRequest 'name' cannot be empty")
	}

	chain, err := k.LoadCertificateChain(&apiv1.LoadCertificateChainRequest{Name: req.Name})
	if err != nil {
		return nil, err
	}

	return chain[0], nil
}

// LoadCertificateChain loads the certificate chain for the key identified by
// name from the TPMKMS.
func (k *TPMKMS) LoadCertificateChain(req *apiv1.LoadCertificateChainRequest) ([]*x509.Certificate, error) {
	if req.Name == "" {
		return nil, errors.New("loadCertificateChainRequest 'name' cannot be empty")
	}

	if k.usesWindowsCertificateStore() {
		chain, err := k.loadCertificateChainFromWindowsCertificateStore(&apiv1.LoadCertificateRequest{
			Name: req.Name,
		})
		if err != nil {
			return nil, fmt.Errorf("failed loading certificate chain using Windows platform cryptography provider: %w", err)
		}
		return chain, nil
	}

	properties, err := parseNameURI(req.Name)
	if err != nil {
		return nil, fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	ctx := context.Background()
	var chain []*x509.Certificate
	if properties.ak {
		ak, err := k.getAK(ctx, properties.name)
		if err != nil {
			return nil, err
		}
		chain = ak.CertificateChain()
	} else {
		key, err := k.getKey(ctx, properties.name)
		if err != nil {
			return nil, err
		}
		chain = key.CertificateChain()
	}

	if len(chain) == 0 {
		return nil, fmt.Errorf("failed getting certificate chain for %q: no certificate chain stored", properties.name)
	}

	return chain, nil
}

const (
	// maximumIterations is the maximum number of times for the recursive
	// intermediate CA lookup loop.
	maximumIterations = 10
)

func (k *TPMKMS) loadCertificateChainFromWindowsCertificateStore(req *apiv1.LoadCertificateRequest) ([]*x509.Certificate, error) {
	pub, err := k.GetPublicKey(&apiv1.GetPublicKeyRequest{
		Name: req.Name,
	})
	if err != nil {
		return nil, fmt.Errorf("failed retrieving public key: %w", err)
	}

	o, err := parseNameURI(req.Name)
	if err != nil {
		return nil, fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	location := k.windowsCertificateStoreLocation
	if o.storeLocation != "" {
		location = o.storeLocation
	}
	store := k.windowsCertificateStore
	if o.store != "" {
		store = o.store
	}

	subjectKeyID, err := generateWindowsSubjectKeyID(pub)
	if err != nil {
		return nil, fmt.Errorf("failed generating subject key id: %w", err)
	}

	cert, err := k.windowsCertificateManager.LoadCertificate(&apiv1.LoadCertificateRequest{
		Name: fmt.Sprintf("capi:key-id=%s;store-location=%s;store=%s;", subjectKeyID, location, store),
	})
	if err != nil {
		return nil, fmt.Errorf("failed retrieving certificate using Windows platform cryptography provider: %w", err)
	}

	intermediateCAStoreLocation := k.windowsIntermediateStoreLocation
	if o.intermediateStoreLocation != "" {
		intermediateCAStoreLocation = o.intermediateStoreLocation
	}

	intermediateCAStore := k.windowsIntermediateStore
	if o.intermediateStore != "" {
		intermediateCAStore = o.intermediateStore
	}

	chain := []*x509.Certificate{cert}
	child := cert
	for i := 0; i < maximumIterations; i++ { // loop a maximum number of times
		authorityKeyID := hex.EncodeToString(child.AuthorityKeyId)
		parent, err := k.windowsCertificateManager.LoadCertificate(&apiv1.LoadCertificateRequest{
			Name: fmt.Sprintf("capi:key-id=%s;store-location=%s;store=%s", authorityKeyID, intermediateCAStoreLocation, intermediateCAStore),
		})
		if err != nil {
			if errors.Is(err, apiv1.NotFoundError{}) {
				// if error indicates the parent wasn't found, assume end of chain for a specific
				// combination of store location and store is reached, and break from the loop
				break
			}
			return nil, fmt.Errorf("failed loading intermediate CA certificate using Windows platform cryptography provider: %w", err)
		}

		// if the discovered parent has a signature from itself, assume it's a root CA,
		// and break from the loop
		if parent.CheckSignatureFrom(parent) == nil {
			break
		}

		// ensure child has a valid signature from the parent
		if err := child.CheckSignatureFrom(parent); err != nil {
			return nil, fmt.Errorf("failed loading intermediate CA certificate using Windows platform cryptography provider: %w", err)
		}

		chain = append(chain, parent)
		child = parent
	}

	return chain, nil
}

// StoreCertificate stores the certificate for the key identified by name to the TPMKMS.
func (k *TPMKMS) StoreCertificate(req *apiv1.StoreCertificateRequest) error {
	switch {
	case req.Name == "":
		return errors.New("storeCertificateRequest 'name' cannot be empty")
	case req.Certificate == nil:
		return errors.New("storeCertificateRequest 'certificate' cannot be empty")
	}

	return k.StoreCertificateChain(&apiv1.StoreCertificateChainRequest{Name: req.Name, CertificateChain: []*x509.Certificate{req.Certificate}})
}

// StoreCertificateChain stores the certificate for the key identified by name to the TPMKMS.
func (k *TPMKMS) StoreCertificateChain(req *apiv1.StoreCertificateChainRequest) error {
	switch {
	case req.Name == "":
		return errors.New("storeCertificateChainRequest 'name' cannot be empty")
	case len(req.CertificateChain) == 0:
		return errors.New("storeCertificateChainRequest 'certificateChain' cannot be empty")
	}

	if k.usesWindowsCertificateStore() {
		if err := k.storeCertificateChainToWindowsCertificateStore(&apiv1.StoreCertificateChainRequest{
			Name:             req.Name,
			CertificateChain: req.CertificateChain,
		}); err != nil {
			return fmt.Errorf("failed storing certificate chain using Windows platform cryptography provider: %w", err)
		}

		return nil
	}

	properties, err := parseNameURI(req.Name)
	if err != nil {
		return fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	ctx := context.Background()
	if properties.ak {
		ak, err := k.getAK(ctx, properties.name)
		if err != nil {
			return err
		}
		err = ak.SetCertificateChain(ctx, req.CertificateChain)
		if err != nil {
			return fmt.Errorf("failed storing certificate for AK %q: %w", properties.name, err)
		}
	} else {
		key, err := k.getKey(ctx, properties.name)
		if err != nil {
			return err
		}

		err = key.SetCertificateChain(ctx, req.CertificateChain)
		if err != nil {
			return fmt.Errorf("failed storing certificate for key %q: %w", properties.name, err)
		}
	}

	return nil
}

func (k *TPMKMS) storeCertificateChainToWindowsCertificateStore(req *apiv1.StoreCertificateChainRequest) error {
	o, err := parseNameURI(req.Name)
	if err != nil {
		return fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	location := k.windowsCertificateStoreLocation
	if o.storeLocation != "" {
		location = o.storeLocation
	}
	store := k.windowsCertificateStore
	if o.store != "" {
		store = o.store
	}
	skipFindCertificateKey := "false"
	if o.skipFindCertificateKey {
		skipFindCertificateKey = "true"
	}

	leaf := req.CertificateChain[0]
	fp, err := fingerprint.New(leaf.Raw, crypto.SHA1, fingerprint.HexFingerprint)
	if err != nil {
		return fmt.Errorf("failed calculating certificate SHA1 fingerprint: %w", err)
	}

	uv := url.Values{}
	uv.Set("sha1", fp)
	uv.Set("store-location", location)
	uv.Set("store", store)
	uv.Set("skip-find-certificate-key", skipFindCertificateKey)

	if err := k.windowsCertificateManager.StoreCertificate(&apiv1.StoreCertificateRequest{
		Name:        uri.New("capi", uv).String(),
		Certificate: leaf,
	}); err != nil {
		return fmt.Errorf("failed storing certificate using Windows platform cryptography provider: %w", err)
	}

	if len(req.CertificateChain) == 1 {
		// no certificate chain; return early
		return nil
	}

	intermediateCAStoreLocation := k.windowsIntermediateStoreLocation
	if o.intermediateStoreLocation != "" {
		intermediateCAStoreLocation = o.intermediateStoreLocation
	}

	intermediateCAStore := k.windowsIntermediateStore
	if o.intermediateStore != "" {
		intermediateCAStore = o.intermediateStore
	}

	for _, c := range req.CertificateChain[1:] {
		if err := validateIntermediateCertificate(c); err != nil {
			return fmt.Errorf("invalid intermediate certificate provided in chain: %w", err)
		}
		if err := k.storeIntermediateToWindowsCertificateStore(c, intermediateCAStoreLocation, intermediateCAStore); err != nil {
			return fmt.Errorf("failed storing intermediate certificate using Windows platform cryptography provider: %w", err)
		}
	}

	return nil
}

func validateIntermediateCertificate(c *x509.Certificate) error {
	switch {
	case !c.IsCA:
		return fmt.Errorf("certificate with serial %q is not a CA certificate", c.SerialNumber.String())
	case !c.BasicConstraintsValid:
		return fmt.Errorf("certificate with serial %q has invalid basic constraints", c.SerialNumber.String())
	case bytes.Equal(c.AuthorityKeyId, c.SubjectKeyId):
		return fmt.Errorf("certificate with serial %q has equal subject and authority key IDs", c.SerialNumber.String())
	case c.CheckSignatureFrom(c) == nil:
		return fmt.Errorf("certificate with serial %q is self-signed root CA", c.SerialNumber.String())
	}

	return nil
}

func (k *TPMKMS) storeIntermediateToWindowsCertificateStore(c *x509.Certificate, storeLocation, store string) error {
	fp, err := fingerprint.New(c.Raw, crypto.SHA1, fingerprint.HexFingerprint)
	if err != nil {
		return fmt.Errorf("failed calculating certificate SHA1 fingerprint: %w", err)
	}

	if err := k.windowsCertificateManager.StoreCertificate(&apiv1.StoreCertificateRequest{
		Name:        fmt.Sprintf("capi:sha1=%s;store-location=%s;store=%s;skip-find-certificate-key=true", fp, storeLocation, store),
		Certificate: c,
	}); err != nil {
		return err
	}

	return nil
}

// DeleteCertificate deletes a certificate for the key identified by name from the
// TPMKMS. If the instance is configured to use the Windows certificate store, it'll
// delete the certificate from the certificate store, backed by a CAPIKMS instance.
//
// It's possible to delete a specific certificate for a key by specifying it's SHA1
// or serial. This is only supported if the instance is configured to use the Windows
// certificate store.
//
// # Experimental
//
// Notice: This method is EXPERIMENTAL and may be changed or removed in a later
// release.
func (k *TPMKMS) DeleteCertificate(req *apiv1.DeleteCertificateRequest) error {
	if req.Name == "" {
		return errors.New("deleteCertificateRequest 'name' cannot be empty")
	}

	if k.usesWindowsCertificateStore() {
		if err := k.deleteCertificateFromWindowsCertificateStore(&apiv1.DeleteCertificateRequest{
			Name: req.Name,
		}); err != nil {
			return fmt.Errorf("failed deleting certificate from Windows platform cryptography provider: %w", err)
		}

		return nil
	}

	// TODO(hs): support delete by serial? If not, the behavior for TPM storage and Windows
	// certificate store storage will be different, and may need different behavior when
	// implementing certificate management.

	properties, err := parseNameURI(req.Name)
	if err != nil {
		return fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	ctx := context.Background()
	if properties.ak {
		ak, err := k.getAK(ctx, properties.name)
		if err != nil {
			return err
		}
		if err := ak.SetCertificateChain(ctx, nil); err != nil {
			return fmt.Errorf("failed storing certificate for AK %q: %w", properties.name, err)
		}
	} else {
		key, err := k.getKey(ctx, properties.name)
		if err != nil {
			return err
		}
		if err := key.SetCertificateChain(ctx, nil); err != nil {
			return fmt.Errorf("failed storing certificate for key %q: %w", properties.name, err)
		}
	}

	return nil
}

func (k *TPMKMS) deleteCertificateFromWindowsCertificateStore(req *apiv1.DeleteCertificateRequest) error {
	o, err := parseNameURI(req.Name)
	if err != nil {
		return fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	location := k.windowsCertificateStoreLocation
	if o.storeLocation != "" {
		location = o.storeLocation
	}
	store := k.windowsCertificateStore
	if o.store != "" {
		store = o.store
	}

	uv := url.Values{}
	uv.Set("store-location", location)
	uv.Set("store", store)

	switch {
	case o.serial != "":
		uv.Set("serial", o.serial)
		uv.Set("issuer", o.issuer)
	case o.keyID != "":
		uv.Set("key-id", o.keyID)
	case o.sha1 != "":
		uv.Set("sha1", o.sha1)
	default:
		return errors.New(`at least one of "serial", "key-id" or "sha1" is expected to be set`)
	}

	dk, ok := k.windowsCertificateManager.(deletingCertificateManager)
	if !ok {
		return fmt.Errorf("expected Windows certificate manager to implement DeleteCertificate")
	}

	if err := dk.DeleteCertificate(&apiv1.DeleteCertificateRequest{
		Name: uri.New("capi", uv).String(),
	}); err != nil {
		return fmt.Errorf("failed deleting certificate using Windows platform cryptography provider: %w", err)
	}

	return nil
}

// attestationClient is a wrapper for [attestation.Client], containing
// all of the required references to perform attestation against the
// Smallstep Attestation CA.
type attestationClient struct {
	c  *attestation.Client
	t  *tpm.TPM
	ek *tpm.EK
	ak *tpm.AK
}

// newAttestorClient creates a new [attestationClient], wrapping references
// to the [tpm.TPM] instance, the EK and the AK to use when attesting.
func (k *TPMKMS) newAttestorClient(ek *tpm.EK, ak *tpm.AK) (*attestationClient, error) {
	if k.attestationCABaseURL == "" {
		return nil, errors.New("failed creating attestation client: attestation CA base URL must not be empty")
	}
	// prepare a client to perform attestation with an Attestation CA
	attestationClientOptions := []attestation.Option{attestation.WithRootsFile(k.attestationCARootFile)}
	if k.attestationCAInsecure {
		attestationClientOptions = append(attestationClientOptions, attestation.WithInsecure())
	}
	client, err := attestation.NewClient(k.attestationCABaseURL, attestationClientOptions...)
	if err != nil {
		return nil, fmt.Errorf("failed creating attestation client: %w", err)
	}
	return &attestationClient{
		c:  client,
		t:  k.tpm,
		ek: ek,
		ak: ak,
	}, nil
}

// Attest implements the [apiv1.AttestationClient] interface, calling into the
// underlying [attestation.Client] to perform an attestation flow with the
// Smallstep Attestation CA.
func (ac *attestationClient) Attest(ctx context.Context) ([]*x509.Certificate, error) {
	return ac.c.Attest(ctx, ac.t, ac.ek, ac.ak)
}

// CreateAttestation implements the [apiv1.Attester] interface for the TPMKMS. It
// can be used to request the required information to verify that an application
// key was created in and by a specific TPM.
//
// It is expected that an application key has been attested at creation time by
// an attestation key (AK) before calling this method. An error will be returned
// otherwise.
//
// The response will include an attestation key (AK) certificate (chain) issued
// to the AK that was used to certify creation of the (application) key, as well
// as the key certification parameters at the time of key creation. Together these
// can be used by a relying party to attest that the key was created by a specific
// TPM.
//
// If no valid AK certificate is available when calling CreateAttestation, an
// enrolment with an instance of the Smallstep Attestation CA is performed. This
// will use the TPM Endorsement Key and the AK as inputs. The Attestation CA will
// return an AK certificate chain on success.
//
// When CreateAttestation is called for an AK, the AK certificate chain will be
// returned. Currently no AK creation parameters are returned.
func (k *TPMKMS) CreateAttestation(req *apiv1.CreateAttestationRequest) (*apiv1.CreateAttestationResponse, error) {
	if req.Name == "" {
		return nil, errors.New("createAttestationRequest 'name' cannot be empty")
	}

	properties, err := parseNameURI(req.Name)
	if err != nil {
		return nil, fmt.Errorf("failed parsing %q: %w", req.Name, err)
	}

	ctx := context.Background()
	eks, err := k.tpm.GetEKs(ctx) // TODO(hs): control the EK used as the caller of this method?
	if err != nil {
		return nil, fmt.Errorf("failed getting EKs: %w", err)
	}
	ek := getPreferredEK(eks)
	ekPublic := ek.Public()
	ekKeyID, err := generateKeyID(ekPublic)
	if err != nil {
		return nil, fmt.Errorf("failed getting EK public key ID: %w", err)
	}
	ekKeyURL := ekURL(ekKeyID)
	permanentIdentifier := ekKeyURL.String()

	// check if the derived EK URI fingerprint representation matches the provided
	// permanent identifier value. The current implementation requires the EK URI to
	// be used as the AK identity, so an error is returned if there's no match. This
	// could be changed in the future, so that another attestation flow takes place,
	// instead, for example.
	if k.permanentIdentifier != "" && permanentIdentifier != k.permanentIdentifier {
		return nil, fmt.Errorf("the provided permanent identifier %q does not match the EK URL %q", k.permanentIdentifier, permanentIdentifier)
	}

	var key *tpm.Key
	akName := properties.name
	if !properties.ak {
		key, err = k.getKey(ctx, properties.name)
		if err != nil {
			return nil, err
		}
		if !key.WasAttested() {
			return nil, fmt.Errorf("key %q was not attested", key.Name())
		}
		akName = key.AttestedBy()
	}

	ak, err := k.getAK(ctx, akName)
	if err != nil {
		return nil, err
	}

	// check if a (valid) AK certificate (chain) is available. Perform attestation flow
	// otherwise. If an AK certificate is available, but not considered valid, e.g. due
	// to it not having the right identity, a new attestation flow will be performed and
	// the old certificate (chain) will be overwritten with the result of that flow.
	if err := k.hasValidIdentity(ak, ekKeyURL); err != nil {
		var ac apiv1.AttestationClient
		if req.AttestationClient != nil {
			// TODO(hs): check if it makes sense to have this; it doesn't capture all
			// behavior of the built-in attestorClient, but at least it does provide
			// a basic extension point for other ways of performing attestation that
			// might be useful for testing or attestation flows against other systems.
			// For it to be truly useful, the logic for determining the AK identity
			// would have to be updated too, though.
			ac = req.AttestationClient
		} else {
			ac, err = k.newAttestorClient(ek, ak)
			if err != nil {
				return nil, fmt.Errorf("failed creating attestor client: %w", err)
			}
		}
		// perform the attestation flow with a (remote) attestation CA
		akChain, err := ac.Attest(ctx)
		if err != nil {
			return nil, fmt.Errorf("failed performing AK attestation: %w", err)
		}
		// store the result with the AK, so that it can be reused for future
		// attestations.
		if err := ak.SetCertificateChain(ctx, akChain); err != nil {
			return nil, fmt.Errorf("failed storing AK certificate chain: %w", err)
		}
	}

	// when a new certificate was issued for the AK, it is possible the
	// certificate that was issued doesn't include the expected and/or required
	// identity, so this is checked before continuing.
	if err := k.hasValidIdentity(ak, ekKeyURL); err != nil {
		return nil, fmt.Errorf("AK certificate (chain) not valid for EK %q: %w", ekKeyURL, err)
	}

	akChain := ak.CertificateChain()

	if properties.ak {
		akPub := ak.Public()
		if akPub == nil {
			return nil, fmt.Errorf("failed getting AK public key")
		}
		// TODO(hs): decide if we want/need to return these; their purpose is slightly
		// different from the key certification parameters.
		_, err = ak.AttestationParameters(ctx)
		if err != nil {
			return nil, fmt.Errorf("failed getting AK attestation parameters: %w", err)
		}
		return &apiv1.CreateAttestationResponse{
			Certificate:         akChain[0], // certificate for the AK
			CertificateChain:    akChain,    // chain for the AK, including the leaf
			PublicKey:           akPub,      // returns the public key of the attestation key
			PermanentIdentifier: permanentIdentifier,
		}, nil
	}

	signer, err := key.Signer(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed getting signer for key %q: %w", properties.name, err)
	}

	params, err := key.CertificationParameters(ctx)
	if err != nil {
		return nil, fmt.Errorf("failed getting key certification parameters for %q: %w", key.Name(), err)
	}

	// prepare the response to return
	akCert := akChain[0]
	return &apiv1.CreateAttestationResponse{
		Certificate:      akCert,          // certificate for the AK that attested the key
		CertificateChain: akChain,         // chain for the AK that attested the key, including the leaf
		PublicKey:        signer.Public(), // returns the public key of the attested key
		CertificationParameters: &apiv1.CertificationParameters{ // key certification parameters
			Public:            params.Public,
			CreateData:        params.CreateData,
			CreateAttestation: params.CreateAttestation,
			CreateSignature:   params.CreateSignature,
		},
		PermanentIdentifier: permanentIdentifier, // NOTE: should always match the valid value of the AK identity (for now)
	}, nil
}

// Close releases the connection to the TPM.
func (k *TPMKMS) Close() (err error) {
	return
}

// getPreferredEK returns the first RSA TPM EK found. If no RSA
// EK exists, it returns the first ECDSA EK found.
func getPreferredEK(eks []*tpm.EK) (ek *tpm.EK) {
	var fallback *tpm.EK
	for _, ek = range eks {
		if _, isRSA := ek.Public().(*rsa.PublicKey); isRSA {
			return
		}
		if fallback == nil {
			fallback = ek
		}
	}
	return fallback
}

// hasValidIdentity indicates if the AK has an associated certificate
// that includes a valid identity. Currently we only consider certificates
// that encode the TPM EK public key ID as one of its URI SANs, which is
// the default behavior of the Smallstep Attestation CA.
func (k *TPMKMS) hasValidIdentity(ak *tpm.AK, ekURL *url.URL) error {
	chain := ak.CertificateChain()
	if len(chain) == 0 {
		return ErrIdentityCertificateUnavailable
	}
	akCert := chain[0]

	now := time.Now()
	if now.Before(akCert.NotBefore) {
		return ErrIdentityCertificateNotYetValid
	}

	notAfter := akCert.NotAfter.Add(-1 * time.Minute).Truncate(time.Second)
	if now.After(notAfter) {
		return ErrIdentityCertificateExpired
	}

	// it's possible to disable early expiration errors for the AK identity
	// certificate when instantiating the TPMKMS.
	if k.identityEarlyRenewalEnabled {
		period := akCert.NotAfter.Sub(akCert.NotBefore).Truncate(time.Second)
		renewBefore := time.Duration(float64(period.Nanoseconds()) * (float64(k.identityRenewalPeriodPercentage) / 100))
		earlyAfter := akCert.NotAfter.Add(-1 * renewBefore)
		if now.After(earlyAfter) {
			return ErrIdentityCertificateIsExpiring
		}
	}

	// the Smallstep Attestation CA will issue AK certifiates that
	// contain the EK public key ID encoded as an URN by default.
	for _, u := range akCert.URIs {
		if ekURL.String() == u.String() {
			return nil
		}
	}

	// TODO(hs): we could consider checking other values to contain
	// a usable identity too.

	return ErrIdentityCertificateInvalid
}

func (k *TPMKMS) getAK(ctx context.Context, name string) (*tpm.AK, error) {
	ak, err := k.tpm.GetAK(ctx, name)
	if err != nil {
		return nil, notFoundError(err)
	}
	return ak, nil
}

func (k *TPMKMS) getKey(ctx context.Context, name string) (*tpm.Key, error) {
	key, err := k.tpm.GetKey(ctx, name)
	if err != nil {
		return nil, notFoundError(err)
	}
	return key, nil
}

func notFoundError(err error) error {
	if errors.Is(err, tpm.ErrNotFound) {
		return apiv1.NotFoundError{
			Message: err.Error(),
		}
	}
	return err
}

// generateKeyID generates a key identifier from the
// SHA256 hash of the public key.
func generateKeyID(pub crypto.PublicKey) ([]byte, error) {
	b, err := x509.MarshalPKIXPublicKey(pub)
	if err != nil {
		return nil, fmt.Errorf("error marshaling public key: %w", err)
	}
	hash := sha256.Sum256(b)
	return hash[:], nil
}

// ekURL generates an EK URI containing the encoded key identifier
// for the EK.
func ekURL(keyID []byte) *url.URL {
	return &url.URL{
		Scheme: "urn",
		Opaque: "ek:sha256:" + base64.StdEncoding.EncodeToString(keyID),
	}
}

func parseTSS2(pemBytes []byte) (*tss2.TPMKey, error) {
	var block *pem.Block
	for len(pemBytes) > 0 {
		block, pemBytes = pem.Decode(pemBytes)
		if block == nil {
			break
		}
		if block.Type != "TSS2 PRIVATE KEY" {
			continue
		}

		key, err := tss2.ParsePrivateKey(block.Bytes)
		if err != nil {
			return nil, fmt.Errorf("failed parsing TSS2 PEM: %w", err)
		}
		return key, nil
	}
	return nil, fmt.Errorf("failed parsing TSS2 PEM: block not found")
}

type subjectPublicKeyInfo struct {
	Algorithm        pkix.AlgorithmIdentifier
	SubjectPublicKey asn1.BitString
}

func generateWindowsSubjectKeyID(pub crypto.PublicKey) (string, error) {
	b, err := x509.MarshalPKIXPublicKey(pub)
	if err != nil {
		return "", err
	}
	var info subjectPublicKeyInfo
	if _, err = asn1.Unmarshal(b, &info); err != nil {
		return "", err
	}
	hash := sha1.Sum(info.SubjectPublicKey.Bytes) //nolint:gosec // required for Windows key ID calculation

	return hex.EncodeToString(hash[:]), nil
}

type deletingCertificateManager interface {
	apiv1.CertificateManager
	DeleteCertificate(req *apiv1.DeleteCertificateRequest) error
}

type deletingCertificateChainManager interface {
	apiv1.CertificateChainManager
	DeleteCertificate(req *apiv1.DeleteCertificateRequest) error
}

var _ apiv1.KeyManager = (*TPMKMS)(nil)
var _ apiv1.Attester = (*TPMKMS)(nil)
var _ apiv1.CertificateManager = (*TPMKMS)(nil)
var _ apiv1.CertificateChainManager = (*TPMKMS)(nil)
var _ deletingCertificateChainManager = (*TPMKMS)(nil)
var _ apiv1.AttestationClient = (*attestationClient)(nil)