This repository has been archived by the owner on Jul 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 26
/
store.go
482 lines (398 loc) · 11.3 KB
/
store.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
// Copyright (c) 2014 Canonical Ltd.
// Licensed under the GPLv3, see the COPYING file for details.
package textsecure
import (
"bytes"
"crypto/sha1"
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"github.com/signal-golang/textsecure/axolotl"
"github.com/signal-golang/textsecure/config"
"github.com/signal-golang/textsecure/fingerprint"
"golang.org/x/crypto/pbkdf2"
log "github.com/sirupsen/logrus"
)
// store implements the PreKeyStore, SignedPreKeyStore,
// IdentityStore and SessionStore interfaces from the axolotl package
// Blobs are encrypted with AES-128 and authenticated with HMAC-SHA1
type store struct {
sync.Mutex
preKeysDir string
signedPreKeysDir string
identityDir string
sessionsDir string
unencrypted bool
aesKey []byte
macKey []byte
}
var lastResortPreKeyID uint32 = 0xFFFFFF
func newStore(password, path string) (*store, error) {
ts := &store{
preKeysDir: filepath.Join(path, "prekeys"),
signedPreKeysDir: filepath.Join(path, "signed_prekeys"),
identityDir: filepath.Join(path, "identity"),
sessionsDir: filepath.Join(path, "sessions"),
unencrypted: password == "",
}
// Create dirs in case this is first run
if err := os.MkdirAll(ts.preKeysDir, 0700); err != nil {
return nil, err
}
if err := os.MkdirAll(ts.signedPreKeysDir, 0700); err != nil {
return nil, err
}
if err := os.MkdirAll(ts.identityDir, 0700); err != nil {
return nil, err
}
if err := os.MkdirAll(ts.sessionsDir, 0700); err != nil {
return nil, err
}
// If there is a password, generate the keys from it
if !ts.unencrypted {
salt := make([]byte, 8)
saltFile := filepath.Join(path, "salt")
var err error
// Create salt if this is first run
if !exists(saltFile) {
randBytes(salt)
err = ioutil.WriteFile(saltFile, salt, 0600)
if err != nil {
return nil, err
}
} else {
salt, err = os.ReadFile(saltFile)
if err != nil {
return nil, err
}
}
ts.genKeys(password, salt, 1024)
}
return ts, nil
}
// Helpers
func idToFilename(id uint32) string {
return fmt.Sprintf("%09d", id)
}
func filenameToID(fname string) (uint32, error) {
var id uint32
_, err := fmt.Sscanf(fname, "%d", &id)
if err != nil {
return 0, err
}
return uint32(id), nil
}
func (s *store) readNumFromFile(path string) (uint32, error) {
b, err := s.readFile(path)
if err != nil {
return 0, err
}
num, err := strconv.Atoi(string(b))
if err != nil {
return 0, err
}
return uint32(num), nil
}
func (s *store) writeNumToFile(path string, num uint32) {
b := []byte(strconv.Itoa(int(num)))
s.writeFile(path, b)
}
func (s *store) genKeys(password string, salt []byte, count int) {
keys := pbkdf2.Key([]byte(password), salt, count, 16+20, sha1.New)
s.aesKey = keys[:16]
s.macKey = keys[16:]
}
func (s *store) encrypt(plaintext []byte) ([]byte, error) {
if s.unencrypted {
return plaintext, nil
}
e, err := aesEncrypt(s.aesKey, plaintext)
if err != nil {
return nil, err
}
return appendMAC(s.macKey, e), nil
}
// ErrStoreBadMAC occurs when MAC verification fails on the records stored using password based encryption.
// The probable cause is using a wrong password.
var ErrStoreBadMAC = errors.New("wrong MAC calculated, possibly due to wrong passphrase")
func (s *store) decrypt(ciphertext []byte) ([]byte, error) {
if s.unencrypted {
return ciphertext, nil
}
macPos := len(ciphertext) - 32
if !verifyMAC(s.macKey, ciphertext[:macPos], ciphertext[macPos:]) {
return nil, ErrStoreBadMAC
}
return aesDecrypt(s.aesKey, ciphertext[:macPos])
}
func (s *store) readFile(path string) ([]byte, error) {
b, err := os.ReadFile(path)
if err != nil {
return nil, err
}
b, err = s.decrypt(b)
return b, err
}
func (s *store) writeFile(path string, b []byte) error {
b, err := s.encrypt(b)
if err != nil {
return err
}
return ioutil.WriteFile(path, b, 0600)
}
// Identity store
func (s *store) GetLocalRegistrationID() (uint32, error) {
regidfile := filepath.Join(s.identityDir, "regid")
return s.readNumFromFile(regidfile)
}
func (s *store) SetLocalRegistrationID(id uint32) {
regidfile := filepath.Join(s.identityDir, "regid")
s.writeNumToFile(regidfile, id)
}
func (s *store) GetIdentityKeyPair() (*axolotl.IdentityKeyPair, error) {
idkeyfile := filepath.Join(s.identityDir, "identity_key")
b, err := s.readFile(idkeyfile)
if err != nil {
return nil, err
}
if len(b) != 64 {
return nil, fmt.Errorf("identity key is %d not 64 bytes long", len(b))
}
return axolotl.NewIdentityKeyPairFromKeys(b[32:], b[:32]), nil
}
func (s *store) SetIdentityKeyPair(ikp *axolotl.IdentityKeyPair) error {
idkeyfile := filepath.Join(s.identityDir, "identity_key")
b := make([]byte, 64)
copy(b, ikp.PublicKey.Key()[:])
copy(b[32:], ikp.PrivateKey.Key()[:])
return s.writeFile(idkeyfile, b)
}
func (s *store) SaveIdentity(id string, key *axolotl.IdentityKey) error {
idkeyfile := filepath.Join(s.identityDir, "remote_"+id)
return s.writeFile(idkeyfile, key.Key()[:])
}
func (s *store) IsTrustedIdentity(id string, key *axolotl.IdentityKey) bool {
if config.ConfigFile.AlwaysTrustPeerID {
// Workaround until we handle peer reregistering situations
// more securely and with a better UI.
return true
}
idkeyfile := filepath.Join(s.identityDir, "remote_"+id)
// Trust on first use (TOFU)
if !exists(idkeyfile) {
return true
}
b, err := s.readFile(idkeyfile)
if err != nil {
return false
}
return bytes.Equal(b, key.Key()[:])
}
// MyIdentityKey returns our serialized public identity key
func MyIdentityKey() []byte {
return identityKey.PublicKey.Serialize()
}
// UnknownContactError is returned when an unknown group id is encountered
type UnknownContactError struct {
id string
}
func (err UnknownContactError) Error() string {
return fmt.Sprintf("unknown contact ID %s", err.id)
}
// ContactIdentityKey returns the serialized public key of the given contact
func ContactIdentityKey(id string) ([]byte, error) {
s := textSecureStore
idClean, err := recID(id)
if err != nil {
return nil, err
}
idkeyfile := filepath.Join(s.identityDir, "remote_"+idClean)
if !exists(idkeyfile) {
return nil, UnknownContactError{id}
}
b, err := s.readFile(idkeyfile)
if err != nil {
return nil, err
}
return append([]byte{5}, b...), nil
}
func GetFingerprint(remoteUUID string, remoteIdentifier string) ([]string, []byte, error) {
localIdentifier := config.ConfigFile.Tel
localIdentityKey := MyIdentityKey()
remoteIdentityKey, err := ContactIdentityKey(remoteUUID)
if err != nil {
return nil, nil, err
}
numericFingerprint, scannableFingerprint, err := fingerprint.CreateFingerprintSimple(1, localIdentifier, localIdentityKey, remoteIdentifier, remoteIdentityKey)
if err != nil {
return nil, nil, err
}
return numericFingerprint, scannableFingerprint, nil
}
// Prekey and signed prekey store
func (s *store) preKeysFilePath(id uint32) string {
return filepath.Join(s.preKeysDir, idToFilename(id))
}
func (s *store) signedPreKeysFilePath(id uint32) string {
return filepath.Join(s.signedPreKeysDir, idToFilename(id))
}
func (s *store) LoadPreKey(id uint32) (*axolotl.PreKeyRecord, error) {
b, err := s.readFile(s.preKeysFilePath(id))
if err != nil {
return nil, err
}
record, err := axolotl.LoadPreKeyRecord(b)
if err != nil {
return nil, err
}
return record, nil
}
func (s *store) LoadSignedPreKey(id uint32) (*axolotl.SignedPreKeyRecord, error) {
b, err := s.readFile(s.signedPreKeysFilePath(id))
if err != nil {
return nil, err
}
record, err := axolotl.LoadSignedPreKeyRecord(b)
if err != nil {
return nil, err
}
return record, nil
}
func (s *store) LoadSignedPreKeys() []axolotl.SignedPreKeyRecord {
keys := []axolotl.SignedPreKeyRecord{}
//FIXME
return keys
}
func (s *store) StorePreKey(id uint32, record *axolotl.PreKeyRecord) error {
b, err := record.Serialize()
if err != nil {
return err
}
return s.writeFile(s.preKeysFilePath(id), b)
}
func (s *store) StoreSignedPreKey(id uint32, record *axolotl.SignedPreKeyRecord) error {
b, err := record.Serialize()
if err != nil {
return err
}
return s.writeFile(s.signedPreKeysFilePath(id), b)
}
func exists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func (s *store) valid() bool {
return s.ContainsPreKey(lastResortPreKeyID)
}
func (s *store) ContainsPreKey(id uint32) bool {
return exists(s.preKeysFilePath(id))
}
func (s *store) ContainsSignedPreKey(id uint32) bool {
return exists(s.signedPreKeysFilePath(id))
}
func (s *store) RemovePreKey(id uint32) {
_ = os.Remove(s.preKeysFilePath(id))
}
func (s *store) RemoveSignedPreKey(id uint32) {
_ = os.Remove(s.signedPreKeysFilePath(id))
}
// HTTP API store
func (s *store) storeHTTPPassword(password string) {
passFile := filepath.Join(s.identityDir, "http_password")
s.writeFile(passFile, []byte(password))
}
func (s *store) loadHTTPPassword() (string, error) {
passFile := filepath.Join(s.identityDir, "http_password")
b, err := s.readFile(passFile)
if err != nil {
return "", err
}
return string(b), nil
}
func (s *store) storeHTTPSignalingKey(key []byte) {
keyFile := filepath.Join(s.identityDir, "http_signaling_key")
s.writeFile(keyFile, key)
}
func (s *store) loadHTTPSignalingKey() ([]byte, error) {
keyFile := filepath.Join(s.identityDir, "http_signaling_key")
b, err := s.readFile(keyFile)
if err != nil {
return nil, err
}
return b, nil
}
// Session store
func (s *store) sessionFilePath(recipientID string, deviceID uint32) string {
return filepath.Join(s.sessionsDir, fmt.Sprintf("%s_%d", recipientID, deviceID))
}
func (s *store) GetSubDeviceSessions(recipientID string) []uint32 {
sessions := []uint32{}
filepath.Walk(s.sessionsDir, func(path string, fi os.FileInfo, err error) error {
if !fi.IsDir() {
i := strings.LastIndex(path, "_")
id, _ := strconv.Atoi(path[i+1:])
sessions = append(sessions, uint32(id))
}
return nil
})
return sessions
}
func (s *store) LoadSession(recipientID string, deviceID uint32) (*axolotl.SessionRecord, error) {
sfile := s.sessionFilePath(recipientID, deviceID)
b, err := s.readFile(sfile)
if err != nil {
return axolotl.NewSessionRecord(), nil
}
record, err := axolotl.LoadSessionRecord(b)
if err != nil {
return nil, err
}
return record, nil
}
func (s *store) StoreSession(recipientID string, deviceID uint32, record *axolotl.SessionRecord) error {
sfile := s.sessionFilePath(recipientID, deviceID)
b, err := record.Serialize()
if err != nil {
return err
}
return s.writeFile(sfile, b)
}
func (s *store) ContainsSession(recipientID string, deviceID uint32) bool {
sfile := s.sessionFilePath(recipientID, deviceID)
return exists(sfile)
}
func (s *store) DeleteSession(recipientID string, deviceID uint32) {
sfile := s.sessionFilePath(recipientID, deviceID)
_ = os.Remove(sfile)
}
func (s *store) DeleteAllSessions(recipientID string) {
log.Debugf("Deleting all sessions for %s\n", recipientID)
sessions := s.GetSubDeviceSessions(recipientID)
for _, dev := range sessions {
_ = os.Remove(s.sessionFilePath(recipientID, dev))
}
}
var textSecureStore *store
func setupStore() error {
var err error
password := ""
if !config.ConfigFile.UnencryptedStorage {
password = config.ConfigFile.StoragePassword
if password == "" {
password = client.GetStoragePassword()
}
}
textSecureStore, err = newStore(password, config.ConfigFile.StorageDir)
if err != nil {
return err
}
if err := setupGroups(); err != nil {
return err
}
return nil
}