forked from keybase/client
/
active_device.go
662 lines (569 loc) · 17.7 KB
/
active_device.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
package libkb
import (
"errors"
"fmt"
"strings"
"sync"
"github.com/keybase/client/go/protocol/keybase1"
context "golang.org/x/net/context"
)
type ActiveDevice struct {
uv keybase1.UserVersion
deviceID keybase1.DeviceID
deviceName string
deviceCtime keybase1.Time
signingKey GenericKey // cached secret signing key
encryptionKey GenericKey // cached secret encryption key
nistFactory *NISTFactory // Non-Interactive Session Token
secretSyncer *SecretSyncer
passphrase *PassphraseStreamCache
// This can be a paper key or a regular device key if we are self
// provisioning.
provisioningKey *SelfDestructingDeviceWithKeys
secretPromptCancelTimer CancelTimer
sync.RWMutex
}
func (a *ActiveDevice) Dump(m MetaContext, prefix string) {
m.Debug("%sActiveDevice: %p", prefix, a)
m.Debug("%sUserVersion: %+v", prefix, a.uv)
m.Debug("%sUsername (via env): %s", prefix, a.Username(m))
m.Debug("%sDeviceID: %s", prefix, a.deviceID)
m.Debug("%sDeviceName: %s", prefix, a.deviceName)
m.Debug("%sDeviceCtime: %s", prefix, keybase1.FormatTime(a.deviceCtime))
if a.signingKey != nil {
m.Debug("%sSigKey: %s", prefix, a.signingKey.GetKID())
}
if a.encryptionKey != nil {
m.Debug("%sEncKey: %s", prefix, a.encryptionKey.GetKID())
}
m.Debug("%sPassphraseCache: cacheObj=%v; valid=%v", prefix, (a.passphrase != nil), (a.passphrase != nil && a.passphrase.ValidPassphraseStream()))
m.Debug("%sProvisioningKeyCache: %v", prefix, (a.provisioningKey != nil && a.provisioningKey.DeviceWithKeys() != nil))
}
// NewProvisionalActiveDevice creates an ActiveDevice that is "provisional", in
// that it should not be considered the global ActiveDevice. Instead, it should
// reside in thread-local context, and can be weaved through the login
// machinery without trampling the actual global ActiveDevice.
func NewProvisionalActiveDevice(m MetaContext, uv keybase1.UserVersion, d keybase1.DeviceID, sigKey GenericKey, encKey GenericKey, deviceName string) *ActiveDevice {
return &ActiveDevice{
uv: uv,
deviceID: d,
deviceName: deviceName,
signingKey: sigKey,
encryptionKey: encKey,
nistFactory: NewNISTFactory(m.G(), uv.Uid, d, sigKey),
secretSyncer: NewSecretSyncer(m.G()),
}
}
func NewActiveDevice() *ActiveDevice {
return &ActiveDevice{}
}
func NewProvisioningKeyActiveDevice(m MetaContext, uv keybase1.UserVersion, d *DeviceWithKeys) *ActiveDevice {
ret := NewActiveDeviceWithDeviceWithKeys(m, uv, d)
ret.provisioningKey = NewSelfDestructingDeviceWithKeys(m, d, ProvisioningKeyMemoryTimeout)
return ret
}
func NewActiveDeviceWithDeviceWithKeys(m MetaContext, uv keybase1.UserVersion, d *DeviceWithKeys) *ActiveDevice {
return &ActiveDevice{
uv: uv,
deviceID: d.deviceID,
deviceName: d.deviceName,
signingKey: d.signingKey,
encryptionKey: d.encryptionKey,
nistFactory: NewNISTFactory(m.G(), uv.Uid, d.deviceID, d.signingKey),
secretSyncer: NewSecretSyncer(m.G()),
}
}
func (a *ActiveDevice) ClearCaches() {
a.Lock()
defer a.Unlock()
a.passphrase = nil
a.provisioningKey = nil
a.secretPromptCancelTimer.Reset()
}
// Copy ActiveDevice info from the given ActiveDevice.
func (a *ActiveDevice) Copy(m MetaContext, src *ActiveDevice) error {
// Take a consistent snapshot of the src device. Be careful not to hold
// locks on both devices at once.
src.Lock()
uv := src.uv
deviceID := src.deviceID
sigKey := src.signingKey
encKey := src.encryptionKey
name := src.deviceName
ctime := src.deviceCtime
src.Unlock()
return a.Set(m, uv, deviceID, sigKey, encKey, name, ctime)
}
func (a *ActiveDevice) SetOrClear(m MetaContext, a2 *ActiveDevice) error {
// Always clear, if we are also setting we set all new values.
a.Clear()
if a2 == nil {
return nil
}
return a.Copy(m, a2)
}
// Set acquires the write lock and sets all the fields in ActiveDevice.
// The acct parameter is not used for anything except to help ensure
// that this is called from inside a LoginState account request.
func (a *ActiveDevice) Set(m MetaContext, uv keybase1.UserVersion, deviceID keybase1.DeviceID,
sigKey, encKey GenericKey, deviceName string, deviceCtime keybase1.Time) error {
a.Lock()
defer a.Unlock()
if err := a.internalUpdateUserVersionDeviceID(uv, deviceID); err != nil {
return err
}
a.signingKey = sigKey
a.encryptionKey = encKey
a.deviceName = deviceName
a.deviceCtime = deviceCtime
a.nistFactory = NewNISTFactory(m.G(), uv.Uid, deviceID, sigKey)
a.secretSyncer = NewSecretSyncer(m.G())
return nil
}
// setSigningKey acquires the write lock and sets the signing key.
// The acct parameter is not used for anything except to help ensure
// that this is called from inside a LogingState account request.
func (a *ActiveDevice) setSigningKey(g *GlobalContext, uv keybase1.UserVersion, deviceID keybase1.DeviceID,
sigKey GenericKey, deviceName string) error {
a.Lock()
defer a.Unlock()
if err := a.internalUpdateUserVersionDeviceID(uv, deviceID); err != nil {
return err
}
a.signingKey = sigKey
if len(deviceName) > 0 {
a.deviceName = deviceName
}
a.nistFactory = NewNISTFactory(g, uv.Uid, deviceID, sigKey)
return nil
}
// setEncryptionKey acquires the write lock and sets the encryption key.
// The acct parameter is not used for anything except to help ensure
// that this is called from inside a LogingState account request.
func (a *ActiveDevice) setEncryptionKey(uv keybase1.UserVersion, deviceID keybase1.DeviceID, encKey GenericKey) error {
a.Lock()
defer a.Unlock()
if err := a.internalUpdateUserVersionDeviceID(uv, deviceID); err != nil {
return err
}
a.encryptionKey = encKey
return nil
}
// setDeviceName acquires the write lock and sets the device name.
// The acct parameter is not used for anything except to help ensure
// that this is called from inside a LoginState account request.
func (a *ActiveDevice) setDeviceName(uv keybase1.UserVersion, deviceID keybase1.DeviceID, deviceName string) error {
a.Lock()
defer a.Unlock()
if strings.TrimSpace(deviceName) == "" {
return errors.New("no device name specified")
}
if err := a.internalUpdateUserVersionDeviceID(uv, deviceID); err != nil {
return err
}
a.deviceName = deviceName
return nil
}
// should only called by the functions in this type, with the write lock.
func (a *ActiveDevice) internalUpdateUserVersionDeviceID(uv keybase1.UserVersion, deviceID keybase1.DeviceID) error {
if uv.IsNil() {
return errors.New("ActiveDevice.set with nil uid")
}
if deviceID.IsNil() {
return errors.New("ActiveDevice.set with nil deviceID")
}
if a.uv.IsNil() && a.deviceID.IsNil() {
a.uv = uv
a.deviceID = deviceID
} else if !a.uv.Eq(uv) {
return errors.New("ActiveDevice.set uid mismatch")
} else if !a.deviceID.Eq(deviceID) {
return errors.New("ActiveDevice.set deviceID mismatch")
}
return nil
}
func (a *ActiveDevice) Clear() error {
return a.clear()
}
// Clear acquires the write lock and resets all the fields to zero values.
func (a *ActiveDevice) clear() error {
a.Lock()
defer a.Unlock()
a.uv = keybase1.UserVersion{}
a.deviceID = ""
a.signingKey = nil
a.encryptionKey = nil
a.nistFactory = nil
a.passphrase = nil
a.provisioningKey = nil
a.secretPromptCancelTimer.Reset()
return nil
}
func (a *ActiveDevice) SecretPromptCancelTimer() *CancelTimer {
a.RLock()
defer a.RUnlock()
return &a.secretPromptCancelTimer
}
// UID returns the user ID that was provided when the device keys were cached.
// Safe for use by concurrent goroutines.
func (a *ActiveDevice) UID() keybase1.UID {
a.RLock()
defer a.RUnlock()
return a.uv.Uid
}
func (a *ActiveDevice) UserVersion() keybase1.UserVersion {
a.RLock()
defer a.RUnlock()
return a.uv
}
// Username tries to get the active user's username by looking into the current
// environment and mapping an UID to a username based on our config file. It
// won't work halfway through a provisioning.
func (a *ActiveDevice) Username(m MetaContext) NormalizedUsername {
return m.G().Env.GetUsernameForUID(a.UID())
}
// DeviceID returns the device ID that was provided when the device keys were
// cached. Safe for use by concurrent goroutines.
func (a *ActiveDevice) DeviceID() keybase1.DeviceID {
a.RLock()
defer a.RUnlock()
return a.deviceID
}
func (a *ActiveDevice) DeviceType(mctx MetaContext) (string, error) {
if a.secretSyncer.keys == nil {
mctx.Debug("keys are not synced with the server for this ActiveDevice. lets do that right now")
a.SyncSecretsForce(mctx)
}
devices, err := a.secretSyncer.Devices()
if err != nil {
return "", err
}
for devID, dev := range devices {
if devID == a.DeviceID() {
return dev.Type, nil
}
}
return "", NotFoundError{
Msg: "Not found: device type",
}
}
// SigningKey returns the signing key for the active device.
// Safe for use by concurrent goroutines.
func (a *ActiveDevice) SigningKey() (GenericKey, error) {
a.RLock()
defer a.RUnlock()
if a.signingKey == nil {
return nil, NotFoundError{
Msg: "Not found: device signing key",
}
}
return a.signingKey, nil
}
// EncryptionKey returns the encryption key for the active device.
// Safe for use by concurrent goroutines.
func (a *ActiveDevice) EncryptionKey() (GenericKey, error) {
a.RLock()
defer a.RUnlock()
if a.encryptionKey == nil {
return nil, NotFoundError{
Msg: "Not found: device encryption key",
}
}
return a.encryptionKey, nil
}
// NaclEncryptionKey returns the encryption key for the active device, as a
// NaclDHKeyPair. If the cast fails (though that should never happen), it
// returns an error.
func (a *ActiveDevice) NaclEncryptionKey() (*NaclDHKeyPair, error) {
genericKey, err := a.EncryptionKey()
if err != nil {
return nil, err
}
naclKey, ok := genericKey.(NaclDHKeyPair)
if !ok {
return nil, fmt.Errorf("expected NaclDHKeyPair, got %T", genericKey)
}
return &naclKey, nil
}
// KeyByType returns a cached key based on SecretKeyType.
// Safe for use by concurrent goroutines.
func (a *ActiveDevice) KeyByType(t SecretKeyType) (GenericKey, error) {
switch t {
case DeviceSigningKeyType:
return a.SigningKey()
case DeviceEncryptionKeyType:
return a.EncryptionKey()
default:
return nil, fmt.Errorf("Invalid type %v", t)
}
}
// AllFields returns all the ActiveDevice fields via one lock for consistency.
// Safe for use by concurrent goroutines.
func (a *ActiveDevice) AllFields() (uv keybase1.UserVersion, deviceID keybase1.DeviceID, deviceName string, sigKey GenericKey, encKey GenericKey) {
a.RLock()
defer a.RUnlock()
return a.uv, a.deviceID, a.deviceName, a.signingKey, a.encryptionKey
}
func (a *ActiveDevice) Name() string {
a.RLock()
defer a.RUnlock()
return a.deviceName
}
func (a *ActiveDevice) HaveKeys() bool {
a.RLock()
defer a.RUnlock()
return a.signingKey != nil && a.encryptionKey != nil
}
func (a *ActiveDevice) Valid() bool {
a.RLock()
defer a.RUnlock()
return a.valid()
}
func (a *ActiveDevice) valid() bool {
return a.signingKey != nil && a.encryptionKey != nil && !a.uv.IsNil() && !a.deviceID.IsNil() && a.deviceName != ""
}
func (a *ActiveDevice) Ctime(m MetaContext) (keybase1.Time, error) {
// make sure the device id doesn't change throughout this function
deviceID := a.DeviceID()
// check if we have a cached ctime already
ctime, err := a.ctimeCached(deviceID)
if err != nil {
return 0, err
}
if ctime > 0 {
return ctime, nil
}
// need to build a device and ask the server for ctimes
decKeys, err := a.deviceKeys(deviceID)
if err != nil {
return 0, err
}
// Note: decKeys.Populate() makes a network API call
if _, err := decKeys.Populate(m); err != nil {
return 0, nil
}
// set the ctime value under a write lock
a.Lock()
defer a.Unlock()
if !a.deviceID.Eq(deviceID) {
return 0, errors.New("active device changed during ctime lookup")
}
a.deviceCtime = decKeys.DeviceCtime()
return a.deviceCtime, nil
}
func (a *ActiveDevice) ctimeCached(deviceID keybase1.DeviceID) (keybase1.Time, error) {
a.RLock()
defer a.RUnlock()
if !a.deviceID.Eq(deviceID) {
return 0, errors.New("active device changed during ctime lookup")
}
return a.deviceCtime, nil
}
func (a *ActiveDevice) deviceKeys(deviceID keybase1.DeviceID) (*DeviceWithKeys, error) {
a.RLock()
defer a.RUnlock()
if !a.valid() {
return nil, errors.New("active device is not valid")
}
if !a.deviceID.Eq(deviceID) {
return nil, errors.New("active device changed")
}
return NewDeviceWithKeysOnly(a.encryptionKey, a.signingKey), nil
}
func (a *ActiveDevice) IsValidFor(uid keybase1.UID, deviceID keybase1.DeviceID) bool {
a.RLock()
defer a.RUnlock()
if a.signingKey == nil || a.encryptionKey == nil {
return false
}
if !uid.Equal(a.uv.Uid) {
return false
}
if !deviceID.Eq(a.deviceID) {
return false
}
return true
}
func (a *ActiveDevice) NIST(ctx context.Context) (*NIST, error) {
a.RLock()
defer a.RUnlock()
return a.nistLocked(ctx)
}
func (a *ActiveDevice) nistLocked(ctx context.Context) (*NIST, error) {
nist, err := a.nistFactory.NIST(ctx)
if err != nil {
return nil, err
}
if nist == nil {
return nil, nil
}
uid := a.nistFactory.UID()
if !uid.Equal(a.uv.Uid) {
return nil, NewUIDMismatchError(fmt.Sprintf("NIST generation error, UIDs didn't match; ActiveDevice said %s, but NIST factory said %s", a.uv.Uid, uid))
}
return nist, nil
}
func (a *ActiveDevice) NISTAndUIDDeviceID(ctx context.Context) (*NIST, keybase1.UID, keybase1.DeviceID, error) {
a.RLock()
defer a.RUnlock()
nist, err := a.nistLocked(ctx)
return nist, a.uv.Uid, a.deviceID, err
}
func (a *ActiveDevice) SyncSecretsForUID(m MetaContext, u keybase1.UID, force bool) (ret *SecretSyncer, err error) {
defer m.Trace("ActiveDevice#SyncSecretsForUID", func() error { return err })()
a.RLock()
s := a.secretSyncer
uid := a.uv.Uid
a.RUnlock()
if !u.IsNil() && !uid.Equal(u) {
return nil, fmt.Errorf("Wrong UID for sync secrets: %s != %s", uid, u)
}
if s == nil {
return nil, fmt.Errorf("Can't sync secrets: nil secret syncer")
}
if uid.IsNil() {
return nil, fmt.Errorf("can't run secret syncer without a UID")
}
if err = RunSyncer(m, s, uid, true, force); err != nil {
return nil, err
}
return s, nil
}
func (a *ActiveDevice) SyncSecrets(m MetaContext) (ret *SecretSyncer, err error) {
defer m.Trace("ActiveDevice#SyncSecrets", func() error { return err })()
var zed keybase1.UID
return a.SyncSecretsForUID(m, zed, false /* force */)
}
func (a *ActiveDevice) SyncSecretsForce(m MetaContext) (ret *SecretSyncer, err error) {
defer m.Trace("ActiveDevice#SyncSecretsForce", func() error { return err })()
var zed keybase1.UID
return a.SyncSecretsForUID(m, zed, true /* force */)
}
func (a *ActiveDevice) CheckForUsername(m MetaContext, n NormalizedUsername) (err error) {
a.RLock()
uid := a.uv.Uid
deviceID := a.deviceID
valid := a.valid()
a.RUnlock()
if !valid {
return NoActiveDeviceError{}
}
return m.G().GetUPAKLoader().CheckDeviceForUIDAndUsername(m.Ctx(), uid, deviceID, n)
}
func (a *ActiveDevice) ProvisioningKeyWrapper(m MetaContext) *SelfDestructingDeviceWithKeys {
a.RLock()
defer a.RUnlock()
return a.provisioningKey
}
func (a *ActiveDevice) ProvisioningKey(m MetaContext) *DeviceWithKeys {
a.RLock()
defer a.RUnlock()
if a.provisioningKey == nil {
return nil
}
return a.provisioningKey.DeviceWithKeys()
}
func (a *ActiveDevice) ClearProvisioningKey(m MetaContext) {
a.Lock()
defer a.Unlock()
a.provisioningKey = nil
}
func (a *ActiveDevice) CacheProvisioningKey(m MetaContext, k *DeviceWithKeys) {
a.Lock()
defer a.Unlock()
a.provisioningKey = NewSelfDestructingDeviceWithKeys(m, k, ProvisioningKeyMemoryTimeout)
}
func (a *ActiveDevice) PassphraseStreamCache() *PassphraseStreamCache {
a.RLock()
defer a.RUnlock()
return a.passphrase
}
func (a *ActiveDevice) PassphraseStream() *PassphraseStream {
a.RLock()
defer a.RUnlock()
c := a.PassphraseStreamCache()
if c == nil || !c.ValidPassphraseStream() {
return nil
}
return c.PassphraseStream()
}
func (a *ActiveDevice) TriplesecAndGeneration() (Triplesec, PassphraseGeneration) {
a.RLock()
defer a.RUnlock()
var zed PassphraseGeneration
c := a.PassphraseStreamCache()
if c == nil {
return nil, zed
}
return c.TriplesecAndGeneration()
}
func (a *ActiveDevice) CachePassphraseStream(c *PassphraseStreamCache) {
a.Lock()
defer a.Unlock()
a.passphrase = c
}
func (a *ActiveDevice) ClearPassphraseStreamCache() {
a.Lock()
defer a.Unlock()
a.passphrase = nil
}
func (a *ActiveDevice) ClearPassphraseStreamCacheIfOutdated(mctx MetaContext) error {
pps := a.PassphraseStream()
if pps == nil {
return nil
}
outdated, err := pps.SyncAndCheckIfOutdated(mctx)
if err != nil {
return err
}
if outdated {
a.ClearPassphraseStreamCache()
}
return nil
}
func (a *ActiveDevice) SigningKeyForUID(u keybase1.UID) GenericKey {
a.RLock()
defer a.RUnlock()
if !a.UID().Equal(u) {
return nil
}
return a.signingKey
}
func (a *ActiveDevice) Keyring(m MetaContext) (ret *SKBKeyringFile, err error) {
defer m.Trace("ActiveDevice#Keyring", func() error { return err })()
un := a.Username(m)
if un.IsNil() {
return nil, NewNoUsernameError()
}
m.Debug("Account: loading keyring for %s", un)
ret, err = LoadSKBKeyring(un, m.G())
if err != nil {
return nil, err
}
return ret, nil
}
func (a *ActiveDevice) CopyCacheToLoginContextIfForUserVersion(m MetaContext, lc LoginContext, uv keybase1.UserVersion) (err error) {
defer m.Trace("ActiveDevice#CopyCacheToLoginContextIfForUID", func() error { return err })()
a.RLock()
defer a.RUnlock()
if !a.uv.Eq(uv) {
return NewUIDMismatchError(fmt.Sprintf("%s v %s", a.uv, uv))
}
if a.passphrase != nil {
m.Debug("| copying non-nil passphrase cache")
lc.SetStreamCache(a.passphrase)
}
return nil
}
func (a *ActiveDevice) GetUsernameAndUserVersionIfValid(m MetaContext) (uv keybase1.UserVersion, un NormalizedUsername) {
a.RLock()
defer a.RUnlock()
if a.uv.IsNil() {
return uv, un
}
un = m.G().Env.GetUsernameForUID(a.uv.Uid)
if un.IsNil() {
return keybase1.UserVersion{}, NormalizedUsername("")
}
return a.uv, un
}