This repository has been archived by the owner on Jul 7, 2020. It is now read-only.
forked from keybase/client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
user_ek_box_storage.go
298 lines (248 loc) · 8.39 KB
/
user_ek_box_storage.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
package ephemeral
import (
"context"
"fmt"
"sync"
"github.com/keybase/client/go/libkb"
"github.com/keybase/client/go/protocol/keybase1"
)
type UserEKBoxMap map[keybase1.EkGeneration]keybase1.UserEkBoxed
type UserEKUnboxedMap map[keybase1.EkGeneration]keybase1.UserEk
// We cache UserEKBoxes from the server in memory and a persist to a local
// KVStore.
type UserEKBoxStorage struct {
libkb.Contextified
sync.Mutex
indexed bool
cache UserEKBoxMap
}
func NewUserEKBoxStorage(g *libkb.GlobalContext) *UserEKBoxStorage {
return &UserEKBoxStorage{
Contextified: libkb.NewContextified(g),
cache: make(UserEKBoxMap),
}
}
func (s *UserEKBoxStorage) dbKey(ctx context.Context) (dbKey libkb.DbKey, err error) {
uv, err := getCurrentUserUV(ctx, s.G())
if err != nil {
return dbKey, err
}
key := fmt.Sprintf("userEphemeralKeyBox-%s-%s", s.G().Env.GetUsername(), uv.EldestSeqno)
return libkb.DbKey{
Typ: libkb.DBUserEKBox,
Key: key,
}, nil
}
func (s *UserEKBoxStorage) getCache(ctx context.Context) (cache UserEKBoxMap, err error) {
defer s.G().CTraceTimed(ctx, "UserEKBoxStorage#getCache", func() error { return err })()
if !s.indexed {
key, err := s.dbKey(ctx)
if err != nil {
return s.cache, err
}
_, err = s.G().GetKVStore().GetInto(&s.cache, key)
if err != nil {
return s.cache, err
}
s.indexed = true
}
return s.cache, nil
}
func (s *UserEKBoxStorage) Get(ctx context.Context, generation keybase1.EkGeneration) (userEK keybase1.UserEk, err error) {
defer s.G().CTraceTimed(ctx, fmt.Sprintf("UserEKBoxStorage#Get: generation:%v", generation), func() error { return err })()
s.Lock()
cache, err := s.getCache(ctx)
if err != nil {
s.Unlock()
return userEK, err
}
// Try cache first
userEKBoxed, ok := cache[generation]
if ok {
defer s.Unlock() // release the lock after we unbox
return s.unbox(ctx, generation, userEKBoxed)
}
// We don't have anything in our cache, fetch from the server
s.Unlock() // release the lock while we fetch
return s.fetchAndStore(ctx, generation)
}
type UserEKBoxedResponse struct {
Result *struct {
Box string `json:"box"`
DeviceEKGeneration keybase1.EkGeneration `json:"device_ek_generation"`
Sig string `json:"sig"`
} `json:"result"`
}
func (s *UserEKBoxStorage) fetchAndStore(ctx context.Context, generation keybase1.EkGeneration) (userEK keybase1.UserEk, err error) {
defer s.G().CTraceTimed(ctx, fmt.Sprintf("UserEKBoxStorage#fetchAndStore: generation: %v", generation), func() error { return err })()
apiArg := libkb.APIArg{
Endpoint: "user/user_ek_box",
SessionType: libkb.APISessionTypeREQUIRED,
NetContext: ctx,
Args: libkb.HTTPArgs{
"generation": libkb.U{Val: uint64(generation)},
"recipient_device_id": libkb.S{Val: string(s.G().Env.GetDeviceID())},
},
}
var result UserEKBoxedResponse
res, err := s.G().GetAPI().Get(apiArg)
if err != nil {
return userEK, err
}
err = res.Body.UnmarshalAgain(&result)
if err != nil {
return userEK, err
}
if result.Result == nil {
return userEK, newEKMissingBoxErr(UserEKStr, generation)
}
// Although we verify the signature is valid, it's possible that this key
// was signed with a PUK that is not our latest and greatest. We allow this
// when we are using this ek for *decryption*. When getting a key for
// *encryption* callers are responsible for verifying the signature is
// signed by the latest PUK or generating a new EK. This logic currently
// lives in ephemeral/lib.go#KeygenIfNeeded (#newUserEKNeeded)
_, userEKStatement, err := extractUserEKStatementFromSig(result.Result.Sig)
if err != nil {
return userEK, err
} else if userEKStatement == nil { // shouldn't happen
return userEK, fmt.Errorf("unable to fetch valid userEKStatement")
}
userEKMetadata := userEKStatement.CurrentUserEkMetadata
userEKBoxed := keybase1.UserEkBoxed{
Box: result.Result.Box,
DeviceEkGeneration: result.Result.DeviceEKGeneration,
Metadata: userEKMetadata,
}
userEK, err = s.unbox(ctx, generation, userEKBoxed)
if err != nil {
return userEK, err
}
seed := UserEKSeed(userEK.Seed)
keypair := seed.DeriveDHKey()
if !keypair.GetKID().Equal(userEKMetadata.Kid) {
return userEK, fmt.Errorf("Failed to verify server given seed against signed KID %s", userEKMetadata.Kid)
}
// Store the boxed version, return the unboxed
err = s.Put(ctx, generation, userEKBoxed)
return userEK, err
}
func (s *UserEKBoxStorage) Put(ctx context.Context, generation keybase1.EkGeneration, userEKBoxed keybase1.UserEkBoxed) (err error) {
defer s.G().CTraceTimed(ctx, fmt.Sprintf("UserEKBoxStorage#Put: generation:%v", generation), func() error { return err })()
s.Lock()
defer s.Unlock()
key, err := s.dbKey(ctx)
if err != nil {
return err
}
cache, err := s.getCache(ctx)
if err != nil {
return err
}
cache[generation] = userEKBoxed
err = s.G().GetKVStore().PutObj(key, nil, cache)
if err != nil {
return err
}
return nil
}
func (s *UserEKBoxStorage) unbox(ctx context.Context, userEKGeneration keybase1.EkGeneration, userEKBoxed keybase1.UserEkBoxed) (userEK keybase1.UserEk, err error) {
defer s.G().CTraceTimed(ctx, fmt.Sprintf("UserEKBoxStorage#unbox: generation:%v", userEKGeneration), func() error { return err })()
deviceEKStorage := s.G().GetDeviceEKStorage()
deviceEK, err := deviceEKStorage.Get(ctx, userEKBoxed.DeviceEkGeneration)
if err != nil {
s.G().Log.CDebugf(ctx, "%v", err)
return userEK, newEKUnboxErr(UserEKStr, userEKGeneration, DeviceEKStr, userEKBoxed.DeviceEkGeneration)
}
deviceSeed := DeviceEKSeed(deviceEK.Seed)
deviceKeypair := deviceSeed.DeriveDHKey()
msg, _, err := deviceKeypair.DecryptFromString(userEKBoxed.Box)
if err != nil {
s.G().Log.CDebugf(ctx, "%v", err)
return userEK, newEKUnboxErr(UserEKStr, userEKGeneration, DeviceEKStr, userEKBoxed.DeviceEkGeneration)
}
seed, err := newUserEKSeedFromBytes(msg)
if err != nil {
return userEK, err
}
return keybase1.UserEk{
Seed: keybase1.Bytes32(seed),
Metadata: userEKBoxed.Metadata,
}, nil
}
func (s *UserEKBoxStorage) Delete(ctx context.Context, generation keybase1.EkGeneration) (err error) {
s.Lock()
defer s.Unlock()
return s.deleteMany(ctx, []keybase1.EkGeneration{generation})
}
func (s *UserEKBoxStorage) deleteMany(ctx context.Context, generations []keybase1.EkGeneration) (err error) {
defer s.G().CTraceTimed(ctx, fmt.Sprintf("UserEKBoxStorage#deleteMany: generations:%v", generations), func() error { return err })()
cache, err := s.getCache(ctx)
if err != nil {
return err
}
for _, generation := range generations {
delete(cache, generation)
}
key, err := s.dbKey(ctx)
if err != nil {
return err
}
return s.G().GetKVStore().PutObj(key, nil, cache)
}
func (s *UserEKBoxStorage) GetAll(ctx context.Context) (userEKs UserEKUnboxedMap, err error) {
defer s.G().CTraceTimed(ctx, "UserEKBoxStorage#GetAll", func() error { return err })()
s.Lock()
defer s.Unlock()
cache, err := s.getCache(ctx)
if err != nil {
return userEKs, err
}
userEKs = make(UserEKUnboxedMap)
for generation, userEKBoxed := range cache {
userEK, err := s.unbox(ctx, generation, userEKBoxed)
if err != nil {
return userEKs, err
}
userEKs[generation] = userEK
}
return userEKs, err
}
func (s *UserEKBoxStorage) ClearCache() {
s.Lock()
defer s.Unlock()
s.cache = make(UserEKBoxMap)
s.indexed = false
}
func (s *UserEKBoxStorage) MaxGeneration(ctx context.Context) (maxGeneration keybase1.EkGeneration, err error) {
defer s.G().CTraceTimed(ctx, "UserEKBoxStorage#MaxGeneration", func() error { return err })()
s.Lock()
defer s.Unlock()
maxGeneration = -1
cache, err := s.getCache(ctx)
if err != nil {
return maxGeneration, err
}
for generation := range cache {
if generation > maxGeneration {
maxGeneration = generation
}
}
return maxGeneration, nil
}
func (s *UserEKBoxStorage) DeleteExpired(ctx context.Context, merkleRoot libkb.MerkleRoot) (expired []keybase1.EkGeneration, err error) {
defer s.G().CTraceTimed(ctx, "DeviceEKStorage#DeleteExpired", func() error { return err })()
s.Lock()
defer s.Unlock()
cache, err := s.getCache(ctx)
if err != nil {
return nil, err
}
keyMap := make(keyExpiryMap)
for generation, userEKBoxed := range cache {
keyMap[generation] = userEKBoxed.Metadata.Ctime
}
expired = getExpiredGenerations(context.Background(), s.G(), keyMap, keybase1.TimeFromSeconds(merkleRoot.Ctime()))
err = s.deleteMany(ctx, expired)
return expired, err
}