/
file.go
258 lines (231 loc) · 5.95 KB
/
file.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
package backend
import (
"context"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"os"
"os/user"
"path"
"time"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/chacha20poly1305"
)
type FileStore struct {
storeLocation string
projectID string
masterPassword []byte
}
func NewFileStore(storeLocation, projectID string) *FileStore {
return &FileStore{
projectID: projectID,
storeLocation: storeFileLocation(storeLocation, projectID),
}
}
type FileStoreEntry struct {
Value []byte
KeyInfo Key
}
// Get reads the store from file, fetches and decrypt the value for given key
func (f *FileStore) Get(_ context.Context, _ *Profile, key string) ([]byte, error) {
storeData, err := f.getStore()
if err != nil {
return nil, err
}
for _, data := range storeData {
if data.KeyInfo.Name == key {
data, err := f.decrypt(data.Value, f.masterPassword)
if err != nil {
return nil, fmt.Errorf("message authentication failed")
}
return data, nil
}
}
return nil, fmt.Errorf("%s not found", key)
}
// List reads the store from file, and fetch all keys
func (f *FileStore) List(_ context.Context, _ *Profile) (keys []Key, err error) {
storeData, err := f.getStore()
if err != nil {
return nil, err
}
for _, info := range storeData {
keys = append(keys, info.KeyInfo)
}
return keys, err
}
// CheckExists checks if given key exists in the (file)store
func (f *FileStore) CheckExists(_ context.Context, _ *Profile, key string) (bool, error) {
storeData, err := f.getStore()
if err != nil {
return false, err
}
for _, each := range storeData {
if each.KeyInfo.Name == key {
return true, nil
}
}
return false, nil
}
// Put a new Key with encrypted password in the store. Put overwrites the entire store file with the updated store
func (f *FileStore) Put(_ context.Context, _ *Profile, key, value string, overwrite bool) error {
if err := f.createStoreIfNotExists(); err != nil {
return err
}
encryptedData, err := f.encrypt([]byte(value), f.masterPassword)
if err != nil {
return err
}
owner := ""
currUser, err := user.Current()
if err == nil {
owner = currUser.Name
}
newStore := FileStoreEntry{
Value: encryptedData,
KeyInfo: Key{
Name: key,
CreatedAt: time.Now(),
Owner: owner,
Info: "",
},
}
var store []FileStoreEntry
discStoreEntries, err := f.getStore()
if err != nil {
return err
}
if discStoreEntries != nil {
store = append(store, discStoreEntries...)
}
store = append(store, newStore)
data, err := json.Marshal(&store)
if err != nil {
return err
}
if err := os.WriteFile(f.storeLocation, data, 0600); err != nil {
return err
}
return nil
}
// Delete a key from the store. Delete overwrites the entire store file with the updated store values
func (f *FileStore) Delete(_ context.Context, _ *Profile, key string) error {
discStoreEntries, err := f.getStore()
if err != nil {
return err
}
var newDiscStore []FileStoreEntry
for _, entry := range discStoreEntries {
if entry.KeyInfo.Name != key {
newDiscStore = append(newDiscStore, entry)
}
}
data := []byte("")
// prevents "nil" being written to file
if len(newDiscStore) > 0 {
data, err = json.Marshal(&newDiscStore)
if err != nil {
return err
}
}
if err := os.WriteFile(f.storeLocation, data, 0600); err != nil {
return err
}
return nil
}
func (f *FileStore) Close() error {
return nil
}
// SetMasterPassword is not relevant for this backend
func (f *FileStore) SetMasterPassword(password []byte) {
f.masterPassword = password
}
// encrypt data based on the argon2 hashing algorithm and xchacha20 cipher algorithm
func (f *FileStore) encrypt(data, pass []byte) ([]byte, error) {
salt := makeNonce(16)
key := argon2.Key(pass, salt, 3, 32*1024, 4, 32)
cipher, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
}
nonce := makeNonce(24)
cipherText := cipher.Seal(nil, nonce, data, nil)
return append(append(salt, nonce...), cipherText...), nil
}
// decrypt data based on the argon2 hashing algorithm and xchacha20 cipher algorithm
func (f *FileStore) decrypt(data, pass []byte) ([]byte, error) {
if len(data) < 40 {
return nil, errors.New("data has incorrect format")
}
salt := data[:16]
nonce := data[16:40]
data = data[40:]
key := argon2.Key(pass, salt, 3, 32*1024, 4, 32)
cipher, err := chacha20poly1305.NewX(key)
if err != nil {
return nil, err
}
plaintext, err := cipher.Open(nil, nonce, data, nil)
if err != nil {
return nil, err
}
return plaintext, nil
}
// getStore loads the file based store from disc
func (f *FileStore) getStore() ([]FileStoreEntry, error) {
if err := f.createStoreIfNotExists(); err != nil {
return nil, err
}
data, err := os.ReadFile(f.storeLocation)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, nil
}
var store []FileStoreEntry
if err := json.Unmarshal(data, &store); err != nil {
return nil, err
}
return store, nil
}
// createStoreIfNotExists creates the file store on disc if it does not exists and initializes with an empty value
func (f *FileStore) createStoreIfNotExists() error {
if _, err := os.Stat(f.storeLocation); err != nil {
if errors.Is(err, os.ErrNotExist) {
err = os.WriteFile(f.storeLocation, []byte(""), 0600)
if err != nil {
return err
}
}
return err
}
return nil
}
func (f *FileStore) SetParameter(key string, value interface{}) {
if key == "masterPassword" {
if val, ok := value.([]byte); ok {
f.masterPassword = val
}
}
}
// makeNonce generates a secure random nonce used for encryption of the passwords
func makeNonce(len int) []byte {
salt := make([]byte, len)
n, err := rand.Reader.Read(salt)
if err != nil {
panic(err)
}
if n != len {
panic("An error occurred while generating salt")
}
return salt
}
// secretStoreLocation calculates the path to the file based store
func storeFileLocation(location, projectID string) string {
if len(location) == 0 {
location = path.Join(os.Getenv("HOME"), fmt.Sprintf("%s.secrets.kiya", projectID))
}
return location
}