forked from canonical/snapd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseal.go
1019 lines (902 loc) · 35 KB
/
seal.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 -*-
/*
* Copyright (C) 2020-2023 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 boot
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"encoding/json"
"fmt"
"os"
"path/filepath"
"github.com/snapcore/snapd/asserts"
"github.com/snapcore/snapd/bootloader"
"github.com/snapcore/snapd/dirs"
"github.com/snapcore/snapd/gadget/device"
"github.com/snapcore/snapd/kernel/fde"
"github.com/snapcore/snapd/logger"
"github.com/snapcore/snapd/osutil"
"github.com/snapcore/snapd/secboot"
"github.com/snapcore/snapd/secboot/keys"
"github.com/snapcore/snapd/seed"
"github.com/snapcore/snapd/snap"
"github.com/snapcore/snapd/strutil"
"github.com/snapcore/snapd/timings"
)
var (
secbootProvisionTPM = secboot.ProvisionTPM
secbootSealKeys = secboot.SealKeys
secbootSealKeysWithFDESetupHook = secboot.SealKeysWithFDESetupHook
secbootResealKeys = secboot.ResealKeys
secbootPCRHandleOfSealedKey = secboot.PCRHandleOfSealedKey
secbootReleasePCRResourceHandles = secboot.ReleasePCRResourceHandles
seedReadSystemEssential = seed.ReadSystemEssential
)
// Hook functions setup by devicestate to support device-specific full
// disk encryption implementations. The state must be locked when these
// functions are called.
var (
// HasFDESetupHook purpose is to detect if the target kernel has a
// fde-setup-hook. If kernelInfo is nil the current kernel is checked
// assuming it is representative` of the target one.
HasFDESetupHook = func(kernelInfo *snap.Info) (bool, error) {
return false, nil
}
RunFDESetupHook fde.RunSetupHookFunc = func(req *fde.SetupRequest) ([]byte, error) {
return nil, fmt.Errorf("internal error: RunFDESetupHook not set yet")
}
)
// MockSecbootResealKeys is only useful in testing. Note that this is a very low
// level call and may need significant environment setup.
func MockSecbootResealKeys(f func(params *secboot.ResealKeysParams) error) (restore func()) {
osutil.MustBeTestBinary("secbootResealKeys only can be mocked in tests")
old := secbootResealKeys
secbootResealKeys = f
return func() {
secbootResealKeys = old
}
}
// MockResealKeyToModeenv is only useful in testing.
func MockResealKeyToModeenv(f func(rootdir string, modeenv *Modeenv, expectReseal bool, unlocker Unlocker) error) (restore func()) {
osutil.MustBeTestBinary("resealKeyToModeenv only can be mocked in tests")
old := resealKeyToModeenv
resealKeyToModeenv = f
return func() {
resealKeyToModeenv = old
}
}
// MockSealKeyToModeenvFlags is used for testing from other packages.
type MockSealKeyToModeenvFlags = sealKeyToModeenvFlags
// MockSealKeyToModeenv is used for testing from other packages.
func MockSealKeyToModeenv(f func(key, saveKey keys.EncryptionKey, model *asserts.Model, modeenv *Modeenv, flags MockSealKeyToModeenvFlags) error) (restore func()) {
old := sealKeyToModeenv
sealKeyToModeenv = f
return func() {
sealKeyToModeenv = old
}
}
func bootChainsFileUnder(rootdir string) string {
return filepath.Join(dirs.SnapFDEDirUnder(rootdir), "boot-chains")
}
func recoveryBootChainsFileUnder(rootdir string) string {
return filepath.Join(dirs.SnapFDEDirUnder(rootdir), "recovery-boot-chains")
}
type sealKeyToModeenvFlags struct {
// HasFDESetupHook is true if the kernel has a fde-setup hook to use
HasFDESetupHook bool
// FactoryReset indicates that the sealing is happening during factory
// reset.
FactoryReset bool
// SnapsDir is set to provide a non-default directory to find
// run mode snaps in.
SnapsDir string
// SeedDir is the path where to find mounted seed with
// essential snaps.
SeedDir string
// Unlocker is used unlock the snapd state for long operations
StateUnlocker Unlocker
}
// sealKeyToModeenvImpl seals the supplied keys to the parameters specified
// in modeenv.
// It assumes to be invoked in install mode.
func sealKeyToModeenvImpl(key, saveKey keys.EncryptionKey, model *asserts.Model, modeenv *Modeenv, flags sealKeyToModeenvFlags) error {
if !isModeeenvLocked() {
return fmt.Errorf("internal error: cannot seal without the modeenv lock")
}
// make sure relevant locations exist
for _, p := range []string{
InitramfsSeedEncryptionKeyDir,
InitramfsBootEncryptionKeyDir,
InstallHostFDEDataDir(model),
InstallHostFDESaveDir,
} {
// XXX: should that be 0700 ?
if err := os.MkdirAll(p, 0755); err != nil {
return err
}
}
if flags.HasFDESetupHook {
return sealKeyToModeenvUsingFDESetupHook(key, saveKey, model, modeenv, flags)
}
if flags.StateUnlocker != nil {
relock := flags.StateUnlocker()
defer relock()
}
return sealKeyToModeenvUsingSecboot(key, saveKey, model, modeenv, flags)
}
func runKeySealRequests(key keys.EncryptionKey) []secboot.SealKeyRequest {
return []secboot.SealKeyRequest{
{
Key: key,
KeyName: "ubuntu-data",
KeyFile: device.DataSealedKeyUnder(InitramfsBootEncryptionKeyDir),
},
}
}
func fallbackKeySealRequests(key, saveKey keys.EncryptionKey, factoryReset bool) []secboot.SealKeyRequest {
saveFallbackKey := device.FallbackSaveSealedKeyUnder(InitramfsSeedEncryptionKeyDir)
if factoryReset {
// factory reset uses alternative sealed key location, such that
// until we boot into the run mode, both sealed keys are present
// on disk
saveFallbackKey = device.FactoryResetFallbackSaveSealedKeyUnder(InitramfsSeedEncryptionKeyDir)
}
return []secboot.SealKeyRequest{
{
Key: key,
KeyName: "ubuntu-data",
KeyFile: device.FallbackDataSealedKeyUnder(InitramfsSeedEncryptionKeyDir),
},
{
Key: saveKey,
KeyName: "ubuntu-save",
KeyFile: saveFallbackKey,
},
}
}
func sealKeyToModeenvUsingFDESetupHook(key, saveKey keys.EncryptionKey, model *asserts.Model, modeenv *Modeenv, flags sealKeyToModeenvFlags) error {
// XXX: Move the auxKey creation to a more generic place, see
// PR#10123 for a possible way of doing this. However given
// that the equivalent key for the TPM case is also created in
// sealKeyToModeenvUsingTPM more symetric to create the auxKey
// here and when we also move TPM to use the auxKey to move
// the creation of it.
auxKey, err := keys.NewAuxKey()
if err != nil {
return fmt.Errorf("cannot create aux key: %v", err)
}
params := secboot.SealKeysWithFDESetupHookParams{
Model: modeenv.ModelForSealing(),
AuxKey: auxKey,
AuxKeyFile: filepath.Join(InstallHostFDESaveDir, "aux-key"),
}
factoryReset := flags.FactoryReset
skrs := append(runKeySealRequests(key), fallbackKeySealRequests(key, saveKey, factoryReset)...)
if err := secbootSealKeysWithFDESetupHook(RunFDESetupHook, skrs, ¶ms); err != nil {
return err
}
if err := device.StampSealedKeys(InstallHostWritableDir(model), "fde-setup-hook"); err != nil {
return err
}
return nil
}
func sealKeyToModeenvUsingSecboot(key, saveKey keys.EncryptionKey, model *asserts.Model, modeenv *Modeenv, flags sealKeyToModeenvFlags) error {
// build the recovery mode boot chain
rbl, err := bootloader.Find(InitramfsUbuntuSeedDir, &bootloader.Options{
Role: bootloader.RoleRecovery,
})
if err != nil {
return fmt.Errorf("cannot find the recovery bootloader: %v", err)
}
tbl, ok := rbl.(bootloader.TrustedAssetsBootloader)
if !ok {
// TODO:UC20: later the exact kind of bootloaders we expect here might change
return fmt.Errorf("internal error: cannot seal keys without a trusted assets bootloader")
}
includeTryModel := false
systems := []string{modeenv.RecoverySystem}
modes := map[string][]string{
// the system we are installing from is considered current and
// tested, hence allow both recover and factory reset modes
modeenv.RecoverySystem: {ModeRecover, ModeFactoryReset},
}
recoveryBootChains, err := recoveryBootChainsForSystems(systems, modes, tbl, modeenv, includeTryModel, flags.SeedDir)
if err != nil {
return fmt.Errorf("cannot compose recovery boot chains: %v", err)
}
logger.Debugf("recovery bootchain:\n%+v", recoveryBootChains)
// build the run mode boot chains
bl, err := bootloader.Find(InitramfsUbuntuBootDir, &bootloader.Options{
Role: bootloader.RoleRunMode,
NoSlashBoot: true,
})
if err != nil {
return fmt.Errorf("cannot find the bootloader: %v", err)
}
// kernel command lines are filled during install
cmdlines := modeenv.CurrentKernelCommandLines
runModeBootChains, err := runModeBootChains(rbl, bl, modeenv, cmdlines, flags.SnapsDir)
if err != nil {
return fmt.Errorf("cannot compose run mode boot chains: %v", err)
}
logger.Debugf("run mode bootchain:\n%+v", runModeBootChains)
pbc := toPredictableBootChains(append(runModeBootChains, recoveryBootChains...))
roleToBlName := map[bootloader.Role]string{
bootloader.RoleRecovery: rbl.Name(),
bootloader.RoleRunMode: bl.Name(),
}
// the boot chains we seal the fallback object to
rpbc := toPredictableBootChains(recoveryBootChains)
// gets written to a file by sealRunObjectKeys()
authKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return fmt.Errorf("cannot generate key for signing dynamic authorization policies: %v", err)
}
runObjectKeyPCRHandle := uint32(secboot.RunObjectPCRPolicyCounterHandle)
fallbackObjectKeyPCRHandle := uint32(secboot.FallbackObjectPCRPolicyCounterHandle)
if flags.FactoryReset {
// during factory reset we may need to rotate the PCR handles,
// seal the new keys using a new set of handles such that the
// old sealed ubuntu-save key is still usable, for this we
// switch between two sets of handles in a round robin fashion,
// first looking at the PCR handle used by the current fallback
// key and then using the other set when sealing the new keys;
// the currently used handles will be released during the first
// boot of a new run system
usesAlt, err := usesAltPCRHandles()
if err != nil {
return err
}
if !usesAlt {
logger.Noticef("using alternative PCR handles")
runObjectKeyPCRHandle = secboot.AltRunObjectPCRPolicyCounterHandle
fallbackObjectKeyPCRHandle = secboot.AltFallbackObjectPCRPolicyCounterHandle
}
}
// we are preparing a new system, hence the TPM needs to be provisioned
lockoutAuthFile := device.TpmLockoutAuthUnder(InstallHostFDESaveDir)
tpmProvisionMode := secboot.TPMProvisionFull
if flags.FactoryReset {
tpmProvisionMode = secboot.TPMPartialReprovision
}
if err := secbootProvisionTPM(tpmProvisionMode, lockoutAuthFile); err != nil {
return err
}
if flags.FactoryReset {
// it is possible that we are sealing the keys again, after a
// previously running factory reset was interrupted by a reboot,
// in which case the PCR handles of the new sealed keys might
// have already been used
if err := secbootReleasePCRResourceHandles(runObjectKeyPCRHandle, fallbackObjectKeyPCRHandle); err != nil {
return err
}
}
// TODO: refactor sealing functions to take a struct instead of so many
// parameters
err = sealRunObjectKeys(key, pbc, authKey, roleToBlName, runObjectKeyPCRHandle)
if err != nil {
return err
}
err = sealFallbackObjectKeys(key, saveKey, rpbc, authKey, roleToBlName, flags.FactoryReset,
fallbackObjectKeyPCRHandle)
if err != nil {
return err
}
if err := device.StampSealedKeys(InstallHostWritableDir(model), device.SealingMethodTPM); err != nil {
return err
}
installBootChainsPath := bootChainsFileUnder(InstallHostWritableDir(model))
if err := writeBootChains(pbc, installBootChainsPath, 0); err != nil {
return err
}
installRecoveryBootChainsPath := recoveryBootChainsFileUnder(InstallHostWritableDir(model))
if err := writeBootChains(rpbc, installRecoveryBootChainsPath, 0); err != nil {
return err
}
return nil
}
func usesAltPCRHandles() (bool, error) {
saveFallbackKey := device.FallbackSaveSealedKeyUnder(InitramfsSeedEncryptionKeyDir)
// inspect the PCR handle of the ubuntu-save fallback key
handle, err := secbootPCRHandleOfSealedKey(saveFallbackKey)
if err != nil {
return false, err
}
logger.Noticef("fallback sealed key %v PCR handle: %#x", saveFallbackKey, handle)
return handle == secboot.AltFallbackObjectPCRPolicyCounterHandle, nil
}
func sealRunObjectKeys(key keys.EncryptionKey, pbc predictableBootChains, authKey *ecdsa.PrivateKey, roleToBlName map[bootloader.Role]string, pcrHandle uint32) error {
modelParams, err := sealKeyModelParams(pbc, roleToBlName)
if err != nil {
return fmt.Errorf("cannot prepare for key sealing: %v", err)
}
sealKeyParams := &secboot.SealKeysParams{
ModelParams: modelParams,
TPMPolicyAuthKey: authKey,
TPMPolicyAuthKeyFile: filepath.Join(InstallHostFDESaveDir, "tpm-policy-auth-key"),
PCRPolicyCounterHandle: pcrHandle,
}
logger.Debugf("sealing run key with PCR handle: %#x", sealKeyParams.PCRPolicyCounterHandle)
// The run object contains only the ubuntu-data key; the ubuntu-save key
// is then stored inside the encrypted data partition, so that the normal run
// path only unseals one object because unsealing is expensive.
// Furthermore, the run object key is stored on ubuntu-boot so that we do not
// need to continually write/read keys from ubuntu-seed.
if err := secbootSealKeys(runKeySealRequests(key), sealKeyParams); err != nil {
return fmt.Errorf("cannot seal the encryption keys: %v", err)
}
return nil
}
func sealFallbackObjectKeys(key, saveKey keys.EncryptionKey, pbc predictableBootChains, authKey *ecdsa.PrivateKey, roleToBlName map[bootloader.Role]string, factoryReset bool, pcrHandle uint32) error {
// also seal the keys to the recovery bootchains as a fallback
modelParams, err := sealKeyModelParams(pbc, roleToBlName)
if err != nil {
return fmt.Errorf("cannot prepare for fallback key sealing: %v", err)
}
sealKeyParams := &secboot.SealKeysParams{
ModelParams: modelParams,
TPMPolicyAuthKey: authKey,
PCRPolicyCounterHandle: pcrHandle,
}
logger.Debugf("sealing fallback key with PCR handle: %#x", sealKeyParams.PCRPolicyCounterHandle)
// The fallback object contains the ubuntu-data and ubuntu-save keys. The
// key files are stored on ubuntu-seed, separate from ubuntu-data so they
// can be used if ubuntu-data and ubuntu-boot are corrupted or unavailable.
if err := secbootSealKeys(fallbackKeySealRequests(key, saveKey, factoryReset), sealKeyParams); err != nil {
return fmt.Errorf("cannot seal the fallback encryption keys: %v", err)
}
return nil
}
var resealKeyToModeenv = resealKeyToModeenvImpl
// resealKeyToModeenv reseals the existing encryption key to the
// parameters specified in modeenv.
// It is *very intentional* that resealing takes the modeenv and only
// the modeenv as input. modeenv content is well defined and updated
// atomically. In particular we want to avoid resealing against
// transient/in-memory information with the risk that successive
// reseals during in-progress operations produce diverging outcomes.
func resealKeyToModeenvImpl(rootdir string, modeenv *Modeenv, expectReseal bool, unlocker Unlocker) error {
if !isModeeenvLocked() {
return fmt.Errorf("internal error: cannot reseal without the modeenv lock")
}
method, err := device.SealedKeysMethod(rootdir)
if err == device.ErrNoSealedKeys {
// nothing to do
return nil
}
if err != nil {
return err
}
switch method {
case device.SealingMethodFDESetupHook:
return resealKeyToModeenvUsingFDESetupHook(rootdir, modeenv, expectReseal)
case device.SealingMethodTPM, device.SealingMethodLegacyTPM:
if unlocker != nil {
// unlock/relock global state
defer unlocker()()
}
return resealKeyToModeenvSecboot(rootdir, modeenv, expectReseal)
default:
return fmt.Errorf("unknown key sealing method: %q", method)
}
}
var resealKeyToModeenvUsingFDESetupHook = resealKeyToModeenvUsingFDESetupHookImpl
func resealKeyToModeenvUsingFDESetupHookImpl(rootdir string, modeenv *Modeenv, expectReseal bool) error {
// TODO: we need to implement reseal at least in terms of
// rebinding the keys to models on remodeling
// TODO: If we have situations that do TPM-like full sealing then:
// Implement reseal using the fde-setup hook. This will
// require a helper like "FDEShouldResealUsingSetupHook"
// that will be set by devicestate and returns (bool,
// error). It needs to return "false" during seeding
// because then there is no kernel available yet. It
// can though return true as soon as there's an active
// kernel if seeded is false
//
// It will also need to run HasFDESetupHook internally
// and return an error if the hook goes missing
// (e.g. because a kernel refresh losses the hook by
// accident). It could also run features directly and
// check for "reseal" in features.
return nil
}
// TODO:UC20: allow more than one model to accommodate the remodel scenario
func resealKeyToModeenvSecboot(rootdir string, modeenv *Modeenv, expectReseal bool) error {
// build the recovery mode boot chain
rbl, err := bootloader.Find(InitramfsUbuntuSeedDir, &bootloader.Options{
Role: bootloader.RoleRecovery,
})
if err != nil {
return fmt.Errorf("cannot find the recovery bootloader: %v", err)
}
tbl, ok := rbl.(bootloader.TrustedAssetsBootloader)
if !ok {
// TODO:UC20: later the exact kind of bootloaders we expect here might change
return fmt.Errorf("internal error: sealed keys but not a trusted assets bootloader")
}
// derive the allowed modes for each system mentioned in the modeenv
modes := modesForSystems(modeenv)
// the recovery boot chains for the run key are generated for all
// recovery systems, including those that are being tried; since this is
// a run key, the boot chains are generated for both models to
// accommodate the dynamics of a remodel
includeTryModel := true
recoveryBootChainsForRunKey, err := recoveryBootChainsForSystems(modeenv.CurrentRecoverySystems, modes, tbl,
modeenv, includeTryModel, dirs.SnapSeedDir)
if err != nil {
return fmt.Errorf("cannot compose recovery boot chains for run key: %v", err)
}
// the boot chains for recovery keys include only those system that were
// tested and are known to be good
testedRecoverySystems := modeenv.GoodRecoverySystems
if len(testedRecoverySystems) == 0 && len(modeenv.CurrentRecoverySystems) > 0 {
// compatibility for systems where good recovery systems list
// has not been populated yet
testedRecoverySystems = modeenv.CurrentRecoverySystems[:1]
logger.Noticef("no good recovery systems for reseal, fallback to known current system %v",
testedRecoverySystems[0])
}
// use the current model as the recovery keys are not expected to be
// used during a remodel
includeTryModel = false
recoveryBootChains, err := recoveryBootChainsForSystems(testedRecoverySystems, modes, tbl, modeenv, includeTryModel, dirs.SnapSeedDir)
if err != nil {
return fmt.Errorf("cannot compose recovery boot chains: %v", err)
}
// build the run mode boot chains
bl, err := bootloader.Find(InitramfsUbuntuBootDir, &bootloader.Options{
Role: bootloader.RoleRunMode,
NoSlashBoot: true,
})
if err != nil {
return fmt.Errorf("cannot find the bootloader: %v", err)
}
cmdlines, err := kernelCommandLinesForResealWithFallback(modeenv)
if err != nil {
return err
}
runModeBootChains, err := runModeBootChains(rbl, bl, modeenv, cmdlines, "")
if err != nil {
return fmt.Errorf("cannot compose run mode boot chains: %v", err)
}
roleToBlName := map[bootloader.Role]string{
bootloader.RoleRecovery: rbl.Name(),
bootloader.RoleRunMode: bl.Name(),
}
saveFDEDir := dirs.SnapFDEDirUnderSave(dirs.SnapSaveDirUnder(rootdir))
authKeyFile := filepath.Join(saveFDEDir, "tpm-policy-auth-key")
// reseal the run object
pbc := toPredictableBootChains(append(runModeBootChains, recoveryBootChainsForRunKey...))
needed, nextCount, err := isResealNeeded(pbc, bootChainsFileUnder(rootdir), expectReseal)
if err != nil {
return err
}
if needed {
pbcJSON, _ := json.Marshal(pbc)
logger.Debugf("resealing (%d) to boot chains: %s", nextCount, pbcJSON)
if err := resealRunObjectKeys(pbc, authKeyFile, roleToBlName); err != nil {
return err
}
logger.Debugf("resealing (%d) succeeded", nextCount)
bootChainsPath := bootChainsFileUnder(rootdir)
if err := writeBootChains(pbc, bootChainsPath, nextCount); err != nil {
return err
}
} else {
logger.Debugf("reseal not necessary")
}
// reseal the fallback object
rpbc := toPredictableBootChains(recoveryBootChains)
var nextFallbackCount int
needed, nextFallbackCount, err = isResealNeeded(rpbc, recoveryBootChainsFileUnder(rootdir), expectReseal)
if err != nil {
return err
}
if needed {
rpbcJSON, _ := json.Marshal(rpbc)
logger.Debugf("resealing (%d) to recovery boot chains: %s", nextFallbackCount, rpbcJSON)
if err := resealFallbackObjectKeys(rpbc, authKeyFile, roleToBlName); err != nil {
return err
}
logger.Debugf("fallback resealing (%d) succeeded", nextFallbackCount)
recoveryBootChainsPath := recoveryBootChainsFileUnder(rootdir)
if err := writeBootChains(rpbc, recoveryBootChainsPath, nextFallbackCount); err != nil {
return err
}
} else {
logger.Debugf("fallback reseal not necessary")
}
return nil
}
func resealRunObjectKeys(pbc predictableBootChains, authKeyFile string, roleToBlName map[bootloader.Role]string) error {
// get model parameters from bootchains
modelParams, err := sealKeyModelParams(pbc, roleToBlName)
if err != nil {
return fmt.Errorf("cannot prepare for key resealing: %v", err)
}
// list all the key files to reseal
keyFiles := []string{device.DataSealedKeyUnder(InitramfsBootEncryptionKeyDir)}
resealKeyParams := &secboot.ResealKeysParams{
ModelParams: modelParams,
KeyFiles: keyFiles,
TPMPolicyAuthKeyFile: authKeyFile,
}
if err := secbootResealKeys(resealKeyParams); err != nil {
return fmt.Errorf("cannot reseal the encryption key: %v", err)
}
return nil
}
func resealFallbackObjectKeys(pbc predictableBootChains, authKeyFile string, roleToBlName map[bootloader.Role]string) error {
// get model parameters from bootchains
modelParams, err := sealKeyModelParams(pbc, roleToBlName)
if err != nil {
return fmt.Errorf("cannot prepare for fallback key resealing: %v", err)
}
// list all the key files to reseal
keyFiles := []string{
device.FallbackDataSealedKeyUnder(InitramfsSeedEncryptionKeyDir),
device.FallbackSaveSealedKeyUnder(InitramfsSeedEncryptionKeyDir),
}
resealKeyParams := &secboot.ResealKeysParams{
ModelParams: modelParams,
KeyFiles: keyFiles,
TPMPolicyAuthKeyFile: authKeyFile,
}
if err := secbootResealKeys(resealKeyParams); err != nil {
return fmt.Errorf("cannot reseal the fallback encryption keys: %v", err)
}
return nil
}
// recoveryModesForSystems returns a map for recovery modes for recovery systems
// mentioned in the modeenv. The returned map contains both tested and candidate
// recovery systems
func modesForSystems(modeenv *Modeenv) map[string][]string {
if len(modeenv.GoodRecoverySystems) == 0 && len(modeenv.CurrentRecoverySystems) == 0 {
return nil
}
systemToModes := map[string][]string{}
// first go through tested recovery systems
modesForTestedSystem := []string{ModeRecover, ModeFactoryReset}
// tried systems can only boot to recovery mode
modesForCandidateSystem := []string{ModeRecover}
// go through current recovery systems which can contain both tried
// systems and candidate ones
for _, sys := range modeenv.CurrentRecoverySystems {
systemToModes[sys] = modesForCandidateSystem
}
// go through recovery systems that were tested and update their modes
for _, sys := range modeenv.GoodRecoverySystems {
systemToModes[sys] = modesForTestedSystem
}
return systemToModes
}
// TODO:UC20: this needs to take more than one model to accommodate the remodel
// scenario
func recoveryBootChainsForSystems(systems []string, modesForSystems map[string][]string, trbl bootloader.TrustedAssetsBootloader, modeenv *Modeenv, includeTryModel bool, seedDir string) (chains []bootChain, err error) {
trustedAssets, err := trbl.TrustedAssets()
if err != nil {
return nil, err
}
chainsForModel := func(model secboot.ModelForSealing) error {
modelID := modelUniqueID(model)
for _, system := range systems {
// get kernel and gadget information from seed
perf := timings.New(nil)
seedSystemModel, snaps, err := seedReadSystemEssential(seedDir, system, []snap.Type{snap.TypeKernel, snap.TypeGadget}, perf)
if err != nil {
return fmt.Errorf("cannot read system %q seed: %v", system, err)
}
if len(snaps) != 2 {
return fmt.Errorf("cannot obtain recovery system snaps")
}
seedModelID := modelUniqueID(seedSystemModel)
// TODO: the generated unique ID contains the model's
// sign key ID, consider relaxing this to ignore the key
// ID when matching models, OTOH we would need to
// properly take into account key expiration and
// revocation
if seedModelID != modelID {
// could be an incompatible recovery system that
// is still currently tracked in modeenv
continue
}
seedKernel, seedGadget := snaps[0], snaps[1]
if snaps[0].EssentialType == snap.TypeGadget {
seedKernel, seedGadget = seedGadget, seedKernel
}
var cmdlines []string
modes, ok := modesForSystems[system]
if !ok {
return fmt.Errorf("internal error: no modes for system %q", system)
}
for _, mode := range modes {
// get the command line for this mode
cmdline, err := composeCommandLine(currentEdition, mode, system, seedGadget.Path, model)
if err != nil {
return fmt.Errorf("cannot obtain kernel command line for mode %q: %v", mode, err)
}
cmdlines = append(cmdlines, cmdline)
}
var kernelRev string
if seedKernel.SideInfo.Revision.Store() {
kernelRev = seedKernel.SideInfo.Revision.String()
}
recoveryBootChains, err := trbl.RecoveryBootChains(seedKernel.Path)
if err != nil {
return err
}
foundChain := false
// get asset chains
for _, recoveryBootChain := range recoveryBootChains {
assetChain, kbf, err := buildBootAssets(recoveryBootChain, modeenv, trustedAssets)
if err != nil {
return err
}
if assetChain == nil {
// This chain is not used as
// it is not in the modeenv,
// we expect another chain to
// work.
continue
}
chains = append(chains, bootChain{
BrandID: model.BrandID(),
Model: model.Model(),
// TODO: test this
Classic: model.Classic(),
Grade: model.Grade(),
ModelSignKeyID: model.SignKeyID(),
AssetChain: assetChain,
Kernel: seedKernel.SnapName(),
KernelRevision: kernelRev,
KernelCmdlines: cmdlines,
kernelBootFile: kbf,
})
foundChain = true
}
if !foundChain {
return fmt.Errorf("could not find any valid chain for this model")
}
}
return nil
}
if err := chainsForModel(modeenv.ModelForSealing()); err != nil {
return nil, err
}
if modeenv.TryModel != "" && includeTryModel {
if err := chainsForModel(modeenv.TryModelForSealing()); err != nil {
return nil, err
}
}
return chains, nil
}
func runModeBootChains(rbl, bl bootloader.Bootloader, modeenv *Modeenv, cmdlines []string, runSnapsDir string) ([]bootChain, error) {
tbl, ok := rbl.(bootloader.TrustedAssetsBootloader)
if !ok {
return nil, fmt.Errorf("recovery bootloader doesn't support trusted assets")
}
chains := make([]bootChain, 0, len(modeenv.CurrentKernels))
trustedAssets, err := tbl.TrustedAssets()
if err != nil {
return nil, err
}
chainsForModel := func(model secboot.ModelForSealing) error {
for _, k := range modeenv.CurrentKernels {
info, err := snap.ParsePlaceInfoFromSnapFileName(k)
if err != nil {
return err
}
var kernelPath string
if runSnapsDir == "" {
kernelPath = info.MountFile()
} else {
kernelPath = filepath.Join(runSnapsDir, info.Filename())
}
runModeBootChains, err := tbl.BootChains(bl, kernelPath)
if err != nil {
return err
}
foundChain := false
for _, runModeBootChain := range runModeBootChains {
// get asset chains
assetChain, kbf, err := buildBootAssets(runModeBootChain, modeenv, trustedAssets)
if err != nil {
return err
}
if assetChain == nil {
// This chain is not used as
// it is not in the modeenv,
// we expect another chain to
// work.
continue
}
var kernelRev string
if info.SnapRevision().Store() {
kernelRev = info.SnapRevision().String()
}
chains = append(chains, bootChain{
BrandID: model.BrandID(),
Model: model.Model(),
// TODO: test this
Classic: model.Classic(),
Grade: model.Grade(),
ModelSignKeyID: model.SignKeyID(),
AssetChain: assetChain,
Kernel: info.SnapName(),
KernelRevision: kernelRev,
KernelCmdlines: cmdlines,
kernelBootFile: kbf,
})
foundChain = true
}
if !foundChain {
return fmt.Errorf("could not find any valid chain for this model")
}
}
return nil
}
if err := chainsForModel(modeenv.ModelForSealing()); err != nil {
return nil, err
}
if modeenv.TryModel != "" {
if err := chainsForModel(modeenv.TryModelForSealing()); err != nil {
return nil, err
}
}
return chains, nil
}
// buildBootAssets takes the BootFiles of a bootloader boot chain and
// produces corresponding bootAssets with the matching current asset
// hashes from modeenv plus it returns separately the last BootFile
// which is for the kernel.
func buildBootAssets(bootFiles []bootloader.BootFile, modeenv *Modeenv, trustedAssets map[string]string) (assets []bootAsset, kernel bootloader.BootFile, err error) {
if len(bootFiles) == 0 {
// useful in testing, when mocking is insufficient
return nil, bootloader.BootFile{}, fmt.Errorf("internal error: cannot build boot assets without boot files")
}
assets = make([]bootAsset, len(bootFiles)-1)
// the last element is the kernel which is not a boot asset
for i, bf := range bootFiles[:len(bootFiles)-1] {
path := bf.Path
name, ok := trustedAssets[path]
if !ok {
return nil, kernel, fmt.Errorf("internal error: asset '%s' is not considered a trusted asset for the bootloader", path)
}
var hashes []string
if bf.Role == bootloader.RoleRecovery {
hashes, ok = modeenv.CurrentTrustedRecoveryBootAssets[name]
} else {
hashes, ok = modeenv.CurrentTrustedBootAssets[name]
}
if !ok {
// We have not found an asset for this
// chain. There are chains expected to not
// exist. So we return without error.
// recoveryBootChainsForSystems and
// runModeBootChains will fail if no chain is
// found
return nil, kernel, nil
}
assets[i] = bootAsset{
Role: bf.Role,
Name: name,
Hashes: hashes,
}
}
return assets, bootFiles[len(bootFiles)-1], nil
}
func sealKeyModelParams(pbc predictableBootChains, roleToBlName map[bootloader.Role]string) ([]*secboot.SealKeyModelParams, error) {
// seal parameters keyed by unique model ID
modelToParams := map[string]*secboot.SealKeyModelParams{}
modelParams := make([]*secboot.SealKeyModelParams, 0, len(pbc))
for _, bc := range pbc {
modelForSealing := bc.modelForSealing()
modelID := modelUniqueID(modelForSealing)
const expectNew = false
loadChains, err := bootAssetsToLoadChains(bc.AssetChain, bc.kernelBootFile, roleToBlName, expectNew)
if err != nil {
return nil, fmt.Errorf("cannot build load chains with current boot assets: %s", err)
}
// group parameters by model, reuse an existing SealKeyModelParams
// if the model is the same.
if params, ok := modelToParams[modelID]; ok {
params.KernelCmdlines = strutil.SortedListsUniqueMerge(params.KernelCmdlines, bc.KernelCmdlines)
params.EFILoadChains = append(params.EFILoadChains, loadChains...)
} else {
param := &secboot.SealKeyModelParams{
Model: modelForSealing,
KernelCmdlines: bc.KernelCmdlines,
EFILoadChains: loadChains,
}
modelParams = append(modelParams, param)
modelToParams[modelID] = param
}
}
return modelParams, nil
}
// isResealNeeded returns true when the predictable boot chains provided as
// input do not match the cached boot chains on disk under rootdir.
// It also returns the next value for the reseal count that is saved
// together with the boot chains.
// A hint expectReseal can be provided, it is used when the matching
// is ambigous because the boot chains contain unrevisioned kernels.
func isResealNeeded(pbc predictableBootChains, bootChainsFile string, expectReseal bool) (ok bool, nextCount int, err error) {
previousPbc, c, err := readBootChains(bootChainsFile)
if err != nil {
return false, 0, err
}
switch predictableBootChainsEqualForReseal(pbc, previousPbc) {
case bootChainEquivalent:
return false, c + 1, nil
case bootChainUnrevisioned:
return expectReseal, c + 1, nil
case bootChainDifferent:
}
return true, c + 1, nil
}
func postFactoryResetCleanupSecboot() error {
// we are inspecting a key which was generated during factory reset, in
// the simplest case the sealed key generated previously used the main
// handles, while the current key uses alt handles, hence we need to
// release the main handles corresponding to the old key
handles := []uint32{secboot.RunObjectPCRPolicyCounterHandle, secboot.FallbackObjectPCRPolicyCounterHandle}
usesAlt, err := usesAltPCRHandles()
if err != nil {
return fmt.Errorf("cannot inspect fallback key: %v", err)
}
if !usesAlt {
// current fallback key using the main handles, which is
// possible of there were subsequent factory reset steps,
// release the alt handles associated with the old key
handles = []uint32{secboot.AltRunObjectPCRPolicyCounterHandle, secboot.AltFallbackObjectPCRPolicyCounterHandle}
}
return secbootReleasePCRResourceHandles(handles...)
}
func postFactoryResetCleanup() error {
hasHook, err := HasFDESetupHook(nil)
if err != nil {
return fmt.Errorf("cannot check for fde-setup hook %v", err)
}
saveFallbackKeyFactory := device.FactoryResetFallbackSaveSealedKeyUnder(InitramfsSeedEncryptionKeyDir)
saveFallbackKey := device.FallbackSaveSealedKeyUnder(InitramfsSeedEncryptionKeyDir)
if err := os.Rename(saveFallbackKeyFactory, saveFallbackKey); err != nil {
// it is possible that the key file was already renamed if we
// came back here after an unexpected reboot
if !os.IsNotExist(err) {
return fmt.Errorf("cannot rotate fallback key: %v", err)
}
}
if hasHook {
// TODO: do we need to invoke FDE hook?
return nil