/
engine.go
636 lines (513 loc) · 15.1 KB
/
engine.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
// Package crypto provides access to secure encryption and signing methods
package crypto
import (
"context"
"crypto/rand"
"encoding/json"
"errors"
"strconv"
"unsafe"
"github.com/dchest/blake2b"
"github.com/keybase/go-triplesec"
"golang.org/x/crypto/ed25519"
"golang.org/x/crypto/nacl/box"
"golang.org/x/crypto/nacl/secretbox"
"github.com/manifoldco/go-base64"
"github.com/manifoldco/torus-cli/identity"
"github.com/manifoldco/torus-cli/primitive"
"github.com/manifoldco/torus-cli/daemon/crypto/secure"
"github.com/manifoldco/torus-cli/daemon/ctxutil"
"github.com/manifoldco/torus-cli/daemon/session"
)
const (
nonceSize = 16
blakeSize = 16
)
// ErrMissingPassphrase occurs when a session does not have a passphrase
var ErrMissingPassphrase = errors.New("Missing passphrase; cannot unseal master key")
// SignatureKeyPair is an ed25519/eddsa digital signature keypair.
// The private portion of the keypair is encrypted with triplesec.
//
// PNonce contains the nonce used when deriving the password used to encrypt
// the private portion.
type SignatureKeyPair struct {
Public ed25519.PublicKey
Private []byte
PNonce []byte
}
// EncryptionKeyPair is a curve25519 encryption keypair.
// The private portion of the keypair is encrypted with triplesec.
//
// PNonce contains the nonce used when deriving the password used to encrypt
// the private portion.
type EncryptionKeyPair struct {
Public [32]byte
Private []byte
PNonce []byte
}
// KeyPairs contains a signature and an encryption keypair for a user.
type KeyPairs struct {
Signature SignatureKeyPair
Encryption EncryptionKeyPair
}
// Engine exposes methods to encrypt, unencrypt and sign values, using
// the logged in user's credentials.
type Engine struct {
sess session.Session
guard *secure.Guard
}
// NewEngine returns a new Engine
func NewEngine(sess session.Session, g *secure.Guard) *Engine {
return &Engine{sess: sess, guard: g}
}
// Seal encrypts the plaintext pt bytes with triplesec-v3 using a key derived
// via blake2b from the user's master key and a nonce (returned).
func (e *Engine) Seal(ctx context.Context, pt []byte) ([]byte, []byte, error) {
mk, err := e.unsealMasterKey(ctx)
defer mk.Destroy()
if err != nil {
return nil, nil, err
}
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, nil, err
}
nonce := make([]byte, nonceSize)
_, err = rand.Read(nonce)
if err != nil {
return nil, nil, err
}
dk, err := deriveKey(ctx, mk.Buffer(), nonce, blakeSize)
if err != nil {
return nil, nil, err
}
ts, err := newTriplesec(ctx, dk)
if err != nil {
return nil, nil, err
}
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, nil, err
}
ct, err := ts.Encrypt(pt)
return ct, nonce, err
}
// Unseal decrypts the ciphertext ct, encrypted with triplesec-v3, using the
// a key derived via blake2b from the user's master key and the provided nonce.
func (e *Engine) Unseal(ctx context.Context, ct, nonce []byte) (*secure.Secret, error) {
mk, err := e.unsealMasterKey(ctx)
defer mk.Destroy()
if err != nil {
return nil, err
}
dk, err := deriveKey(ctx, mk.Buffer(), nonce, blakeSize)
if err != nil {
return nil, err
}
ts, err := newTriplesec(ctx, dk)
if err != nil {
return nil, err
}
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
b, err := ts.Decrypt(ct)
if err != nil {
return nil, err
}
return e.guard.Secret(b)
}
// Box encrypts the plaintext pt bytes with Box, using the private key found in
// privKP, first decrypted with the user's master key, and encrypted for the
// public key pubKey.
//
// It returns the ciphertext, the nonce used for encrypting the plaintext,
// and an optional error.
func (e *Engine) Box(ctx context.Context, pt *secure.Secret, privKP *EncryptionKeyPair,
pubKey []byte) ([]byte, []byte, error) {
err := ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, nil, err
}
nonce := [24]byte{}
_, err = rand.Read(nonce[:])
if err != nil {
return nil, nil, err
}
privKey, err := e.Unseal(ctx, privKP.Private, privKP.PNonce)
if err != nil {
return nil, nil, err
}
defer privKey.Destroy()
// Get a pointer to the underlying private key in memory
privkb := (*[32]byte)(unsafe.Pointer(&privKey.Buffer()[0]))
pubkb := [32]byte{}
copy(pubkb[:], pubKey)
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, nil, err
}
return box.Seal([]byte{}, pt.Buffer(), &nonce, &pubkb, privkb), nonce[:], nil
}
// Unbox Decrypts and verifies ciphertext ct that was previously encrypted using
// the provided nonce, and the inverse parts of the provided keypairs.
func (e *Engine) Unbox(ctx context.Context, ct, nonce []byte,
privKP *EncryptionKeyPair, pubKey []byte) (*secure.Secret, error) {
privKey, err := e.Unseal(ctx, privKP.Private, privKP.PNonce)
if err != nil {
return nil, err
}
defer privKey.Destroy()
nonceb := [24]byte{}
copy(nonceb[:], nonce)
// Get a pointer to the underlying private key in memory
privkb := (*[32]byte)(unsafe.Pointer(&privKey.Buffer()[0]))
pubkb := [32]byte{}
copy(pubkb[:], pubKey)
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
pt, success := box.Open([]byte{}, ct, &nonceb, &pubkb, privkb)
if !success {
return nil, errors.New("Failed to decrypt ciphertext")
}
return e.guard.Secret(pt)
}
// BoxCredential encrypts the credential value pt via symmetric secretbox
// encryption.
//
// Doing so is a multistep process.
// First we use the user's session data to unseal their private encryption key.
// With their encryption key and the public encryption key provided, we can
// decrypt the keyring master key (mek).
// Using mek and a generated nonce, we derive the credential encryption key
// (cek) via blake2b.
// Finally, we use the cek and a generated nonce to encrypt the credential.
//
// BoxCredential returns the nonce generated to derive the credential
// encryption key, the nonce generated for encrypting the credential, and the
// encrypted credential.
func (e *Engine) BoxCredential(ctx context.Context, pt, encMec, mecNonce []byte,
privKP *EncryptionKeyPair, pubKey []byte) ([]byte, []byte, []byte, error) {
err := ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, nil, nil, err
}
nonces := make([]byte, 48)
_, err = rand.Read(nonces)
if err != nil {
return nil, nil, nil, err
}
cekNonce := nonces[:24]
nonce := [24]byte{}
copy(nonce[:], nonces[24:])
mek, err := e.Unbox(ctx, encMec, mecNonce, privKP, pubKey)
if err != nil {
return nil, nil, nil, err
}
defer mek.Destroy()
cek, err := deriveKey(ctx, mek.Buffer(), cekNonce, 32)
if err != nil {
return nil, nil, nil, err
}
cekb := [32]byte{}
copy(cekb[:], cek)
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, nil, nil, err
}
ct := secretbox.Seal([]byte{}, pt, &nonce, &cekb)
return cekNonce, nonce[:], ct, err
}
// UnboxCredential does the inverse of BoxCredential to retrieve the plaintext
// version of a credential.
func (e *Engine) UnboxCredential(ctx context.Context, ct, encMec, mecNonce,
cekNonce, ctNonce []byte, privKP *EncryptionKeyPair, pubKey []byte) ([]byte, error) {
mek, err := e.Unbox(ctx, encMec, mecNonce, privKP, pubKey)
if err != nil {
return nil, err
}
defer mek.Destroy()
cek, err := deriveKey(ctx, mek.Buffer(), cekNonce, 32)
if err != nil {
return nil, err
}
cekb := [32]byte{}
copy(cekb[:], cek)
ctNonceb := [24]byte{}
copy(ctNonceb[:], ctNonce)
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
pt, success := secretbox.Open([]byte{}, ct, &ctNonceb, &cekb)
if !success {
return nil, errors.New("Failed to decrypt ciphertext")
}
return pt, nil
}
// Unsealer providers an interface to unbox public encryption keypairs using
// the users master encryption key
type Unsealer interface {
WithUnboxer(context.Context, []byte, []byte, func(Unboxer) error) error
}
type unsealerImpl struct {
engine *Engine
privkey *secure.Secret
pubkey []byte
}
// WithUnboxer returns an Unboxer for unboxing credentials tied to the unsealed
// keypairs.
func (u *unsealerImpl) WithUnboxer(ctx context.Context, encMec, mecNonce []byte,
fn func(Unboxer) error) error {
nonce := [24]byte{}
copy(nonce[:], mecNonce)
// Get a pointer to the private key buffer
privkb := (*[32]byte)(unsafe.Pointer(&u.privkey.Buffer()[0]))
pubkb := [32]byte{}
copy(pubkb[:], u.pubkey)
err := ctxutil.ErrIfDone(ctx)
if err != nil {
return err
}
mek, success := box.Open([]byte{}, encMec, &nonce, &pubkb, privkb)
if !success {
return errors.New("Failed to decrypt keyring")
}
s, err := u.engine.guard.Secret(mek)
if err != nil {
return err
}
defer s.Destroy()
unboxer := unboxerImpl{mek: s}
return fn(&unboxer)
}
// Unboxer provides an interface to unbox credentials, within the context
type Unboxer interface {
Unbox(context.Context, []byte, []byte, []byte) ([]byte, error)
}
type unboxerImpl struct {
mek *secure.Secret
}
func (u *unboxerImpl) Unbox(ctx context.Context, ct, cekNonce, ctNonce []byte) ([]byte, error) {
cek, err := deriveKey(ctx, u.mek.Buffer(), cekNonce, 32)
if err != nil {
return nil, err
}
cekb := [32]byte{}
copy(cekb[:], cek)
ctNonceb := [24]byte{}
copy(ctNonceb[:], ctNonce)
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
pt, success := secretbox.Open([]byte{}, ct, &ctNonceb, &cekb)
if !success {
return nil, errors.New("Failed to decrypt ciphertext")
}
return pt, nil
}
// WithUnboxer returns an Unboxer for unboxing credentials within the context
// of the provided keypairs.
func (e *Engine) WithUnboxer(ctx context.Context, encMec, mecNonce []byte,
privKP *EncryptionKeyPair, pubKey []byte, fn func(Unboxer) error) error {
mek, err := e.Unbox(ctx, encMec, mecNonce, privKP, pubKey)
if err != nil {
return err
}
defer mek.Destroy()
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return err
}
u := unboxerImpl{mek: mek}
return fn(&u)
}
// WithUnsealer returns an Unsealer to unseal keypairs which can
// subsequentently perform crypto operations through the Unsealer interface.
func (e *Engine) WithUnsealer(ctx context.Context, privKP *EncryptionKeyPair,
pubKey []byte, fn func(Unsealer) error) error {
privKey, err := e.Unseal(ctx, privKP.Private, privKP.PNonce)
if err != nil {
return err
}
defer privKey.Destroy()
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return err
}
u := unsealerImpl{privkey: privKey, pubkey: pubKey, engine: e}
return fn(&u)
}
// CloneMembership decrypts the given KeyringMember object, and creates another
// for the targeted user.
func (e *Engine) CloneMembership(ctx context.Context, encMec, mecNonce []byte, privKP *EncryptionKeyPair, encPubKey, targetPubKey []byte) ([]byte, []byte, error) {
mek, err := e.Unbox(ctx, encMec, mecNonce, privKP, encPubKey)
if err != nil {
return nil, nil, err
}
defer mek.Destroy()
return e.Box(ctx, mek, privKP, targetPubKey)
}
// GenerateKeyPairs generates and ed25519 signing key pair, and a curve25519
// encryption key pair for the user, encrypting the private keys in
// triplesec-v3 with the user's master key.
func (e *Engine) GenerateKeyPairs(ctx context.Context) (*KeyPairs, error) {
kp := &KeyPairs{}
err := ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
pubSig, privSig, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
sealedSig, nonceSig, err := e.Seal(ctx, privSig)
if err != nil {
return nil, err
}
kp.Signature.Private = sealedSig
kp.Signature.Public = pubSig
kp.Signature.PNonce = nonceSig
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
pubEnc, privEnc, err := box.GenerateKey(rand.Reader)
if err != nil {
return nil, err
}
sealedEnc, nonceEnc, err := e.Seal(ctx, (*privEnc)[:])
if err != nil {
return nil, err
}
kp.Encryption.Private = sealedEnc
kp.Encryption.Public = *pubEnc
kp.Encryption.PNonce = nonceEnc
return kp, nil
}
// Sign signs b bytes using the provided Sealed ed25519 keypair.
func (e *Engine) Sign(ctx context.Context, s SignatureKeyPair, b []byte) ([]byte, error) {
pk, err := e.Unseal(ctx, s.Private, s.PNonce)
if err != nil {
return nil, err
}
defer pk.Destroy()
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
return ed25519.Sign(pk.Buffer(), b), nil
}
// Verify verifies that sig is the correct signature for b given
// SignatureKeyPair s.
func (e *Engine) Verify(ctx context.Context, s SignatureKeyPair, b, sig []byte) (bool, error) {
err := ctxutil.ErrIfDone(ctx)
if err != nil {
return false, err
}
return ed25519.Verify(s.Public, b, sig), nil
}
func (e *Engine) signAndID(ctx context.Context, body identity.Immutable,
sigID *identity.ID, sigKP *SignatureKeyPair) (*identity.ID, *primitive.Signature, error) {
err := ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, nil, err
}
b, err := json.Marshal(&body)
if err != nil {
return nil, nil, err
}
s, err := e.Sign(ctx, *sigKP, append([]byte(strconv.Itoa(body.Version())), b...))
if err != nil {
return nil, nil, err
}
sig := primitive.Signature{
PublicKeyID: sigID,
Algorithm: EdDSA,
Value: base64.New(s),
}
id, err := identity.NewImmutable(body, &sig)
if err != nil {
return nil, nil, err
}
return &id, &sig, err
}
// unsealMasterKey uses the scrypt stretched password to decrypt the master
// password, which is encrypted with triplesec-v3
func (e *Engine) unsealMasterKey(ctx context.Context) (*secure.Secret, error) {
if !e.sess.HasPassphrase() {
return nil, ErrMissingPassphrase
}
ts, err := newTriplesec(ctx, e.sess.Passphrase())
if err != nil {
return nil, err
}
masterKey, err := e.sess.MasterKey()
if err != nil {
return nil, err
}
err = ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
mk, err := ts.Decrypt(*masterKey)
if err != nil {
return nil, err
}
return e.guard.Secret(mk)
}
func newTriplesec(ctx context.Context, k []byte) (*triplesec.Cipher, error) {
err := ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
ts, err := triplesec.NewCipher(k, nil)
if err != nil {
return nil, err
}
return ts, nil
}
// ChangePassword creates a password object and re-encrypts the master key
func (e *Engine) ChangePassword(ctx context.Context, newPassword string) (*primitive.UserPassword, *primitive.MasterKey, *primitive.LoginPublicKey, error) {
// We need to re-use the master key
cmk, err := e.unsealMasterKey(ctx)
defer cmk.Destroy()
if err != nil {
return nil, nil, nil, err
}
// Encrypt the new password and re-encrypt the original master key
b := cmk.Buffer()
pw, master, err := EncryptPasswordObject(ctx, newPassword, &b)
if err != nil {
return nil, nil, nil, err
}
// Now derive LoginKeypair
s, err := base64.NewFromString(pw.Salt)
if err != nil {
return nil, nil, nil, err
}
keypair, err := DeriveLoginKeypair(ctx, []byte(newPassword), s)
if err != nil {
return nil, nil, nil, err
}
return pw, master, &primitive.LoginPublicKey{
Salt: keypair.Salt(),
Value: keypair.PublicKey(),
Alg: EdDSA,
}, nil
}
// deriveKey Derives a single use key from the given master key via blake2b
// and a nonce.
func deriveKey(ctx context.Context, mk, nonce []byte, size uint8) ([]byte, error) {
err := ctxutil.ErrIfDone(ctx)
if err != nil {
return nil, err
}
h := blake2b.NewMAC(size, nonce) // NewMAC can panic if size is too big.
h.Sum(mk)
return h.Sum(nil), nil
}