MCPcopy Create free account
hub / github.com/Keeper-Security/Commander / rotate

Function rotate

keepercommander/plugins/sshkey/sshkey.py:31–218  ·  view source on GitHub ↗
(record, new_password)

Source from the content-addressed store, hash-verified

29
30
31def rotate(record, new_password): # type: (vault.KeeperRecord, str) -> bool
32 private_key = ''
33 if isinstance(record, vault.PasswordRecord):
34 cf = next((x for x in record.custom if x.name == 'cmdr:private_key'), None)
35 if cf:
36 private_key = cf.value
37 elif isinstance(record, vault.TypedRecord):
38 ssh_key_field = record.get_typed_field('keyPair')
39 if ssh_key_field:
40 key_value = ssh_key_field.get_default_value(dict)
41 if isinstance(key_value, dict):
42 private_key = key_value.get('privateKey', '')
43 else:
44 cf = next((x for x in record.custom if x.label == 'cmdr:private_key'), None)
45 if cf:
46 value = cf.get_default_value(str)
47 if value:
48 private_key = value
49
50 old_password = RecordMixin.get_record_field(record, 'password')
51
52 old_pk = None
53 backend = default_backend()
54 ssh_key_format = serialization.PrivateFormat.TraditionalOpenSSL
55 if private_key:
56 header, _, _ = private_key.partition('\n')
57 if 'BEGIN OPENSSH PRIVATE KEY' in header:
58 ssh_key_format = serialization.PrivateFormat.OpenSSH
59 try:
60 old_pk = load_private_key(private_key, old_password)
61 if isinstance(old_pk, rsa.RSAPrivateKey):
62 pub_key_exponent = old_pk.public_key().public_numbers().e
63 new_pk = rsa.generate_private_key(
64 key_size=old_pk.key_size, public_exponent=pub_key_exponent, backend=backend)
65 elif isinstance(old_pk, ec.EllipticCurvePrivateKey):
66 new_pk = ec.generate_private_key(old_pk.curve, backend=backend)
67 elif isinstance(old_pk, ed25519.Ed25519PrivateKey):
68 new_pk = ed25519.Ed25519PrivateKey.generate()
69 ssh_key_format = serialization.PrivateFormat.OpenSSH
70 else:
71 raise Exception('Unsupported private key type')
72 except Exception as e:
73 logging.info('SSH Key rotation plugin: load key error: %s', e)
74 return False
75 else:
76 new_pk, _ = crypto.generate_rsa_key()
77
78 new_private_key = new_pk.private_bytes(
79 encoding=serialization.Encoding.PEM, format=ssh_key_format,
80 encryption_algorithm=serialization.BestAvailableEncryption(new_password.encode('utf-8'))).decode()
81
82 new_public_ssh_key = new_pk.public_key().public_bytes(
83 encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH).decode()
84
85 optional_port = RecordMixin.get_custom_field(record, 'cmdr:port')
86 if optional_port:
87 try:
88 port = int(optional_port)

Callers

nothing calls this directly

Calls 15

load_private_keyFunction · 0.85
get_default_valueMethod · 0.80
get_record_fieldMethod · 0.80
public_keyMethod · 0.80
warningMethod · 0.80
countMethod · 0.80
communicateMethod · 0.80
pollMethod · 0.80
formatMethod · 0.80
removeMethod · 0.80
get_typed_fieldMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected