/
boxer.go
530 lines (465 loc) · 16.6 KB
/
boxer.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
package bundle
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/msgpack"
"github.com/keybase/client/go/protocol/keybase1"
"github.com/keybase/client/go/protocol/stellar1"
"golang.org/x/crypto/nacl/secretbox"
)
// BoxedEncoded is the result of boxing and encoding a Bundle object.
type BoxedEncoded struct {
EncParent stellar1.EncryptedBundle
EncParentB64 string // base64 msgpacked Enc
VisParentB64 string
FormatVersionParent stellar1.BundleVersion
AcctBundles map[stellar1.AccountID]AcctBoxedEncoded
}
func newBoxedEncoded() *BoxedEncoded {
return &BoxedEncoded{
FormatVersionParent: stellar1.BundleVersion_V2,
AcctBundles: make(map[stellar1.AccountID]AcctBoxedEncoded),
}
}
func newVisibleParent(a *stellar1.Bundle, accountsVisible []stellar1.BundleVisibleEntryV2) stellar1.BundleVisibleV2 {
return stellar1.BundleVisibleV2{
Revision: a.Revision,
Prev: a.Prev,
Accounts: accountsVisible,
}
}
func (b BoxedEncoded) toBundleEncodedB64() BundleEncoded {
benc := BundleEncoded{
EncParent: b.EncParentB64,
VisParent: b.VisParentB64,
AcctBundles: make(map[stellar1.AccountID]string),
}
for acctID, acctBundle := range b.AcctBundles {
benc.AcctBundles[acctID] = acctBundle.EncB64
}
return benc
}
// BundleEncoded contains all the encoded fields for communicating
// with the api server to post and get account bundles.
type BundleEncoded struct {
EncParent string `json:"encrypted_parent"` // base64 msgpacked Enc
VisParent string `json:"visible_parent"`
FormatVersionParent stellar1.BundleVersion `json:"version_parent"`
AcctBundles map[stellar1.AccountID]string `json:"account_bundles"`
}
// BoxAndEncode encrypts and encodes a Bundle object.
func BoxAndEncode(a *stellar1.Bundle, pukGen keybase1.PerUserKeyGeneration, puk libkb.PerUserKeySeed) (*BoxedEncoded, error) {
err := a.CheckInvariants()
if err != nil {
return nil, err
}
accountsVisible, accountsSecret := visibilitySplit(a)
// visible portion parent
visibleV2 := newVisibleParent(a, accountsVisible)
boxed := newBoxedEncoded()
// encrypted account bundles
for i, acctEntry := range visibleV2.Accounts {
secret, ok := a.AccountBundles[acctEntry.AccountID]
if !ok {
continue
}
ab, err := accountBoxAndEncode(acctEntry.AccountID, secret, pukGen, puk)
if err != nil {
return nil, err
}
boxed.AcctBundles[acctEntry.AccountID] = *ab
visibleV2.Accounts[i].EncAcctBundleHash = ab.EncHash
}
// have to do this after to get hashes of encrypted account bundles
visiblePack, err := msgpack.Encode(visibleV2)
if err != nil {
return nil, err
}
visibleHash := sha256.Sum256(visiblePack)
boxed.VisParentB64 = base64.StdEncoding.EncodeToString(visiblePack)
// secret portion parent
versionedSecret := stellar1.NewBundleSecretVersionedWithV2(stellar1.BundleSecretV2{
VisibleHash: visibleHash[:],
Accounts: accountsSecret,
})
boxed.EncParent, boxed.EncParentB64, err = parentBoxAndEncode(versionedSecret, pukGen, puk)
if err != nil {
return nil, err
}
return boxed, nil
}
func visibilitySplit(a *stellar1.Bundle) ([]stellar1.BundleVisibleEntryV2, []stellar1.BundleSecretEntryV2) {
vis := make([]stellar1.BundleVisibleEntryV2, len(a.Accounts))
sec := make([]stellar1.BundleSecretEntryV2, len(a.Accounts))
for i, acct := range a.Accounts {
vis[i] = stellar1.BundleVisibleEntryV2{
AccountID: acct.AccountID,
Mode: acct.Mode,
IsPrimary: acct.IsPrimary,
AcctBundleRevision: acct.AcctBundleRevision,
EncAcctBundleHash: acct.EncAcctBundleHash,
}
sec[i] = stellar1.BundleSecretEntryV2{
AccountID: acct.AccountID,
Name: acct.Name,
}
}
return vis, sec
}
func parentBoxAndEncode(bundle stellar1.BundleSecretVersioned, pukGen keybase1.PerUserKeyGeneration, puk libkb.PerUserKeySeed) (stellar1.EncryptedBundle, string, error) {
// Msgpack (inner)
clearpack, err := msgpack.Encode(bundle)
if err != nil {
return stellar1.EncryptedBundle{}, "", err
}
// Derive key
symmetricKey, err := puk.DeriveSymmetricKey(libkb.DeriveReasonPUKStellarBundle)
if err != nil {
return stellar1.EncryptedBundle{}, "", err
}
// Secretbox
var nonce [libkb.NaclDHNonceSize]byte
nonce, err = libkb.RandomNaclDHNonce()
if err != nil {
return stellar1.EncryptedBundle{}, "", err
}
secbox := secretbox.Seal(nil, clearpack, &nonce, (*[libkb.NaclSecretBoxKeySize]byte)(&symmetricKey))
// Annotate
res := stellar1.EncryptedBundle{
V: 2,
E: secbox,
N: nonce,
Gen: pukGen,
}
// Msgpack (outer) + b64
cipherpack, err := msgpack.Encode(res)
if err != nil {
return stellar1.EncryptedBundle{}, "", err
}
resB64 := base64.StdEncoding.EncodeToString(cipherpack)
return res, resB64, nil
}
// AcctBoxedEncoded is the result of boxing and encoding the per-account secrets.
type AcctBoxedEncoded struct {
Enc stellar1.EncryptedAccountBundle
EncHash stellar1.Hash
EncB64 string // base64 msgpacked Enc
FormatVersion stellar1.AccountBundleVersion
}
func accountBoxAndEncode(accountID stellar1.AccountID, accountBundle stellar1.AccountBundle, pukGen keybase1.PerUserKeyGeneration, puk libkb.PerUserKeySeed) (*AcctBoxedEncoded, error) {
versionedSecret := stellar1.NewAccountBundleSecretVersionedWithV1(stellar1.AccountBundleSecretV1{
AccountID: accountID,
Signers: accountBundle.Signers,
})
encBundle, b64, err := accountEncrypt(versionedSecret, pukGen, puk)
if err != nil {
return nil, err
}
encPack, err := msgpack.Encode(encBundle)
if err != nil {
return nil, err
}
encHash := sha256.Sum256(encPack)
res := AcctBoxedEncoded{Enc: encBundle, EncHash: encHash[:], EncB64: b64, FormatVersion: 1}
return &res, nil
}
// PukFinder helps this package find puks.
type PukFinder interface {
SeedByGeneration(m libkb.MetaContext, generation keybase1.PerUserKeyGeneration) (libkb.PerUserKeySeed, error)
}
type AccountPukGens map[stellar1.AccountID](keybase1.PerUserKeyGeneration)
// DecodeAndUnbox decodes the encrypted and visible encoded bundles and unboxes
// the encrypted bundle using PukFinder to find the correct puk. It combines
// the results into a stellar1.Bundle and also returns additional information
// about the bundle: its version, pukGen, and the pukGens of each of the
// decrypted account secrets.
func DecodeAndUnbox(m libkb.MetaContext, finder PukFinder, encodedBundle BundleEncoded) (*stellar1.Bundle, stellar1.BundleVersion, keybase1.PerUserKeyGeneration, AccountPukGens, error) {
accountPukGens := make(AccountPukGens)
encBundle, hash, err := decodeParent(encodedBundle.EncParent)
if err != nil {
return nil, 0, 0, accountPukGens, err
}
puk, err := finder.SeedByGeneration(m, encBundle.Gen)
if err != nil {
return nil, 0, 0, accountPukGens, err
}
parent, parentVersion, err := unboxParent(encBundle, hash, encodedBundle.VisParent, puk)
if err != nil {
return nil, 0, 0, accountPukGens, err
}
parent.AccountBundles = make(map[stellar1.AccountID]stellar1.AccountBundle)
for _, parentEntry := range parent.Accounts {
if acctEncB64, ok := encodedBundle.AcctBundles[parentEntry.AccountID]; ok {
acctBundle, acctGen, err := decodeAndUnboxAcctBundle(m, finder, acctEncB64, parentEntry)
accountPukGens[parentEntry.AccountID] = acctGen
if err != nil {
return nil, 0, 0, accountPukGens, err
}
if acctBundle == nil {
return nil, 0, 0, accountPukGens, fmt.Errorf("error unboxing account bundle: missing for account %s", parentEntry.AccountID)
}
parent.AccountBundles[parentEntry.AccountID] = *acctBundle
}
}
if err = parent.CheckInvariants(); err != nil {
return nil, 0, 0, accountPukGens, err
}
return parent, parentVersion, encBundle.Gen, accountPukGens, nil
}
func decodeAndUnboxAcctBundle(m libkb.MetaContext, finder PukFinder, encB64 string, parentEntry stellar1.BundleEntry) (*stellar1.AccountBundle, keybase1.PerUserKeyGeneration, error) {
eab, hash, err := decode(encB64)
if err != nil {
return nil, 0, err
}
if !libkb.SecureByteArrayEq(hash, parentEntry.EncAcctBundleHash) {
return nil, 0, errors.New("account bundle and parent entry hash mismatch")
}
puk, err := finder.SeedByGeneration(m, eab.Gen)
if err != nil {
return nil, 0, err
}
ab, _, err := unbox(eab, hash, puk)
if err != nil {
return nil, 0, err
}
if ab.AccountID != parentEntry.AccountID {
return nil, 0, errors.New("account bundle and parent entry account ID mismatch")
}
return ab, eab.Gen, nil
}
// accountEncrypt encrypts the stellar account key bundle for the PUK.
// Returns the encrypted struct and a base64 encoding for posting to the server.
// Does not check invariants.
func accountEncrypt(bundle stellar1.AccountBundleSecretVersioned, pukGen keybase1.PerUserKeyGeneration, puk libkb.PerUserKeySeed) (res stellar1.EncryptedAccountBundle, resB64 string, err error) {
// Msgpack (inner)
clearpack, err := msgpack.Encode(bundle)
if err != nil {
return res, resB64, err
}
// Derive key
symmetricKey, err := puk.DeriveSymmetricKey(libkb.DeriveReasonPUKStellarAcctBundle)
if err != nil {
return res, resB64, err
}
// Secretbox
var nonce [libkb.NaclDHNonceSize]byte
nonce, err = libkb.RandomNaclDHNonce()
if err != nil {
return res, resB64, err
}
secbox := secretbox.Seal(nil, clearpack, &nonce, (*[libkb.NaclSecretBoxKeySize]byte)(&symmetricKey))
// Annotate
res = stellar1.EncryptedAccountBundle{
V: 1,
E: secbox,
N: nonce,
Gen: pukGen,
}
// Msgpack (outer) + b64
cipherpack, err := msgpack.Encode(res)
if err != nil {
return res, resB64, err
}
resB64 = base64.StdEncoding.EncodeToString(cipherpack)
return res, resB64, nil
}
// decodeParent decodes a base64-encoded encrypted parent bundle.
func decodeParent(encryptedB64 string) (stellar1.EncryptedBundle, stellar1.Hash, error) {
cipherpack, err := base64.StdEncoding.DecodeString(encryptedB64)
if err != nil {
return stellar1.EncryptedBundle{}, stellar1.Hash{}, err
}
encHash := sha256.Sum256(cipherpack)
var enc stellar1.EncryptedBundle
if err = msgpack.Decode(&enc, cipherpack); err != nil {
return stellar1.EncryptedBundle{}, stellar1.Hash{}, err
}
return enc, encHash[:], nil
}
// unboxParent unboxes an encrypted parent bundle and decodes the visual portion of the bundle.
// It validates the visible hash in the secret portion.
func unboxParent(encBundle stellar1.EncryptedBundle, hash stellar1.Hash, visB64 string, puk libkb.PerUserKeySeed) (*stellar1.Bundle, stellar1.BundleVersion, error) {
versioned, err := decryptParent(encBundle, puk)
if err != nil {
return nil, 0, err
}
version, err := versioned.Version()
if err != nil {
return nil, 0, err
}
var bundleOut stellar1.Bundle
switch version {
case stellar1.BundleVersion_V2:
bundleOut, err = unboxParentV2(versioned, visB64)
if err != nil {
return nil, 0, err
}
default:
return nil, 0, fmt.Errorf("unsupported parent bundle version: %d", version)
}
bundleOut.OwnHash = hash
if len(bundleOut.OwnHash) == 0 {
return nil, 0, errors.New("stellar account bundle missing own hash")
}
return &bundleOut, version, nil
}
func unboxParentV2(versioned stellar1.BundleSecretVersioned, visB64 string) (stellar1.Bundle, error) {
var empty stellar1.Bundle
visiblePack, err := base64.StdEncoding.DecodeString(visB64)
if err != nil {
return empty, err
}
visibleHash := sha256.Sum256(visiblePack)
secretV2 := versioned.V2()
if !hmac.Equal(visibleHash[:], secretV2.VisibleHash) {
return empty, errors.New("corrupted bundle: visible hash mismatch")
}
var visibleV2 stellar1.BundleVisibleV2
err = msgpack.Decode(&visibleV2, visiblePack)
if err != nil {
return empty, err
}
return merge(secretV2, visibleV2)
}
// decryptParent decrypts an encrypted parent bundle with the provided puk.
func decryptParent(encBundle stellar1.EncryptedBundle, puk libkb.PerUserKeySeed) (res stellar1.BundleSecretVersioned, err error) {
switch encBundle.V {
case 1:
// CORE-8135
return res, fmt.Errorf("stellar secret bundle encryption version 1 has been retired")
case 2:
default:
return res, fmt.Errorf("unsupported stellar secret bundle encryption version: %v", encBundle.V)
}
// Derive key
reason := libkb.DeriveReasonPUKStellarBundle
symmetricKey, err := puk.DeriveSymmetricKey(reason)
if err != nil {
return res, err
}
// Secretbox
clearpack, ok := secretbox.Open(nil, encBundle.E,
(*[libkb.NaclDHNonceSize]byte)(&encBundle.N),
(*[libkb.NaclSecretBoxKeySize]byte)(&symmetricKey))
if !ok {
return res, errors.New("stellar bundle secret box open failed")
}
// Msgpack (inner)
err = msgpack.Decode(&res, clearpack)
return res, err
}
// decode decodes a base64-encoded encrypted account bundle.
func decode(encryptedB64 string) (stellar1.EncryptedAccountBundle, stellar1.Hash, error) {
cipherpack, err := base64.StdEncoding.DecodeString(encryptedB64)
if err != nil {
return stellar1.EncryptedAccountBundle{}, stellar1.Hash{}, err
}
encHash := sha256.Sum256(cipherpack)
var enc stellar1.EncryptedAccountBundle
if err = msgpack.Decode(&enc, cipherpack); err != nil {
return stellar1.EncryptedAccountBundle{}, stellar1.Hash{}, err
}
return enc, encHash[:], nil
}
// unbox unboxes an encrypted account bundle and decodes the visual portion of the bundle.
// It validates the visible hash in the secret portion.
func unbox(encBundle stellar1.EncryptedAccountBundle, hash stellar1.Hash /* visB64 string, */, puk libkb.PerUserKeySeed) (*stellar1.AccountBundle, stellar1.AccountBundleVersion, error) {
versioned, err := decrypt(encBundle, puk)
if err != nil {
return nil, 0, err
}
version, err := versioned.Version()
if err != nil {
return nil, 0, err
}
var bundleOut stellar1.AccountBundle
switch version {
case stellar1.AccountBundleVersion_V1:
secretV1 := versioned.V1()
bundleOut = stellar1.AccountBundle{
AccountID: secretV1.AccountID,
Signers: secretV1.Signers,
}
case stellar1.AccountBundleVersion_V2,
stellar1.AccountBundleVersion_V3,
stellar1.AccountBundleVersion_V4,
stellar1.AccountBundleVersion_V5,
stellar1.AccountBundleVersion_V6,
stellar1.AccountBundleVersion_V7,
stellar1.AccountBundleVersion_V8,
stellar1.AccountBundleVersion_V9,
stellar1.AccountBundleVersion_V10:
return nil, 0, errors.New("unsupported AccountBundleSecret version")
default:
return nil, 0, errors.New("invalid AccountBundle version")
}
bundleOut.OwnHash = hash
if len(bundleOut.OwnHash) == 0 {
return nil, 0, errors.New("stellar account bundle missing own hash")
}
return &bundleOut, version, nil
}
// decrypt decrypts an encrypted account bundle with the provided puk.
func decrypt(encBundle stellar1.EncryptedAccountBundle, puk libkb.PerUserKeySeed) (stellar1.AccountBundleSecretVersioned, error) {
var empty stellar1.AccountBundleSecretVersioned
if encBundle.V != 1 {
return empty, errors.New("invalid stellar secret account bundle encryption version")
}
// Derive key
reason := libkb.DeriveReasonPUKStellarAcctBundle
symmetricKey, err := puk.DeriveSymmetricKey(reason)
if err != nil {
return empty, err
}
// Secretbox
clearpack, ok := secretbox.Open(nil, encBundle.E,
(*[libkb.NaclDHNonceSize]byte)(&encBundle.N),
(*[libkb.NaclSecretBoxKeySize]byte)(&symmetricKey))
if !ok {
return empty, errors.New("stellar bundle secret box open failed")
}
// Msgpack (inner)
var bver stellar1.AccountBundleSecretVersioned
err = msgpack.Decode(&bver, clearpack)
if err != nil {
return empty, err
}
return bver, nil
}
func convertVisibleAccounts(in []stellar1.BundleVisibleEntryV2) []stellar1.BundleEntry {
out := make([]stellar1.BundleEntry, len(in))
for i, e := range in {
out[i] = stellar1.BundleEntry{
AccountID: e.AccountID,
Mode: e.Mode,
IsPrimary: e.IsPrimary,
AcctBundleRevision: e.AcctBundleRevision,
EncAcctBundleHash: e.EncAcctBundleHash,
}
}
return out
}
// merge combines the versioned secret account bundle and the visible account bundle into
// a stellar1.AccountBundle for local use.
func merge(secret stellar1.BundleSecretV2, visible stellar1.BundleVisibleV2) (stellar1.Bundle, error) {
if len(secret.Accounts) != len(visible.Accounts) {
return stellar1.Bundle{}, errors.New("invalid bundle, mismatched number of visible and secret accounts")
}
accounts := convertVisibleAccounts(visible.Accounts)
// these should be in the same order
for i, secretAccount := range secret.Accounts {
if accounts[i].AccountID != secretAccount.AccountID {
return stellar1.Bundle{}, errors.New("invalid bundle, mismatched order of visible and secret accounts")
}
accounts[i].Name = secretAccount.Name
}
return stellar1.Bundle{
Revision: visible.Revision,
Prev: visible.Prev,
Accounts: accounts,
}, nil
}