forked from canonical/secboot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypt_test.go
1785 lines (1494 loc) · 61.4 KB
/
crypt_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 -*-
/*
* Copyright (C) 2019 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"
"errors"
"fmt"
"io/ioutil"
"math/rand"
"os"
"path/filepath"
"strings"
"time"
. "github.com/snapcore/secboot"
"github.com/snapcore/secboot/internal/luks2"
"github.com/snapcore/secboot/internal/luks2/luks2test"
"github.com/snapcore/secboot/internal/paths"
"github.com/snapcore/secboot/internal/paths/pathstest"
"github.com/snapcore/secboot/internal/testutil"
snapd_testutil "github.com/snapcore/snapd/testutil"
. "gopkg.in/check.v1"
)
type cryptTestBase struct {
testutil.KeyringTestBase
dir string
passwordFile string // a newline delimited list of passwords for the mock systemd-ask-password to return
mockKeyslotsDir string
mockKeyslotsCount int
mockLUKS2ActivateCalls []struct {
volumeName string
sourceDevicePath string
}
mockSdAskPassword *snapd_testutil.MockCmd
}
func (ctb *cryptTestBase) SetUpTest(c *C) {
ctb.KeyringTestBase.SetUpTest(c)
ctb.dir = c.MkDir()
ctb.AddCleanup(pathstest.MockRunDir(ctb.dir))
ctb.passwordFile = filepath.Join(ctb.dir, "password") // passwords to be returned by the mock sd-ask-password
ctb.mockKeyslotsCount = 0
ctb.mockKeyslotsDir = c.MkDir()
ctb.mockLUKS2ActivateCalls = nil
ctb.AddCleanup(MockLUKS2Activate(func(volumeName, sourceDevicePath string, key []byte) error {
ctb.mockLUKS2ActivateCalls = append(ctb.mockLUKS2ActivateCalls, struct {
volumeName string
sourceDevicePath string
}{volumeName, sourceDevicePath})
f, err := os.Open(ctb.mockKeyslotsDir)
if err != nil {
return err
}
defer f.Close()
slots, err := f.Readdir(0)
if err != nil {
return err
}
for _, slot := range slots {
k, err := ioutil.ReadFile(filepath.Join(ctb.mockKeyslotsDir, slot.Name()))
if err != nil {
return err
}
if bytes.Equal(k, key) {
return nil
}
}
return errors.New("systemd-cryptsetup failed with: exit status 1")
}))
sdAskPasswordBottom := `
head -1 %[1]s
sed -i -e '1,1d' %[1]s
`
ctb.mockSdAskPassword = snapd_testutil.MockCommand(c, "systemd-ask-password", fmt.Sprintf(sdAskPasswordBottom, ctb.passwordFile))
ctb.AddCleanup(ctb.mockSdAskPassword.Restore)
}
func (ctb *cryptTestBase) addMockKeyslot(c *C, key []byte) {
c.Assert(ioutil.WriteFile(filepath.Join(ctb.mockKeyslotsDir, fmt.Sprintf("%d", ctb.mockKeyslotsCount)), key, 0644), IsNil)
ctb.mockKeyslotsCount++
}
func (ctb *cryptTestBase) newPrimaryKey() []byte {
key := make([]byte, 32)
rand.Read(key)
return key
}
func (ctb *cryptTestBase) newRecoveryKey() RecoveryKey {
var key RecoveryKey
rand.Read(key[:])
return key
}
func (ctb *cryptTestBase) checkRecoveryKeyInKeyring(c *C, prefix, path string, expected RecoveryKey) {
// The following test will fail if the user keyring isn't reachable from the session keyring. If the test have succeeded
// so far, mark the current test as expected to fail.
if !ctb.ProcessPossessesUserKeyringKeys && !c.Failed() {
c.ExpectFailure("Cannot possess user keys because the user keyring isn't reachable from the session keyring")
}
key, err := GetDiskUnlockKeyFromKernel(prefix, path, false)
c.Check(err, IsNil)
c.Check(key, DeepEquals, DiskUnlockKey(expected[:]))
}
func (ctb *cryptTestBase) addTryPassphrases(c *C, passphrases []string) {
for _, passphrase := range passphrases {
f, err := os.OpenFile(ctb.passwordFile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
c.Assert(err, IsNil)
_, err = f.WriteString(passphrase + "\n")
c.Check(err, IsNil)
f.Close()
}
}
type cryptSuite struct {
cryptTestBase
keyDataTestBase
snapModelTestBase
mockLUKS2DeactivateCalls int
cryptsetupInvocationCountDir string
cryptsetupKey string // The file in which the mock cryptsetup dumps the provided key
cryptsetupNewkey string // The file in which the mock cryptsetup dumps the provided new key
mockCryptsetup *snapd_testutil.MockCmd
}
var _ = Suite(&cryptSuite{})
func (s *cryptSuite) SetUpSuite(c *C) {
s.cryptTestBase.SetUpSuite(c)
s.keyDataTestBase.SetUpSuite(c)
}
func (s *cryptSuite) SetUpTest(c *C) {
s.cryptTestBase.SetUpTest(c)
s.keyDataTestBase.SetUpTest(c)
s.mockLUKS2DeactivateCalls = 0
s.AddCleanup(MockLUKS2Deactivate(func(volumeName string) error {
s.mockLUKS2DeactivateCalls++
if volumeName == "bad-volume" {
return errors.New("systemd-cryptsetup failed with: exit status 1")
}
return nil
}))
dir := c.MkDir()
s.cryptsetupKey = filepath.Join(dir, "cryptsetupkey") // File in which the mock cryptsetup records the passed in key
s.cryptsetupNewkey = filepath.Join(dir, "cryptsetupnewkey") // File in which the mock cryptsetup records the passed in new key
s.cryptsetupInvocationCountDir = c.MkDir()
cryptsetupBottom := `
keyfile=""
action=""
while [ $# -gt 0 ]; do
case "$1" in
--key-file)
keyfile=$2
shift 2
;;
--type | --cipher | --key-size | --pbkdf | --pbkdf-force-iterations | --pbkdf-memory | --label | --priority | --key-slot | --iter-time)
shift 2
;;
-*)
shift
;;
*)
if [ -z "$action" ]; then
action=$1
shift
else
break
fi
esac
done
new_keyfile=""
if [ "$action" = "luksAddKey" ]; then
new_keyfile=$2
fi
invocation=$(find %[3]s | wc -l)
mktemp %[3]s/XXXX
dump_key()
{
in=$1
out=$2
if [ -z "$in" ]; then
touch "$out"
elif [ "$in" == "-" ]; then
cat /dev/stdin > "$out"
else
cat "$in" > "$out"
fi
}
dump_key "$keyfile" "%[1]s.$invocation"
dump_key "$new_keyfile" "%[2]s.$invocation"
`
s.mockCryptsetup = snapd_testutil.MockCommand(c, "cryptsetup", fmt.Sprintf(cryptsetupBottom, s.cryptsetupKey, s.cryptsetupNewkey, s.cryptsetupInvocationCountDir))
s.AddCleanup(s.mockCryptsetup.Restore)
}
func (s *cryptSuite) checkKeyDataKeysInKeyring(c *C, prefix, path string, expectedKey DiskUnlockKey, expectedAuxKey AuxiliaryKey) {
// The following test will fail if the user keyring isn't reachable from the session keyring. If the test have succeeded
// so far, mark the current test as expected to fail.
if !s.ProcessPossessesUserKeyringKeys && !c.Failed() {
c.ExpectFailure("Cannot possess user keys because the user keyring isn't reachable from the session keyring")
}
key, err := GetDiskUnlockKeyFromKernel(prefix, path, false)
c.Check(err, IsNil)
c.Check(key, DeepEquals, expectedKey)
auxKey, err := GetAuxiliaryKeyFromKernel(prefix, path, false)
c.Check(err, IsNil)
c.Check(auxKey, DeepEquals, expectedAuxKey)
}
func (s *cryptSuite) newMultipleNamedKeyData(c *C, names ...string) (keyData []*KeyData, keys []DiskUnlockKey, auxKeys []AuxiliaryKey) {
for _, name := range names {
key, auxKey := s.newKeyDataKeys(c, 32, 32)
protected := s.mockProtectKeys(c, key, auxKey, crypto.SHA256)
kd, err := NewKeyData(protected)
c.Assert(err, IsNil)
w := makeMockKeyDataWriter()
c.Check(kd.WriteAtomic(w), IsNil)
r := &mockKeyDataReader{name, w.Reader()}
kd, err = ReadKeyData(r)
c.Assert(err, IsNil)
keyData = append(keyData, kd)
keys = append(keys, key)
auxKeys = append(auxKeys, auxKey)
}
return keyData, keys, auxKeys
}
func (s *cryptSuite) newNamedKeyData(c *C, name string) (*KeyData, DiskUnlockKey, AuxiliaryKey) {
keyData, keys, auxKeys := s.newMultipleNamedKeyData(c, name)
return keyData[0], keys[0], auxKeys[0]
}
type testActivateVolumeWithRecoveryKeyData struct {
recoveryKey RecoveryKey
volumeName string
sourceDevicePath string
tries int
keyringPrefix string
recoveryPassphrases []string
activateTries int
}
func (s *cryptSuite) testActivateVolumeWithRecoveryKey(c *C, data *testActivateVolumeWithRecoveryKeyData) {
s.addMockKeyslot(c, data.recoveryKey[:])
c.Assert(ioutil.WriteFile(s.passwordFile, []byte(strings.Join(data.recoveryPassphrases, "\n")+"\n"), 0644), IsNil)
options := ActivateVolumeOptions{RecoveryKeyTries: data.tries, KeyringPrefix: data.keyringPrefix}
c.Assert(ActivateVolumeWithRecoveryKey(data.volumeName, data.sourceDevicePath, nil, &options), IsNil)
c.Check(len(s.mockSdAskPassword.Calls()), Equals, len(data.recoveryPassphrases))
for _, call := range s.mockSdAskPassword.Calls() {
c.Check(call, DeepEquals, []string{"systemd-ask-password", "--icon", "drive-harddisk", "--id",
filepath.Base(os.Args[0]) + ":" + data.sourceDevicePath, "Please enter the recovery key for disk " + data.sourceDevicePath + ":"})
}
c.Assert(s.mockLUKS2ActivateCalls, HasLen, data.activateTries)
for _, call := range s.mockLUKS2ActivateCalls {
c.Check(call.volumeName, Equals, data.volumeName)
c.Check(call.sourceDevicePath, Equals, data.sourceDevicePath)
}
// This should be done last because it may fail in some circumstances.
s.checkRecoveryKeyInKeyring(c, data.keyringPrefix, data.sourceDevicePath, data.recoveryKey)
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKey1(c *C) {
// Test with a recovery key which is entered with a hyphen between each group of 5 digits.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKey(c, &testActivateVolumeWithRecoveryKeyData{
recoveryKey: recoveryKey,
volumeName: "data",
sourceDevicePath: "/dev/sda1",
tries: 1,
recoveryPassphrases: []string{recoveryKey.String()},
activateTries: 1,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKey2(c *C) {
// Test with a recovery key which is entered without a hyphen between each group of 5 digits.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKey(c, &testActivateVolumeWithRecoveryKeyData{
recoveryKey: recoveryKey,
volumeName: "data",
sourceDevicePath: "/dev/sda1",
tries: 1,
recoveryPassphrases: []string{strings.Replace(recoveryKey.String(), "-", "", -1)},
activateTries: 1,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKey3(c *C) {
// Test that activation succeeds when the correct recovery key is provided on the second attempt.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKey(c, &testActivateVolumeWithRecoveryKeyData{
recoveryKey: recoveryKey,
volumeName: "data",
sourceDevicePath: "/dev/sda1",
tries: 2,
recoveryPassphrases: []string{
"00000-00000-00000-00000-00000-00000-00000-00000",
recoveryKey.String(),
},
activateTries: 2,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKey4(c *C) {
// Test that activation succeeds when the correct recovery key is provided on the second attempt, and the first
// attempt is badly formatted.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKey(c, &testActivateVolumeWithRecoveryKeyData{
recoveryKey: recoveryKey,
volumeName: "data",
sourceDevicePath: "/dev/sda1",
tries: 2,
recoveryPassphrases: []string{
"1234",
recoveryKey.String(),
},
activateTries: 1,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKey5(c *C) {
// Test with a different volume name / device path.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKey(c, &testActivateVolumeWithRecoveryKeyData{
recoveryKey: recoveryKey,
volumeName: "foo",
sourceDevicePath: "/dev/vdb2",
tries: 1,
recoveryPassphrases: []string{recoveryKey.String()},
activateTries: 1,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKey6(c *C) {
// Test with a different keyring prefix
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKey(c, &testActivateVolumeWithRecoveryKeyData{
recoveryKey: recoveryKey,
volumeName: "data",
sourceDevicePath: "/dev/sda1",
tries: 1,
keyringPrefix: "test",
recoveryPassphrases: []string{recoveryKey.String()},
activateTries: 1,
})
}
type testActivateVolumeWithRecoveryKeyUsingKeyReaderData struct {
recoveryKey RecoveryKey
tries int
recoveryKeyFileContents string
recoveryPassphrases []string
activateTries int
}
func (s *cryptSuite) testActivateVolumeWithRecoveryKeyUsingKeyReader(c *C, data *testActivateVolumeWithRecoveryKeyUsingKeyReaderData) {
s.addMockKeyslot(c, data.recoveryKey[:])
c.Assert(ioutil.WriteFile(s.passwordFile, []byte(strings.Join(data.recoveryPassphrases, "\n")+"\n"), 0644), IsNil)
c.Assert(ioutil.WriteFile(filepath.Join(s.dir, "keyfile"), []byte(data.recoveryKeyFileContents), 0644), IsNil)
r, err := os.Open(filepath.Join(s.dir, "keyfile"))
c.Assert(err, IsNil)
defer r.Close()
options := ActivateVolumeOptions{RecoveryKeyTries: data.tries}
c.Assert(ActivateVolumeWithRecoveryKey("data", "/dev/sda1", r, &options), IsNil)
c.Check(len(s.mockSdAskPassword.Calls()), Equals, len(data.recoveryPassphrases))
for _, call := range s.mockSdAskPassword.Calls() {
c.Check(call, DeepEquals, []string{"systemd-ask-password", "--icon", "drive-harddisk", "--id",
filepath.Base(os.Args[0]) + ":/dev/sda1", "Please enter the recovery key for disk /dev/sda1:"})
}
c.Assert(s.mockLUKS2ActivateCalls, HasLen, data.activateTries)
for _, call := range s.mockLUKS2ActivateCalls {
c.Check(call.volumeName, Equals, "data")
c.Check(call.sourceDevicePath, Equals, "/dev/sda1")
}
// This should be done last because it may fail in some circumstances.
s.checkRecoveryKeyInKeyring(c, "", "/dev/sda1", data.recoveryKey)
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyUsingKeyReader1(c *C) {
// Test with the correct recovery key supplied via a io.Reader, with a hyphen separating each group of 5 digits.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKeyUsingKeyReader(c, &testActivateVolumeWithRecoveryKeyUsingKeyReaderData{
recoveryKey: recoveryKey,
tries: 1,
recoveryKeyFileContents: recoveryKey.String() + "\n",
activateTries: 1,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyUsingKeyReader2(c *C) {
// Test with the correct recovery key supplied via a io.Reader, without a hyphen separating each group of 5 digits.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKeyUsingKeyReader(c, &testActivateVolumeWithRecoveryKeyUsingKeyReaderData{
recoveryKey: recoveryKey,
tries: 1,
recoveryKeyFileContents: strings.Replace(recoveryKey.String(), "-", "", -1) + "\n",
activateTries: 1,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyUsingKeyReader3(c *C) {
// Test with the correct recovery key supplied via a io.Reader when the key doesn't end in a newline.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKeyUsingKeyReader(c, &testActivateVolumeWithRecoveryKeyUsingKeyReaderData{
recoveryKey: recoveryKey,
tries: 1,
recoveryKeyFileContents: recoveryKey.String(),
activateTries: 1,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyUsingKeyReader4(c *C) {
// Test that falling back to requesting a recovery key works if the one provided by the io.Reader is incorrect.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKeyUsingKeyReader(c, &testActivateVolumeWithRecoveryKeyUsingKeyReaderData{
recoveryKey: recoveryKey,
tries: 2,
recoveryKeyFileContents: "00000-00000-00000-00000-00000-00000-00000-00000\n",
recoveryPassphrases: []string{recoveryKey.String()},
activateTries: 2,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyUsingKeyReader5(c *C) {
// Test that falling back to requesting a recovery key works if the one provided by the io.Reader is badly formatted.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKeyUsingKeyReader(c, &testActivateVolumeWithRecoveryKeyUsingKeyReaderData{
recoveryKey: recoveryKey,
tries: 2,
recoveryKeyFileContents: "5678\n",
recoveryPassphrases: []string{recoveryKey.String()},
activateTries: 1,
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyUsingKeyReader6(c *C) {
// Test that falling back to requesting a recovery key works if the provided io.Reader is backed by an empty buffer,
// without using up a try.
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithRecoveryKeyUsingKeyReader(c, &testActivateVolumeWithRecoveryKeyUsingKeyReaderData{
recoveryKey: recoveryKey,
tries: 1,
recoveryPassphrases: []string{recoveryKey.String()},
activateTries: 1,
})
}
type testParseRecoveryKeyData struct {
formatted string
expected []byte
}
func (s *cryptSuite) testParseRecoveryKey(c *C, data *testParseRecoveryKeyData) {
k, err := ParseRecoveryKey(data.formatted)
c.Check(err, IsNil)
c.Check(k[:], DeepEquals, data.expected)
}
func (s *cryptSuite) TestParseRecoveryKey1(c *C) {
s.testParseRecoveryKey(c, &testParseRecoveryKeyData{
formatted: "00000-00000-00000-00000-00000-00000-00000-00000",
expected: testutil.DecodeHexString(c, "00000000000000000000000000000000"),
})
}
func (s *cryptSuite) TestParseRecoveryKey2(c *C) {
s.testParseRecoveryKey(c, &testParseRecoveryKeyData{
formatted: "61665-00531-54469-09783-47273-19035-40077-28287",
expected: testutil.DecodeHexString(c, "e1f01302c5d43726a9b85b4a8d9c7f6e"),
})
}
func (s *cryptSuite) TestParseRecoveryKey3(c *C) {
s.testParseRecoveryKey(c, &testParseRecoveryKeyData{
formatted: "6166500531544690978347273190354007728287",
expected: testutil.DecodeHexString(c, "e1f01302c5d43726a9b85b4a8d9c7f6e"),
})
}
type testParseRecoveryKeyErrorHandlingData struct {
formatted string
errChecker Checker
errCheckerArgs []interface{}
}
func (s *cryptSuite) testParseRecoveryKeyErrorHandling(c *C, data *testParseRecoveryKeyErrorHandlingData) {
_, err := ParseRecoveryKey(data.formatted)
c.Check(err, data.errChecker, data.errCheckerArgs...)
}
func (s *cryptSuite) TestParseRecoveryKeyErrorHandling1(c *C) {
s.testParseRecoveryKeyErrorHandling(c, &testParseRecoveryKeyErrorHandlingData{
formatted: "00000-1234",
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"incorrectly formatted: insufficient characters"},
})
}
func (s *cryptSuite) TestParseRecoveryKeyErrorHandling2(c *C) {
s.testParseRecoveryKeyErrorHandling(c, &testParseRecoveryKeyErrorHandlingData{
formatted: "00000-123bc",
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"incorrectly formatted: strconv.ParseUint: parsing \"123bc\": invalid syntax"},
})
}
func (s *cryptSuite) TestParseRecoveryKeyErrorHandling3(c *C) {
s.testParseRecoveryKeyErrorHandling(c, &testParseRecoveryKeyErrorHandlingData{
formatted: "00000-00000-00000-00000-00000-00000-00000-00000-00000",
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"incorrectly formatted: too many characters"},
})
}
func (s *cryptSuite) TestParseRecoveryKeyErrorHandling4(c *C) {
s.testParseRecoveryKeyErrorHandling(c, &testParseRecoveryKeyErrorHandlingData{
formatted: "-00000-00000-00000-00000-00000-00000-00000-00000",
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"incorrectly formatted: strconv.ParseUint: parsing \"-0000\": invalid syntax"},
})
}
func (s *cryptSuite) TestParseRecoveryKeyErrorHandling5(c *C) {
s.testParseRecoveryKeyErrorHandling(c, &testParseRecoveryKeyErrorHandlingData{
formatted: "00000-00000-00000-00000-00000-00000-00000-00000-",
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"incorrectly formatted: too many characters"},
})
}
type testRecoveryKeyStringifyData struct {
key []byte
expected string
}
func (s *cryptSuite) testRecoveryKeyStringify(c *C, data *testRecoveryKeyStringifyData) {
var key RecoveryKey
copy(key[:], data.key)
c.Check(key.String(), Equals, data.expected)
}
func (s *cryptSuite) TestRecoveryKeyStringify1(c *C) {
s.testRecoveryKeyStringify(c, &testRecoveryKeyStringifyData{
expected: "00000-00000-00000-00000-00000-00000-00000-00000",
})
}
func (s *cryptSuite) TestRecoveryKeyStringify2(c *C) {
s.testRecoveryKeyStringify(c, &testRecoveryKeyStringifyData{
key: testutil.DecodeHexString(c, "e1f01302c5d43726a9b85b4a8d9c7f6e"),
expected: "61665-00531-54469-09783-47273-19035-40077-28287",
})
}
type testActivateVolumeWithRecoveryKeyErrorHandlingData struct {
tries int
recoveryPassphrases []string
activateTries int
errChecker Checker
errCheckerArgs []interface{}
}
func (s *cryptSuite) testActivateVolumeWithRecoveryKeyErrorHandling(c *C, data *testActivateVolumeWithRecoveryKeyErrorHandlingData) {
recoveryKey := s.newRecoveryKey()
s.addMockKeyslot(c, recoveryKey[:])
c.Assert(ioutil.WriteFile(s.passwordFile, []byte(strings.Join(data.recoveryPassphrases, "\n")+"\n"), 0644), IsNil)
options := ActivateVolumeOptions{RecoveryKeyTries: data.tries}
c.Check(ActivateVolumeWithRecoveryKey("data", "/dev/sda1", nil, &options), data.errChecker, data.errCheckerArgs...)
c.Check(len(s.mockSdAskPassword.Calls()), Equals, len(data.recoveryPassphrases))
for _, call := range s.mockSdAskPassword.Calls() {
c.Check(call, DeepEquals, []string{"systemd-ask-password", "--icon", "drive-harddisk", "--id",
filepath.Base(os.Args[0]) + ":/dev/sda1", "Please enter the recovery key for disk /dev/sda1:"})
}
c.Assert(s.mockLUKS2ActivateCalls, HasLen, data.activateTries)
for _, call := range s.mockLUKS2ActivateCalls {
c.Check(call.volumeName, Equals, "data")
c.Check(call.sourceDevicePath, Equals, "/dev/sda1")
}
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyErrorHandling1(c *C) {
// Test with an invalid RecoveryKeyTries value.
s.testActivateVolumeWithRecoveryKeyErrorHandling(c, &testActivateVolumeWithRecoveryKeyErrorHandlingData{
tries: -1,
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"invalid RecoveryKeyTries"},
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyErrorHandling2(c *C) {
// Test with Tries set to zero.
s.testActivateVolumeWithRecoveryKeyErrorHandling(c, &testActivateVolumeWithRecoveryKeyErrorHandlingData{
tries: 0,
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"no recovery key tries permitted"},
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyErrorHandling3(c *C) {
// Test with a badly formatted recovery key.
s.testActivateVolumeWithRecoveryKeyErrorHandling(c, &testActivateVolumeWithRecoveryKeyErrorHandlingData{
tries: 1,
recoveryPassphrases: []string{"00000-1234"},
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"cannot decode recovery key: incorrectly formatted: insufficient characters"},
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyErrorHandling4(c *C) {
// Test with a badly formatted recovery key.
s.testActivateVolumeWithRecoveryKeyErrorHandling(c, &testActivateVolumeWithRecoveryKeyErrorHandlingData{
tries: 1,
recoveryPassphrases: []string{"00000-123bc"},
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"cannot decode recovery key: incorrectly formatted: strconv.ParseUint: parsing \"123bc\": invalid syntax"},
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyErrorHandling5(c *C) {
// Test with the wrong recovery key.
s.testActivateVolumeWithRecoveryKeyErrorHandling(c, &testActivateVolumeWithRecoveryKeyErrorHandlingData{
tries: 1,
recoveryPassphrases: []string{"00000-00000-00000-00000-00000-00000-00000-00000"},
activateTries: 1,
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"cannot activate volume: systemd-cryptsetup failed with: exit status 1"},
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyErrorHandling6(c *C) {
// Test that the last error is returned when there are consecutive failures for different reasons.
s.testActivateVolumeWithRecoveryKeyErrorHandling(c, &testActivateVolumeWithRecoveryKeyErrorHandlingData{
tries: 2,
recoveryPassphrases: []string{"00000-00000-00000-00000-00000-00000-00000-00000", "1234"},
activateTries: 1,
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"cannot decode recovery key: incorrectly formatted: insufficient characters"},
})
}
func (s *cryptSuite) TestActivateVolumeWithRecoveryKeyErrorHandling7(c *C) {
// Test with a badly formatted recovery key.
s.testActivateVolumeWithRecoveryKeyErrorHandling(c, &testActivateVolumeWithRecoveryKeyErrorHandlingData{
tries: 1,
recoveryPassphrases: []string{"00000-00000-00000-00000-00000-00000-00000-00000-00000"},
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"cannot decode recovery key: incorrectly formatted: too many characters"},
})
}
type testActivateVolumeWithKeyDataData struct {
authorizedModels []SnapModel
volumeName string
sourceDevicePath string
keyringPrefix string
model SnapModel
authorized bool
}
func (s *cryptSuite) testActivateVolumeWithKeyData(c *C, data *testActivateVolumeWithKeyDataData) {
keyData, key, auxKey := s.newNamedKeyData(c, "")
s.addMockKeyslot(c, key)
c.Check(keyData.SetAuthorizedSnapModels(auxKey, data.authorizedModels...), IsNil)
options := &ActivateVolumeOptions{KeyringPrefix: data.keyringPrefix}
modelChecker, err := ActivateVolumeWithKeyData(data.volumeName, data.sourceDevicePath, keyData, options)
c.Assert(err, IsNil)
authorized, err := modelChecker.IsModelAuthorized(data.model)
c.Check(err, IsNil)
c.Check(authorized, Equals, data.authorized)
c.Check(s.mockSdAskPassword.Calls(), HasLen, 0)
c.Assert(s.mockLUKS2ActivateCalls, HasLen, 1)
c.Check(s.mockLUKS2ActivateCalls[0].volumeName, Equals, data.volumeName)
c.Check(s.mockLUKS2ActivateCalls[0].sourceDevicePath, Equals, data.sourceDevicePath)
// This should be done last because it may fail in some circumstances.
s.checkKeyDataKeysInKeyring(c, data.keyringPrefix, data.sourceDevicePath, key, auxKey)
}
func (s *cryptSuite) TestActivateVolumeWithKeyData1(c *C) {
models := []SnapModel{
s.makeMockCore20ModelAssertion(c, map[string]interface{}{
"authority-id": "fake-brand",
"series": "16",
"brand-id": "fake-brand",
"model": "fake-model",
"grade": "secured",
}, "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij")}
s.testActivateVolumeWithKeyData(c, &testActivateVolumeWithKeyDataData{
authorizedModels: models,
volumeName: "data",
sourceDevicePath: "/dev/sda1",
model: models[0],
authorized: true})
}
func (s *cryptSuite) TestActivateVolumeWithKeyData2(c *C) {
// Test with different volumeName / sourceDevicePath
models := []SnapModel{
s.makeMockCore20ModelAssertion(c, map[string]interface{}{
"authority-id": "fake-brand",
"series": "16",
"brand-id": "fake-brand",
"model": "fake-model",
"grade": "secured",
}, "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij")}
s.testActivateVolumeWithKeyData(c, &testActivateVolumeWithKeyDataData{
authorizedModels: models,
volumeName: "foo",
sourceDevicePath: "/dev/vda2",
model: models[0],
authorized: true})
}
func (s *cryptSuite) TestActivateVolumeWithKeyData3(c *C) {
// Test with different authorized models
models := []SnapModel{
s.makeMockCore20ModelAssertion(c, map[string]interface{}{
"authority-id": "fake-brand",
"series": "16",
"brand-id": "fake-brand",
"model": "fake-model",
"grade": "secured",
}, "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij"),
s.makeMockCore20ModelAssertion(c, map[string]interface{}{
"authority-id": "fake-brand",
"series": "16",
"brand-id": "fake-brand",
"model": "other-model",
"grade": "secured",
}, "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij")}
s.testActivateVolumeWithKeyData(c, &testActivateVolumeWithKeyDataData{
authorizedModels: models,
volumeName: "data",
sourceDevicePath: "/dev/sda1",
model: models[0],
authorized: true})
}
func (s *cryptSuite) TestActivateVolumeWithKeyData4(c *C) {
// Test with unauthorized model
models := []SnapModel{
s.makeMockCore20ModelAssertion(c, map[string]interface{}{
"authority-id": "fake-brand",
"series": "16",
"brand-id": "fake-brand",
"model": "fake-model",
"grade": "secured",
}, "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij")}
s.testActivateVolumeWithKeyData(c, &testActivateVolumeWithKeyDataData{
authorizedModels: models,
volumeName: "data",
sourceDevicePath: "/dev/sda1",
model: s.makeMockCore20ModelAssertion(c, map[string]interface{}{
"authority-id": "fake-brand",
"series": "16",
"brand-id": "fake-brand",
"model": "other-model",
"grade": "secured",
}, "Jv8_JiHiIzJVcO9M55pPdqSDWUvuhfDIBJUS-3VW7F_idjix7Ffn5qMxB21ZQuij"),
authorized: false})
}
type testActivateVolumeWithKeyDataErrorHandlingData struct {
primaryKey DiskUnlockKey
recoveryKey RecoveryKey
passphrases []string
recoveryKeyTries int
keyringPrefix string
keyData *KeyData
errChecker Checker
errCheckerArgs []interface{}
activateTries int
}
func (s *cryptSuite) testActivateVolumeWithKeyDataErrorHandling(c *C, data *testActivateVolumeWithKeyDataErrorHandlingData) {
s.addMockKeyslot(c, data.primaryKey)
s.addMockKeyslot(c, data.recoveryKey[:])
s.addTryPassphrases(c, data.passphrases)
options := &ActivateVolumeOptions{
RecoveryKeyTries: data.recoveryKeyTries,
KeyringPrefix: data.keyringPrefix}
modelChecker, err := ActivateVolumeWithKeyData("data", "/dev/sda1", data.keyData, options)
c.Check(modelChecker, IsNil)
if data.errChecker != nil {
c.Check(err, data.errChecker, data.errCheckerArgs...)
} else {
c.Check(err, Equals, ErrRecoveryKeyUsed)
}
c.Check(s.mockSdAskPassword.Calls(), HasLen, len(data.passphrases))
for _, call := range s.mockSdAskPassword.Calls() {
c.Check(call, DeepEquals, []string{"systemd-ask-password", "--icon", "drive-harddisk", "--id",
filepath.Base(os.Args[0]) + ":/dev/sda1", "Please enter the recovery key for disk /dev/sda1:"})
}
c.Assert(s.mockLUKS2ActivateCalls, HasLen, data.activateTries)
for _, call := range s.mockLUKS2ActivateCalls {
c.Check(call.volumeName, Equals, "data")
c.Check(call.sourceDevicePath, Equals, "/dev/sda1")
}
if data.errChecker != nil {
return
}
// This should be done last because it may fail in some circumstances.
s.checkRecoveryKeyInKeyring(c, data.keyringPrefix, "/dev/sda1", data.recoveryKey)
}
func (s *cryptSuite) TestActivateVolumeWithKeyDataErrorHandling1(c *C) {
// Test with an invalid value for RecoveryKeyTries.
keyData, _, _ := s.newNamedKeyData(c, "")
s.testActivateVolumeWithKeyDataErrorHandling(c, &testActivateVolumeWithKeyDataErrorHandlingData{
recoveryKeyTries: -1,
keyData: keyData,
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"invalid RecoveryKeyTries"}})
}
func (s *cryptSuite) TestActivateVolumeWithKeyDataErrorHandling2(c *C) {
// Test that recovery fallback works with the platform is unavailable
keyData, key, _ := s.newNamedKeyData(c, "")
recoveryKey := s.newRecoveryKey()
s.handler.state = mockPlatformDeviceStateUnavailable
s.testActivateVolumeWithKeyDataErrorHandling(c, &testActivateVolumeWithKeyDataErrorHandlingData{
primaryKey: key,
recoveryKey: recoveryKey,
passphrases: []string{recoveryKey.String()},
recoveryKeyTries: 1,
keyData: keyData,
activateTries: 1})
}
func (s *cryptSuite) TestActivateVolumeWithKeyDataErrorHandling3(c *C) {
// Test that recovery fallback works when the platform device isn't properly initialized
keyData, key, _ := s.newNamedKeyData(c, "")
recoveryKey := s.newRecoveryKey()
s.handler.state = mockPlatformDeviceStateUninitialized
s.testActivateVolumeWithKeyDataErrorHandling(c, &testActivateVolumeWithKeyDataErrorHandlingData{
primaryKey: key,
recoveryKey: recoveryKey,
passphrases: []string{recoveryKey.String()},
recoveryKeyTries: 1,
keyData: keyData,
activateTries: 1})
}
func (s *cryptSuite) TestActivateVolumeWithKeyDataErrorHandling4(c *C) {
// Test that recovery fallback works when the recovered key is incorrect
keyData, _, _ := s.newNamedKeyData(c, "")
recoveryKey := s.newRecoveryKey()
s.testActivateVolumeWithKeyDataErrorHandling(c, &testActivateVolumeWithKeyDataErrorHandlingData{
recoveryKey: recoveryKey,
passphrases: []string{recoveryKey.String()},
recoveryKeyTries: 1,
keyData: keyData,
activateTries: 2})
}
func (s *cryptSuite) TestActivateVolumeWithKeyDataErrorHandling5(c *C) {
// Test that activation fails if RecoveryKeyTries is zero.
keyData, key, _ := s.newNamedKeyData(c, "foo")
recoveryKey := s.newRecoveryKey()
s.handler.state = mockPlatformDeviceStateUnavailable
s.testActivateVolumeWithKeyDataErrorHandling(c, &testActivateVolumeWithKeyDataErrorHandlingData{
primaryKey: key,
recoveryKey: recoveryKey,
recoveryKeyTries: 0,
keyData: keyData,
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"cannot activate with platform protected keys:\n" +
"- foo: cannot recover key: the platform's secure device is unavailable: the " +
"platform device is unavailable\n" +
"and activation with recovery key failed: no recovery key tries permitted"},
activateTries: 0})
}
func (s *cryptSuite) TestActivateVolumeWithKeyDataErrorHandling6(c *C) {
// Test that activation fails if the supplied recovery key is incorrect
keyData, key, _ := s.newNamedKeyData(c, "bar")
recoveryKey := s.newRecoveryKey()
s.handler.state = mockPlatformDeviceStateUnavailable
s.testActivateVolumeWithKeyDataErrorHandling(c, &testActivateVolumeWithKeyDataErrorHandlingData{
primaryKey: key,
recoveryKey: recoveryKey,
passphrases: []string{"00000-00000-00000-00000-00000-00000-00000-00000"},
recoveryKeyTries: 1,
keyData: keyData,
errChecker: ErrorMatches,
errCheckerArgs: []interface{}{"cannot activate with platform protected keys:\n" +
"- bar: cannot recover key: the platform's secure device is unavailable: the " +
"platform device is unavailable\n" +
"and activation with recovery key failed: cannot activate volume: " +
"systemd-cryptsetup failed with: exit status 1"},
activateTries: 1})
}
func (s *cryptSuite) TestActivateVolumeWithKeyDataErrorHandling7(c *C) {
// Test that recovery fallback works if the correct key is eventually supplied
keyData, key, _ := s.newNamedKeyData(c, "")
recoveryKey := s.newRecoveryKey()
s.handler.state = mockPlatformDeviceStateUnavailable