forked from canonical/secboot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeydata.go
510 lines (421 loc) · 14.5 KB
/
keydata.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
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* 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
import (
"bytes"
"crypto"
"encoding/binary"
"encoding/json"
"errors"
"fmt"
"io"
"github.com/canonical/go-sp800.90a-drbg"
"golang.org/x/xerrors"
)
// ErrNoPlatformHandlerRegistered is returned from any of the KeyData.RecoverKeys*
// functions if the keys cannot be successfully recovered because there is no
// appropriate platform handler registered.
var ErrNoPlatformHandlerRegistered = errors.New("cannot recover key because there isn't a platform handler registered for it")
// InvalidKeyDataError is returned from any of the KeyData.RecoverKeys* functions
// if the keys cannot be successfully recovered because the key data is invalid in
// some way.
type InvalidKeyDataError struct {
err error
}
func (e *InvalidKeyDataError) Error() string {
return fmt.Sprintf("invalid key data: %v", e.err)
}
func (e *InvalidKeyDataError) Unwrap() error {
return e.err
}
// PlatformUninitializedError is returned from any of the KeyData.RecoverKeys* functions
// if the keys cannot be successfully recovered because the platform's secure device has
// not been initialized properly.
type PlatformUninitializedError struct {
err error
}
func (e *PlatformUninitializedError) Error() string {
return fmt.Sprintf("the platform's secure device is not properly initialized: %v", e.err)
}
func (e *PlatformUninitializedError) Unwrap() error {
return e.err
}
// PlatformDeviceUnavailableError is returned from any of the KeyData.RecoverKeys*
// functions if the keys cannot be recovered because the platform's secure device is
// currently unavailable.
type PlatformDeviceUnavailableError struct {
err error
}
func (e *PlatformDeviceUnavailableError) Error() string {
return fmt.Sprintf("the platform's secure device is unavailable: %v", e.err)
}
func (e *PlatformDeviceUnavailableError) Unwrap() error {
return e.err
}
// DiskUnlockKey is the key used to unlock a LUKS volume.
type DiskUnlockKey []byte
// AuxiliaryKey is an additional key used to modify properties of a KeyData
// object without having to create a new object.
type AuxiliaryKey []byte
// KeyPayload is the payload that should be encrypted by a platform's secure device.
type KeyPayload []byte
// Unmarshal obtains the keys from this payload.
func (c KeyPayload) Unmarshal() (key DiskUnlockKey, auxKey AuxiliaryKey, err error) {
r := bytes.NewReader(c)
var sz uint16
if err := binary.Read(r, binary.BigEndian, &sz); err != nil {
return nil, nil, err
}
if sz > 0 {
key = make(DiskUnlockKey, sz)
if _, err := r.Read(key); err != nil {
return nil, nil, err
}
}
if err := binary.Read(r, binary.BigEndian, &sz); err != nil {
return nil, nil, err
}
if sz > 0 {
auxKey = make(AuxiliaryKey, sz)
if _, err := r.Read(auxKey); err != nil {
return nil, nil, err
}
}
if r.Len() > 0 {
return nil, nil, fmt.Errorf("%v excess byte(s)", r.Len())
}
return
}
// AuthMode corresponds to a set of authentication mechanisms.
type AuthMode uint32
const (
AuthModeNone AuthMode = 0
AuthModePassphrase AuthMode = 1 << iota
)
// KeyCreationData is the data required to create a new KeyData object.
// It should be produced by a platform implementation.
type KeyCreationData struct {
PlatformKeyData
PlatformName string // Name of the platform that produced this data
// AuxiliaryKey is a key used to authorize changes to the key data.
// It must match the key protected inside PlatformKeyData.EncryptedPayload.
AuxiliaryKey AuxiliaryKey
// SnapModelAuthHash is the digest algorithm used for HMACs of Snap
// device models, and also the digest algorithm used to produce the
// key digest.
SnapModelAuthHash crypto.Hash
}
// KeyID is the unique ID for a KeyData object. It is used to facilitate the
// sharing of state between the early boot environment and OS runtime.
type KeyID []byte
// KeyDataWriter is an interface used by KeyData to write the data to
// persistent storage in an atomic way.
type KeyDataWriter interface {
io.Writer
Commit() error
}
// KeyDataReader is an interface used to read and decode a KeyData
// from persistent storage.
type KeyDataReader interface {
io.Reader
ReadableName() string
}
type hashAlg struct {
crypto.Hash
}
func (a hashAlg) MarshalJSON() ([]byte, error) {
var s string
switch a.Hash {
case crypto.SHA1:
s = "sha1"
case crypto.SHA224:
s = "sha224"
case crypto.SHA256:
s = "sha256"
case crypto.SHA384:
s = "sha384"
case crypto.SHA512:
s = "sha512"
default:
return nil, fmt.Errorf("unknown has algorithm: %v", a.Hash)
}
return json.Marshal(s)
}
func (a *hashAlg) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
switch s {
case "sha1":
a.Hash = crypto.SHA1
case "sha224":
a.Hash = crypto.SHA224
case "sha256":
a.Hash = crypto.SHA256
case "sha384":
a.Hash = crypto.SHA384
case "sha512":
a.Hash = crypto.SHA512
default:
a.Hash = crypto.Hash(0)
}
return nil
}
type snapModelHMAC []byte
type snapModelHMACList []snapModelHMAC
func (l snapModelHMACList) contains(h snapModelHMAC) bool {
for _, v := range l {
if bytes.Equal(v, h) {
return true
}
}
return false
}
type authorizedSnapModels struct {
Alg hashAlg `json:"alg"`
KeyDigest []byte `json:"key_digest"`
Hmacs snapModelHMACList `json:"hmacs"`
}
type kdfData struct {
Type string `json:"type"`
Salt []byte `json:"salt"`
Time int `json:"time"`
Memory int `json:"memory"`
CPUs int `json:"cpus"`
}
type passphraseData struct {
KDF kdfData `json:"kdf"`
EncryptedPayload []byte `json:"encrypted_payload"`
}
type keyData struct {
PlatformName string `json:"platform_name"`
PlatformHandle json.RawMessage `json:"platform_handle"`
EncryptedPayload []byte `json:"encrypted_payload,omitempty"`
PassphraseProtectedPayload *passphraseData `json:"passphrase_protected_payload,omitempty"`
AuthorizedSnapModels authorizedSnapModels `json:"authorized_snap_models"`
}
func processPlatformKeyRecoveryError(err error) error {
var pe *PlatformKeyRecoveryError
if xerrors.As(err, &pe) {
switch pe.Type {
case PlatformKeyRecoveryErrorInvalidData:
return &InvalidKeyDataError{pe.Err}
case PlatformKeyRecoveryErrorUninitialized:
return &PlatformUninitializedError{pe.Err}
case PlatformKeyRecoveryErrorUnavailable:
return &PlatformDeviceUnavailableError{pe.Err}
}
}
return xerrors.Errorf("cannot recover keys because of an unexpected error: %w", err)
}
// KeyData represents a disk unlock key and auxiliary key protected by a platform's
// secure device.
type KeyData struct {
readableName string
data keyData
}
func (d *KeyData) snapModelAuthKey(auxKey AuxiliaryKey) ([]byte, error) {
rng, err := drbg.NewCTRWithExternalEntropy(32, auxKey, nil, []byte("SNAP-MODEL-HMAC"), nil)
if err != nil {
return nil, xerrors.Errorf("cannot instantiate DRBG: %w", err)
}
alg := d.data.AuthorizedSnapModels.Alg
if alg.Hash == crypto.Hash(0) {
return nil, errors.New("invalid digest algorithm")
}
hmacKey := make([]byte, alg.Size())
if _, err := rng.Read(hmacKey); err != nil {
return nil, xerrors.Errorf("cannot derive key: %w", err)
}
return hmacKey, nil
}
// ReadableName returns a human-readable name for this key data, useful for
// including in errors.
func (d *KeyData) ReadableName() string {
return d.readableName
}
// UniqueID returns the unique ID for this key data.
func (d *KeyData) UniqueID() (KeyID, error) {
h := crypto.SHA256.New()
enc := json.NewEncoder(h)
if err := enc.Encode(&d.data); err != nil {
return nil, xerrors.Errorf("cannot compute ID: %w", err)
}
return KeyID(h.Sum(nil)), nil
}
// AuthMode indicates the authentication mechanisms enabled for this key data.
func (d *KeyData) AuthMode() (out AuthMode) {
if len(d.data.EncryptedPayload) > 0 {
return AuthModeNone
}
if d.data.PassphraseProtectedPayload != nil {
out |= AuthModePassphrase
}
return out
}
// RecoverKeys recovers the disk unlock key and auxiliary key associated with this
// key data from the platform's secure device, for key data that doesn't have any
// additional authentication modes enabled (AuthMode returns AuthModeNone).
//
// If AuthMode returns anything other than AuthModeNone, then this will return an error.
//
// If no platform handler has been registered for this key data, an
// ErrNoPlatformHandlerRegistered error will be returned.
//
// If the keys cannot be recovered because the key data is invalid, a *InvalidKeyDataError
// error will be returned.
//
// If the keys cannot be recovered because the platform's secure device is not
// properly initialized, a *PlatformUninitializedError error will be returned.
//
// If the keys cannot be recovered because the platform's secure device is not
// available, a *PlatformDeviceUnavailableError error will be returned.
func (d *KeyData) RecoverKeys() (DiskUnlockKey, AuxiliaryKey, error) {
if d.AuthMode() != AuthModeNone {
return nil, nil, errors.New("cannot recover key without authorization")
}
handler := handlers[d.data.PlatformName]
if handler == nil {
return nil, nil, ErrNoPlatformHandlerRegistered
}
c, err := handler.RecoverKeys(&PlatformKeyData{
Handle: d.data.PlatformHandle,
EncryptedPayload: d.data.EncryptedPayload})
if err != nil {
return nil, nil, processPlatformKeyRecoveryError(err)
}
key, auxKey, err := c.Unmarshal()
if err != nil {
return nil, nil, &InvalidKeyDataError{xerrors.Errorf("cannot unmarshal cleartext key payload: %w", err)}
}
return key, auxKey, nil
}
//func (d *KeyData) RecoverKeysWithPassphrase(passphrase string) (DiskUnlockKey, AuxiliaryKey, error) {
//}
// IsSnapModelAuthorized indicates whether the supplied Snap device model is trusted to
// access the data on the encrypted volume protected by this key data.
//
// The supplied auxKey is obtained using one of the RecoverKeys* functions.
func (d *KeyData) IsSnapModelAuthorized(auxKey AuxiliaryKey, model SnapModel) (bool, error) {
hmacKey, err := d.snapModelAuthKey(auxKey)
if err != nil {
return false, xerrors.Errorf("cannot obtain auth key: %w", err)
}
alg := d.data.AuthorizedSnapModels.Alg
if alg.Hash == crypto.Hash(0) {
return false, errors.New("invalid digest algorithm")
}
h, err := computeSnapModelHMAC(alg.Hash, hmacKey, model)
if err != nil {
return false, xerrors.Errorf("cannot compute HMAC of model: %w", err)
}
return d.data.AuthorizedSnapModels.Hmacs.contains(h), nil
}
// SetAuthorizedSnapModels marks the supplied Snap device models as trusted to access
// the data on the encrypted volume protected by this key data. This function replaces all
// previously trusted models.
//
// This makes changes to the key data, which will need to persisted afterwards using
// WriteAtomic.
//
// The supplied auxKey is obtained using one of the RecoverKeys* functions. If the
// supplied auxKey is incorrect, then an error will be returned.
func (d *KeyData) SetAuthorizedSnapModels(auxKey AuxiliaryKey, models ...SnapModel) error {
hmacKey, err := d.snapModelAuthKey(auxKey)
if err != nil {
return xerrors.Errorf("cannot obtain auth key: %w", err)
}
alg := d.data.AuthorizedSnapModels.Alg
if alg.Hash == crypto.Hash(0) {
return errors.New("invalid digest algorithm")
}
h := alg.New()
h.Write(hmacKey)
if !bytes.Equal(h.Sum(nil), d.data.AuthorizedSnapModels.KeyDigest) {
return errors.New("incorrect key supplied")
}
var modelHMACs snapModelHMACList
for _, model := range models {
h, err := computeSnapModelHMAC(alg.Hash, hmacKey, model)
if err != nil {
return xerrors.Errorf("cannot compute HMAC of model: %w", err)
}
modelHMACs = append(modelHMACs, h)
}
d.data.AuthorizedSnapModels.Hmacs = modelHMACs
return nil
}
//func (d *KeyData) ChangePasshprase(old, new string) error {
//}
// WriteAtomic saves this key data to the supplied KeyDataWriter.
func (d *KeyData) WriteAtomic(w KeyDataWriter) error {
enc := json.NewEncoder(w)
if err := enc.Encode(d.data); err != nil {
return xerrors.Errorf("cannot encode keydata: %w", err)
}
if err := w.Commit(); err != nil {
return xerrors.Errorf("cannot commit keydata: %w", err)
}
return nil
}
// ReadKeyData reads the key data from the supplied KeyDataReader, returning a
// new KeyData object.
func ReadKeyData(r KeyDataReader) (*KeyData, error) {
d := &KeyData{readableName: r.ReadableName()}
dec := json.NewDecoder(r)
if err := dec.Decode(&d.data); err != nil {
return nil, xerrors.Errorf("cannot decode key data: %w", err)
}
return d, nil
}
// NewKeyData creates a new KeyData object using the supplied KeyCreationData, which
// should be created by a platform-specific package, containing a payload encrypted by
// the platform's secure device and the associated handle required for subsequent
// recovery of the keys.
func NewKeyData(creationData *KeyCreationData) (*KeyData, error) {
if !json.Valid(creationData.Handle) {
return nil, errors.New("handle is not valid JSON")
}
rng, err := drbg.NewCTRWithExternalEntropy(32, creationData.AuxiliaryKey, nil, []byte("SNAP-MODEL-HMAC"), nil)
if err != nil {
return nil, xerrors.Errorf("cannot instantiate DRBG: %w", err)
}
h := creationData.SnapModelAuthHash.New()
if _, err := io.CopyN(h, rng, int64(creationData.SnapModelAuthHash.Size())); err != nil {
return nil, xerrors.Errorf("cannot create hash of snap model auth key: %w", err)
}
return &KeyData{
data: keyData{
PlatformName: creationData.PlatformName,
PlatformHandle: json.RawMessage(creationData.Handle),
EncryptedPayload: creationData.EncryptedPayload,
AuthorizedSnapModels: authorizedSnapModels{
Alg: hashAlg{creationData.SnapModelAuthHash},
KeyDigest: h.Sum(nil)}}}, nil
}
// MarshalKeys serializes the supplied disk unlock key and auxiliary key in
// to a format that is ready to be encrypted by a platform's secure device.
func MarshalKeys(key DiskUnlockKey, auxKey AuxiliaryKey) KeyPayload {
w := new(bytes.Buffer)
binary.Write(w, binary.BigEndian, uint16(len(key)))
w.Write(key)
binary.Write(w, binary.BigEndian, uint16(len(auxKey)))
w.Write(auxKey)
return w.Bytes()
}