forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_keystore.go
384 lines (315 loc) · 9.87 KB
/
file_keystore.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
package keystore
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/sha512"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime"
"sync"
"golang.org/x/crypto/pbkdf2"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/common/file"
)
const (
filePermission = 0600
// Encryption Related constants
iVLength = 12
saltLength = 64
iterationsCount = 10000
keyLength = 32
)
// Version of the keystore format, will be added at the beginning of the file.
var version = []byte("v1")
// FileKeystore Allows to store key / secrets pair securely into an encrypted local file.
type FileKeystore struct {
sync.RWMutex
Path string
secrets map[string]serializableSecureString
dirty bool
password *SecureString
}
// Allow the original SecureString type to be correctly serialized to json.
type serializableSecureString struct {
*SecureString
Value []byte `json:"value"`
}
// NewFileKeystore returns an new File based keystore or an error, currently users cannot set their
// own password on the keystore, the default password will be an empty string. When the keystore
// is initialied the secrets are automatically loaded into memory.
func NewFileKeystore(keystoreFile string) (Keystore, error) {
return NewFileKeystoreWithPassword(keystoreFile, NewSecureString([]byte("")))
}
// NewFileKeystoreWithPassword return a new File based keystore or an error, allow to define what
// password to use to create the keystore.
func NewFileKeystoreWithPassword(keystoreFile string, password *SecureString) (Keystore, error) {
keystore := FileKeystore{
Path: keystoreFile,
dirty: false,
password: password,
secrets: make(map[string]serializableSecureString),
}
err := keystore.load()
if err != nil {
return nil, err
}
return &keystore, nil
}
// Retrieve return a SecureString instance that will contains both the key and the secret.
func (k *FileKeystore) Retrieve(key string) (*SecureString, error) {
k.RLock()
defer k.RUnlock()
secret, ok := k.secrets[key]
if !ok {
return nil, ErrKeyDoesntExists
}
return NewSecureString(secret.Value), nil
}
// Store add the key pair to the secret store and mark the store as dirty.
func (k *FileKeystore) Store(key string, value []byte) error {
k.Lock()
defer k.Unlock()
k.secrets[key] = serializableSecureString{Value: value}
k.dirty = true
return nil
}
// Delete an existing key from the store and mark the store as dirty.
func (k *FileKeystore) Delete(key string) error {
k.Lock()
defer k.Unlock()
delete(k.secrets, key)
k.dirty = true
return nil
}
// Save persists the in memory data to disk if needed.
func (k *FileKeystore) Save() error {
k.Lock()
err := k.doSave(true)
k.Unlock()
return err
}
// List return the availables keys.
func (k *FileKeystore) List() ([]string, error) {
k.RLock()
defer k.RUnlock()
keys := make([]string, 0, len(k.secrets))
for key := range k.secrets {
keys = append(keys, key)
}
return keys, nil
}
// GetConfig returns common.Config representation of the key / secret pair to be merged with other
// loaded configuration.
func (k *FileKeystore) GetConfig() (*common.Config, error) {
k.RLock()
defer k.RUnlock()
configHash := make(map[string]interface{})
for key, secret := range k.secrets {
configHash[key] = string(secret.Value)
}
return common.NewConfigFrom(configHash)
}
// Create create an empty keystore, if the store already exist we will return an error.
func (k *FileKeystore) Create(override bool) error {
k.Lock()
k.secrets = make(map[string]serializableSecureString)
k.dirty = true
err := k.doSave(override)
k.Unlock()
return err
}
// IsPersisted return if the keystore is physically persisted on disk.
func (k *FileKeystore) IsPersisted() bool {
k.Lock()
defer k.Unlock()
// We just check if the file is present on disk, we don't need to do any validation
// for a file based keystore, since all the keys will be fetched when we initialize the object
// if the file is invalid it will already fails. Creating a new FileKeystore will raise
// any errors concerning the permissions
f, err := os.OpenFile(k.Path, os.O_RDONLY, filePermission)
if err != nil {
return false
}
f.Close()
return true
}
// doSave lock/unlocking of the ressource need to be done by the caller.
func (k *FileKeystore) doSave(override bool) error {
if k.dirty == false {
return nil
}
temporaryPath := fmt.Sprintf("%s.tmp", k.Path)
w := new(bytes.Buffer)
jsonEncoder := json.NewEncoder(w)
if err := jsonEncoder.Encode(k.secrets); err != nil {
return fmt.Errorf("cannot serialize the keystore before saving it to disk: %v", err)
}
encrypted, err := k.encrypt(w)
if err != nil {
return fmt.Errorf("cannot encrypt the keystore: %v", err)
}
flags := os.O_RDWR | os.O_CREATE
if override {
flags |= os.O_TRUNC
} else {
flags |= os.O_EXCL
}
f, err := os.OpenFile(temporaryPath, flags, filePermission)
if err != nil {
return fmt.Errorf("cannot open file to save the keystore to '%s', error: %s", k.Path, err)
}
f.Write(version)
base64Encoder := base64.NewEncoder(base64.StdEncoding, f)
io.Copy(base64Encoder, encrypted)
base64Encoder.Close()
f.Sync()
f.Close()
err = file.SafeFileRotate(k.Path, temporaryPath)
if err != nil {
os.Remove(temporaryPath)
return fmt.Errorf("cannot replace the existing keystore, with the new keystore file at '%s', error: %s", k.Path, err)
}
os.Remove(temporaryPath)
k.dirty = false
return nil
}
func (k *FileKeystore) load() error {
k.Lock()
defer k.Unlock()
f, err := os.OpenFile(k.Path, os.O_RDONLY, filePermission)
if err != nil {
if os.IsNotExist(err) {
return nil
}
return err
}
defer f.Close()
if common.IsStrictPerms() {
if err := k.checkPermissions(k.Path); err != nil {
return err
}
}
raw, err := ioutil.ReadAll(f)
if err != nil {
return err
}
v := raw[0:len(version)]
if !bytes.Equal(v, version) {
return fmt.Errorf("keystore format doesn't match expected version: '%s' got '%s'", version, v)
}
base64Content := raw[len(version):]
if len(base64Content) == 0 {
return fmt.Errorf("corrupt or empty keystore")
}
base64Decoder := base64.NewDecoder(base64.StdEncoding, bytes.NewReader(base64Content))
plaintext, err := k.decrypt(base64Decoder)
if err != nil {
return fmt.Errorf("could not decrypt the keystore: %v", err)
}
jsonDecoder := json.NewDecoder(plaintext)
return jsonDecoder.Decode(&k.secrets)
}
// Encrypt the data payload using a derived keys and the AES-256-GCM algorithm.
func (k *FileKeystore) encrypt(reader io.Reader) (io.Reader, error) {
// randomly generate the salt and the initialization vector, this information will be saved
// on disk in the file as part of the header
iv, err := common.RandomBytes(iVLength)
if err != nil {
return nil, err
}
salt, err := common.RandomBytes(saltLength)
if err != nil {
return nil, err
}
// Stretch the user provided key
password, _ := k.password.Get()
passwordBytes := k.hashPassword(password, salt)
// Select AES-256: because len(passwordBytes) == 32 bytes
block, err := aes.NewCipher(passwordBytes)
if err != nil {
return nil, fmt.Errorf("could not create the keystore cipher to encrypt, error: %s", err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("could not create the keystore cipher to encrypt, error: %s", err)
}
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("could not read unencrypted data, error: %s", err)
}
encodedBytes := aesgcm.Seal(nil, iv, data, nil)
// Generate the payload with all the additional information required to decrypt the
// output format of the document: VERSION|SALT|IV|PAYLOAD
buf := bytes.NewBuffer(salt)
buf.Write(iv)
buf.Write(encodedBytes)
return buf, nil
}
// should receive an io.reader...
func (k *FileKeystore) decrypt(reader io.Reader) (io.Reader, error) {
data, err := ioutil.ReadAll(reader)
if err != nil {
return nil, fmt.Errorf("could not read all the data from the encrypted file, error: %s", err)
}
if len(data) < saltLength+iVLength+1 {
return nil, fmt.Errorf("missing information in the file for decrypting the keystore")
}
// extract the necessary information to decrypt the data from the data payload
salt := data[0:saltLength]
iv := data[saltLength : saltLength+iVLength]
encodedBytes := data[saltLength+iVLength:]
password, _ := k.password.Get()
passwordBytes := k.hashPassword(password, salt)
block, err := aes.NewCipher(passwordBytes)
if err != nil {
return nil, fmt.Errorf("could not create the keystore cipher to decrypt the data: %s", err)
}
aesgcm, err := cipher.NewGCM(block)
if err != nil {
return nil, fmt.Errorf("could not create the keystore cipher to decrypt the data: %s", err)
}
decodedBytes, err := aesgcm.Open(nil, iv, encodedBytes, nil)
if err != nil {
return nil, fmt.Errorf("could not decrypt keystore data: %s", err)
}
return bytes.NewReader(decodedBytes), nil
}
// checkPermission enforces permission on the keystore file itself, the file should have strict
// permission (0600) and the keystore should refuses to start if its not the case.
func (k *FileKeystore) checkPermissions(f string) error {
if runtime.GOOS == "windows" {
return nil
}
info, err := file.Stat(f)
if err != nil {
return err
}
euid := os.Geteuid()
fileUID, _ := info.UID()
perm := info.Mode().Perm()
if fileUID != 0 && euid != fileUID {
return fmt.Errorf(`config file ("%v") must be owned by the beat user `+
`(uid=%v) or root`, f, euid)
}
// Test if group or other have write permissions.
if perm != filePermission {
nameAbs, err := filepath.Abs(f)
if err != nil {
nameAbs = f
}
return fmt.Errorf(`file ("%v") can only be writable and readable by the `+
`owner but the permissions are "%v" (to fix the permissions use: `+
`'chmod go-wrx %v')`,
f, perm, nameAbs)
}
return nil
}
func (k *FileKeystore) hashPassword(password, salt []byte) []byte {
return pbkdf2.Key(password, salt, iterationsCount, keyLength, sha512.New)
}