-
Notifications
You must be signed in to change notification settings - Fork 0
/
genkey.go
417 lines (376 loc) · 10.9 KB
/
genkey.go
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
package tpm2genkey
import (
"bytes"
"fmt"
"io"
keyfile "github.com/foxboron/go-tpm-keyfiles"
"github.com/google/go-tpm/tpm2"
"github.com/google/go-tpm/tpm2/transport"
)
const ()
var ()
type NewKeyConfig struct {
Debug bool // debug logging
TPMDevice io.ReadWriteCloser // initialized transport for the TPM
Alg string // aes, rsa, ecdsa or hmac
Exponent int // for rsa 65537
Ownerpw []byte
Parentpw []byte
Parent uint32 // Parent handle
Password []byte // auth password
RSAKeySize int // for rsa 2048
Curve string // for ecdsa [secp224r1|prime256v1|secp384r1|secp521r1"
Mode string // for aes [cfb|crt|ofb|cbc|ecb]
AESKeySize int // for aes, 128
PCRs []uint // PCR banks to bind to
Description string
EnablePolicySyntax bool // enable policy syntax https://www.hansenpartnership.com/draft-bottomley-tpm2-keys.html#section-4.1
}
func NewKey(h *NewKeyConfig) ([]byte, error) {
// todo: validate input
rwr := transport.FromReadWriter(h.TPMDevice)
// setup the key template
var keyTemplate tpm2.TPMTPublic
sess, cleanup1, err := tpm2.PolicySession(rwr, tpm2.TPMAlgSHA256, 16, []tpm2.AuthOption{tpm2.Trial(), tpm2.AESEncryption(128, tpm2.EncryptIn), tpm2.AESEncryption(128, tpm2.EncryptOut)}...)
if err != nil {
return nil, fmt.Errorf("setting up trial session: %v", err)
}
defer func() {
if err := cleanup1(); err != nil {
fmt.Printf("cleaning up trial session: %v", err)
}
}()
var commandParameter []byte
if len(h.PCRs) > 0 {
sel := tpm2.TPMLPCRSelection{
PCRSelections: []tpm2.TPMSPCRSelection{
{
Hash: tpm2.TPMAlgSHA256,
PCRSelect: tpm2.PCClientCompatible.PCRs(h.PCRs...),
},
},
}
expectedDigest, err := getExpectedPCRDigest(rwr, sel, tpm2.TPMAlgSHA256)
if err != nil {
return nil, fmt.Errorf("ERROR: could not get PolicySession: %v", err)
}
_, err = tpm2.PolicyPCR{
PolicySession: sess.Handle(),
Pcrs: tpm2.TPMLPCRSelection{
PCRSelections: sel.PCRSelections,
},
PcrDigest: tpm2.TPM2BDigest{
Buffer: expectedDigest,
},
}.Execute(rwr)
if err != nil {
return nil, fmt.Errorf("error executing PolicyPCR: %v", err)
}
// 23.7 TPM2_PolicyPCR https://trustedcomputinggroup.org/wp-content/uploads/TPM-Rev-2.0-Part-3-Commands-01.38.pdf
pcrSelectionSegment := tpm2.Marshal(sel)
pcrDigestSegment := tpm2.Marshal(tpm2.TPM2BDigest{
Buffer: expectedDigest,
})
commandParameter = append(pcrDigestSegment, pcrSelectionSegment...)
}
if h.Password != nil {
_, err = tpm2.PolicyAuthValue{
PolicySession: sess.Handle(),
}.Execute(rwr)
if err != nil {
return nil, fmt.Errorf("error executing PolicyPCR: %v", err)
}
}
pgd, err := tpm2.PolicyGetDigest{
PolicySession: sess.Handle(),
}.Execute(rwr)
if err != nil {
return nil, fmt.Errorf("error executing PolicyGetDigest: %v", err)
}
if h.Alg == "rsa" {
keyTemplate = tpm2.TPMTPublic{
Type: tpm2.TPMAlgRSA,
NameAlg: tpm2.TPMAlgSHA256,
ObjectAttributes: tpm2.TPMAObject{
SignEncrypt: true,
FixedTPM: true,
FixedParent: true,
SensitiveDataOrigin: true,
UserWithAuth: true,
},
AuthPolicy: tpm2.TPM2BDigest{
Buffer: pgd.PolicyDigest.Buffer,
},
Parameters: tpm2.NewTPMUPublicParms(
tpm2.TPMAlgRSA,
&tpm2.TPMSRSAParms{
Scheme: tpm2.TPMTRSAScheme{
Scheme: tpm2.TPMAlgRSASSA,
Details: tpm2.NewTPMUAsymScheme(
tpm2.TPMAlgRSASSA,
&tpm2.TPMSSigSchemeRSASSA{
HashAlg: tpm2.TPMAlgSHA256,
},
),
},
KeyBits: tpm2.TPMKeyBits(h.RSAKeySize),
Exponent: uint32(h.Exponent),
},
),
}
} else if h.Alg == "ecdsa" {
var crv tpm2.TPMECCCurve
switch h.Curve {
// case "prime192v1": // not an armored key
// crv = tpm2.TPMECCNistP192
case "secp224r1":
crv = tpm2.TPMECCNistP224
case "prime256v1":
crv = tpm2.TPMECCNistP256
case "secp384r1":
crv = tpm2.TPMECCNistP384
case "secp521r1":
crv = tpm2.TPMECCNistP521
default:
return nil, fmt.Errorf("tpm2-genkey: unsuported ecdsa curve: %s must be one of [secp224r1|prime256v1|secp384r1|secp521r1]\n", h.Curve)
}
keyTemplate = tpm2.TPMTPublic{
Type: tpm2.TPMAlgECC,
NameAlg: tpm2.TPMAlgSHA256,
ObjectAttributes: tpm2.TPMAObject{
SignEncrypt: true,
FixedTPM: true,
FixedParent: true,
SensitiveDataOrigin: true,
UserWithAuth: true,
},
AuthPolicy: tpm2.TPM2BDigest{
Buffer: pgd.PolicyDigest.Buffer,
},
Parameters: tpm2.NewTPMUPublicParms(
tpm2.TPMAlgECC,
&tpm2.TPMSECCParms{
CurveID: crv,
Scheme: tpm2.TPMTECCScheme{
Scheme: tpm2.TPMAlgECDSA,
Details: tpm2.NewTPMUAsymScheme(
tpm2.TPMAlgECDSA,
&tpm2.TPMSSigSchemeECDSA{
HashAlg: tpm2.TPMAlgSHA256,
},
),
},
},
),
}
} else if h.Alg == "aes" {
var mode tpm2.TPMAlgID
switch h.Mode {
// case "prime192v1": // not an armored key
// crv = tpm2.TPMECCNistP192
case "cfb":
mode = tpm2.TPMAlgCFB
case "crt":
mode = tpm2.TPMAlgCTR
case "ofb":
mode = tpm2.TPMAlgOFB
case "cbc":
mode = tpm2.TPMAlgCBC
case "ecb":
mode = tpm2.TPMAlgECB
default:
return nil, fmt.Errorf("tpm2-genkey: unsuported ecdsa curve: %s must be one of [cfb|crt|ofb|cbc|ecb]\n", h.Mode)
}
keyTemplate = tpm2.TPMTPublic{
Type: tpm2.TPMAlgSymCipher,
NameAlg: tpm2.TPMAlgSHA256,
ObjectAttributes: tpm2.TPMAObject{
FixedTPM: true,
FixedParent: true,
UserWithAuth: true,
SensitiveDataOrigin: true,
Decrypt: true,
SignEncrypt: true,
},
AuthPolicy: tpm2.TPM2BDigest{
Buffer: pgd.PolicyDigest.Buffer,
},
Parameters: tpm2.NewTPMUPublicParms(
tpm2.TPMAlgSymCipher,
&tpm2.TPMSSymCipherParms{
Sym: tpm2.TPMTSymDefObject{
Algorithm: tpm2.TPMAlgAES,
Mode: tpm2.NewTPMUSymMode(tpm2.TPMAlgAES, mode),
KeyBits: tpm2.NewTPMUSymKeyBits(
tpm2.TPMAlgAES,
tpm2.TPMKeyBits(h.AESKeySize),
),
},
},
),
}
} else if h.Alg == "hmac" {
keyTemplate = tpm2.TPMTPublic{
Type: tpm2.TPMAlgKeyedHash,
NameAlg: tpm2.TPMAlgSHA256,
ObjectAttributes: tpm2.TPMAObject{
FixedTPM: true,
FixedParent: true,
SensitiveDataOrigin: true,
UserWithAuth: true,
SignEncrypt: true,
},
AuthPolicy: tpm2.TPM2BDigest{
Buffer: pgd.PolicyDigest.Buffer,
},
Parameters: tpm2.NewTPMUPublicParms(tpm2.TPMAlgKeyedHash,
&tpm2.TPMSKeyedHashParms{
Scheme: tpm2.TPMTKeyedHashScheme{
Scheme: tpm2.TPMAlgHMAC,
Details: tpm2.NewTPMUSchemeKeyedHash(tpm2.TPMAlgHMAC,
&tpm2.TPMSSchemeHMAC{
HashAlg: tpm2.TPMAlgSHA256,
}),
},
}),
}
} else {
return nil, fmt.Errorf("tpm2-genkey: unknown key algorithm")
}
// now create the key, if the parent is a permanent handle,
// use the default h2 tenplate as the primary key teplate and then a key under that primary key
// if the parent is a persistent handle, create a key using that as the parent.
var keyresponse *tpm2.CreateResponse
if keyfile.IsMSO(tpm2.TPMHandle(h.Parent), keyfile.TPM_HT_PERMANENT) {
primary, err := tpm2.CreatePrimary{
PrimaryHandle: tpm2.AuthHandle{
Handle: tpm2.TPMHandle(h.Parent),
Auth: tpm2.PasswordAuth(h.Ownerpw),
},
InPublic: tpm2.New2B(keyfile.ECCSRK_H2_Template),
InSensitive: tpm2.TPM2BSensitiveCreate{
Sensitive: &tpm2.TPMSSensitiveCreate{
UserAuth: tpm2.TPM2BAuth{
Buffer: h.Parentpw,
},
},
},
}.Execute(rwr)
if err != nil {
return nil, fmt.Errorf("tpm2-genkey: can't create primary: %v", err)
}
defer func() {
flushContextCmd := tpm2.FlushContext{
FlushHandle: primary.ObjectHandle,
}
_, _ = flushContextCmd.Execute(rwr)
}()
keyresponse, err = tpm2.Create{
ParentHandle: tpm2.AuthHandle{
Handle: primary.ObjectHandle,
Name: primary.Name,
Auth: tpm2.PasswordAuth(h.Parentpw),
},
InPublic: tpm2.New2B(keyTemplate),
InSensitive: tpm2.TPM2BSensitiveCreate{
Sensitive: &tpm2.TPMSSensitiveCreate{
UserAuth: tpm2.TPM2BAuth{
Buffer: h.Password,
},
},
},
}.Execute(rwr)
if err != nil {
return nil, fmt.Errorf("tpm2-genkey: can't create key: %v", err)
}
} else if keyfile.IsMSO(tpm2.TPMHandle(h.Parent), keyfile.TPM_HT_PERSISTENT) {
p, err := tpm2.ReadPublic{
ObjectHandle: tpm2.TPMHandle(h.Parent),
}.Execute(rwr)
if err != nil {
return nil, fmt.Errorf("tpm2-genkey: can't read public: %v", err)
}
keyresponse, err = tpm2.Create{
ParentHandle: tpm2.AuthHandle{
Handle: tpm2.TPMHandle(h.Parent),
Name: p.Name,
Auth: tpm2.PasswordAuth(h.Parentpw),
},
InPublic: tpm2.New2B(keyTemplate),
InSensitive: tpm2.TPM2BSensitiveCreate{
Sensitive: &tpm2.TPMSSensitiveCreate{
UserAuth: tpm2.TPM2BAuth{
Buffer: h.Password,
},
},
},
}.Execute(rwr)
if err != nil {
return nil, fmt.Errorf("tpm2-genkey: can't create key: %v", err)
}
} else {
return nil, fmt.Errorf("tpm2-genkey: unsupported parent handle %d\n", h.Parent)
}
// var authpol []*keyfile.TPMAuthPolicy
// if len(h.PCRs) > 0 {
// var pol []*keyfile.TPMPolicy
// pol = append(pol, &keyfile.TPMPolicy{
// CommandCode: int(tpm2.TPMCCPolicyPCR),
// CommandPolicy: pgd.PolicyDigest.Buffer,
// })
// authpol = append(authpol, &keyfile.TPMAuthPolicy{
// Name: h.AuthPolicyName,
// Policy: pol,
// })
// }
var pol []*keyfile.TPMPolicy
if h.EnablePolicySyntax {
if len(h.PCRs) > 0 {
pol = append(pol, &keyfile.TPMPolicy{
CommandCode: int(tpm2.TPMCCPolicyPCR),
CommandPolicy: commandParameter,
})
}
if len(h.Password) > 0 {
pol = append(pol, &keyfile.TPMPolicy{
CommandCode: int(tpm2.TPMCCPolicyAuthValue),
CommandPolicy: nil,
})
}
}
kf := keyfile.NewTPMKey(
keyfile.OIDLoadableKey,
keyresponse.OutPublic,
keyresponse.OutPrivate,
keyfile.WithParent(tpm2.TPMHandle(h.Parent)),
keyfile.WithUserAuth(h.Password),
keyfile.WithDescription(h.Description),
keyfile.WithPolicy(pol),
)
keyFileBytes := new(bytes.Buffer)
err = keyfile.Encode(keyFileBytes, kf)
if err != nil {
return nil, fmt.Errorf("tpm2-genkey: can't create key bytes: %v", err)
}
return keyFileBytes.Bytes(), nil
}
func getExpectedPCRDigest(thetpm transport.TPM, selection tpm2.TPMLPCRSelection, hashAlg tpm2.TPMAlgID) ([]byte, error) {
pcrRead := tpm2.PCRRead{
PCRSelectionIn: selection,
}
pcrReadRsp, err := pcrRead.Execute(thetpm)
if err != nil {
return nil, err
}
var expectedVal []byte
for _, digest := range pcrReadRsp.PCRValues.Digests {
expectedVal = append(expectedVal, digest.Buffer...)
}
cryptoHashAlg, err := hashAlg.Hash()
if err != nil {
return nil, err
}
hash := cryptoHashAlg.New()
hash.Write(expectedVal)
return hash.Sum(nil), nil
}