-
Notifications
You must be signed in to change notification settings - Fork 27
/
ghost.py
1819 lines (1539 loc) · 58.6 KB
/
ghost.py
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2015,2016 Nir Cohen
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# TODO: Add categories
# TODO: Add ghost backend which exports and loads stuff
# TODO: Document how to export a key to a file using bash redirection
import os
import sys
import json
import time
import uuid
import base64
import random
import string
import difflib
import logging
import binascii
import warnings
import tempfile
import subprocess
from datetime import datetime
try:
from urllib.parse import urljoin, urlparse
except ImportError:
from urlparse import urljoin, urlparse
import click
from tinydb import TinyDB, Query
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
try:
from sqlalchemy import (Column,
Table,
MetaData,
String,
PickleType,
create_engine,
sql)
from sqlalchemy_utils import database_exists, create_database
SQLALCHEMY_EXISTS = True
except ImportError:
SQLALCHEMY_EXISTS = False
try:
import requests
REQUESTS_EXISTS = True
except ImportError:
REQUESTS_EXISTS = False
try:
import hvac
HVAC_EXISTS = True
except ImportError:
HVAC_EXISTS = False
try:
import elasticsearch
ES_EXISTS = True
except ImportError:
ES_EXISTS = False
try:
import boto3
import botocore
S3_EXISTS = True
except ImportError:
S3_EXISTS = False
GHOST_HOME = os.path.join(os.path.expanduser('~'), '.ghost')
STORAGE_DEFAULT_PATH_MAPPING = {
'tinydb': os.path.join(GHOST_HOME, 'stash.json'),
'sqlalchemy': os.path.join(GHOST_HOME, 'stash.sql'),
'consul': 'http://127.0.0.1:8500',
'vault': 'http://127.0.0.1:8200',
'elasticsearch': 'http://127.0.0.1:9200'
}
AUDIT_LOG_FILE_PATH = os.environ.get(
'GHOST_AUDIT_LOG', os.path.join(GHOST_HOME, 'audit.log'))
KEY_FIELD_SCHEMA = {
'ssh': {
'requires': ['conn'],
'oneof': [['ssh_key_path', 'ssh_key']],
},
'secret': {
'requires': [],
'oneof': [[]],
'optional': [],
'optionaloneof': [[]]
}
}
PASSPHRASE_FILENAME = 'passphrase.ghost'
POTENTIAL_PASSPHRASE_LOCATIONS = [
os.path.abspath(PASSPHRASE_FILENAME),
os.path.join(GHOST_HOME, PASSPHRASE_FILENAME),
]
if not os.name == 'nt':
POTENTIAL_PASSPHRASE_LOCATIONS.append(
os.path.join(os.sep, 'etc', 'ghost', PASSPHRASE_FILENAME))
# audit logger
def get_logger():
handler = logging.FileHandler(AUDIT_LOG_FILE_PATH)
formatter = logging.Formatter('%(asctime)s - %(message)s')
handler.setFormatter(formatter)
logger = logging.getLogger(__file__)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
return logger
def audit(storage, action, message):
logger = get_logger()
logger.info('[%s] [%s] - %s', storage, action, message)
def get_passphrase(passphrase=None):
"""Return a passphrase as found in a passphrase.ghost file
Lookup is done in three locations on non-Windows systems and two on Windows
All:
`cwd/passphrase.ghost`
`~/.ghost/passphrase.ghost`
Only non-Windows:
`/etc/ghost/passphrase.ghost`
"""
for passphrase_file_path in POTENTIAL_PASSPHRASE_LOCATIONS:
if os.path.isfile(passphrase_file_path):
with open(passphrase_file_path) as passphrase_file:
return passphrase_file.read()
return passphrase
class Stash(object):
def __init__(self,
storage,
passphrase=None,
passphrase_size=12,
iterations=1000000):
self._storage = storage
passphrase = passphrase or generate_passphrase(passphrase_size)
self.passphrase = passphrase
self._iterations = iterations
# TODO: Consider base64 encoding instead of hexlification
_key = None
def init(self):
# For the audit log
if not os.path.isdir(GHOST_HOME):
os.makedirs(GHOST_HOME)
if self.is_initialized:
return
self._storage.init()
self.put(
name='stored_passphrase',
value={'passphrase': self.passphrase},
lock=True)
return self.passphrase
@property
def is_initialized(self):
if self._storage.is_initialized:
self.passphrase = get_passphrase(self.passphrase)
if self.get('stored_passphrase'):
return True
return False
def _validate_key_schema(self, value, key_type):
# TODO: Replace with normal, jsonschema style validation
# 'ssh': {
# 'requires': ['conn'],
# 'oneof': [['ssh_key_path', 'ssh_key']]
# }
schema = KEY_FIELD_SCHEMA[key_type]
def validate_single(list_of_keys, value):
for key in list_of_keys:
if key not in value.keys():
raise GhostError(
'Must provide value `{0}` for key of type {1}'
.format(key, key_type))
def validate_oneof(key_sets, value):
for key_set in key_sets:
if key_set:
keys_exist = [k in value.keys() for k in key_set]
if not (any(keys_exist) and not all(keys_exist)):
raise GhostError(
'Must provide one of {0} for key of type {1}'
.format(key_set, key_type))
validate_single(schema['requires'], value)
validate_oneof(schema['oneof'], value)
# validate_single(schema['optional'], value)
# validate_oneof(schema['optionaloneof'], value)
def put(self,
name,
value=None,
modify=False,
metadata=None,
description='',
encrypt=True,
lock=False,
key_type='secret',
add=False):
"""Put a key inside the stash
if key exists and modify true: delete and create
if key exists and modify false: fail
if key doesn't exist and modify true: fail
if key doesn't exist and modify false: create
`name` is unique and cannot be changed.
`value` must be provided if the key didn't already exist, otherwise,
the previous value will be retained.
`created_at` will be left unmodified if the key
already existed. Otherwise, the current time will be used.
`modified_at` will be changed to the current time
if the field is being modified.
`metadata` will be updated if provided. If it wasn't
provided the field from the existing key will be used and the
same goes for the `uid` which will be generated if it didn't
previously exist.
`lock` will lock the key to prevent it from being modified or deleted
`add` allows to add values to an existing key instead of overwriting.
Returns the id of the key in the database
"""
def assert_key_is_unlocked(existing_key):
if existing_key and existing_key.get('lock'):
raise GhostError(
'Key `{0}` is locked and therefore cannot be modified. '
'Unlock the key and try again'.format(name))
def assert_value_provided_for_new_key(value, existing_key):
if not value and not existing_key.get('value'):
raise GhostError('You must provide a value for new keys')
self._assert_valid_stash()
self._validate_key_schema(value, key_type)
if value and encrypt and not isinstance(value, dict):
raise GhostError('Value must be of type dict')
# TODO: This should be refactored. `_handle_existing_key` deletes
# the key rather implicitly. It shouldn't do that.
# `existing_key` will be an empty dict if it doesn't exist
key = self._handle_existing_key(name, modify or add)
assert_key_is_unlocked(key)
assert_value_provided_for_new_key(value, key)
new_key = dict(name=name, lock=lock)
if value:
# TODO: fix edge case in which encrypt is false and yet we might
# try to add to an existing key. encrypt=false is only used when
# `load`ing into a new stash, but someone might use it directly
# from the API.
if add:
value = self._update_existing_key(key, value)
new_key['value'] = self._encrypt(value) if encrypt else value
else:
new_key['value'] = key.get('value')
# TODO: Treat a case in which we try to update an existing key
# but don't provide a value in which nothing will happen.
new_key['description'] = description or key.get('description')
new_key['created_at'] = key.get('created_at') or _get_current_time()
new_key['modified_at'] = _get_current_time()
new_key['metadata'] = metadata or key.get('metadata')
new_key['uid'] = key.get('uid') or str(uuid.uuid4())
new_key['type'] = key.get('type') or key_type
key_id = self._storage.put(new_key)
audit(
storage=self._storage.db_path,
action='MODIFY' if (modify or add) else 'PUT',
message=json.dumps(dict(
key_name=new_key['name'],
value='HIDDEN',
description=new_key['description'],
uid=new_key['uid'],
metadata=json.dumps(new_key['metadata']),
lock=new_key['lock'],
type=new_key['type'])))
return key_id
def _update_existing_key(self, existing_key, value):
current_value = self._decrypt(existing_key.get('value')).copy()
# We update current_value with value to overwrite
# existing values if the user provided overriding values
current_value.update(value)
return current_value
def _handle_existing_key(self, key_name, modify):
existing_key = self._storage.get(key_name) or {}
if existing_key and modify:
# TODO: Consider replacing this with self.delete(key_name)
if not existing_key['lock']:
self._storage.delete(key_name)
elif existing_key:
raise GhostError(
'Key `{0}` already exists. Use the modify flag to overwrite'
.format(key_name))
elif modify:
raise GhostError(
"Key `{0}` doesn't exist and therefore cannot be modified"
.format(key_name))
return existing_key
def get(self, key_name, decrypt=True):
"""Return a key with its parameters if it was found.
"""
self._assert_valid_stash()
key = self._storage.get(key_name).copy()
if not key.get('value'):
return None
if decrypt:
key['value'] = self._decrypt(key['value'])
audit(
storage=self._storage.db_path,
action='GET',
message=json.dumps(dict(key_name=key_name)))
return key
def list(self,
key_name=None,
max_suggestions=100,
cutoff=0.5,
locked_only=False,
key_type=None):
"""Return a list of all keys.
"""
self._assert_valid_stash()
key_list = [k for k in self._storage.list()
if k['name'] != 'stored_passphrase' and
(k.get('lock') if locked_only else True)]
if key_type:
# To maintain backward compatibility with keys without a type.
# The default key type is secret, in which case we also look for
# keys with no (None) types.
types = ('secret', None) if key_type == 'secret' else [key_type]
key_list = [k for k in key_list if k.get('type') in types]
key_list = [k['name'] for k in key_list]
if key_name:
if key_name.startswith('~'):
key_list = difflib.get_close_matches(
key_name.lstrip('~'), key_list, max_suggestions, cutoff)
else:
key_list = [k for k in key_list if key_name in k]
audit(
storage=self._storage.db_path,
action='LIST' + ('[LOCKED]' if locked_only else ''),
message=json.dumps(dict()))
return key_list
def delete(self, key_name):
"""Delete a key if it exists.
"""
self._assert_valid_stash()
if key_name == 'stored_passphrase':
raise GhostError(
'`stored_passphrase` is a reserved ghost key name '
'which cannot be deleted')
# TODO: Optimize. We get from the storage twice here for no reason
if not self.get(key_name):
raise GhostError('Key `{0}` not found'.format(key_name))
key = self._storage.get(key_name)
if key.get('lock'):
raise GhostError(
'Key `{0}` is locked and therefore cannot be deleted '
'Please unlock the key and try again'.format(key_name))
deleted = self._storage.delete(key_name)
audit(
storage=self._storage.db_path,
action='DELETE',
message=json.dumps(dict(key_name=key_name)))
if not deleted:
raise GhostError('Failed to delete {0}'.format(key_name))
def _change_lock_state(self, key_name, lock):
self._assert_valid_stash()
if not self.get(key_name):
raise GhostError('Key `{0}` not found'.format(key_name))
key = self._storage.get(key_name)
if not key.get('lock') == lock:
key['lock'] = lock
self._storage.delete(key_name)
self._storage.put(key)
audit(
storage=self._storage.db_path,
action='LOCK' if lock else 'UNLOCK',
message=json.dumps(dict(key_name=key_name)))
def lock(self, key_name):
"""Lock a key to prevent it from being deleted, purged and modified
"""
self._change_lock_state(key_name, lock=True)
def unlock(self, key_name):
"""Unlock a locked key
"""
self._change_lock_state(key_name, lock=False)
def is_locked(self, key_name):
return self._storage.get(key_name).get('lock')
def purge(self, force=False, key_type=None):
"""Purge the stash from all keys
"""
self._assert_valid_stash()
if not force:
raise GhostError(
"The `force` flag must be provided to perform a stash purge. "
"I mean, you don't really want to just delete everything "
"without precautionary measures eh?")
audit(
storage=self._storage.db_path,
action='PURGE',
message=json.dumps(dict()))
for key_name in self.list(key_type=key_type):
self.delete(key_name)
def export(self, output_path=None, decrypt=False):
"""Export all keys in the stash to a list or a file
"""
self._assert_valid_stash()
all_keys = []
for key in self.list():
# We `dict` this as a precaution as tinydb returns
# a tinydb.database.Element instead of a dictionary
# and well.. I ain't taking no chances
all_keys.append(dict(self.get(key, decrypt=decrypt)))
if all_keys:
if output_path:
with open(output_path, 'w') as output_file:
output_file.write(json.dumps(all_keys, indent=4))
return all_keys
else:
raise GhostError('There are no keys to export')
def load(self, origin_passphrase, keys=None, key_file=None):
"""Import keys to the stash from either a list of keys or a file
`keys` is a list of dictionaries created by `self.export`
`stash_path` is a path to a file created by `self.export`
"""
# TODO: Handle keys not dict or key_file not json
self._assert_valid_stash()
# Check if both or none are provided (ahh, the mighty xor)
if not (bool(keys) ^ bool(key_file)):
raise GhostError(
'You must either provide a path to an exported stash file '
'or a list of key dicts to import')
if key_file:
with open(key_file) as stash_file:
keys = json.loads(stash_file.read())
# If the passphrases are the same, there's no reason to decrypt
# and re-encrypt. We can simply pass the value.
decrypt = origin_passphrase != self.passphrase
if decrypt:
# TODO: The fact that we need to create a stub stash just to
# decrypt means we should probably have some encryptor class.
stub = Stash(TinyDBStorage('stub'), origin_passphrase)
# TODO: Handle existing keys when loading
for key in keys:
self.put(
name=key['name'],
value=stub._decrypt(key['value']) if decrypt else key['value'],
metadata=key['metadata'],
description=key['description'],
lock=key.get('lock'),
key_type=key.get('type'),
encrypt=decrypt)
@property
def key(self):
passphrase = self.passphrase.encode('utf-8')
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=b'ghost',
iterations=self._iterations,
backend=default_backend())
self._key = base64.urlsafe_b64encode(kdf.derive(passphrase))
return self._key
@property
def cipher(self):
return Fernet(self.key)
def _encrypt(self, value):
"""Turn a json serializable value into an jsonified, encrypted,
hexa string.
"""
value = json.dumps(value)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
encrypted_value = self.cipher.encrypt(value.encode('utf8'))
hexified_value = binascii.hexlify(encrypted_value).decode('ascii')
return hexified_value
def _decrypt(self, hexified_value):
"""The exact opposite of _encrypt
"""
encrypted_value = binascii.unhexlify(hexified_value)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
jsonified_value = self.cipher.decrypt(
encrypted_value).decode('ascii')
value = json.loads(jsonified_value)
return value
def _assert_valid_stash(self):
if not self._storage.is_initialized:
raise GhostError(
'Stash not initialized. Please initialize it and try again')
else:
try:
key = self._storage.get('stored_passphrase')
if key:
self._decrypt(key['value'])
except InvalidToken:
raise GhostError(
'The passphrase provided is invalid for this stash. '
'Please provide the correct passphrase')
def migrate(src_path,
src_passphrase,
src_backend,
dst_path,
dst_passphrase,
dst_backend):
"""Migrate all keys in a source stash to a destination stash
The migration process will decrypt all keys using the source
stash's passphrase and then encrypt them based on the destination
stash's passphrase.
re-encryption will take place only if the passphrases are differing
"""
src_storage = STORAGE_MAPPING[src_backend](**_parse_path_string(src_path))
dst_storage = STORAGE_MAPPING[dst_backend](**_parse_path_string(dst_path))
src_stash = Stash(src_storage, src_passphrase)
dst_stash = Stash(dst_storage, dst_passphrase)
# TODO: Test that re-encryption does not occur on similar
# passphrases
keys = src_stash.export()
dst_stash.load(src_passphrase, keys=keys)
class TinyDBStorage(object):
def __init__(self,
db_path=STORAGE_DEFAULT_PATH_MAPPING['tinydb'],
stash_name='ghost'):
self.db_path = os.path.expanduser(db_path)
self._db = None
self._stash_name = stash_name
def init(self):
dirname = os.path.dirname(self.db_path)
if dirname and not os.path.isdir(dirname):
os.makedirs(os.path.dirname(self.db_path))
if not os.path.isfile(self.db_path):
open(self.db_path, 'w').close()
@property
def is_initialized(self):
return os.path.isfile(self.db_path)
def put(self, key):
"""Insert the key and return its database id
"""
return self.db.insert(key)
def get(self, key_name):
"""Return a dictionary consisting of the key itself
e.g.
{u'created_at': u'2016-10-10 08:31:53',
u'description': None,
u'metadata': None,
u'modified_at': u'2016-10-10 08:31:53',
u'name': u'aws',
u'uid': u'459f12c0-f341-413e-9d7e-7410f912fb74',
u'value': u'the_value'}
"""
result = self.db.search(Query().name == key_name)
if not result:
return {}
return result[0]
def list(self):
"""Return a list of all keys (not just key names, but rather the keys
themselves).
e.g.
{u'created_at': u'2016-10-10 08:31:53',
u'description': None,
u'metadata': None,
u'modified_at': u'2016-10-10 08:31:53',
u'name': u'aws',
u'uid': u'459f12c0-f341-413e-9d7e-7410f912fb74',
u'value': u'the_value'},
{u'created_at': u'2016-10-10 08:32:29',
u'description': u'my gcp token',
u'metadata': {u'owner': u'nir'},
u'modified_at': u'2016-10-10 08:32:29',
u'name': u'gcp',
u'uid': u'a51a0043-f241-4d52-93c1-266a3c5de15e',
u'value': u'the_value'}]
"""
# TODO: Return only the key names from all storages
return self.db.search(Query().name.matches('.*'))
def delete(self, key_name):
"""Delete the key and return true if the key was deleted, else false
"""
self.db.remove(Query().name == key_name)
return self.get(key_name) == {}
@property
def db(self):
if self._db is None:
self._db = TinyDB(
self.db_path,
indent=4,
sort_keys=True,
separators=(',', ': '))
return self._db.table(self._stash_name)
class SQLAlchemyStorage(object):
def __init__(self,
db_path=STORAGE_DEFAULT_PATH_MAPPING['sqlalchemy'],
stash_name='ghost'):
if not SQLALCHEMY_EXISTS:
raise ImportError('SQLAlchemy must be installed first')
if 'sqlite' in db_path:
self.db_path = db_path
self._local_path = urlparse(db_path).path[1:]
elif '://' in db_path:
self.db_path = db_path
self._local_path = None
else:
self.db_path = 'sqlite:///' + db_path
self._local_path = db_path
self.metadata = MetaData()
self.keys = Table(
stash_name,
self.metadata,
Column('name', String, primary_key=True),
Column('value', PickleType),
Column('description', String),
Column('metadata', PickleType),
Column('modified_at', String),
Column('created_at', String),
Column('uid', String))
self._db = None
def init(self):
if self._local_path:
dirname = os.path.dirname(self._local_path)
if dirname and not os.path.isdir(dirname):
os.makedirs(dirname)
if not database_exists(self.db.url):
create_database(self.db.url)
# More on connection strings for sqlalchemy:
# http://docs.sqlalchemy.org/en/latest/core/engines.html
self.metadata.bind = self.db
self.metadata.create_all()
@property
def is_initialized(self):
return database_exists(self.db.url)
def put(self, key):
return self.db.execute(self.keys.insert(), **key).lastrowid
def get(self, key_name):
results = self.db.execute(sql.select(
[self.keys], self.keys.c.name == key_name))
# Supposed to be only one key_values. There's a hidden assumption
# (is the mother of all fuckups) that you can't insert more
# than one record with the same `name` since it is verified
# in `put`.
key_values = None
for result in results:
key_values = result
if not key_values:
return {}
return self._construct_key(key_values)
def list(self):
all_key_values = self.db.execute(sql.select([self.keys]))
key_list = []
for key_values in all_key_values:
key_list.append(self._construct_key(key_values))
return key_list
def delete(self, key_name):
result = self.db.execute(
self.keys.delete().where(self.keys.c.name == key_name))
return result.rowcount > 0
@property
def db(self):
if self._db is None:
self._db = create_engine(self.db_path)
return self._db
def _construct_key(self, values):
"""Return a dictionary representing a key from a list of columns
and a tuple of values
"""
key = {}
for column, value in zip(self.keys.columns, values):
key.update({column.name: value})
return key
class ConsulStorage(object):
def __init__(self,
db_path=STORAGE_DEFAULT_PATH_MAPPING['consul'],
stash_name='ghost',
verify=True,
client_cert=None,
auth=None):
if not REQUESTS_EXISTS:
raise ImportError('Requests must be installed first')
self._url = urljoin(db_path, 'v1/kv/{0}/'.format(stash_name))
self._session = requests.Session()
self._session.verify = verify
self._session.cert = client_cert
self._session.auth = auth
def init(self):
"""Consul creates directories on the fly, so no init is required."""
@property
def is_initialized(self):
"""...and therefore, this should always return true
"""
return True
def put(self, key):
"""Put and return the only unique identifier possible, its url
"""
self._consul_request('PUT', self._key_url(key['name']), json=key)
return key['name']
def get(self, key_name):
value = self._consul_request('GET', self._key_url(key_name))
if value is None:
return {}
return self._decode(value[0])
def list(self):
keys = self._consul_request('GET', self._url + '?recurse')
return [self._decode(key) for key in keys]
def delete(self, key_name):
self._consul_request('DELETE', self._key_url(key_name))
# Consul returns either true or false for delete operations.
# Instead of relying on it, we actually check that the key
# is not retrieveable
return self.get(key_name) == {}
def _decode(self, data):
"""Decode one key as returned by consul.
The format of the data returned is [{'Value': base-64-encoded-json,
'Key': keyname}]. We need to decode and return just the values.
"""
return json.loads(base64.b64decode(data['Value']).decode('utf-8'))
def _key_url(self, key):
return urljoin(self._url, key)
def _consul_request(self, method, url, *args, **kwargs):
handler = getattr(self._session, method.lower())
response = handler(url, *args, **kwargs)
if response.status_code == 404:
return None
if response.status_code >= 400:
raise GhostError('{0} {1} returned {2}: {3}'.format(
method, url, response.status_code,
response.content))
return response.json()
class VaultStorage(object):
def __init__(self,
db_path=STORAGE_DEFAULT_PATH_MAPPING['vault'],
token=None or os.environ.get('VAULT_TOKEN'),
cert=None,
stash_name='ghost'):
if not HVAC_EXISTS:
raise ImportError('hvac must be installed first')
if not token:
raise GhostError(
'The `VAULT_TOKEN` env var must be set to use this storage '
'type')
self.client = hvac.Client(url=db_path, token=token, cert=cert)
self._stash_name = stash_name
def init(self):
"""
"""
@property
def is_initialized(self):
return True
def put(self, key):
"""Put and return the only unique identifier possible, its path
"""
self.client.write(self._key_path(key['name']), **key)
return self._key_path(key['name'])
def get(self, key_name):
vault_record = self.client.read(self._key_path(key_name))
if not vault_record:
return {}
return self._convert_vault_record_to_ghost_record(vault_record)
def list(self):
keys = self.client.list(self._stash_name)
if not keys:
return []
keys = keys['data']['keys']
key_list = []
for key_name in keys:
key_list.append(self.get(key_name))
return key_list
def delete(self, key_name):
self.client.delete(self._key_path(key_name))
return self.get(key_name) == {}
def _key_path(self, key_name):
"""Return a valid vault path
Note that we don't use os.path.join as the path is read by vault using
slashes even on Windows.
"""
return 'secret/' + self._stash_name + '/' + key_name
@staticmethod
def _convert_vault_record_to_ghost_record(vault_record):
ghost_record = dict(**vault_record['data'])
ghost_record['metadata'] = ghost_record.get('metadata') or {}
del vault_record['data']
ghost_record['metadata'].update(vault_record)
return ghost_record
class ElasticsearchStorage(object):
def __init__(self,
db_path=STORAGE_DEFAULT_PATH_MAPPING['elasticsearch'],
stash_name='ghost',
use_ssl=False,
verify_certs=False,
ca_certs='',
client_cert='',
client_key=''):
if not ES_EXISTS:
raise ImportError('elasticsearch-py must be installed first')
# TODO: Allow multiple hosts
self.es = elasticsearch.Elasticsearch(
[db_path],
use_ssl=use_ssl,
verify_certs=verify_certs,
ca_certs=ca_certs,
client_cert=client_cert,
client_key=client_key)
self.params = dict(index=stash_name, doc_type='doc')
def init(self):
"""Create an Elasticsearch index if necessary
"""
# ignore 400 (IndexAlreadyExistsException) when creating an index
self.es.indices.create(index=self.params['index'], ignore=400)
@property
def is_initialized(self):
return self.es.indices.exists(index=self.params['index'])
def put(self, key):
document = self.es.index(body=key, **self.params)
return document['_id']
def get(self, key_name):
document_list = self._get_document(key_name)
if not document_list:
return {}
return document_list[0]['_source']
def list(self):
query = {"query": {"match_all": {}}}
result = self.es.search(
body=query,
filter_path=['hits.hits._source', 'hits.hits._id'],
**self.params)
key_list = []
for key in result['hits']['hits']:
key_list.append(key['_source'])
return key_list
def delete(self, key_name):
document_list = self._get_document(key_name)
if not document_list:
return True
# `wait_for` a refresh to make this available for search
self.es.delete(
id=document_list[0]['_id'],
refresh='wait_for',
**self.params)
# The response returned by es.delete actually contains
# the success status of the request. We're not taking
# any chances here but rather verify that you can't
# get that key anymore.
return self.get(key_name) == {}
def _get_document(self, key_name):
query = {"query": {"match": {"name": key_name}}}
result = self.es.search(
body=query,
filter_path=['hits.hits._source', 'hits.hits._id'],
**self.params)
return result['hits']['hits'] if result else {}
class S3Storage(object):
def __init__(self,
db_path,
bucket_location=None or os.environ.get(