openssl_certificate, openssl_csr: refactoring / cleanup (#54287)

* Moving common cryptography-related code to module_utils/crypto.py.

* Fix typo / linting.
This commit is contained in:
Felix Fontein 2019-03-25 14:20:05 +01:00 committed by Martin Krizek
parent 5d460ae865
commit 9c355e5c52
3 changed files with 205 additions and 323 deletions

View file

@ -28,6 +28,7 @@ try:
from cryptography.hazmat.backends import default_backend as cryptography_backend
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.primitives import hashes
import ipaddress
except ImportError:
# Error handled in the calling module.
pass
@ -41,7 +42,7 @@ import os
import re
from ansible.module_utils import six
from ansible.module_utils._text import to_bytes
from ansible.module_utils._text import to_bytes, to_text
class OpenSSLObjectError(Exception):
@ -128,7 +129,7 @@ def load_privatekey(path, passphrase=None, check_passphrase=True, backend='pyope
# Since we can load the key without an exception, the
# key isn't password-protected
raise OpenSSLBadPassphraseError('Passphrase provided, but private key is not password-protected!')
except crypto.Error:
except crypto.Error as e:
if passphrase is None and len(e.args) > 0 and len(e.args[0]) > 0 and e.args[0][0][2] == 'bad decrypt':
# The key is obviously protected by the empty string.
# Don't do this at home (if it's possible at all)...
@ -138,9 +139,9 @@ def load_privatekey(path, passphrase=None, check_passphrase=True, backend='pyope
result = load_pem_private_key(priv_key_detail,
passphrase,
cryptography_backend())
except TypeError as e:
except TypeError as dummy:
raise OpenSSLBadPassphraseError('Wrong or empty passphrase provided for private key')
except ValueError as e:
except ValueError as dummy:
raise OpenSSLBadPassphraseError('Wrong passphrase provided for private key')
return result
@ -283,3 +284,185 @@ class OpenSSLObject(object):
raise OpenSSLObjectError(exc)
else:
pass
def cryptography_get_name_oid(id):
'''
Given a symbolic ID, finds the appropriate OID for use with cryptography.
Raises an OpenSSLObjectError if the ID is unknown.
'''
if id in ('CN', 'commonName'):
return x509.oid.NameOID.COMMON_NAME
if id in ('C', 'countryName'):
return x509.oid.NameOID.COUNTRY_NAME
if id in ('L', 'localityName'):
return x509.oid.NameOID.LOCALITY_NAME
if id in ('ST', 'stateOrProvinceName'):
return x509.oid.NameOID.STATE_OR_PROVINCE_NAME
if id in ('street', 'streetAddress'):
return x509.oid.NameOID.STREET_ADDRESS
if id in ('O', 'organizationName'):
return x509.oid.NameOID.ORGANIZATION_NAME
if id in ('OU', 'organizationalUnitName'):
return x509.oid.NameOID.ORGANIZATIONAL_UNIT_NAME
if id in ('serialNumber', ):
return x509.oid.NameOID.SERIAL_NUMBER
if id in ('SN', 'surname'):
return x509.oid.NameOID.SURNAME
if id in ('GN', 'givenName'):
return x509.oid.NameOID.GIVEN_NAME
if id in ('title', ):
return x509.oid.NameOID.TITLE
if id in ('generationQualifier', ):
return x509.oid.NameOID.GENERATION_QUALIFIER
if id in ('x500UniqueIdentifier', ):
return x509.oid.NameOID.X500_UNIQUE_IDENTIFIER
if id in ('dnQualifier', ):
return x509.oid.NameOID.DN_QUALIFIER
if id in ('pseudonym', ):
return x509.oid.NameOID.PSEUDONYM
if id in ('UID', 'userId'):
return x509.oid.NameOID.USER_ID
if id in ('DC', 'domainComponent'):
return x509.oid.NameOID.DOMAIN_COMPONENT
if id in ('emailAddress', ):
return x509.oid.NameOID.EMAIL_ADDRESS
if id in ('jurisdictionC', 'jurisdictionCountryName'):
return x509.oid.NameOID.JURISDICTION_COUNTRY_NAME
if id in ('jurisdictionL', 'jurisdictionLocalityName'):
return x509.oid.NameOID.JURISDICTION_LOCALITY_NAME
if id in ('jurisdictionST', 'jurisdictionStateOrProvinceName'):
return x509.oid.NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME
if id in ('businessCategory', ):
return x509.oid.NameOID.BUSINESS_CATEGORY
if id in ('postalAddress', ):
return x509.oid.NameOID.POSTAL_ADDRESS
if id in ('postalCode', ):
return x509.oid.NameOID.POSTAL_CODE
raise OpenSSLObjectError('Unknown subject field identifier "{0}"'.format(id))
def cryptography_get_name(name):
'''
Given a name string, returns a cryptography x509.Name object.
Raises an OpenSSLObjectError if the name is unknown or cannot be parsed.
'''
try:
if name.startswith('DNS:'):
return x509.DNSName(to_text(name[4:]))
if name.startswith('IP:'):
return x509.IPAddress(ipaddress.ip_address(to_text(name[3:])))
if name.startswith('email:'):
return x509.RFC822Name(to_text(name[6:]))
if name.startswith('URI:'):
return x509.UniformResourceIdentifier(to_text(name[4:]))
except Exception as e:
raise OpenSSLObjectError('Cannot parse Subject Alternative Name "{0}": {1}'.format(name, e))
if ':' not in name:
raise OpenSSLObjectError('Cannot parse Subject Alternative Name "{0}" (forgot "DNS:" prefix?)'.format(name))
raise OpenSSLObjectError('Cannot parse Subject Alternative Name "{0}" (potentially unsupported by cryptography backend)'.format(name))
def _cryptography_get_keyusage(usage):
'''
Given a key usage identifier string, returns the parameter name used by cryptography's x509.KeyUsage().
Raises an OpenSSLObjectError if the identifier is unknown.
'''
if usage in ('Digital Signature', 'digitalSignature'):
return 'digital_signature'
if usage in ('Non Repudiation', 'nonRepudiation'):
return 'content_commitment'
if usage in ('Key Encipherment', 'keyEncipherment'):
return 'key_encipherment'
if usage in ('Data Encipherment', 'dataEncipherment'):
return 'data_encipherment'
if usage in ('Key Agreement', 'keyAgreement'):
return 'key_agreement'
if usage in ('Certificate Sign', 'keyCertSign'):
return 'key_cert_sign'
if usage in ('CRL Sign', 'cRLSign'):
return 'crl_sign'
if usage in ('Encipher Only', 'encipherOnly'):
return 'encipher_only'
if usage in ('Decipher Only', 'decipherOnly'):
return 'decipher_only'
raise OpenSSLObjectError('Unknown key usage "{0}"'.format(usage))
def cryptography_parse_key_usage_params(usages):
'''
Given a list of key usage identifier strings, returns the parameters for cryptography's x509.KeyUsage().
Raises an OpenSSLObjectError if an identifier is unknown.
'''
params = dict(
digital_signature=False,
content_commitment=False,
key_encipherment=False,
data_encipherment=False,
key_agreement=False,
key_cert_sign=False,
crl_sign=False,
encipher_only=False,
decipher_only=False,
)
for usage in usages:
params[_cryptography_get_keyusage(usage)] = True
return params
def cryptography_get_ext_keyusage(usage):
'''
Given an extended key usage identifier string, returns the OID used by cryptography.
Raises an OpenSSLObjectError if the identifier is unknown.
'''
if usage in ('serverAuth', 'TLS Web Server Authentication'):
return x509.oid.ExtendedKeyUsageOID.SERVER_AUTH
if usage in ('clientAuth', 'TLS Web Client Authentication'):
return x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH
if usage in ('codeSigning', 'Code Signing'):
return x509.oid.ExtendedKeyUsageOID.CODE_SIGNING
if usage in ('emailProtection', 'E-mail Protection'):
return x509.oid.ExtendedKeyUsageOID.EMAIL_PROTECTION
if usage in ('timeStamping', 'Time Stamping'):
return x509.oid.ExtendedKeyUsageOID.TIME_STAMPING
if usage in ('OCSPSigning', 'OCSP Signing'):
return x509.oid.ExtendedKeyUsageOID.OCSP_SIGNING
if usage in ('anyExtendedKeyUsage', 'Any Extended Key Usage'):
return x509.oid.ExtendedKeyUsageOID.ANY_EXTENDED_KEY_USAGE
if usage in ('qcStatements', ):
return x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.1.3")
if usage in ('DVCS', ):
return x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.3.10")
if usage in ('IPSec User', 'ipsecUser'):
return x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.3.7")
if usage in ('Biometric Info', 'biometricInfo'):
return x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.1.2")
# FIXME need some more, probably all from https://www.iana.org/assignments/smi-numbers/smi-numbers.xhtml#smi-numbers-1.3.6.1.5.5.7.3
raise OpenSSLObjectError('Unknown extended key usage "{0}"'.format(usage))
def cryptography_get_basic_constraints(constraints):
'''
Given a list of constraints, returns a tuple (ca, path_length).
Raises an OpenSSLObjectError if a constraint is unknown or cannot be parsed.
'''
ca = False
path_length = None
if constraints:
for constraint in constraints:
if constraint.startswith('CA:'):
if constraint == 'CA:TRUE':
ca = True
elif constraint == 'CA:FALSE':
ca = False
else:
raise OpenSSLObjectError('Unknown basic constraint value "{0}" for CA'.format(constraint[3:]))
elif constraint.startswith('pathlen:'):
v = constraint[len('pathlen:'):]
try:
path_length = int(v)
except Exception as e:
raise OpenSSLObjectError('Cannot parse path length constraint "{0}" ({1})'.format(v, e))
else:
raise OpenSSLObjectError('Unknown basic constraint "{0}"'.format(constraint))
return ca, path_length