-
Notifications
You must be signed in to change notification settings - Fork 0
/
store.go
435 lines (344 loc) · 9.03 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
package store
import (
"github.com/schmich/ward/crypto"
_ "github.com/mattn/go-sqlite3"
"database/sql"
"strings"
"errors"
"fmt"
"os"
)
type Store struct {
db *sql.DB
passwordCipher *crypto.Cipher
keyCipher *crypto.Cipher
}
type Credential struct {
id int
Login string `json:"login"`
Password string `json:"password"`
Realm string `json:"realm"`
Note string `json:"note"`
}
func Open(fileName string, password string) (*Store, error) {
if _, err := os.Stat(fileName); os.IsNotExist(err) {
return nil, errors.New("Credential database does not exist.")
}
db, err := sql.Open("sqlite3", fileName)
if err != nil {
return nil, err
}
query := `
SELECT password_salt, password_stretch, password_nonce, encrypted_key, key_nonce, version
FROM settings
`
rows, err := db.Query(query)
if err != nil {
return nil, err
}
defer rows.Close()
rows.Next()
var passwordSalt, passwordNonce, encryptedKey, keyNonce []byte
var passwordStretch, version int
rows.Scan(&passwordSalt, &passwordStretch, &passwordNonce, &encryptedKey, &keyNonce, &version)
if version > 1 {
return nil, errors.New(fmt.Sprintf("Unsupported version: %d.", version))
}
if len(encryptedKey) <= 0 {
return nil, errors.New("Invalid encrypted key.")
}
passwordKey, err := crypto.LoadPasswordKey(password, passwordSalt, passwordStretch)
if err != nil {
return nil, err
}
passwordCipher, err := crypto.LoadCipher(passwordKey, passwordNonce)
if err != nil {
return nil, err
}
key, err := passwordCipher.TryDecrypt(encryptedKey)
if err != nil {
return nil, err
}
keyCipher, err := crypto.LoadCipher(key, keyNonce)
if err != nil {
return nil, err
}
return &Store {
db: db,
passwordCipher: passwordCipher,
keyCipher: keyCipher,
}, nil
}
func createCipher(db *sql.DB, password string, passwordStretch int) (*crypto.Cipher, *crypto.Cipher, error) {
const version = 1
tx, err := db.Begin()
if err != nil {
return nil, nil, err
}
defer func() {
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
}()
passwordKey, passwordSalt, err := crypto.NewPasswordKey(password, passwordStretch)
if err != nil {
return nil, nil, err
}
passwordCipher, err := crypto.NewCipher(passwordKey)
if err != nil {
return nil, nil, err
}
key := crypto.NewKey()
keyCipher, err := crypto.NewCipher(key)
if err != nil {
return nil, nil, err
}
insert, err := tx.Prepare(`
INSERT INTO settings (password_salt, password_stretch, password_nonce, encrypted_key, key_nonce, version)
VALUES (?, ?, ?, ?, ?, ?)
`)
if err != nil {
return nil, nil, err
}
defer insert.Close()
encryptedKey := passwordCipher.Encrypt(key)
insert.Exec(
passwordSalt,
passwordStretch,
passwordCipher.GetNonce(),
encryptedKey,
keyCipher.GetNonce(),
version)
return passwordCipher, keyCipher, nil
}
func Create(fileName string, password string, passwordStretch int) (*Store, error) {
if _, err := os.Stat(fileName); err == nil {
return nil, errors.New("Credential database already exists.")
}
db, err := sql.Open("sqlite3", fileName)
if err != nil {
return nil, err
}
defer func() {
if err != nil {
db.Close()
os.Remove(fileName)
}
}()
create := `
CREATE TABLE credentials (
id INTEGER NOT NULL PRIMARY KEY,
login BLOB,
password BLOB,
realm BLOB,
note BLOB
);
CREATE TABLE settings (
password_salt BLOB,
password_stretch INTEGER,
password_nonce BLOB,
encrypted_key BLOB,
key_nonce BLOB,
version INTEGER
);
`
_, err = db.Exec(create)
if err != nil {
return nil, err
}
passwordCipher, keyCipher, err := createCipher(db, password, passwordStretch)
if err != nil {
return nil, err
}
return &Store {
db: db,
passwordCipher: passwordCipher,
keyCipher: keyCipher,
}, nil
}
func (store *Store) updateNonce(passwordNonce, keyNonce []byte, tx *sql.Tx) error {
update, err := tx.Prepare("UPDATE settings SET password_nonce=?, key_nonce=?")
if err != nil {
return err
}
defer update.Close()
update.Exec(passwordNonce, keyNonce)
return nil
}
func (store *Store) update(updateFn func(*sql.Tx) error) error {
tx, err := store.db.Begin()
if err != nil {
return err
}
defer func() {
if err != nil {
tx.Rollback()
} else {
tx.Commit()
}
}()
if err = updateFn(tx); err != nil {
return err
}
return store.updateNonce(
store.passwordCipher.GetNonce(),
store.keyCipher.GetNonce(),
tx)
}
func (store *Store) AddCredential(credential *Credential) {
store.update(func(tx *sql.Tx) error {
insert, err := tx.Prepare(`
INSERT INTO credentials (login, password, realm, note)
VALUES (?, ?, ?, ?)
`)
if err != nil {
return err
}
defer insert.Close()
insert.Exec(
store.keyCipher.Encrypt([]byte(credential.Login)),
store.keyCipher.Encrypt([]byte(credential.Password)),
store.keyCipher.Encrypt([]byte(credential.Realm)),
store.keyCipher.Encrypt([]byte(credential.Note)),
)
return nil
})
}
func (store *Store) eachCredential() chan *Credential {
yield := make(chan *Credential)
go func() {
defer close(yield)
rows, err := store.db.Query(`
SELECT id, login, password, realm, note
FROM credentials
`)
if err != nil {
panic(err)
}
defer rows.Close()
for rows.Next() {
var id int
var cipherLogin, cipherPassword, cipherRealm, cipherNote []byte
rows.Scan(&id, &cipherLogin, &cipherPassword, &cipherRealm, &cipherNote)
credential := &Credential {
id: id,
Login: string(store.keyCipher.Decrypt(cipherLogin)),
Password: string(store.keyCipher.Decrypt(cipherPassword)),
Realm: string(store.keyCipher.Decrypt(cipherRealm)),
Note: string(store.keyCipher.Decrypt(cipherNote)),
}
yield <- credential
}
}()
return yield
}
func (store *Store) AllCredentials() []*Credential {
credentials := make([]*Credential, 0)
for credential := range store.eachCredential() {
credentials = append(credentials, credential)
}
return credentials
}
func (store *Store) FindCredentials(query []string) []*Credential {
matches := make([]*Credential, 0)
patterns := make([]string, len(query))
for i, queryString := range query {
patterns[i] = strings.ToLower(queryString)
}
for credential := range store.eachCredential() {
valid := true
llogin := strings.ToLower(credential.Login)
lrealm := strings.ToLower(credential.Realm)
lnote := strings.ToLower(credential.Note)
for _, pattern := range patterns {
if !strings.Contains(llogin, pattern) && !strings.Contains(lrealm, pattern) && !strings.Contains(lnote, pattern) {
valid = false
break
}
}
if (valid) {
matches = append(matches, credential)
}
}
return matches
}
func (store *Store) UpdateCredential(credential *Credential) {
if credential.id == 0 {
panic("Invalid credential ID.")
}
store.update(func(tx *sql.Tx) error {
update, err := tx.Prepare(`
UPDATE credentials
SET login=?, password=?, realm=?, note=?
WHERE id=?
`)
if err != nil {
return err
}
defer update.Close()
update.Exec(
store.keyCipher.Encrypt([]byte(credential.Login)),
store.keyCipher.Encrypt([]byte(credential.Password)),
store.keyCipher.Encrypt([]byte(credential.Realm)),
store.keyCipher.Encrypt([]byte(credential.Note)),
credential.id,
)
return nil
})
}
func (store *Store) DeleteCredential(credential *Credential) {
if credential.id == 0 {
panic("Invalid credential ID.")
}
store.update(func(tx *sql.Tx) error {
delete, err := tx.Prepare("DELETE FROM credentials WHERE id=?")
if err != nil {
return err
}
defer delete.Close()
delete.Exec(credential.id)
return nil
})
}
func (store *Store) UpdateMasterPassword(password string, passwordStretch int) error {
return store.update(func(tx *sql.Tx) error {
query := "SELECT encrypted_key FROM settings"
rows, err := tx.Query(query)
if err != nil {
return err
}
defer rows.Close()
rows.Next()
var encryptedKey []byte
rows.Scan(&encryptedKey)
key := store.passwordCipher.Decrypt(encryptedKey)
passwordKey, passwordSalt, err := crypto.NewPasswordKey(password, passwordStretch)
if err != nil {
return err
}
passwordCipher, err := crypto.NewCipher(passwordKey)
if err != nil {
return err
}
update, err := tx.Prepare(`
UPDATE settings
SET password_salt=?, password_stretch=?, password_nonce=?, encrypted_key=?
`)
if err != nil {
return err
}
defer update.Close()
update.Exec(
passwordSalt,
passwordStretch,
passwordCipher.GetNonce(),
passwordCipher.Encrypt(key))
store.passwordCipher = passwordCipher
return nil
})
}
func (store *Store) Close() {
store.db.Close()
}