mirror of
https://github.com/ansible-collections/community.crypto.git
synced 2026-05-07 13:53:06 +00:00
Reformat everything with black.
I had to undo the u string prefix removals to not drop Python 2 compatibility. That's why black isn't enabled in antsibull-nox.toml yet.
This commit is contained in:
@@ -38,7 +38,7 @@ from ansible_collections.community.crypto.plugins.module_utils.version import (
|
||||
)
|
||||
|
||||
|
||||
MINIMAL_CRYPTOGRAPHY_VERSION = '1.2.3'
|
||||
MINIMAL_CRYPTOGRAPHY_VERSION = "1.2.3"
|
||||
|
||||
CRYPTOGRAPHY_IMP_ERR = None
|
||||
try:
|
||||
@@ -50,6 +50,7 @@ try:
|
||||
import cryptography.hazmat.primitives.asymmetric.rsa
|
||||
import cryptography.hazmat.primitives.asymmetric.utils
|
||||
import cryptography.hazmat.primitives.serialization
|
||||
|
||||
CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__)
|
||||
except ImportError:
|
||||
CRYPTOGRAPHY_IMP_ERR = traceback.format_exc()
|
||||
@@ -73,18 +74,18 @@ class PrivateKeyError(OpenSSLObjectError):
|
||||
class PrivateKeyConvertBackend:
|
||||
def __init__(self, module, backend):
|
||||
self.module = module
|
||||
self.src_path = module.params['src_path']
|
||||
self.src_content = module.params['src_content']
|
||||
self.src_passphrase = module.params['src_passphrase']
|
||||
self.format = module.params['format']
|
||||
self.dest_passphrase = module.params['dest_passphrase']
|
||||
self.src_path = module.params["src_path"]
|
||||
self.src_content = module.params["src_content"]
|
||||
self.src_passphrase = module.params["src_passphrase"]
|
||||
self.format = module.params["format"]
|
||||
self.dest_passphrase = module.params["dest_passphrase"]
|
||||
self.backend = backend
|
||||
|
||||
self.src_private_key = None
|
||||
if self.src_path is not None:
|
||||
self.src_private_key_bytes = load_file(self.src_path, module)
|
||||
else:
|
||||
self.src_private_key_bytes = self.src_content.encode('utf-8')
|
||||
self.src_private_key_bytes = self.src_content.encode("utf-8")
|
||||
|
||||
self.dest_private_key = None
|
||||
self.dest_private_key_bytes = None
|
||||
@@ -109,17 +110,25 @@ class PrivateKeyConvertBackend:
|
||||
|
||||
def needs_conversion(self):
|
||||
"""Check whether a conversion is necessary. Must only be called if needs_regeneration() returned False."""
|
||||
dummy, self.src_private_key = self._load_private_key(self.src_private_key_bytes, self.src_passphrase)
|
||||
dummy, self.src_private_key = self._load_private_key(
|
||||
self.src_private_key_bytes, self.src_passphrase
|
||||
)
|
||||
|
||||
if not self.has_existing_destination():
|
||||
return True
|
||||
|
||||
try:
|
||||
format, self.dest_private_key = self._load_private_key(self.dest_private_key_bytes, self.dest_passphrase, current_hint=self.src_private_key)
|
||||
format, self.dest_private_key = self._load_private_key(
|
||||
self.dest_private_key_bytes,
|
||||
self.dest_passphrase,
|
||||
current_hint=self.src_private_key,
|
||||
)
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
return format != self.format or not cryptography_compare_private_keys(self.dest_private_key, self.src_private_key)
|
||||
return format != self.format or not cryptography_compare_private_keys(
|
||||
self.dest_private_key, self.src_private_key
|
||||
)
|
||||
|
||||
def dump(self):
|
||||
"""Serialize the object into a dictionary."""
|
||||
@@ -129,7 +138,9 @@ class PrivateKeyConvertBackend:
|
||||
# Implementation with using cryptography
|
||||
class PrivateKeyConvertCryptographyBackend(PrivateKeyConvertBackend):
|
||||
def __init__(self, module):
|
||||
super(PrivateKeyConvertCryptographyBackend, self).__init__(module=module, backend='cryptography')
|
||||
super(PrivateKeyConvertCryptographyBackend, self).__init__(
|
||||
module=module, backend="cryptography"
|
||||
)
|
||||
|
||||
self.cryptography_backend = cryptography.hazmat.backends.default_backend()
|
||||
|
||||
@@ -138,72 +149,140 @@ class PrivateKeyConvertCryptographyBackend(PrivateKeyConvertBackend):
|
||||
# Select export format and encoding
|
||||
try:
|
||||
export_encoding = cryptography.hazmat.primitives.serialization.Encoding.PEM
|
||||
if self.format == 'pkcs1':
|
||||
if self.format == "pkcs1":
|
||||
# "TraditionalOpenSSL" format is PKCS1
|
||||
export_format = cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL
|
||||
elif self.format == 'pkcs8':
|
||||
export_format = cryptography.hazmat.primitives.serialization.PrivateFormat.PKCS8
|
||||
elif self.format == 'raw':
|
||||
export_format = cryptography.hazmat.primitives.serialization.PrivateFormat.Raw
|
||||
export_encoding = cryptography.hazmat.primitives.serialization.Encoding.Raw
|
||||
export_format = (
|
||||
cryptography.hazmat.primitives.serialization.PrivateFormat.TraditionalOpenSSL
|
||||
)
|
||||
elif self.format == "pkcs8":
|
||||
export_format = (
|
||||
cryptography.hazmat.primitives.serialization.PrivateFormat.PKCS8
|
||||
)
|
||||
elif self.format == "raw":
|
||||
export_format = (
|
||||
cryptography.hazmat.primitives.serialization.PrivateFormat.Raw
|
||||
)
|
||||
export_encoding = (
|
||||
cryptography.hazmat.primitives.serialization.Encoding.Raw
|
||||
)
|
||||
except AttributeError:
|
||||
self.module.fail_json(msg='Cryptography backend does not support the selected output format "{0}"'.format(self.format))
|
||||
self.module.fail_json(
|
||||
msg='Cryptography backend does not support the selected output format "{0}"'.format(
|
||||
self.format
|
||||
)
|
||||
)
|
||||
|
||||
# Select key encryption
|
||||
encryption_algorithm = cryptography.hazmat.primitives.serialization.NoEncryption()
|
||||
encryption_algorithm = (
|
||||
cryptography.hazmat.primitives.serialization.NoEncryption()
|
||||
)
|
||||
if self.dest_passphrase:
|
||||
encryption_algorithm = cryptography.hazmat.primitives.serialization.BestAvailableEncryption(to_bytes(self.dest_passphrase))
|
||||
encryption_algorithm = (
|
||||
cryptography.hazmat.primitives.serialization.BestAvailableEncryption(
|
||||
to_bytes(self.dest_passphrase)
|
||||
)
|
||||
)
|
||||
|
||||
# Serialize key
|
||||
try:
|
||||
return self.src_private_key.private_bytes(
|
||||
encoding=export_encoding,
|
||||
format=export_format,
|
||||
encryption_algorithm=encryption_algorithm
|
||||
encryption_algorithm=encryption_algorithm,
|
||||
)
|
||||
except ValueError:
|
||||
self.module.fail_json(
|
||||
msg='Cryptography backend cannot serialize the private key in the required format "{0}"'.format(self.format)
|
||||
msg='Cryptography backend cannot serialize the private key in the required format "{0}"'.format(
|
||||
self.format
|
||||
)
|
||||
)
|
||||
except Exception:
|
||||
self.module.fail_json(
|
||||
msg='Error while serializing the private key in the required format "{0}"'.format(self.format),
|
||||
exception=traceback.format_exc()
|
||||
msg='Error while serializing the private key in the required format "{0}"'.format(
|
||||
self.format
|
||||
),
|
||||
exception=traceback.format_exc(),
|
||||
)
|
||||
|
||||
def _load_private_key(self, data, passphrase, current_hint=None):
|
||||
try:
|
||||
# Interpret bytes depending on format.
|
||||
format = identify_private_key_format(data)
|
||||
if format == 'raw':
|
||||
if format == "raw":
|
||||
if passphrase is not None:
|
||||
raise PrivateKeyError('Cannot load raw key with passphrase')
|
||||
raise PrivateKeyError("Cannot load raw key with passphrase")
|
||||
if len(data) == 56 and CRYPTOGRAPHY_HAS_X448:
|
||||
return format, cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey.from_private_bytes(data)
|
||||
return (
|
||||
format,
|
||||
cryptography.hazmat.primitives.asymmetric.x448.X448PrivateKey.from_private_bytes(
|
||||
data
|
||||
),
|
||||
)
|
||||
if len(data) == 57 and CRYPTOGRAPHY_HAS_ED448:
|
||||
return format, cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey.from_private_bytes(data)
|
||||
return (
|
||||
format,
|
||||
cryptography.hazmat.primitives.asymmetric.ed448.Ed448PrivateKey.from_private_bytes(
|
||||
data
|
||||
),
|
||||
)
|
||||
if len(data) == 32:
|
||||
if CRYPTOGRAPHY_HAS_X25519 and not CRYPTOGRAPHY_HAS_ED25519:
|
||||
return format, cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.from_private_bytes(data)
|
||||
return (
|
||||
format,
|
||||
cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.from_private_bytes(
|
||||
data
|
||||
),
|
||||
)
|
||||
if CRYPTOGRAPHY_HAS_ED25519 and not CRYPTOGRAPHY_HAS_X25519:
|
||||
return format, cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.from_private_bytes(data)
|
||||
return (
|
||||
format,
|
||||
cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.from_private_bytes(
|
||||
data
|
||||
),
|
||||
)
|
||||
if CRYPTOGRAPHY_HAS_X25519 and CRYPTOGRAPHY_HAS_ED25519:
|
||||
if isinstance(current_hint, cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey):
|
||||
if isinstance(
|
||||
current_hint,
|
||||
cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey,
|
||||
):
|
||||
try:
|
||||
return format, cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.from_private_bytes(data)
|
||||
return (
|
||||
format,
|
||||
cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.from_private_bytes(
|
||||
data
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
return format, cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.from_private_bytes(data)
|
||||
return (
|
||||
format,
|
||||
cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.from_private_bytes(
|
||||
data
|
||||
),
|
||||
)
|
||||
else:
|
||||
try:
|
||||
return format, cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.from_private_bytes(data)
|
||||
return (
|
||||
format,
|
||||
cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey.from_private_bytes(
|
||||
data
|
||||
),
|
||||
)
|
||||
except Exception:
|
||||
return format, cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.from_private_bytes(data)
|
||||
raise PrivateKeyError('Cannot load raw key')
|
||||
return (
|
||||
format,
|
||||
cryptography.hazmat.primitives.asymmetric.x25519.X25519PrivateKey.from_private_bytes(
|
||||
data
|
||||
),
|
||||
)
|
||||
raise PrivateKeyError("Cannot load raw key")
|
||||
else:
|
||||
return format, cryptography.hazmat.primitives.serialization.load_pem_private_key(
|
||||
data,
|
||||
None if passphrase is None else to_bytes(passphrase),
|
||||
backend=self.cryptography_backend
|
||||
return (
|
||||
format,
|
||||
cryptography.hazmat.primitives.serialization.load_pem_private_key(
|
||||
data,
|
||||
None if passphrase is None else to_bytes(passphrase),
|
||||
backend=self.cryptography_backend,
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
raise PrivateKeyError(e)
|
||||
@@ -211,24 +290,28 @@ class PrivateKeyConvertCryptographyBackend(PrivateKeyConvertBackend):
|
||||
|
||||
def select_backend(module):
|
||||
if not CRYPTOGRAPHY_FOUND:
|
||||
module.fail_json(msg=missing_required_lib('cryptography >= {0}'.format(MINIMAL_CRYPTOGRAPHY_VERSION)),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR)
|
||||
module.fail_json(
|
||||
msg=missing_required_lib(
|
||||
"cryptography >= {0}".format(MINIMAL_CRYPTOGRAPHY_VERSION)
|
||||
),
|
||||
exception=CRYPTOGRAPHY_IMP_ERR,
|
||||
)
|
||||
return PrivateKeyConvertCryptographyBackend(module)
|
||||
|
||||
|
||||
def get_privatekey_argument_spec():
|
||||
return ArgumentSpec(
|
||||
argument_spec=dict(
|
||||
src_path=dict(type='path'),
|
||||
src_content=dict(type='str'),
|
||||
src_passphrase=dict(type='str', no_log=True),
|
||||
dest_passphrase=dict(type='str', no_log=True),
|
||||
format=dict(type='str', required=True, choices=['pkcs1', 'pkcs8', 'raw']),
|
||||
src_path=dict(type="path"),
|
||||
src_content=dict(type="str"),
|
||||
src_passphrase=dict(type="str", no_log=True),
|
||||
dest_passphrase=dict(type="str", no_log=True),
|
||||
format=dict(type="str", required=True, choices=["pkcs1", "pkcs8", "raw"]),
|
||||
),
|
||||
mutually_exclusive=[
|
||||
['src_path', 'src_content'],
|
||||
["src_path", "src_content"],
|
||||
],
|
||||
required_one_of=[
|
||||
['src_path', 'src_content'],
|
||||
["src_path", "src_content"],
|
||||
],
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user