-
Notifications
You must be signed in to change notification settings - Fork 10
/
tpm2_test.go
468 lines (415 loc) · 16.1 KB
/
tpm2_test.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
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
// Copyright 2019 Canonical Ltd.
// Licensed under the LGPLv3 with static-linking exception.
// See LICENCE file for details.
package tpm2_test
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rsa"
"flag"
"fmt"
"io"
"math/big"
"os"
"reflect"
"testing"
. "github.com/canonical/go-tpm2"
"github.com/canonical/go-tpm2/mu"
"github.com/canonical/go-tpm2/testutil"
"github.com/canonical/go-tpm2/util"
. "gopkg.in/check.v1"
)
func init() {
testutil.AddCommandLineFlags()
}
func Test(t *testing.T) { TestingT(t) }
var (
dummyAuth = []byte("dummy")
testAuth = []byte("1234")
)
type mockResourceContext struct {
handle Handle
name Name
authValue []byte
}
func (r *mockResourceContext) Handle() Handle { return r.handle }
func (r *mockResourceContext) Name() Name { return r.name }
func (r *mockResourceContext) SerializeToBytes() []byte { return nil }
func (r *mockResourceContext) SerializeToWriter(w io.Writer) error { return nil }
func (r *mockResourceContext) SetAuthValue(authValue []byte) { r.authValue = authValue }
func (r *mockResourceContext) AuthValue() []byte { return r.authValue }
func (r *mockResourceContext) SetHandle(handle Handle) { r.handle = handle }
func (r *mockResourceContext) Dispose() {}
type mockSessionContext struct {
handle Handle
data SessionContextData
attrs SessionAttributes
limited bool
}
func (s *mockSessionContext) Handle() Handle { return s.handle }
func (s *mockSessionContext) Name() Name {
var name Name
mu.MustMarshalToBytes(name, s.handle)
return name
}
func (s *mockSessionContext) SerializeToBytes() []byte { return nil }
func (s *mockSessionContext) SerializeToWriter(w io.Writer) error { return nil }
func (s *mockSessionContext) Params() SessionContextParams { return s.data.Params }
func (s *mockSessionContext) State() *SessionContextState {
if s.limited {
return nil
}
return &s.data.State
}
func (s *mockSessionContext) HashAlg() HashAlgorithmId { return s.data.Params.HashAlg }
func (s *mockSessionContext) NonceTPM() Nonce { return s.data.State.NonceTPM }
func (s *mockSessionContext) IsAudit() bool { return s.data.State.IsAudit }
func (s *mockSessionContext) IsExclusive() bool { return s.data.State.IsExclusive }
func (s *mockSessionContext) Attrs() SessionAttributes { return s.attrs }
func (s *mockSessionContext) SetAttrs(attrs SessionAttributes) { s.attrs = attrs }
func (s *mockSessionContext) WithAttrs(attrs SessionAttributes) SessionContext {
return &mockSessionContext{handle: s.handle, data: s.data, attrs: attrs}
}
func (s *mockSessionContext) IncludeAttrs(attrs SessionAttributes) SessionContext {
return &mockSessionContext{handle: s.handle, data: s.data, attrs: s.attrs | attrs}
}
func (s *mockSessionContext) ExcludeAttrs(attrs SessionAttributes) SessionContext {
return &mockSessionContext{handle: s.handle, data: s.data, attrs: s.attrs &^ attrs}
}
func (s *mockSessionContext) Dispose() { s.handle = HandleUnassigned }
func authSessionHandle(sc SessionContext) Handle {
if sc == nil {
return HandlePW
}
return sc.Handle()
}
// Set the hierarchy auth to testAuth. Fatal on failure
func setHierarchyAuthForTest(t *testing.T, tpm *TPMContext, hierarchy ResourceContext) {
if err := tpm.HierarchyChangeAuth(hierarchy, Auth(testAuth), nil); err != nil {
t.Fatalf("HierarchyChangeAuth failed: %v", err)
}
}
// Reset the hierarchy auth to nil.
func resetHierarchyAuth(t *testing.T, tpm *TPMContext, hierarchy ResourceContext) {
if err := tpm.HierarchyChangeAuth(hierarchy, nil, nil); err != nil {
t.Errorf("HierarchyChangeAuth failed: %v", err)
}
}
// Undefine a NV index set by a test. Fails the test if it doesn't succeed.
func undefineNVSpace(t *testing.T, tpm *TPMContext, context, authHandle ResourceContext) {
if err := tpm.NVUndefineSpace(authHandle, context, nil); err != nil {
t.Errorf("NVUndefineSpace failed: %v", err)
}
}
func verifyPublicAgainstTemplate(t *testing.T, public, template *Public) {
if public.Type != template.Type {
t.Errorf("public object has wrong type: %v", public.Type)
}
if public.NameAlg != template.NameAlg {
t.Errorf("public object has wrong name alg: %v", public.NameAlg)
}
if public.Attrs != template.Attrs {
t.Errorf("public object has wrong name attrs: %v", public.Attrs)
}
if !bytes.Equal(public.AuthPolicy, template.AuthPolicy) {
t.Errorf("public object has wrong auth policy")
}
pp, err := mu.MarshalToBytes(public.Params.Select(reflect.ValueOf(public.Type)))
if err != nil {
t.Errorf("cannot marshal public params: %v", err)
}
tp, err := mu.MarshalToBytes(template.Params.Select(reflect.ValueOf(template.Type)))
if err != nil {
t.Errorf("cannot marshal template params: %v", err)
}
if !bytes.Equal(pp, tp) {
t.Errorf("public object has wrong params")
}
}
func verifyRSAAgainstTemplate(t *testing.T, public, template *Public) {
if len(public.Unique.RSA) != int(template.Params.RSADetail.KeyBits)/8 {
t.Errorf("public object has wrong public key length (got %d bytes)", len(public.Unique.RSA))
}
}
func verifyCreationData(t *testing.T, tpm *TPMContext, creationData *CreationData, creationHash Digest, template *Public, outsideInfo Data, creationPCR PCRSelectionList, parent ResourceContext) {
var parentQualifiedName Name
if parent.Handle().Type() == HandleTypePermanent {
parentQualifiedName = parent.Name()
} else {
var err error
_, _, parentQualifiedName, err = tpm.ReadPublic(parent)
if err != nil {
t.Fatalf("ReadPublic failed: %v", err)
}
}
if !mu.DeepEqual(creationData.PCRSelect, creationPCR) {
t.Errorf("creation data has invalid pcrSelect")
}
if len(creationData.PCRDigest) != template.NameAlg.Size() {
t.Errorf("creation data has a pcrDigest of the wrong length (got %d)", len(creationData.PCRDigest))
}
if creationData.ParentNameAlg != AlgorithmId(parent.Name().Algorithm()) {
t.Errorf("creation data has the wrong parentNameAlg (got %v)", creationData.ParentNameAlg)
}
if !bytes.Equal(creationData.ParentName, parent.Name()) {
t.Errorf("creation data has the wrong parentName")
}
if !bytes.Equal(creationData.ParentQualifiedName, parentQualifiedName) {
t.Errorf("creation data has the wrong parentQualifiedName")
}
if !bytes.Equal(creationData.OutsideInfo, outsideInfo) {
t.Errorf("creation data has the wrong outsideInfo (got %x)", creationData.OutsideInfo)
}
hasher := template.NameAlg.NewHash()
if _, err := mu.MarshalToWriter(hasher, creationData); err != nil {
t.Fatalf("Failed to marshal creation data: %v", err)
}
if !bytes.Equal(hasher.Sum(nil), creationHash) {
t.Errorf("Invalid creation hash")
}
}
func verifyCreationTicket(t *testing.T, creationTicket *TkCreation, hierarchy HandleContext) {
if creationTicket.Tag != TagCreation {
t.Errorf("creation ticket has the wrong tag")
}
if creationTicket.Hierarchy != hierarchy.Handle() {
t.Errorf("creation ticket has the wrong hierarchy (got 0x%08x)", creationTicket.Hierarchy)
}
}
func computePCRDigestFromTPM(t *testing.T, tpm *TPMContext, alg HashAlgorithmId, pcrs PCRSelectionList) Digest {
_, pcrValues, err := tpm.PCRRead(pcrs)
if err != nil {
t.Fatalf("PCRRead failed: %v", err)
}
digest, err := util.ComputePCRDigest(alg, pcrs, pcrValues)
if err != nil {
t.Fatalf("ComputePCRDigest failed: %v", err)
}
return digest
}
func verifySignature(t *testing.T, pub *Public, digest []byte, signature *Signature) {
switch pub.Type {
case ObjectTypeRSA:
exp := int(pub.Params.RSADetail.Exponent)
if exp == 0 {
exp = DefaultRSAExponent
}
pubKey := rsa.PublicKey{N: new(big.Int).SetBytes(pub.Unique.RSA), E: exp}
switch signature.SigAlg {
case SigSchemeAlgRSASSA:
sig := (*SignatureRSA)(signature.Signature.RSASSA)
if !sig.Hash.Available() {
t.Fatalf("Signature has unavailable digest")
}
if err := rsa.VerifyPKCS1v15(&pubKey, sig.Hash.GetHash(), digest, sig.Sig); err != nil {
t.Errorf("Signature is invalid")
}
case SigSchemeAlgRSAPSS:
sig := (*SignatureRSA)(signature.Signature.RSAPSS)
if !sig.Hash.Available() {
t.Fatalf("Signature has unavailable digest")
}
if err := rsa.VerifyPSS(&pubKey, sig.Hash.GetHash(), digest, sig.Sig, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash}); err != nil {
t.Errorf("Signature is invalid")
}
default:
t.Errorf("Unknown signature algorithm")
}
case ObjectTypeECC:
pubKey := ecdsa.PublicKey{Curve: elliptic.P256(), X: new(big.Int).SetBytes(pub.Unique.ECC.X), Y: new(big.Int).SetBytes(pub.Unique.ECC.Y)}
switch signature.SigAlg {
case SigSchemeAlgECDSA:
sig := signature.Signature.ECDSA
if !ecdsa.Verify(&pubKey, digest, new(big.Int).SetBytes(sig.SignatureR), new(big.Int).SetBytes(sig.SignatureS)) {
t.Errorf("Signature is invalid")
}
default:
t.Errorf("Unknown signature algorithm")
}
default:
t.Errorf("Unknown public type")
}
}
func createRSASrkForTesting(t *testing.T, tpm *TPMContext, userAuth Auth) ResourceContext {
template := Public{
Type: ObjectTypeRSA,
NameAlg: HashAlgorithmSHA256,
Attrs: AttrFixedTPM | AttrFixedParent | AttrSensitiveDataOrigin | AttrUserWithAuth | AttrNoDA | AttrRestricted | AttrDecrypt,
Params: &PublicParamsU{
RSADetail: &RSAParams{
Symmetric: SymDefObject{
Algorithm: SymObjectAlgorithmAES,
KeyBits: &SymKeyBitsU{Sym: 128},
Mode: &SymModeU{Sym: SymModeCFB}},
Scheme: RSAScheme{Scheme: RSASchemeNull},
KeyBits: 2048,
Exponent: 0}}}
sensitiveCreate := SensitiveCreate{UserAuth: userAuth}
objectHandle, _, _, _, _, err := tpm.CreatePrimary(tpm.OwnerHandleContext(), &sensitiveCreate, &template, nil, nil, nil)
if err != nil {
t.Fatalf("CreatePrimary failed: %v", err)
}
return objectHandle
}
func createECCSrkForTesting(t *testing.T, tpm *TPMContext, userAuth Auth) ResourceContext {
template := Public{
Type: ObjectTypeECC,
NameAlg: HashAlgorithmSHA256,
Attrs: AttrFixedTPM | AttrFixedParent | AttrSensitiveDataOrigin | AttrUserWithAuth | AttrNoDA | AttrRestricted | AttrDecrypt,
Params: &PublicParamsU{
ECCDetail: &ECCParams{
Symmetric: SymDefObject{
Algorithm: SymObjectAlgorithmAES,
KeyBits: &SymKeyBitsU{Sym: 128},
Mode: &SymModeU{Sym: SymModeCFB}},
Scheme: ECCScheme{Scheme: ECCSchemeNull},
CurveID: ECCCurveNIST_P256,
KDF: KDFScheme{Scheme: KDFAlgorithmNull}}}}
sensitiveCreate := SensitiveCreate{UserAuth: userAuth}
objectHandle, _, _, _, _, err := tpm.CreatePrimary(tpm.OwnerHandleContext(), &sensitiveCreate, &template, nil, nil, nil)
if err != nil {
t.Fatalf("CreatePrimary failed: %v", err)
}
return objectHandle
}
func createRSAEkForTesting(t *testing.T, tpm *TPMContext) ResourceContext {
template := Public{
Type: ObjectTypeRSA,
NameAlg: HashAlgorithmSHA256,
Attrs: AttrFixedTPM | AttrFixedParent | AttrSensitiveDataOrigin | AttrAdminWithPolicy | AttrRestricted | AttrDecrypt,
AuthPolicy: []byte{0x83, 0x71, 0x97, 0x67, 0x44, 0x84, 0xb3, 0xf8, 0x1a, 0x90, 0xcc, 0x8d, 0x46, 0xa5, 0xd7, 0x24, 0xfd, 0x52,
0xd7, 0x6e, 0x06, 0x52, 0x0b, 0x64, 0xf2, 0xa1, 0xda, 0x1b, 0x33, 0x14, 0x69, 0xaa},
Params: &PublicParamsU{
RSADetail: &RSAParams{
Symmetric: SymDefObject{
Algorithm: SymObjectAlgorithmAES,
KeyBits: &SymKeyBitsU{Sym: 128},
Mode: &SymModeU{Sym: SymModeCFB}},
Scheme: RSAScheme{Scheme: RSASchemeNull},
KeyBits: 2048,
Exponent: 0}}}
objectHandle, _, _, _, _, err := tpm.CreatePrimary(tpm.EndorsementHandleContext(), nil, &template, nil, nil, nil)
if err != nil {
t.Fatalf("CreatePrimary failed: %v", err)
}
return objectHandle
}
func createAndLoadRSAAkForTesting(t *testing.T, tpm *TPMContext, ek ResourceContext, userAuth Auth) ResourceContext {
sessionContext, err := tpm.StartAuthSession(nil, nil, SessionTypePolicy, nil, HashAlgorithmSHA256)
if err != nil {
t.Fatalf("StartAuthSession failed: %v", err)
}
defer flushContext(t, tpm, sessionContext)
endorsement := tpm.EndorsementHandleContext()
sessionContext.SetAttrs(AttrContinueSession)
if _, _, err := tpm.PolicySecret(endorsement, sessionContext, nil, nil, 0, nil); err != nil {
t.Fatalf("PolicySecret failed: %v", err)
}
template := Public{
Type: ObjectTypeRSA,
NameAlg: HashAlgorithmSHA256,
Attrs: AttrFixedTPM | AttrFixedParent | AttrSensitiveDataOrigin | AttrUserWithAuth | AttrRestricted | AttrSign,
Params: &PublicParamsU{
RSADetail: &RSAParams{
Symmetric: SymDefObject{Algorithm: SymObjectAlgorithmNull},
Scheme: RSAScheme{
Scheme: RSASchemeRSASSA,
Details: &AsymSchemeU{RSASSA: &SigSchemeRSASSA{HashAlg: HashAlgorithmSHA256}}},
KeyBits: 2048,
Exponent: 0}}}
sensitiveCreate := SensitiveCreate{UserAuth: userAuth}
priv, pub, _, _, _, err := tpm.Create(ek, &sensitiveCreate, &template, nil, nil, sessionContext)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
if _, _, err := tpm.PolicySecret(endorsement, sessionContext, nil, nil, 0, nil); err != nil {
t.Fatalf("PolicySecret failed: %v", err)
}
akContext, err := tpm.Load(ek, priv, pub, sessionContext)
if err != nil {
t.Fatalf("Load failed: %v", err)
}
akContext.SetAuthValue(userAuth)
return akContext
}
func createAndLoadRSAPSSKeyForTesting(t *testing.T, tpm *TPMContext, parent ResourceContext) ResourceContext {
template := Public{
Type: ObjectTypeRSA,
NameAlg: HashAlgorithmSHA256,
Attrs: AttrFixedTPM | AttrFixedParent | AttrSensitiveDataOrigin | AttrUserWithAuth | AttrSign | AttrNoDA,
Params: &PublicParamsU{
RSADetail: &RSAParams{
Symmetric: SymDefObject{Algorithm: SymObjectAlgorithmNull},
Scheme: RSAScheme{
Scheme: RSASchemeRSAPSS,
Details: &AsymSchemeU{
RSAPSS: &SigSchemeRSAPSS{HashAlg: HashAlgorithmSHA256}}},
KeyBits: 2048,
Exponent: 0}}}
priv, pub, _, _, _, err := tpm.Create(parent, nil, &template, nil, nil, nil)
if err != nil {
t.Fatalf("Create failed: %v", err)
}
key, err := tpm.Load(parent, priv, pub, nil)
if err != nil {
t.Fatalf("Load failed: %v", err)
}
return key
}
// Persist a transient object for testing. If the persistent handle is already in use, it tries to evict the
// existing resource first. Fatal if persisting the transient object fails.
func persistObjectForTesting(t *testing.T, tpm *TPMContext, auth, transient ResourceContext, persist Handle) ResourceContext {
if context, err := tpm.NewResourceContext(persist); err == nil {
_, err := tpm.EvictControl(auth, context, persist, nil)
if err != nil {
t.Logf("EvictControl failed whilst trying to remove a persistent handle that has previously been leaked: %v", err)
}
}
persistentContext, err := tpm.EvictControl(auth, transient, persist, nil)
if err != nil {
t.Fatalf("EvictControl failed: %v", err)
}
return persistentContext
}
// Evict a persistent object. Fails the test if the resource context is valid but the eviction doesn't succeed.
func evictPersistentObject(t *testing.T, tpm *TPMContext, auth, context ResourceContext) {
if _, err := tpm.EvictControl(auth, context, context.Handle(), nil); err != nil {
t.Errorf("EvictControl failed: %v", err)
}
}
func verifyPersistentObjectEvicted(t *testing.T, tpm *TPMContext, auth, context ResourceContext) {
if context.Handle() == HandleUnassigned {
return
}
t.Errorf("Context is still live")
evictPersistentObject(t, tpm, auth, context)
}
// Flush a resource context. Fails the test if the resource context is valid but the flush doesn't succeed.
func flushContext(t *testing.T, tpm *TPMContext, context HandleContext) {
if err := tpm.FlushContext(context); err != nil {
t.Errorf("FlushContext failed: %v", err)
}
}
// Fail the test if the resource context hasn't been invalidated. Will attempt to flush a valid resource context.
func verifyContextFlushed(t *testing.T, tpm *TPMContext, context HandleContext) {
if context.Handle() == HandleUnassigned {
return
}
t.Errorf("Context is still live")
flushContext(t, tpm, context)
}
func TestMain(m *testing.M) {
flag.Parse()
os.Exit(func() int {
if testutil.TPMBackend == testutil.TPMBackendMssim {
simulatorCleanup, err := testutil.LaunchTPMSimulator(nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Cannot launch TPM simulator: %v\n", err)
return 1
}
defer simulatorCleanup()
}
return m.Run()
}())
}