From 70f52e304371ac01df0b9f468602acb9e745024a Mon Sep 17 00:00:00 2001 From: Yanis Guenane Date: Fri, 21 Jul 2017 17:54:04 +0200 Subject: [PATCH] crypto: Build a base object for openssl modules (#26945) More openssl modules are about to be made, each of them rewriting some pieces of code that can be refactored and used via a common library. This commit aims to create this "base" object and the common functions one might want to reuse in order to avoid duplication. --- lib/ansible/module_utils/crypto.py | 75 ++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/lib/ansible/module_utils/crypto.py b/lib/ansible/module_utils/crypto.py index d9526b8026..4f2b770cd4 100644 --- a/lib/ansible/module_utils/crypto.py +++ b/lib/ansible/module_utils/crypto.py @@ -23,7 +23,16 @@ except ImportError: # user know that OpenSSL couldn't be found. pass +import abc +import errno import hashlib +import os + +from ansible.module_utils import six + + +class OpenSSLObjectError(Exception): + pass def get_fingerprint(path, passphrase): @@ -48,3 +57,69 @@ def get_fingerprint(path, passphrase): pass return fingerprint + + +def load_privatekey(path, passphrase=None): + """Load the specified OpenSSL private key.""" + + try: + privatekey_content = open(path, 'rb').read() + privatekey = crypto.load_privatekey(crypto.FILETYPE_PEM, + privatekey_content, + passphrase) + return privatekey + except (IOError, OSError) as exc: + raise OpenSSLObjectError(exc) + + +def load_certificate(path): + """Load the specified certificate.""" + + try: + cert_content = open(path, 'rb').read() + cert = crypto.load_certificate(crypto.FILETYPE_PEM, cert_content) + return cert + except (IOError, OSError) as exc: + raise OpenSSLObjectError(exc) + + +@six.add_metaclass(abc.ABCMeta) +class OpenSSLObject(object): + + def __init__(self, path, state, force, check_mode): + self.path = path + self.state = state + self.force = force + self.name = os.path.basename(path) + self.changed = False + self.check_mode = check_mode + + @abc.abstractmethod + def check(self): + """Ensure the resource is in its desired state.""" + + pass + + @abc.abstractmethod + def dump(self): + """Serialize the object into a dictionary.""" + + pass + + @abc.abstractmethod + def generate(self): + """Generate the resource.""" + + pass + + def remove(self): + """Remove the resource from the filesystem.""" + + try: + os.remove(self.path) + self.changed = True + except OSError as exc: + if exc.errno != errno.ENOENT: + raise OpenSSLObjectError(exc) + else: + pass