-
Notifications
You must be signed in to change notification settings - Fork 601
/
Copy pathsecboot_sb_test.go
2208 lines (1986 loc) · 71 KB
/
secboot_sb_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
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
// -*- Mode: Go; indent-tabs-mode: t -*-
//go:build !nosecboot
/*
* Copyright (C) 2021 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package secboot_test
import (
"bytes"
"crypto/ecdsa"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"github.com/canonical/go-tpm2"
"github.com/canonical/go-tpm2/linux"
"github.com/canonical/go-tpm2/mu"
sb "github.com/snapcore/secboot"
sb_efi "github.com/snapcore/secboot/efi"
sb_tpm2 "github.com/snapcore/secboot/tpm2"
. "gopkg.in/check.v1"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/asserts/assertstest"
"github.com/snapcore/snapd/bootloader"
"github.com/snapcore/snapd/bootloader/efi"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/gadget/device"
"github.com/snapcore/snapd/kernel/fde"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/osutil/disks"
"github.com/snapcore/snapd/secboot"
"github.com/snapcore/snapd/secboot/keys"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/snap/snapfile"
"github.com/snapcore/snapd/snap/squashfs"
"github.com/snapcore/snapd/testutil"
)
type secbootSuite struct {
testutil.BaseTest
}
var _ = Suite(&secbootSuite{})
func (s *secbootSuite) SetUpTest(c *C) {
rootDir := c.MkDir()
err := os.MkdirAll(filepath.Join(rootDir, "/run"), 0755)
c.Assert(err, IsNil)
dirs.SetRootDir(rootDir)
s.AddCleanup(func() { dirs.SetRootDir("/") })
}
func (s *secbootSuite) TestCheckTPMKeySealingSupported(c *C) {
c.Check(secboot.WithSecbootSupport, Equals, true)
sbEmpty := []uint8{}
sbEnabled := []uint8{1}
sbDisabled := []uint8{0}
efiNotSupported := []uint8(nil)
tpmErr := errors.New("TPM error")
tpmModesBoth := []secboot.TPMProvisionMode{secboot.TPMProvisionFull, secboot.TPMPartialReprovision}
type testCase struct {
tpmErr error
tpmEnabled bool
tpmLockout bool
tpmModes []secboot.TPMProvisionMode
sbData []uint8
err string
}
for i, tc := range []testCase{
// happy case
{tpmErr: nil, tpmEnabled: true, tpmLockout: false, tpmModes: tpmModesBoth, sbData: sbEnabled, err: ""},
// secure boot EFI var is empty
{tpmErr: nil, tpmEnabled: true, tpmLockout: false, tpmModes: tpmModesBoth, sbData: sbEmpty, err: "secure boot variable does not exist"},
// secure boot is disabled
{tpmErr: nil, tpmEnabled: true, tpmLockout: false, tpmModes: tpmModesBoth, sbData: sbDisabled, err: "secure boot is disabled"},
// EFI not supported
{tpmErr: nil, tpmEnabled: true, tpmLockout: false, tpmModes: tpmModesBoth, sbData: efiNotSupported, err: "not a supported EFI system"},
// TPM connection error
{tpmErr: tpmErr, sbData: sbEnabled, tpmLockout: false, tpmModes: tpmModesBoth, err: "cannot connect to TPM device: TPM error"},
// TPM was detected but it's not enabled
{tpmErr: nil, tpmEnabled: false, tpmLockout: false, tpmModes: tpmModesBoth, sbData: sbEnabled, err: "TPM device is not enabled"},
// No TPM device
{tpmErr: sb_tpm2.ErrNoTPM2Device, tpmLockout: false, tpmModes: tpmModesBoth, sbData: sbEnabled, err: "cannot connect to TPM device: no TPM2 device is available"},
// In DA lockout mode full provision errors
{tpmErr: nil, tpmEnabled: true, tpmLockout: true, tpmModes: []secboot.TPMProvisionMode{secboot.TPMProvisionFull}, sbData: sbEnabled, err: "the TPM is in DA lockout mode"},
// In DA lockout mode partial provision is fine
{tpmErr: nil, tpmEnabled: true, tpmLockout: true, tpmModes: []secboot.TPMProvisionMode{secboot.TPMPartialReprovision}, sbData: sbEnabled, err: ""},
} {
c.Logf("%d: %v %v %v %v %q", i, tc.tpmErr, tc.tpmEnabled, tc.tpmModes, tc.sbData, tc.err)
_, restore := mockSbTPMConnection(c, tc.tpmErr)
defer restore()
restore = secboot.MockSbLockoutAuthSet(func(tpm *sb_tpm2.Connection) bool {
return tc.tpmLockout
})
defer restore()
restore = secboot.MockIsTPMEnabled(func(tpm *sb_tpm2.Connection) bool {
return tc.tpmEnabled
})
defer restore()
var vars map[string][]byte
if tc.sbData != nil {
vars = map[string][]byte{"SecureBoot-8be4df61-93ca-11d2-aa0d-00e098032b8c": tc.sbData}
}
restoreEfiVars := efi.MockVars(vars, nil)
defer restoreEfiVars()
for _, tpmMode := range tc.tpmModes {
err := secboot.CheckTPMKeySealingSupported(tpmMode)
if tc.err == "" {
c.Assert(err, IsNil)
} else {
c.Assert(err, ErrorMatches, tc.err)
}
}
}
}
func (s *secbootSuite) TestMeasureSnapSystemEpochWhenPossible(c *C) {
for _, tc := range []struct {
tpmErr error
tpmEnabled bool
callNum int
err string
}{
{
// normal connection to the TPM device
tpmErr: nil, tpmEnabled: true, callNum: 1, err: "",
},
{
// TPM device exists but returns error
tpmErr: errors.New("tpm error"), callNum: 0,
err: "cannot measure snap system epoch: cannot open TPM connection: tpm error",
},
{
// TPM device exists but is disabled
tpmErr: nil, tpmEnabled: false,
},
{
// TPM device does not exist
tpmErr: sb_tpm2.ErrNoTPM2Device,
},
} {
mockTpm, restore := mockSbTPMConnection(c, tc.tpmErr)
defer restore()
restore = secboot.MockIsTPMEnabled(func(tpm *sb_tpm2.Connection) bool {
return tc.tpmEnabled
})
defer restore()
calls := 0
restore = secboot.MockSbMeasureSnapSystemEpochToTPM(func(tpm *sb_tpm2.Connection, pcrIndex int) error {
calls++
c.Assert(tpm, Equals, mockTpm)
c.Assert(pcrIndex, Equals, 12)
return nil
})
defer restore()
err := secboot.MeasureSnapSystemEpochWhenPossible()
if tc.err == "" {
c.Assert(err, IsNil)
} else {
c.Assert(err, ErrorMatches, tc.err)
}
c.Assert(calls, Equals, tc.callNum)
}
}
func (s *secbootSuite) TestMeasureSnapModelWhenPossible(c *C) {
for i, tc := range []struct {
tpmErr error
tpmEnabled bool
modelErr error
callNum int
err string
}{
{
// normal connection to the TPM device
tpmErr: nil, tpmEnabled: true, modelErr: nil, callNum: 1, err: "",
},
{
// normal connection to the TPM device with model error
tpmErr: nil, tpmEnabled: true, modelErr: errors.New("model error"), callNum: 0,
err: "cannot measure snap model: model error",
},
{
// TPM device exists but returns error
tpmErr: errors.New("tpm error"), callNum: 0,
err: "cannot measure snap model: cannot open TPM connection: tpm error",
},
{
// TPM device exists but is disabled
tpmErr: nil, tpmEnabled: false,
},
{
// TPM device does not exist
tpmErr: sb_tpm2.ErrNoTPM2Device,
},
} {
c.Logf("%d: tpmErr:%v tpmEnabled:%v", i, tc.tpmErr, tc.tpmEnabled)
mockModel := &asserts.Model{}
mockTpm, restore := mockSbTPMConnection(c, tc.tpmErr)
defer restore()
restore = secboot.MockIsTPMEnabled(func(tpm *sb_tpm2.Connection) bool {
return tc.tpmEnabled
})
defer restore()
calls := 0
restore = secboot.MockSbMeasureSnapModelToTPM(func(tpm *sb_tpm2.Connection, pcrIndex int, model sb.SnapModel) error {
calls++
c.Assert(tpm, Equals, mockTpm)
c.Assert(model, Equals, mockModel)
c.Assert(pcrIndex, Equals, 12)
return nil
})
defer restore()
findModel := func() (*asserts.Model, error) {
if tc.modelErr != nil {
return nil, tc.modelErr
}
return mockModel, nil
}
err := secboot.MeasureSnapModelWhenPossible(findModel)
if tc.err == "" {
c.Assert(err, IsNil)
} else {
c.Assert(err, ErrorMatches, tc.err)
}
c.Assert(calls, Equals, tc.callNum)
}
}
func (s *secbootSuite) TestLockTPMSealedKeys(c *C) {
tt := []struct {
tpmErr error
tpmEnabled bool
lockOk bool
expError string
}{
// can't connect to tpm
{
tpmErr: fmt.Errorf("failed to connect to tpm"),
expError: "cannot lock TPM: failed to connect to tpm",
},
// no TPM2 device, shouldn't return an error
{
tpmErr: sb_tpm2.ErrNoTPM2Device,
},
// tpm is not enabled but we can lock it
{
tpmEnabled: false,
lockOk: true,
},
// can't lock pcr protection profile
{
tpmEnabled: true,
lockOk: false,
expError: "block failed",
},
// tpm enabled, we can lock it
{
tpmEnabled: true,
lockOk: true,
},
}
for _, tc := range tt {
mockSbTPM, restoreConnect := mockSbTPMConnection(c, tc.tpmErr)
defer restoreConnect()
restore := secboot.MockIsTPMEnabled(func(tpm *sb_tpm2.Connection) bool {
return tc.tpmEnabled
})
defer restore()
sbBlockPCRProtectionPolicesCalls := 0
restore = secboot.MockSbBlockPCRProtectionPolicies(func(tpm *sb_tpm2.Connection, pcrs []int) error {
sbBlockPCRProtectionPolicesCalls++
c.Assert(tpm, Equals, mockSbTPM)
c.Assert(pcrs, DeepEquals, []int{12})
if tc.lockOk {
return nil
}
return errors.New("block failed")
})
defer restore()
err := secboot.LockTPMSealedKeys()
if tc.expError == "" {
c.Assert(err, IsNil)
} else {
c.Assert(err, ErrorMatches, tc.expError)
}
// if there was no TPM connection error, we should have tried to lock it
if tc.tpmErr == nil {
c.Assert(sbBlockPCRProtectionPolicesCalls, Equals, 1)
} else {
c.Assert(sbBlockPCRProtectionPolicesCalls, Equals, 0)
}
}
}
func (s *secbootSuite) TestProvisionForCVM(c *C) {
mockTpm, restore := mockSbTPMConnection(c, nil)
defer restore()
restore = secboot.MockIsTPMEnabled(func(tpm *sb_tpm2.Connection) bool {
c.Check(tpm, Equals, mockTpm)
return true
})
defer restore()
expectedTemplate := &tpm2.Public{
Type: tpm2.ObjectTypeRSA,
NameAlg: tpm2.HashAlgorithmSHA256,
Attrs: tpm2.AttrFixedTPM | tpm2.AttrFixedParent | tpm2.AttrSensitiveDataOrigin | tpm2.AttrUserWithAuth | tpm2.AttrNoDA |
tpm2.AttrRestricted | tpm2.AttrDecrypt,
Params: &tpm2.PublicParamsU{
RSADetail: &tpm2.RSAParams{
Symmetric: tpm2.SymDefObject{
Algorithm: tpm2.SymObjectAlgorithmAES,
KeyBits: &tpm2.SymKeyBitsU{Sym: 128},
Mode: &tpm2.SymModeU{Sym: tpm2.SymModeCFB}},
Scheme: tpm2.RSAScheme{Scheme: tpm2.RSASchemeNull},
KeyBits: 2048,
Exponent: 0}}}
mu.MustCopyValue(&expectedTemplate, expectedTemplate)
dir := c.MkDir()
f, err := os.OpenFile(filepath.Join(dir, "tpm2-srk.tmpl"), os.O_RDWR|os.O_CREATE, 0600)
c.Assert(err, IsNil)
defer f.Close()
mu.MustMarshalToWriter(f, mu.Sized(expectedTemplate))
provisioningCalls := 0
restore = secboot.MockSbTPMEnsureProvisionedWithCustomSRK(func(tpm *sb_tpm2.Connection, mode sb_tpm2.ProvisionMode, lockoutAuth []byte, srkTemplate *tpm2.Public) error {
provisioningCalls += 1
c.Check(tpm, Equals, mockTpm)
c.Check(mode, Equals, sb_tpm2.ProvisionModeWithoutLockout)
c.Check(lockoutAuth, IsNil)
c.Check(srkTemplate, DeepEquals, expectedTemplate)
return nil
})
defer restore()
c.Check(secboot.ProvisionForCVM(dir), IsNil)
c.Check(provisioningCalls, Equals, 1)
}
func (s *secbootSuite) TestProvisionForCVMNoTPM(c *C) {
_, restore := mockSbTPMConnection(c, sb_tpm2.ErrNoTPM2Device)
defer restore()
restore = secboot.MockSbTPMEnsureProvisionedWithCustomSRK(func(tpm *sb_tpm2.Connection, mode sb_tpm2.ProvisionMode, lockoutAuth []byte, srkTemplate *tpm2.Public) error {
c.Error("unexpected provisioning call")
return nil
})
defer restore()
c.Check(secboot.ProvisionForCVM(c.MkDir()), IsNil)
}
func (s *secbootSuite) TestProvisionForCVMTPMNotEnabled(c *C) {
mockTpm, restore := mockSbTPMConnection(c, nil)
defer restore()
restore = secboot.MockIsTPMEnabled(func(tpm *sb_tpm2.Connection) bool {
c.Check(tpm, Equals, mockTpm)
return false
})
defer restore()
restore = secboot.MockSbTPMEnsureProvisionedWithCustomSRK(func(tpm *sb_tpm2.Connection, mode sb_tpm2.ProvisionMode, lockoutAuth []byte, srkTemplate *tpm2.Public) error {
c.Error("unexpected provisioning call")
return nil
})
defer restore()
c.Check(secboot.ProvisionForCVM(c.MkDir()), IsNil)
}
func (s *secbootSuite) TestUnlockVolumeUsingSealedKeyIfEncrypted(c *C) {
// setup mock disks to use for locating the partition
// restore := disks.MockMountPointDisksToPartitionMapping()
// defer restore()
mockDiskWithEncDev := &disks.MockDiskMapping{
Structure: []disks.Partition{
{
FilesystemLabel: "name-enc",
PartitionUUID: "enc-dev-partuuid",
},
},
}
mockDiskWithoutAnyDev := &disks.MockDiskMapping{}
mockDiskWithUnencDev := &disks.MockDiskMapping{
Structure: []disks.Partition{
{
FilesystemLabel: "name",
PartitionUUID: "unenc-dev-partuuid",
},
},
}
for idx, tc := range []struct {
tpmErr error
tpmEnabled bool // TPM storage and endorsement hierarchies disabled, only relevant if TPM available
hasEncdev bool // an encrypted device exists
rkAllow bool // allow recovery key activation
rkErr error // recovery key unlock error, only relevant if TPM not available
activated bool // the activation operation succeeded
activateErr error // the activation error
uuidFailure bool // failure to get valid uuid
err string
skipDiskEnsureCheck bool // whether to check to ensure the mock disk contains the device label
expUnlockMethod secboot.UnlockMethod
disk *disks.MockDiskMapping
}{
{
// happy case with tpm and encrypted device
tpmEnabled: true, hasEncdev: true,
activated: true,
disk: mockDiskWithEncDev,
expUnlockMethod: secboot.UnlockedWithSealedKey,
}, {
// encrypted device: failure to generate uuid based target device name
tpmEnabled: true, hasEncdev: true, activated: true, uuidFailure: true,
disk: mockDiskWithEncDev,
err: "mocked uuid error",
}, {
// device activation fails
tpmEnabled: true, hasEncdev: true,
err: "cannot activate encrypted device .*: activation error",
disk: mockDiskWithEncDev,
}, {
// device activation fails
tpmEnabled: true, hasEncdev: true,
err: "cannot activate encrypted device .*: activation error",
disk: mockDiskWithEncDev,
}, {
// happy case without encrypted device
tpmEnabled: true,
disk: mockDiskWithUnencDev,
}, {
// happy case with tpm and encrypted device, activation
// with recovery key
tpmEnabled: true, hasEncdev: true, activated: true,
activateErr: sb.ErrRecoveryKeyUsed,
disk: mockDiskWithEncDev,
expUnlockMethod: secboot.UnlockedWithRecoveryKey,
}, {
// tpm error, no encrypted device
tpmErr: errors.New("tpm error"),
disk: mockDiskWithUnencDev,
}, {
// tpm error, has encrypted device
tpmErr: errors.New("tpm error"), hasEncdev: true,
err: `cannot unlock encrypted device "name": tpm error`,
disk: mockDiskWithEncDev,
}, {
// tpm disabled, no encrypted device
disk: mockDiskWithUnencDev,
}, {
// tpm disabled, has encrypted device, unlocked using the recovery key
hasEncdev: true,
rkAllow: true,
disk: mockDiskWithEncDev,
expUnlockMethod: secboot.UnlockedWithRecoveryKey,
}, {
// tpm disabled, has encrypted device, recovery key unlocking fails
hasEncdev: true, rkErr: errors.New("cannot unlock with recovery key"),
rkAllow: true,
disk: mockDiskWithEncDev,
err: `cannot unlock encrypted device ".*/enc-dev-partuuid": cannot unlock with recovery key`,
}, {
// no tpm, has encrypted device, unlocked using the recovery key
tpmErr: sb_tpm2.ErrNoTPM2Device, hasEncdev: true,
rkAllow: true,
disk: mockDiskWithEncDev,
expUnlockMethod: secboot.UnlockedWithRecoveryKey,
}, {
// no tpm, has encrypted device, unlocking with recovery key not allowed
tpmErr: sb_tpm2.ErrNoTPM2Device, hasEncdev: true,
disk: mockDiskWithEncDev,
err: `cannot activate encrypted device ".*/enc-dev-partuuid": activation error`,
}, {
// no tpm, has encrypted device, recovery key unlocking fails
rkErr: errors.New("cannot unlock with recovery key"),
tpmErr: sb_tpm2.ErrNoTPM2Device, hasEncdev: true,
rkAllow: true,
disk: mockDiskWithEncDev,
err: `cannot unlock encrypted device ".*/enc-dev-partuuid": cannot unlock with recovery key`,
}, {
// no tpm, no encrypted device
tpmErr: sb_tpm2.ErrNoTPM2Device,
disk: mockDiskWithUnencDev,
}, {
// no disks at all
disk: mockDiskWithoutAnyDev,
skipDiskEnsureCheck: true,
// error is specifically for failing to find name, NOT name-enc, we
// will properly fall back to looking for name if we didn't find
// name-enc
err: "error enumerating partitions for disk to find unencrypted device \"name\": filesystem label \"name\" not found",
},
} {
c.Logf("tc %v: %+v", idx, tc)
randomUUID := fmt.Sprintf("random-uuid-for-test-%d", idx)
restore := secboot.MockRandomKernelUUID(func() (string, error) {
if tc.uuidFailure {
return "", errors.New("mocked uuid error")
}
return randomUUID, nil
})
defer restore()
_, restoreConnect := mockSbTPMConnection(c, tc.tpmErr)
defer restoreConnect()
restore = secboot.MockIsTPMEnabled(func(tpm *sb_tpm2.Connection) bool {
return tc.tpmEnabled
})
defer restore()
defaultDevice := "name"
fsLabel := defaultDevice
if tc.hasEncdev {
fsLabel += "-enc"
}
partuuid := ""
if !tc.skipDiskEnsureCheck {
for _, p := range tc.disk.Structure {
if p.FilesystemLabel == fsLabel {
partuuid = p.PartitionUUID
break
}
}
c.Assert(partuuid, Not(Equals), "", Commentf("didn't find fs label %s in disk", fsLabel))
}
devicePath := filepath.Join("/dev/disk/by-partuuid", partuuid)
keyPath := filepath.Join("test-data", "keyfile")
kd, err := sb_tpm2.NewKeyDataFromSealedKeyObjectFile(keyPath)
c.Assert(err, IsNil)
expectedID, err := kd.UniqueID()
c.Assert(err, IsNil)
restore = secboot.MockSbActivateVolumeWithKeyData(func(volumeName, sourceDevicePath string, keyData *sb.KeyData, options *sb.ActivateVolumeOptions) (sb.SnapModelChecker, error) {
c.Assert(volumeName, Equals, "name-"+randomUUID)
c.Assert(sourceDevicePath, Equals, devicePath)
c.Assert(keyData, NotNil)
uID, err := keyData.UniqueID()
c.Assert(err, IsNil)
c.Check(uID, DeepEquals, expectedID)
if tc.rkAllow {
c.Assert(*options, DeepEquals, sb.ActivateVolumeOptions{
PassphraseTries: 1,
RecoveryKeyTries: 3,
KeyringPrefix: "ubuntu-fde",
})
} else {
c.Assert(*options, DeepEquals, sb.ActivateVolumeOptions{
PassphraseTries: 1,
// activation with recovery key was disabled
RecoveryKeyTries: 0,
KeyringPrefix: "ubuntu-fde",
})
}
if !tc.activated && tc.activateErr == nil {
return nil, errors.New("activation error")
}
return nil, tc.activateErr
})
defer restore()
restore = secboot.MockSbActivateVolumeWithRecoveryKey(func(name, device string, keyReader io.Reader,
options *sb.ActivateVolumeOptions) error {
if !tc.rkAllow {
c.Fatalf("unexpected attempt to activate with recovery key")
return fmt.Errorf("unexpected call")
}
return tc.rkErr
})
defer restore()
opts := &secboot.UnlockVolumeUsingSealedKeyOptions{
AllowRecoveryKey: tc.rkAllow,
}
unlockRes, err := secboot.UnlockVolumeUsingSealedKeyIfEncrypted(tc.disk, defaultDevice, keyPath, opts)
if tc.err == "" {
c.Assert(err, IsNil)
c.Assert(unlockRes.IsEncrypted, Equals, tc.hasEncdev)
c.Assert(unlockRes.PartDevice, Equals, devicePath)
if tc.hasEncdev {
c.Assert(unlockRes.FsDevice, Equals, filepath.Join("/dev/mapper", defaultDevice+"-"+randomUUID))
} else {
c.Assert(unlockRes.FsDevice, Equals, devicePath)
}
} else {
c.Assert(err, ErrorMatches, tc.err)
// also check that the IsEncrypted value matches, this is
// important for robust callers to know whether they should try to
// unlock using a different method or not
// this is only skipped on some test cases where we get an error
// very early, like trying to connect to the tpm
c.Assert(unlockRes.IsEncrypted, Equals, tc.hasEncdev)
if tc.hasEncdev {
c.Check(unlockRes.PartDevice, Equals, devicePath)
c.Check(unlockRes.FsDevice, Equals, "")
} else {
c.Check(unlockRes.PartDevice, Equals, "")
c.Check(unlockRes.FsDevice, Equals, "")
}
}
c.Assert(unlockRes.UnlockMethod, Equals, tc.expUnlockMethod)
}
}
func (s *secbootSuite) TestEFIImageFromBootFile(c *C) {
tmpDir := c.MkDir()
// set up some test files
existingFile := filepath.Join(tmpDir, "foo")
err := os.WriteFile(existingFile, nil, 0644)
c.Assert(err, IsNil)
missingFile := filepath.Join(tmpDir, "bar")
snapFile := filepath.Join(tmpDir, "test.snap")
snapf, err := createMockSnapFile(c.MkDir(), snapFile, "app")
for _, tc := range []struct {
bootFile bootloader.BootFile
efiImage sb_efi.Image
err string
}{
{
// happy case for EFI image
bootFile: bootloader.NewBootFile("", existingFile, bootloader.RoleRecovery),
efiImage: sb_efi.FileImage(existingFile),
},
{
// missing EFI image
bootFile: bootloader.NewBootFile("", missingFile, bootloader.RoleRecovery),
err: fmt.Sprintf("file %s/bar does not exist", tmpDir),
},
{
// happy case for snap file
bootFile: bootloader.NewBootFile(snapFile, "rel", bootloader.RoleRecovery),
efiImage: sb_efi.SnapFileImage{Container: snapf, FileName: "rel"},
},
{
// invalid snap file
bootFile: bootloader.NewBootFile(existingFile, "rel", bootloader.RoleRecovery),
err: fmt.Sprintf(`cannot process snap or snapdir: cannot read "%s/foo": EOF`, tmpDir),
},
{
// missing snap file
bootFile: bootloader.NewBootFile(missingFile, "rel", bootloader.RoleRecovery),
err: fmt.Sprintf(`cannot process snap or snapdir: open %s/bar: no such file or directory`, tmpDir),
},
} {
o, err := secboot.EFIImageFromBootFile(&tc.bootFile)
if tc.err == "" {
c.Assert(err, IsNil)
c.Assert(o, DeepEquals, tc.efiImage)
} else {
c.Assert(err, ErrorMatches, tc.err)
}
}
}
func (s *secbootSuite) TestProvisionTPM(c *C) {
mockErr := errors.New("some error")
for idx, tc := range []struct {
tpmErr error
tpmEnabled bool
mode secboot.TPMProvisionMode
writeLockoutAuth bool
provisioningErr error
provisioningCalls int
expectedErr string
}{
{
tpmErr: mockErr, mode: secboot.TPMProvisionFull,
expectedErr: "cannot connect to TPM: some error",
}, {
tpmEnabled: false, mode: secboot.TPMProvisionFull, expectedErr: "TPM device is not enabled",
}, {
tpmEnabled: true, mode: secboot.TPMProvisionFull, provisioningErr: mockErr,
provisioningCalls: 1, expectedErr: "cannot provision TPM: some error",
}, {
tpmEnabled: true, mode: secboot.TPMPartialReprovision, provisioningCalls: 0,
expectedErr: "cannot read existing lockout auth: open .*/lockout-auth: no such file or directory",
},
// happy cases
{
tpmEnabled: true, mode: secboot.TPMProvisionFull, provisioningCalls: 1,
}, {
tpmEnabled: true, mode: secboot.TPMPartialReprovision, writeLockoutAuth: true,
provisioningCalls: 1,
},
} {
c.Logf("tc: %v", idx)
d := c.MkDir()
tpm, restore := mockSbTPMConnection(c, tc.tpmErr)
defer restore()
// mock TPM enabled check
restore = secboot.MockIsTPMEnabled(func(t *sb_tpm2.Connection) bool {
return tc.tpmEnabled
})
defer restore()
lockoutAuthData := []byte{'l', 'o', 'c', 'k', 'o', 'u', 't', 1, 1, 1, 1, 1, 1, 1, 1, 1}
if tc.writeLockoutAuth {
c.Assert(os.WriteFile(filepath.Join(d, "lockout-auth"), lockoutAuthData, 0644), IsNil)
}
// mock provisioning
provisioningCalls := 0
restore = secboot.MockSbTPMEnsureProvisioned(func(t *sb_tpm2.Connection, mode sb_tpm2.ProvisionMode, newLockoutAuth []byte) error {
provisioningCalls++
c.Assert(t, Equals, tpm)
c.Assert(mode, Equals, sb_tpm2.ProvisionModeFull)
return tc.provisioningErr
})
defer restore()
err := secboot.ProvisionTPM(tc.mode, filepath.Join(d, "lockout-auth"))
if tc.expectedErr != "" {
c.Assert(err, ErrorMatches, tc.expectedErr)
} else {
c.Assert(err, IsNil)
}
c.Check(provisioningCalls, Equals, tc.provisioningCalls)
}
}
func (s *secbootSuite) TestSealKey(c *C) {
mockErr := errors.New("some error")
for idx, tc := range []struct {
tpmErr error
tpmEnabled bool
missingFile bool
badSnapFile bool
addEFISbPolicyErr error
addEFIBootManagerErr error
addSystemdEFIStubErr error
addSnapModelErr error
provisioningErr error
sealErr error
sealCalls int
expectedErr string
}{
{tpmErr: mockErr, expectedErr: "cannot connect to TPM: some error"},
{tpmEnabled: false, expectedErr: "TPM device is not enabled"},
{tpmEnabled: true, missingFile: true, expectedErr: "cannot build EFI image load sequences: file /does/not/exist does not exist"},
{tpmEnabled: true, badSnapFile: true, expectedErr: `cannot build EFI image load sequences: cannot process snap or snapdir: cannot read ".*/kernel.snap": EOF`},
{tpmEnabled: true, addEFISbPolicyErr: mockErr, expectedErr: "cannot add EFI secure boot policy profile: some error"},
{tpmEnabled: true, addEFIBootManagerErr: mockErr, expectedErr: "cannot add EFI boot manager profile: some error"},
{tpmEnabled: true, addSystemdEFIStubErr: mockErr, expectedErr: "cannot add systemd EFI stub profile: some error"},
{tpmEnabled: true, addSnapModelErr: mockErr, expectedErr: "cannot add snap model profile: some error"},
{tpmEnabled: true, sealErr: mockErr, sealCalls: 1, expectedErr: "some error"},
{tpmEnabled: true, sealCalls: 1, expectedErr: ""},
} {
c.Logf("tc: %v", idx)
tmpDir := c.MkDir()
var mockBF []bootloader.BootFile
for _, name := range []string{"a", "b", "c", "d"} {
mockFileName := filepath.Join(tmpDir, name)
err := os.WriteFile(mockFileName, nil, 0644)
c.Assert(err, IsNil)
mockBF = append(mockBF, bootloader.NewBootFile("", mockFileName, bootloader.RoleRecovery))
}
if tc.missingFile {
mockBF[0].Path = "/does/not/exist"
}
var kernelSnap snap.Container
snapPath := filepath.Join(tmpDir, "kernel.snap")
if tc.badSnapFile {
err := os.WriteFile(snapPath, nil, 0644)
c.Assert(err, IsNil)
} else {
var err error
kernelSnap, err = createMockSnapFile(c.MkDir(), snapPath, "kernel")
c.Assert(err, IsNil)
}
mockBF = append(mockBF, bootloader.NewBootFile(snapPath, "kernel.efi", bootloader.RoleRecovery))
myAuthKey := &ecdsa.PrivateKey{}
myParams := secboot.SealKeysParams{
ModelParams: []*secboot.SealKeyModelParams{
{
EFILoadChains: []*secboot.LoadChain{
secboot.NewLoadChain(mockBF[0],
secboot.NewLoadChain(mockBF[4])),
},
KernelCmdlines: []string{"cmdline1"},
Model: &asserts.Model{},
},
{
EFILoadChains: []*secboot.LoadChain{
secboot.NewLoadChain(mockBF[0],
secboot.NewLoadChain(mockBF[2],
secboot.NewLoadChain(mockBF[4])),
secboot.NewLoadChain(mockBF[3],
secboot.NewLoadChain(mockBF[4]))),
secboot.NewLoadChain(mockBF[1],
secboot.NewLoadChain(mockBF[2],
secboot.NewLoadChain(mockBF[4])),
secboot.NewLoadChain(mockBF[3],
secboot.NewLoadChain(mockBF[4]))),
},
KernelCmdlines: []string{"cmdline2", "cmdline3"},
Model: &asserts.Model{},
},
},
TPMPolicyAuthKey: myAuthKey,
TPMPolicyAuthKeyFile: filepath.Join(tmpDir, "policy-auth-key-file"),
PCRPolicyCounterHandle: 42,
}
myKey := keys.EncryptionKey{}
myKey2 := keys.EncryptionKey{}
for i := range myKey {
myKey[i] = byte(i)
myKey2[i] = byte(128 + i)
}
myKeys := []secboot.SealKeyRequest{
{
Key: myKey,
KeyFile: "keyfile",
},
{
Key: myKey2,
KeyFile: "keyfile2",
},
}
// events for
// a -> kernel
sequences1 := []*sb_efi.ImageLoadEvent{
{
Source: sb_efi.Firmware,
Image: sb_efi.FileImage(mockBF[0].Path),
Next: []*sb_efi.ImageLoadEvent{
{
Source: sb_efi.Shim,
Image: sb_efi.SnapFileImage{
Container: kernelSnap,
FileName: "kernel.efi",
},
},
},
},
}
// "cdk" events for
// c -> kernel OR
// d -> kernel
cdk := []*sb_efi.ImageLoadEvent{
{
Source: sb_efi.Shim,
Image: sb_efi.FileImage(mockBF[2].Path),
Next: []*sb_efi.ImageLoadEvent{
{
Source: sb_efi.Shim,
Image: sb_efi.SnapFileImage{
Container: kernelSnap,
FileName: "kernel.efi",
},
},
},
},
{
Source: sb_efi.Shim,
Image: sb_efi.FileImage(mockBF[3].Path),
Next: []*sb_efi.ImageLoadEvent{
{
Source: sb_efi.Shim,
Image: sb_efi.SnapFileImage{
Container: kernelSnap,
FileName: "kernel.efi",
},
},
},
},
}
// events for
// a -> "cdk"
// b -> "cdk"
sequences2 := []*sb_efi.ImageLoadEvent{
{
Source: sb_efi.Firmware,
Image: sb_efi.FileImage(mockBF[0].Path),
Next: cdk,
},
{
Source: sb_efi.Firmware,
Image: sb_efi.FileImage(mockBF[1].Path),
Next: cdk,
},
}
tpm, restore := mockSbTPMConnection(c, tc.tpmErr)
defer restore()
// mock adding EFI secure boot policy profile
var pcrProfile *sb_tpm2.PCRProtectionProfile
addEFISbPolicyCalls := 0
restore = secboot.MockSbEfiAddSecureBootPolicyProfile(func(profile *sb_tpm2.PCRProtectionProfile, params *sb_efi.SecureBootPolicyProfileParams) error {
addEFISbPolicyCalls++
pcrProfile = profile
c.Assert(params.PCRAlgorithm, Equals, tpm2.HashAlgorithmSHA256)
switch addEFISbPolicyCalls {
case 1:
c.Assert(params.LoadSequences, DeepEquals, sequences1)
case 2:
c.Assert(params.LoadSequences, DeepEquals, sequences2)
default:
c.Error("AddSecureBootPolicyProfile shouldn't be called a third time")
}
return tc.addEFISbPolicyErr
})
defer restore()
// mock adding EFI boot manager profile
addEFIBootManagerCalls := 0
restore = secboot.MockSbEfiAddBootManagerProfile(func(profile *sb_tpm2.PCRProtectionProfile, params *sb_efi.BootManagerProfileParams) error {
addEFIBootManagerCalls++
c.Assert(profile, Equals, pcrProfile)
c.Assert(params.PCRAlgorithm, Equals, tpm2.HashAlgorithmSHA256)
switch addEFISbPolicyCalls {
case 1:
c.Assert(params.LoadSequences, DeepEquals, sequences1)
case 2:
c.Assert(params.LoadSequences, DeepEquals, sequences2)
default:
c.Error("AddBootManagerProfile shouldn't be called a third time")
}
return tc.addEFIBootManagerErr
})
defer restore()
// mock adding systemd EFI stub profile
addSystemdEfiStubCalls := 0
restore = secboot.MockSbEfiAddSystemdStubProfile(func(profile *sb_tpm2.PCRProtectionProfile, params *sb_efi.SystemdStubProfileParams) error {
addSystemdEfiStubCalls++