Completed
Pull Request — master (#2631)
by Lakshmi
06:40
created

_backup_old_key()   A

Complexity

Conditions 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
1
#!/usr/bin/env python
2
3
import argparse
4
import datetime
5
import os
6
import shutil
7
import sys
8
import traceback
9
10
from keyczar.keys import AesKey
11
12
13
def _backup_old_key(key_path):
14
    base_path = os.path.dirname(key_path)
15
    dt_str = datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%S.%fZ")
16
    bkup_file_name = os.path.basename(key_path) + '.bkup-%s' % dt_str
17
    shutil.move(key_path, os.path.join(base_path, bkup_file_name))
18
    print('WARNING: Backed up old key file to %s.' % bkup_file_name)
19
20
21
def main(key_path, force=False):
22
    base_path = os.path.dirname(key_path)
23
    if not os.access(base_path, os.W_OK):
24
        print('ERROR: You do not have sufficient permissions to write to path: %s.' % key_path)
25
        print('Try setting up permissions correctly and then run this tool.')
26
        sys.exit(1)
27
28
    if os.path.exists(key_path):
29
        print('You already have a key at the specified location %s!' % key_path)
30
31
        if not force:
32
            print('Not generating a new key. Either delete the file or re-run with --force.')
33
            sys.exit(2)
34
        else:
35
            try:
36
                _backup_old_key(key_path)
37
            except:
38
                traceback.print_exc()
39
                print('WARNING: Failed backing up old key! Ignoring!')
40
41
        print('Generating new key...')
42
43
    with open(key_path, 'w') as key_file:
44
        k = AesKey.Generate()
45
        key_file.write(str(k))
46
        key_file.flush()
47
48
    msg = ('Key written to %s. ' % key_path + 'Secure the permissions so only StackStorm API ' +
49
           'process and StackStorm admin access the file.')
50
    print(msg)
51
52
if __name__ == '__main__':
53
    parser = argparse.ArgumentParser(description='Tool for crypto key generation.')
54
    parser.add_argument('-k', '--key-path',
55
                        required=True,
56
                        help='Path to file to write key to. Secure permissions of file so ' +
57
                        'only admin can read the crypto key.')
58
    parser.add_argument('-f', '--force', action='store_true',
59
                        help='Force rewrite the key file if already exists.')
60
61
    args = parser.parse_args()
62
    main(key_path=args.key_path, force=args.force)
63