-
Notifications
You must be signed in to change notification settings - Fork 9
/
session.go
632 lines (559 loc) · 16.4 KB
/
session.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
package handshake
import (
"bytes"
"encoding/base64"
"encoding/gob"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"time"
)
const (
// DefaultSessionTTL is the default TTL before a Session closes
DefaultSessionTTL = 15 * 60 // 15 minutes in seconds
// DefaultMaxLoginAttempts is the number of times failed login attempts are allowed
DefaultMaxLoginAttempts = 10
chatIDLength = 12
defaultLookupCount = 10000
)
// Session is the primary struct for a logged in user. It holds the profile data
// as well as settings information
type Session struct {
profile Profile
storage storage
cipher cipher
ttl int64
startTime int64
globalConfig globalConfig
activeHandshake *handshake
}
// SessionOptions holds session options for initialization
type SessionOptions struct {
StorageEngine StorageEngine
StorageFilePath string
}
// GlobalConfig holds global settings used by the app
// These may end up just being global constants.
type globalConfig struct {
TTL int
FailedLoginAttempts int
MaxLoginAttempts int
}
// newGlobalConfig creates a new global config struct with default settings.
// This is primarily used for initializing a new data store
func newGlobalConfig() globalConfig {
return globalConfig{
TTL: DefaultSessionTTL,
FailedLoginAttempts: 0,
MaxLoginAttempts: DefaultMaxLoginAttempts,
}
}
// ToJSON is a helper method for GlobalConfig
func (g globalConfig) ToJSON() []byte {
b, _ := json.Marshal(g)
return b
}
// NewSession takes a password and opts and returns a pointer to Session and an error
func NewSession(password string, opts SessionOptions) (*Session, error) {
storageOpts := StorageOptions{Engine: opts.StorageEngine}
storageOpts.FilePath = opts.StorageFilePath
storage, err := newStorage(storageOpts)
if err != nil {
return nil, err
}
cipher := newTimeSeriesSBCipher()
session := Session{
storage: storage,
cipher: cipher,
ttl: DefaultSessionTTL,
startTime: time.Now().Unix(),
}
profilePaths, err := storage.List(profileKeyPrefix)
if err != nil {
return nil, err
}
if len(profilePaths) == 0 {
return nil, errors.New("no profile found")
}
for _, profilePath := range profilePaths {
id, err := getIDFromPath(profilePath)
if err != nil {
return nil, err
}
key := deriveKey([]byte(password), id)
profile, err := getProfileFromEncryptedStorage(profilePath, key, cipher, storage)
if err == nil {
session.setProfile(profile)
return &session, err
}
}
return nil, errors.New("invalid password")
}
// NewDefaultSession is a wrapper around NewSession and applies simple defaults. This is intended to be used
//by the reference apps.
func NewDefaultSession(password string) (*Session, error) {
opts := SessionOptions{StorageEngine: defaultStorageEngine}
return NewSession(password, opts)
}
// setProfile takes a profile and sets it to the private variable in the Session struct
func (s *Session) setProfile(p Profile) {
s.profile = p
}
// GetProfile returns the profile in the Session struct
func (s *Session) GetProfile() Profile {
return s.profile
}
// Close gracefully closes the session
func (s *Session) Close() error {
return s.storage.Close()
}
// NewInitiatorWithDefaults provides a simple method with no arguments to create a default handshake
// for an initiator. Adds this handshake pointer to the ActiveHandshake in the session.
func (s *Session) NewInitiatorWithDefaults() {
s.activeHandshake = newHandshakeInitiatorWithDefaults()
}
// NewPeerWithDefaults provides a simple method with no arguments to create a default handshake
// for an peer. Adds this handshake pointer to the ActiveHandshake in the session.
func (s *Session) NewPeerWithDefaults() {
s.activeHandshake = newHandshakePeerWithDefaults()
}
// ShareHandshakePosition returns the values from negotiator.Share() from the ActiveHandshake
func (s *Session) ShareHandshakePosition() (b []byte, err error) {
// TODO: add encryption wrapper
return s.activeHandshake.Position.Share()
}
// AddPeerToHandshake takes a json encoded peerConfig, attempts to unmarshal it and add it as a peer.
// It returns a bool and an error. The bool indicates if handshake.AllPeersReceived == true, in which case
// the handshake can safely be conversted int a chat.
func (s *Session) AddPeerToHandshake(body []byte) (bool, error) {
// TODO: add decryption wrapper
var config peerConfig
if err := json.Unmarshal(body, &config); err != nil {
return false, err
}
if err := s.activeHandshake.AddPeer(config); err != nil {
return false, err
}
return s.activeHandshake.AllPeersReceived(), nil
}
// GetHandshakePeerTotal returns an int count of the number of peers to expect for a handshake
func (s *Session) GetHandshakePeerTotal() int {
return s.activeHandshake.GetPeerTotal()
}
// GetHandshakePeerConfig returns the json bytes encoded peerConfig based on peerID or and an error
func (s *Session) GetHandshakePeerConfig(sortNumber int) ([]byte, error) {
configs, err := s.activeHandshake.GetAllConfigs()
if err != nil {
return []byte{}, err
}
if sortNumber <= 0 {
return []byte{}, errors.New("sortNumber must be greater than 0")
}
if sortNumber > len(configs) {
return []byte{}, errors.New("sortNumber is out of range")
}
return json.Marshal(configs[sortNumber-1])
}
// set is a wrapper for combining the cipher and storage interfaces. Data in the value component is encrypted and then
// stored in the storage engine.
func (s *Session) set(key string, value []byte) (string, error) {
encrypted, err := s.cipher.Encrypt(value, s.profile.Key)
if err != nil {
return "", err
}
return s.storage.Set(key, encrypted)
}
// get is a wrapper for combining the cipher and storage interfaces. Retrieved data is decrypted and returned
// unencrypted as a byte slice and error
func (s *Session) get(key string) ([]byte, error) {
encrypted, err := s.storage.Get(key)
if err != nil {
return []byte{}, err
}
return s.cipher.Decrypt(encrypted, s.profile.Key)
}
// NewChat creates a new chat from the activeHandshake and returns a chat ID string and error.
// If the chat is successfully created, it deletes the contents of the activeHandshake
func (s *Session) NewChat() (string, error) {
peerTotal := s.GetHandshakePeerTotal()
negotiatorCount := len(s.activeHandshake.Negotiators)
if peerTotal < 2 {
return "", errors.New("not enough peers to start a chat")
}
if peerTotal != negotiatorCount {
return "", fmt.Errorf("expected peer total to be %v but counted %v", peerTotal, negotiatorCount)
}
chatID := hex.EncodeToString(genRandBytes(chatIDLength))
negotiators, err := s.activeHandshake.SortedNegotiatorList()
if err != nil {
return "", err
}
pepper := generatePepper(negotiators)
config := chat{
ID: chatID,
Peers: make(map[string]chatPeer),
}
basePath := fmt.Sprintf("chats/%v/%v", chatID, s.profile.ID)
for _, n := range negotiators {
cp := chatPeer{
ID: hex.EncodeToString(genRandBytes(chatIDLength)),
Alias: n.Alias,
Strategy: n.Strategy,
}
config.Peers[cp.ID] = cp
if bytes.Equal(n.Entropy, s.activeHandshake.Position.Entropy) {
config.PeerID = cp.ID
}
var p [64]byte
var e [96]byte
copy(p[:], pepper)
copy(e[:], n.Entropy)
// TODO support cipherType inspection
lookups, err := genLookups(p, e, SecretBox, defaultLookupCount)
if err != nil {
return "", err
}
if err := s.setLookup(chatID, cp.ID, lookups); err != nil {
deleteAllWithPrefix(s.storage, basePath)
return "", err
}
}
if config.PeerID == "" {
deleteAllWithPrefix(s.storage, basePath)
return "", errors.New("primary PeerID not found for chat")
}
if err := s.setChat(chatID, config); err != nil {
deleteAllWithPrefix(s.storage, basePath)
return "", err
}
if err := s.setChatlog(chatID, make(chatLog)); err != nil {
deleteAllWithPrefix(s.storage, basePath)
return "", err
}
s.activeHandshake = &handshake{}
return chatID, nil
}
// ListChats returns a json encoded list of chatIDs and an error
func (s *Session) ListChats() ([]byte, error) {
list, err := s.storage.List("chats/")
if err != nil {
return []byte{}, err
}
return json.Marshal(uniqueChatIDsFromPaths(list, s.profile.ID))
}
func (s *Session) getChat(chatID string) (chat, error) {
key := fmt.Sprintf("chats/%v/%v/config", chatID, s.profile.ID)
chatGob, err := s.get(key)
if err != nil {
return chat{}, err
}
return newChatFromGob(chatGob)
}
func (s *Session) setChat(chatID string, c chat) error {
key := fmt.Sprintf("chats/%v/%v/config", chatID, s.profile.ID)
safeConfig, err := c.Config()
if err != nil {
return err
}
chatGob, err := encodeGob(safeConfig)
if err != nil {
return err
}
_, err = s.set(key, chatGob)
return err
}
func (s *Session) getLookup(chatID, peerID string) (lookup, error) {
key := fmt.Sprintf("chats/%v/%v/lookups/%v", chatID, s.profile.ID, peerID)
lookupGob, err := s.get(key)
if err != nil {
return lookup{}, err
}
return newLookupFromGob(lookupGob)
}
func (s *Session) setLookup(chatID, peerID string, l lookup) error {
key := fmt.Sprintf("chats/%v/%v/lookups/%v", chatID, s.profile.ID, peerID)
lookupGob, err := encodeGob(l)
if err != nil {
return err
}
_, err = s.set(key, lookupGob)
return err
}
func (s *Session) GetChatlog(chatID string) (chatLog, error) {
key := fmt.Sprintf("chats/%v/%v/chatlog", chatID, s.profile.ID)
chatLogGob, err := s.get(key)
if err != nil {
return chatLog{}, err
}
return newChatLogFromGob(chatLogGob)
}
func (s *Session) setChatlog(chatID string, cl chatLog) error {
key := fmt.Sprintf("chats/%v/%v/chatlog", chatID, s.profile.ID)
chatLogGob, err := encodeGob(cl)
if err != nil {
return err
}
_, err = s.set(key, chatLogGob)
return err
}
func (s *Session) getRendezvousHash(chatID, peerID string) (hash string) {
c, err := s.getChat(chatID)
if err != nil {
return
}
l, err := s.getLookup(chatID, peerID)
if err != nil {
return
}
rBytes, err := c.Peers[peerID].Strategy.Rendezvous.Get("")
if err != nil {
return // TODO: skip for now, there should be more logic here.
}
rHash := base64.StdEncoding.EncodeToString(rBytes[:lookupHashLength])
rKey := l.popKey(rHash)
if err := s.setLookup(chatID, peerID, l); err != nil {
return
}
hashBytes, err := c.Peers[peerID].Strategy.Cipher.Decrypt(rBytes[lookupHashLength:], rKey)
if err != nil {
return
}
hash = string(hashBytes)
cl, err := s.GetChatlog(chatID)
if err != nil {
return
}
if cl.HashInLog(hash) {
return ""
}
if err := s.setChat(chatID, c); err != nil {
return ""
}
return hash
}
func (s *Session) retrieveMessage(chatID, hash, peerID string) (data chatData, err error) {
c, err := s.getChat(chatID)
if err != nil {
return
}
l, err := s.getLookup(chatID, peerID)
if err != nil {
return
}
b, err := c.Peers[peerID].Strategy.Storage.Get(hash)
if err != nil {
return
}
lookupHash := base64.StdEncoding.EncodeToString(b[:lookupHashLength])
key := l.popKey(lookupHash)
if len(key) == 0 {
return data, errors.New("no key")
}
err = s.setLookup(chatID, peerID, l)
if err != nil {
return
}
d, err := c.Peers[peerID].Strategy.Cipher.Decrypt(b[lookupHashLength:], key)
if err != nil {
return
}
err = json.Unmarshal(d, &data)
if err != nil {
return
}
err = s.setChat(chatID, c)
return
}
func (s *Session) logChatData(chatID string, peerID string, hash string, data chatData) error {
cl, err := s.GetChatlog(chatID)
if err != nil {
return err
}
clEntry := chatLogEntry{
ID: hash,
Sender: peerID,
Sent: data.Timestamp,
TTL: data.TTL,
Data: data,
}
if err := cl.AddEntry(clEntry); err != nil {
return err
}
return s.setChatlog(chatID, cl)
}
func (s *Session) recursivelyLogParents(chatID string, peerID string, data chatData) error {
if data.Parent == "" {
return nil // if no parent set, return early
}
cl, err := s.GetChatlog(chatID)
if err != nil {
return err
}
if cl.HashInLog(data.Parent) {
return nil // if hash already in log, return early
}
parentData, err := s.retrieveMessage(chatID, data.Parent, peerID)
if err != nil {
if err.Error() == "no key" {
return nil
}
return err
}
if err := s.logChatData(chatID, peerID, data.Parent, parentData); err != nil {
return err
}
if parentData.Parent != "" {
return s.recursivelyLogParents(chatID, peerID, parentData)
}
return nil
}
// RetrieveMessages takes a chatID and initiates the retrieval process for all peers
// it returns a json encoded chatLogList and error
func (s *Session) RetrieveMessages(chatID string) ([]byte, error) {
// this should query all peer endpoints and update the chatlog
// this step also runs ttl validation to clear out old messages
// it returns a json encoded chatLogList
c, err := s.getChat(chatID)
if err != nil {
return []byte{}, err
}
for peerID := range c.Peers {
if peerID == c.PeerID { // skip self
continue
}
hash := s.getRendezvousHash(chatID, peerID)
if hash == "" {
continue
}
data, err := s.retrieveMessage(chatID, hash, peerID)
if err != nil {
continue
}
if err := s.logChatData(chatID, peerID, hash, data); err != nil {
continue
}
if err := s.recursivelyLogParents(chatID, peerID, data); err != nil {
continue
}
}
cl, err := s.GetChatlog(chatID)
if err != nil {
return []byte{}, err
}
return cl.SortedJSON()
}
// GetMyPeerID returns a string of the profile user's peerID for a specific chat, returns the peerID and an error
func (s *Session) GetMyPeerID(chatID string) (string, error) {
c, err := s.getChat(chatID)
if err != nil {
return "", err
}
return c.PeerID, nil
}
// SendMessage takes a chatID and message bytes and submits the message to the message
// storage and rendezvous point. It returns a json encoded chatLogList and error
func (s *Session) SendMessage(chatID string, b []byte) ([]byte, error) {
if len(b) > maxMessageSize {
return []byte{}, fmt.Errorf("messag sized exceeds max size of %v bytes", maxMessageSize)
}
c, err := s.getChat(chatID)
if err != nil {
return []byte{}, err
}
var data chatData
if err := json.Unmarshal(b, &data); err != nil {
return []byte{}, err
}
data.Parent = c.LastSent
data.Timestamp = time.Now().UnixNano()
data.TTL = c.TTL()
dataBytes, err := json.Marshal(data)
if err != nil {
return []byte{}, nil
}
sender := c.Peers[c.PeerID]
l, err := s.getLookup(chatID, c.PeerID)
if err != nil {
return []byte{}, err
}
mStoreKey, mStoreValue := l.popRandom()
if err := s.setLookup(chatID, c.PeerID, l); err != nil {
return []byte{}, err
}
mStoreKeyBytes, err := base64.StdEncoding.DecodeString(mStoreKey)
if err != nil {
return []byte{}, err
}
cipherText, err := sender.Strategy.Cipher.Encrypt(dataBytes, mStoreValue)
if err != nil {
return []byte{}, err
}
var payload []byte
payload = append(payload, mStoreKeyBytes...)
payload = append(payload, cipherText...)
hash, err := sender.Strategy.Storage.Set("", payload)
if err != nil {
return []byte{}, err
}
c.LastSent = hash
if err := s.setChat(chatID, c); err != nil {
return []byte{}, err
}
rStoreKey, rStoreValue := l.popRandom()
if err := s.setLookup(chatID, c.PeerID, l); err != nil {
return []byte{}, err
}
rStoreKeyBytes, err := base64.StdEncoding.DecodeString(rStoreKey)
if err != nil {
return []byte{}, err
}
rCipherText, err := sender.Strategy.Cipher.Encrypt([]byte(hash), rStoreValue)
if err != nil {
return []byte{}, err
}
var rPayload []byte
rPayload = append(rPayload, rStoreKeyBytes...)
rPayload = append(rPayload, rCipherText...)
if _, err := sender.Strategy.Rendezvous.Set("", rPayload); err != nil {
return []byte{}, err
}
cl, err := s.GetChatlog(chatID)
if err != nil {
return []byte{}, err
}
clEntry := chatLogEntry{
ID: hash,
Sender: c.PeerID,
Sent: data.Timestamp,
TTL: data.TTL,
Data: data,
}
if err := cl.AddEntry(clEntry); err != nil {
return []byte{}, err
}
if err := s.setChatlog(chatID, cl); err != nil {
return []byte{}, err
}
return cl.SortedJSON()
}
// deleteAllWithPrefix takes a storage interface and a prefix string. It looks up all keys that
// match the prefix and attempts to run the Delete method on all keys, returns a error or nil.
func deleteAllWithPrefix(s storage, prefix string) error {
keys, err := s.List(prefix)
if err != nil {
return err
}
for _, key := range keys {
if err := s.Delete(key); err != nil {
return err
}
}
return nil
}
// gobBytes takes an empty interface and returns a byte slice and error
func encodeGob(x interface{}) ([]byte, error) {
var buffer bytes.Buffer
err := gob.NewEncoder(&buffer).Encode(x)
return buffer.Bytes(), err
}