2017-04-06 16:09:07 +00:00
|
|
|
#!/usr/bin/python
|
|
|
|
# -*- coding: utf-8 -*-
|
|
|
|
#
|
|
|
|
# (c) 2017, Yanis Guenane <yanis+ansible@guenane.org>
|
2017-07-29 07:20:36 +00:00
|
|
|
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
|
|
|
|
|
|
|
|
from __future__ import absolute_import, division, print_function
|
|
|
|
__metaclass__ = type
|
|
|
|
|
2017-04-06 16:09:07 +00:00
|
|
|
|
2017-08-16 03:16:38 +00:00
|
|
|
ANSIBLE_METADATA = {'metadata_version': '1.1',
|
2017-04-06 17:16:50 +00:00
|
|
|
'status': ['preview'],
|
|
|
|
'supported_by': 'community'}
|
|
|
|
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
DOCUMENTATION = '''
|
|
|
|
---
|
|
|
|
module: openssl_csr
|
|
|
|
author: "Yanis Guenane (@Spredzy)"
|
2017-04-17 19:46:12 +00:00
|
|
|
version_added: "2.4"
|
2017-04-06 16:09:07 +00:00
|
|
|
short_description: Generate OpenSSL Certificate Signing Request (CSR)
|
|
|
|
description:
|
2017-09-11 19:05:15 +00:00
|
|
|
- "This module allows one to (re)generate OpenSSL certificate signing requests.
|
2017-08-03 11:27:17 +00:00
|
|
|
It uses the pyOpenSSL python library to interact with openssl. This module supports
|
2018-02-08 12:03:28 +00:00
|
|
|
the subjectAltName, keyUsage, extendedKeyUsage, basicConstraints and OCSP Must Staple
|
|
|
|
extensions."
|
2017-04-06 16:09:07 +00:00
|
|
|
requirements:
|
2019-01-21 17:19:05 +00:00
|
|
|
- "One of the following Python libraries:"
|
|
|
|
- "cryptography >= 1.3"
|
|
|
|
- "pyOpenSSL >= 0.15"
|
2017-04-06 16:09:07 +00:00
|
|
|
options:
|
|
|
|
state:
|
|
|
|
required: false
|
|
|
|
default: "present"
|
|
|
|
choices: [ present, absent ]
|
|
|
|
description:
|
|
|
|
- Whether the certificate signing request should exist or not, taking action if the state is different from what is stated.
|
|
|
|
digest:
|
|
|
|
required: false
|
|
|
|
default: "sha256"
|
|
|
|
description:
|
|
|
|
- Digest used when signing the certificate signing request with the private key
|
|
|
|
privatekey_path:
|
|
|
|
required: true
|
|
|
|
description:
|
|
|
|
- Path to the privatekey to use when signing the certificate signing request
|
2017-07-19 10:02:29 +00:00
|
|
|
privatekey_passphrase:
|
|
|
|
required: false
|
|
|
|
description:
|
|
|
|
- The passphrase for the privatekey.
|
2017-04-06 16:09:07 +00:00
|
|
|
version:
|
|
|
|
required: false
|
2017-09-14 13:21:32 +00:00
|
|
|
default: 1
|
2017-04-06 16:09:07 +00:00
|
|
|
description:
|
|
|
|
- Version of the certificate signing request
|
|
|
|
force:
|
|
|
|
required: false
|
|
|
|
default: False
|
2018-04-24 17:05:50 +00:00
|
|
|
type: bool
|
2017-04-06 16:09:07 +00:00
|
|
|
description:
|
|
|
|
- Should the certificate signing request be forced regenerated by this ansible module
|
|
|
|
path:
|
|
|
|
required: true
|
|
|
|
description:
|
2018-01-18 14:43:05 +00:00
|
|
|
- Name of the file into which the generated OpenSSL certificate signing request will be written
|
2017-12-12 12:35:22 +00:00
|
|
|
subject:
|
|
|
|
required: false
|
|
|
|
description:
|
|
|
|
- Key/value pairs that will be present in the subject name field of the certificate signing request.
|
|
|
|
- If you need to specify more than one value with the same key, use a list as value.
|
|
|
|
version_added: '2.5'
|
2017-09-11 19:05:15 +00:00
|
|
|
country_name:
|
2017-04-06 16:09:07 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'C', 'countryName' ]
|
2017-04-06 16:09:07 +00:00
|
|
|
description:
|
|
|
|
- countryName field of the certificate signing request subject
|
2017-09-11 19:05:15 +00:00
|
|
|
state_or_province_name:
|
2017-04-06 16:09:07 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'ST', 'stateOrProvinceName' ]
|
2017-04-06 16:09:07 +00:00
|
|
|
description:
|
|
|
|
- stateOrProvinceName field of the certificate signing request subject
|
2017-09-11 19:05:15 +00:00
|
|
|
locality_name:
|
2017-04-06 16:09:07 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'L', 'localityName' ]
|
2017-04-06 16:09:07 +00:00
|
|
|
description:
|
|
|
|
- localityName field of the certificate signing request subject
|
2017-09-11 19:05:15 +00:00
|
|
|
organization_name:
|
2017-04-06 16:09:07 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'O', 'organizationName' ]
|
2017-04-06 16:09:07 +00:00
|
|
|
description:
|
|
|
|
- organizationName field of the certificate signing request subject
|
2017-09-11 19:05:15 +00:00
|
|
|
organizational_unit_name:
|
2017-04-06 16:09:07 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'OU', 'organizationalUnitName' ]
|
2017-04-06 16:09:07 +00:00
|
|
|
description:
|
2017-07-19 09:17:45 +00:00
|
|
|
- organizationalUnitName field of the certificate signing request subject
|
2017-09-11 19:05:15 +00:00
|
|
|
common_name:
|
2017-04-06 16:09:07 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'CN', 'commonName' ]
|
2017-04-06 16:09:07 +00:00
|
|
|
description:
|
|
|
|
- commonName field of the certificate signing request subject
|
2017-09-11 19:05:15 +00:00
|
|
|
email_address:
|
2017-04-06 16:09:07 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'E', 'emailAddress' ]
|
2017-04-06 16:09:07 +00:00
|
|
|
description:
|
|
|
|
- emailAddress field of the certificate signing request subject
|
2017-09-11 19:05:15 +00:00
|
|
|
subject_alt_name:
|
2017-08-03 11:27:17 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'subjectAltName' ]
|
2017-08-03 11:27:17 +00:00
|
|
|
description:
|
|
|
|
- SAN extension to attach to the certificate signing request
|
|
|
|
- This can either be a 'comma separated string' or a YAML list.
|
2018-02-08 20:36:28 +00:00
|
|
|
- Values should be prefixed by their options. (i.e., C(email), C(URI), C(DNS), C(RID), C(IP), C(dirName),
|
|
|
|
C(otherName) and the ones specific to your CA)
|
2019-01-21 17:19:05 +00:00
|
|
|
- Note that if no SAN is specified, but a common name, the common
|
|
|
|
name will be added as a SAN except if C(useCommonNameForSAN) is
|
|
|
|
set to I(false).
|
2018-02-07 10:07:23 +00:00
|
|
|
- More at U(https://tools.ietf.org/html/rfc5280#section-4.2.1.6)
|
2017-09-11 19:05:15 +00:00
|
|
|
subject_alt_name_critical:
|
2017-08-15 08:29:29 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'subjectAltName_critical' ]
|
2017-08-15 08:29:29 +00:00
|
|
|
description:
|
|
|
|
- Should the subjectAltName extension be considered as critical
|
2019-01-21 17:19:05 +00:00
|
|
|
useCommonNameForSAN:
|
|
|
|
type: bool
|
|
|
|
default: true
|
|
|
|
description:
|
|
|
|
- If set to I(true), the module will fill the common name in for
|
|
|
|
C(subject_alt_name) with C(DNS:) prefix if no SAN is specified.
|
|
|
|
version_added: '2.8'
|
2017-09-11 19:05:15 +00:00
|
|
|
key_usage:
|
2017-08-03 11:27:17 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'keyUsage' ]
|
2017-08-03 11:27:17 +00:00
|
|
|
description:
|
|
|
|
- This defines the purpose (e.g. encipherment, signature, certificate signing)
|
|
|
|
of the key contained in the certificate.
|
|
|
|
- This can either be a 'comma separated string' or a YAML list.
|
2017-09-11 19:05:15 +00:00
|
|
|
key_usage_critical:
|
2017-08-15 08:29:29 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'keyUsage_critical' ]
|
2017-08-15 08:29:29 +00:00
|
|
|
description:
|
|
|
|
- Should the keyUsage extension be considered as critical
|
2017-09-11 19:05:15 +00:00
|
|
|
extended_key_usage:
|
2017-08-03 11:27:17 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'extKeyUsage', 'extendedKeyUsage' ]
|
2017-08-03 11:27:17 +00:00
|
|
|
description:
|
|
|
|
- Additional restrictions (e.g. client authentication, server authentication)
|
|
|
|
on the allowed purposes for which the public key may be used.
|
|
|
|
- This can either be a 'comma separated string' or a YAML list.
|
2017-09-11 19:05:15 +00:00
|
|
|
extended_key_usage_critical:
|
2017-08-15 08:29:29 +00:00
|
|
|
required: false
|
2017-09-11 19:05:15 +00:00
|
|
|
aliases: [ 'extKeyUsage_critical', 'extendedKeyUsage_critical' ]
|
2017-08-15 08:29:29 +00:00
|
|
|
description:
|
|
|
|
- Should the extkeyUsage extension be considered as critical
|
2017-11-30 13:50:45 +00:00
|
|
|
basic_constraints:
|
|
|
|
required: false
|
|
|
|
aliases: ['basicConstraints']
|
|
|
|
description:
|
|
|
|
- Indicates basic constraints, such as if the certificate is a CA.
|
|
|
|
version_added: 2.5
|
|
|
|
basic_constraints_critical:
|
|
|
|
required: false
|
|
|
|
aliases: [ 'basicConstraints_critical' ]
|
|
|
|
description:
|
|
|
|
- Should the basicConstraints extension be considered as critical
|
|
|
|
version_added: 2.5
|
2018-02-08 12:03:28 +00:00
|
|
|
ocsp_must_staple:
|
|
|
|
required: false
|
|
|
|
aliases: ['ocspMustStaple']
|
|
|
|
description:
|
|
|
|
- Indicates that the certificate should contain the OCSP Must Staple
|
|
|
|
extension (U(https://tools.ietf.org/html/rfc7633)).
|
|
|
|
version_added: 2.5
|
|
|
|
ocsp_must_staple_critical:
|
|
|
|
required: false
|
|
|
|
aliases: [ 'ocspMustStaple_critical' ]
|
|
|
|
description:
|
|
|
|
- Should the OCSP Must Staple extension be considered as critical
|
|
|
|
- "Warning: according to the RFC, this extension should not be marked
|
|
|
|
as critical, as old clients not knowing about OCSP Must Staple
|
|
|
|
are required to reject such certificates
|
|
|
|
(see U(https://tools.ietf.org/html/rfc7633#section-4))."
|
|
|
|
version_added: 2.5
|
2019-01-21 17:19:05 +00:00
|
|
|
select_crypto_backend:
|
|
|
|
description:
|
|
|
|
- "Determines which crypto backend to use. The default choice is C(auto),
|
|
|
|
which tries to use C(cryptography) if available, and falls back to
|
|
|
|
C(pyopenssl)."
|
|
|
|
- "If set to C(pyopenssl), will try to use the L(pyOpenSSL,https://pypi.org/project/pyOpenSSL/)
|
|
|
|
library."
|
|
|
|
- "If set to C(cryptography), will try to use the
|
|
|
|
L(cryptography,https://cryptography.io/) library."
|
|
|
|
type: str
|
|
|
|
default: 'auto'
|
|
|
|
choices:
|
|
|
|
- auto
|
|
|
|
- cryptography
|
|
|
|
- pyopenssl
|
|
|
|
version_added: "2.8"
|
2017-11-25 21:50:28 +00:00
|
|
|
extends_documentation_fragment: files
|
2017-08-03 11:27:17 +00:00
|
|
|
|
|
|
|
notes:
|
|
|
|
- "If the certificate signing request already exists it will be checked whether subjectAltName,
|
2018-02-08 12:03:28 +00:00
|
|
|
keyUsage, extendedKeyUsage and basicConstraints only contain the requested values, whether
|
|
|
|
OCSP Must Staple is as requested, and if the request was signed by the given private key."
|
2017-04-06 16:09:07 +00:00
|
|
|
'''
|
|
|
|
|
|
|
|
|
|
|
|
EXAMPLES = '''
|
|
|
|
# Generate an OpenSSL Certificate Signing Request
|
|
|
|
- openssl_csr:
|
|
|
|
path: /etc/ssl/csr/www.ansible.com.csr
|
|
|
|
privatekey_path: /etc/ssl/private/ansible.com.pem
|
2017-09-11 19:05:15 +00:00
|
|
|
common_name: www.ansible.com
|
2017-04-06 16:09:07 +00:00
|
|
|
|
2017-07-19 10:02:29 +00:00
|
|
|
# Generate an OpenSSL Certificate Signing Request with a
|
|
|
|
# passphrase protected private key
|
|
|
|
- openssl_csr:
|
|
|
|
path: /etc/ssl/csr/www.ansible.com.csr
|
|
|
|
privatekey_path: /etc/ssl/private/ansible.com.pem
|
|
|
|
privatekey_passphrase: ansible
|
2017-09-11 19:05:15 +00:00
|
|
|
common_name: www.ansible.com
|
2017-07-19 10:02:29 +00:00
|
|
|
|
2017-06-12 06:55:19 +00:00
|
|
|
# Generate an OpenSSL Certificate Signing Request with Subject information
|
2017-04-06 16:09:07 +00:00
|
|
|
- openssl_csr:
|
|
|
|
path: /etc/ssl/csr/www.ansible.com.csr
|
|
|
|
privatekey_path: /etc/ssl/private/ansible.com.pem
|
2017-09-11 19:05:15 +00:00
|
|
|
country_name: FR
|
|
|
|
organization_name: Ansible
|
|
|
|
email_address: jdoe@ansible.com
|
|
|
|
common_name: www.ansible.com
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
# Generate an OpenSSL Certificate Signing Request with subjectAltName extension
|
|
|
|
- openssl_csr:
|
|
|
|
path: /etc/ssl/csr/www.ansible.com.csr
|
|
|
|
privatekey_path: /etc/ssl/private/ansible.com.pem
|
2017-09-11 19:05:15 +00:00
|
|
|
subject_alt_name: 'DNS:www.ansible.com,DNS:m.ansible.com'
|
2017-04-06 16:09:07 +00:00
|
|
|
|
2018-06-20 06:28:59 +00:00
|
|
|
# Generate an OpenSSL CSR with subjectAltName extension with dynamic list
|
|
|
|
- openssl_csr:
|
|
|
|
path: /etc/ssl/csr/www.ansible.com.csr
|
|
|
|
privatekey_path: /etc/ssl/private/ansible.com.pem
|
|
|
|
subject_alt_name: "{{ item.value | map('regex_replace', '^', 'DNS:') | list }}"
|
|
|
|
with_dict:
|
|
|
|
dns_server:
|
|
|
|
- www.ansible.com
|
|
|
|
- m.ansible.com
|
|
|
|
|
2017-04-06 16:09:07 +00:00
|
|
|
# Force re-generate an OpenSSL Certificate Signing Request
|
|
|
|
- openssl_csr:
|
|
|
|
path: /etc/ssl/csr/www.ansible.com.csr
|
|
|
|
privatekey_path: /etc/ssl/private/ansible.com.pem
|
|
|
|
force: True
|
2017-09-11 19:05:15 +00:00
|
|
|
common_name: www.ansible.com
|
2017-08-03 11:27:17 +00:00
|
|
|
|
|
|
|
# Generate an OpenSSL Certificate Signing Request with special key usages
|
|
|
|
- openssl_csr:
|
|
|
|
path: /etc/ssl/csr/www.ansible.com.csr
|
|
|
|
privatekey_path: /etc/ssl/private/ansible.com.pem
|
2017-09-11 19:05:15 +00:00
|
|
|
common_name: www.ansible.com
|
|
|
|
key_usage:
|
2017-11-06 18:39:10 +00:00
|
|
|
- digitalSignature
|
2017-08-03 11:27:17 +00:00
|
|
|
- keyAgreement
|
2017-09-11 19:05:15 +00:00
|
|
|
extended_key_usage:
|
2017-08-03 11:27:17 +00:00
|
|
|
- clientAuth
|
2018-02-08 12:03:28 +00:00
|
|
|
|
|
|
|
# Generate an OpenSSL Certificate Signing Request with OCSP Must Staple
|
|
|
|
- openssl_csr:
|
|
|
|
path: /etc/ssl/csr/www.ansible.com.csr
|
|
|
|
privatekey_path: /etc/ssl/private/ansible.com.pem
|
|
|
|
common_name: www.ansible.com
|
|
|
|
ocsp_must_staple: true
|
2017-04-06 16:09:07 +00:00
|
|
|
'''
|
|
|
|
|
|
|
|
|
|
|
|
RETURN = '''
|
2017-08-03 11:27:17 +00:00
|
|
|
privatekey:
|
|
|
|
description: Path to the TLS/SSL private key the CSR was generated for
|
|
|
|
returned: changed or success
|
2018-12-18 21:25:30 +00:00
|
|
|
type: str
|
2017-08-03 11:27:17 +00:00
|
|
|
sample: /etc/ssl/private/ansible.com.pem
|
|
|
|
filename:
|
2017-04-06 16:09:07 +00:00
|
|
|
description: Path to the generated Certificate Signing Request
|
2017-04-26 14:56:13 +00:00
|
|
|
returned: changed or success
|
2018-12-18 21:25:30 +00:00
|
|
|
type: str
|
2017-04-06 16:09:07 +00:00
|
|
|
sample: /etc/ssl/csr/www.ansible.com.csr
|
|
|
|
subject:
|
2017-12-12 12:35:22 +00:00
|
|
|
description: A list of the subject tuples attached to the CSR
|
2017-04-26 14:56:13 +00:00
|
|
|
returned: changed or success
|
2017-04-06 16:09:07 +00:00
|
|
|
type: list
|
2017-12-12 12:35:22 +00:00
|
|
|
sample: "[('CN', 'www.ansible.com'), ('O', 'Ansible')]"
|
2017-04-06 16:09:07 +00:00
|
|
|
subjectAltName:
|
|
|
|
description: The alternative names this CSR is valid for
|
2017-04-26 14:56:13 +00:00
|
|
|
returned: changed or success
|
2017-08-03 11:27:17 +00:00
|
|
|
type: list
|
|
|
|
sample: [ 'DNS:www.ansible.com', 'DNS:m.ansible.com' ]
|
|
|
|
keyUsage:
|
|
|
|
description: Purpose for which the public key may be used
|
|
|
|
returned: changed or success
|
|
|
|
type: list
|
|
|
|
sample: [ 'digitalSignature', 'keyAgreement' ]
|
|
|
|
extendedKeyUsage:
|
|
|
|
description: Additional restriction on the public key purposes
|
|
|
|
returned: changed or success
|
|
|
|
type: list
|
|
|
|
sample: [ 'clientAuth' ]
|
2017-11-30 13:50:45 +00:00
|
|
|
basicConstraints:
|
|
|
|
description: Indicates if the certificate belongs to a CA
|
|
|
|
returned: changed or success
|
|
|
|
type: list
|
|
|
|
sample: ['CA:TRUE', 'pathLenConstraint:0']
|
2018-02-08 12:03:28 +00:00
|
|
|
ocsp_must_staple:
|
|
|
|
description: Indicates whether the certificate has the OCSP
|
|
|
|
Must Staple feature enabled
|
|
|
|
returned: changed or success
|
|
|
|
type: bool
|
|
|
|
sample: false
|
2017-04-06 16:09:07 +00:00
|
|
|
'''
|
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
import abc
|
2017-04-06 17:41:18 +00:00
|
|
|
import os
|
2019-01-21 17:19:05 +00:00
|
|
|
from distutils.version import LooseVersion
|
2017-04-06 16:09:07 +00:00
|
|
|
|
2017-08-03 11:27:17 +00:00
|
|
|
from ansible.module_utils import crypto as crypto_utils
|
|
|
|
from ansible.module_utils.basic import AnsibleModule
|
2019-01-21 17:19:05 +00:00
|
|
|
from ansible.module_utils._text import to_native, to_bytes, to_text
|
|
|
|
|
|
|
|
MINIMAL_PYOPENSSL_VERSION = '0.15'
|
|
|
|
MINIMAL_CRYPTOGRAPHY_VERSION = '1.3'
|
2017-08-03 11:27:17 +00:00
|
|
|
|
2017-04-06 16:09:07 +00:00
|
|
|
try:
|
2017-09-14 16:03:00 +00:00
|
|
|
import OpenSSL
|
2017-04-06 16:09:07 +00:00
|
|
|
from OpenSSL import crypto
|
2019-01-21 17:19:05 +00:00
|
|
|
PYOPENSSL_VERSION = LooseVersion(OpenSSL.__version__)
|
2017-04-06 16:09:07 +00:00
|
|
|
except ImportError:
|
2019-01-21 17:19:05 +00:00
|
|
|
PYOPENSSL_FOUND = False
|
2017-04-06 16:09:07 +00:00
|
|
|
else:
|
2019-01-21 17:19:05 +00:00
|
|
|
PYOPENSSL_FOUND = True
|
2018-02-08 12:03:28 +00:00
|
|
|
if OpenSSL.SSL.OPENSSL_VERSION_NUMBER >= 0x10100000:
|
|
|
|
# OpenSSL 1.1.0 or newer
|
2019-01-21 17:19:05 +00:00
|
|
|
OPENSSL_MUST_STAPLE_NAME = b"tlsfeature"
|
|
|
|
OPENSSL_MUST_STAPLE_VALUE = b"status_request"
|
2018-02-08 12:03:28 +00:00
|
|
|
else:
|
|
|
|
# OpenSSL 1.0.x or older
|
2019-01-21 17:19:05 +00:00
|
|
|
OPENSSL_MUST_STAPLE_NAME = b"1.3.6.1.5.5.7.1.24"
|
|
|
|
OPENSSL_MUST_STAPLE_VALUE = b"DER:30:03:02:01:05"
|
|
|
|
|
|
|
|
try:
|
|
|
|
import cryptography
|
|
|
|
import cryptography.x509
|
|
|
|
import cryptography.x509.oid
|
|
|
|
import cryptography.exceptions
|
|
|
|
import cryptography.hazmat.backends
|
|
|
|
import cryptography.hazmat.primitives.serialization
|
|
|
|
import cryptography.hazmat.primitives.hashes
|
|
|
|
CRYPTOGRAPHY_VERSION = LooseVersion(cryptography.__version__)
|
|
|
|
except ImportError:
|
|
|
|
CRYPTOGRAPHY_FOUND = False
|
|
|
|
else:
|
|
|
|
CRYPTOGRAPHY_FOUND = True
|
|
|
|
CRYPTOGRAPHY_MUST_STAPLE_NAME = cryptography.x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.1.24")
|
|
|
|
CRYPTOGRAPHY_MUST_STAPLE_VALUE = b"\x30\x03\x02\x01\x05"
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
|
2017-08-03 11:27:17 +00:00
|
|
|
class CertificateSigningRequestError(crypto_utils.OpenSSLObjectError):
|
2017-04-06 16:09:07 +00:00
|
|
|
pass
|
|
|
|
|
2017-04-06 17:41:18 +00:00
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
class CertificateSigningRequestBase(crypto_utils.OpenSSLObject):
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
def __init__(self, module):
|
2019-01-21 17:19:05 +00:00
|
|
|
super(CertificateSigningRequestBase, self).__init__(
|
2017-08-03 11:27:17 +00:00
|
|
|
module.params['path'],
|
|
|
|
module.params['state'],
|
|
|
|
module.params['force'],
|
|
|
|
module.check_mode
|
|
|
|
)
|
2017-04-06 16:09:07 +00:00
|
|
|
self.digest = module.params['digest']
|
|
|
|
self.privatekey_path = module.params['privatekey_path']
|
2017-07-19 10:02:29 +00:00
|
|
|
self.privatekey_passphrase = module.params['privatekey_passphrase']
|
2017-04-06 16:09:07 +00:00
|
|
|
self.version = module.params['version']
|
2017-08-03 11:27:17 +00:00
|
|
|
self.subjectAltName = module.params['subjectAltName']
|
2017-08-15 08:29:29 +00:00
|
|
|
self.subjectAltName_critical = module.params['subjectAltName_critical']
|
2017-08-03 11:27:17 +00:00
|
|
|
self.keyUsage = module.params['keyUsage']
|
2017-08-15 08:29:29 +00:00
|
|
|
self.keyUsage_critical = module.params['keyUsage_critical']
|
2017-08-03 11:27:17 +00:00
|
|
|
self.extendedKeyUsage = module.params['extendedKeyUsage']
|
2017-08-15 08:29:29 +00:00
|
|
|
self.extendedKeyUsage_critical = module.params['extendedKeyUsage_critical']
|
2017-11-30 13:50:45 +00:00
|
|
|
self.basicConstraints = module.params['basicConstraints']
|
|
|
|
self.basicConstraints_critical = module.params['basicConstraints_critical']
|
2018-02-08 12:03:28 +00:00
|
|
|
self.ocspMustStaple = module.params['ocspMustStaple']
|
|
|
|
self.ocspMustStaple_critical = module.params['ocspMustStaple_critical']
|
2017-04-06 16:09:07 +00:00
|
|
|
self.request = None
|
|
|
|
self.privatekey = None
|
|
|
|
|
2017-12-12 12:35:22 +00:00
|
|
|
self.subject = [
|
|
|
|
('C', module.params['countryName']),
|
|
|
|
('ST', module.params['stateOrProvinceName']),
|
|
|
|
('L', module.params['localityName']),
|
|
|
|
('O', module.params['organizationName']),
|
|
|
|
('OU', module.params['organizationalUnitName']),
|
|
|
|
('CN', module.params['commonName']),
|
|
|
|
('emailAddress', module.params['emailAddress']),
|
|
|
|
]
|
2017-04-06 16:09:07 +00:00
|
|
|
|
2017-12-12 12:35:22 +00:00
|
|
|
if module.params['subject']:
|
|
|
|
self.subject = self.subject + crypto_utils.parse_name_field(module.params['subject'])
|
|
|
|
self.subject = [(entry[0], entry[1]) for entry in self.subject if entry[1]]
|
2017-04-06 16:09:07 +00:00
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
if not self.subjectAltName and module.params['useCommonNameForSAN']:
|
2017-12-12 12:35:22 +00:00
|
|
|
for sub in self.subject:
|
2019-01-21 17:19:05 +00:00
|
|
|
if sub[0] in ('commonName', 'CN'):
|
2017-12-12 12:35:22 +00:00
|
|
|
self.subjectAltName = ['DNS:%s' % sub[1]]
|
|
|
|
break
|
2017-04-06 16:09:07 +00:00
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
@abc.abstractmethod
|
|
|
|
def _generate_csr(self):
|
|
|
|
pass
|
|
|
|
|
2017-04-06 16:09:07 +00:00
|
|
|
def generate(self, module):
|
|
|
|
'''Generate the certificate signing request.'''
|
2017-08-03 11:27:17 +00:00
|
|
|
if not self.check(module, perms_required=False) or self.force:
|
2019-01-21 17:19:05 +00:00
|
|
|
result = self._generate_csr()
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
try:
|
2017-07-13 13:42:48 +00:00
|
|
|
csr_file = open(self.path, 'wb')
|
2019-01-21 17:19:05 +00:00
|
|
|
csr_file.write(result)
|
2017-04-06 16:09:07 +00:00
|
|
|
csr_file.close()
|
2017-07-03 10:07:42 +00:00
|
|
|
except (IOError, OSError) as exc:
|
|
|
|
raise CertificateSigningRequestError(exc)
|
2017-08-03 11:27:17 +00:00
|
|
|
|
|
|
|
self.changed = True
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
file_args = module.load_file_common_arguments(module.params)
|
|
|
|
if module.set_fs_attributes_if_different(file_args, False):
|
|
|
|
self.changed = True
|
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
@abc.abstractmethod
|
|
|
|
def _load_private_key(self):
|
|
|
|
pass
|
|
|
|
|
|
|
|
@abc.abstractmethod
|
|
|
|
def _check_csr(self):
|
|
|
|
pass
|
|
|
|
|
2017-08-03 11:27:17 +00:00
|
|
|
def check(self, module, perms_required=True):
|
|
|
|
"""Ensure the resource is in its desired state."""
|
2019-01-21 17:19:05 +00:00
|
|
|
state_and_perms = super(CertificateSigningRequestBase, self).check(module, perms_required)
|
|
|
|
|
|
|
|
self._load_private_key()
|
|
|
|
|
|
|
|
if not state_and_perms:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return self._check_csr()
|
|
|
|
|
|
|
|
def dump(self):
|
|
|
|
'''Serialize the object into a dictionary.'''
|
|
|
|
|
|
|
|
result = {
|
|
|
|
'privatekey': self.privatekey_path,
|
|
|
|
'filename': self.path,
|
|
|
|
'subject': self.subject,
|
|
|
|
'subjectAltName': self.subjectAltName,
|
|
|
|
'keyUsage': self.keyUsage,
|
|
|
|
'extendedKeyUsage': self.extendedKeyUsage,
|
|
|
|
'basicConstraints': self.basicConstraints,
|
|
|
|
'ocspMustStaple': self.ocspMustStaple,
|
|
|
|
'changed': self.changed
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
|
|
|
|
|
|
|
|
class CertificateSigningRequestPyOpenSSL(CertificateSigningRequestBase):
|
|
|
|
|
|
|
|
def __init__(self, module):
|
|
|
|
super(CertificateSigningRequestPyOpenSSL, self).__init__(module)
|
2017-04-06 16:09:07 +00:00
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
def _generate_csr(self):
|
|
|
|
req = crypto.X509Req()
|
|
|
|
req.set_version(self.version - 1)
|
|
|
|
subject = req.get_subject()
|
|
|
|
for entry in self.subject:
|
|
|
|
if entry[1] is not None:
|
|
|
|
# Workaround for https://github.com/pyca/pyopenssl/issues/165
|
|
|
|
nid = OpenSSL._util.lib.OBJ_txt2nid(to_bytes(entry[0]))
|
|
|
|
OpenSSL._util.lib.X509_NAME_add_entry_by_NID(subject._name, nid, OpenSSL._util.lib.MBSTRING_UTF8, to_bytes(entry[1]), -1, -1, 0)
|
|
|
|
|
|
|
|
extensions = []
|
|
|
|
if self.subjectAltName:
|
|
|
|
altnames = ', '.join(self.subjectAltName)
|
|
|
|
extensions.append(crypto.X509Extension(b"subjectAltName", self.subjectAltName_critical, altnames.encode('ascii')))
|
|
|
|
|
|
|
|
if self.keyUsage:
|
|
|
|
usages = ', '.join(self.keyUsage)
|
|
|
|
extensions.append(crypto.X509Extension(b"keyUsage", self.keyUsage_critical, usages.encode('ascii')))
|
|
|
|
|
|
|
|
if self.extendedKeyUsage:
|
|
|
|
usages = ', '.join(self.extendedKeyUsage)
|
|
|
|
extensions.append(crypto.X509Extension(b"extendedKeyUsage", self.extendedKeyUsage_critical, usages.encode('ascii')))
|
|
|
|
|
|
|
|
if self.basicConstraints:
|
|
|
|
usages = ', '.join(self.basicConstraints)
|
|
|
|
extensions.append(crypto.X509Extension(b"basicConstraints", self.basicConstraints_critical, usages.encode('ascii')))
|
|
|
|
|
|
|
|
if self.ocspMustStaple:
|
|
|
|
extensions.append(crypto.X509Extension(OPENSSL_MUST_STAPLE_NAME, self.ocspMustStaple_critical, OPENSSL_MUST_STAPLE_VALUE))
|
|
|
|
|
|
|
|
if extensions:
|
|
|
|
req.add_extensions(extensions)
|
|
|
|
|
|
|
|
req.set_pubkey(self.privatekey)
|
|
|
|
req.sign(self.privatekey, self.digest)
|
|
|
|
self.request = req
|
|
|
|
|
|
|
|
return crypto.dump_certificate_request(crypto.FILETYPE_PEM, self.request)
|
|
|
|
|
|
|
|
def _load_private_key(self):
|
2017-08-03 11:27:17 +00:00
|
|
|
self.privatekey = crypto_utils.load_privatekey(self.privatekey_path, self.privatekey_passphrase)
|
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
def _check_csr(self):
|
2017-08-03 11:27:17 +00:00
|
|
|
def _check_subject(csr):
|
2017-12-12 12:35:22 +00:00
|
|
|
subject = [(OpenSSL._util.lib.OBJ_txt2nid(to_bytes(sub[0])), to_bytes(sub[1])) for sub in self.subject]
|
|
|
|
current_subject = [(OpenSSL._util.lib.OBJ_txt2nid(to_bytes(sub[0])), to_bytes(sub[1])) for sub in csr.get_subject().get_components()]
|
|
|
|
if not set(subject) == set(current_subject):
|
|
|
|
return False
|
2017-08-03 11:27:17 +00:00
|
|
|
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _check_subjectAltName(extensions):
|
2017-08-15 08:29:29 +00:00
|
|
|
altnames_ext = next((ext for ext in extensions if ext.get_short_name() == b'subjectAltName'), '')
|
|
|
|
altnames = [altname.strip() for altname in str(altnames_ext).split(',')]
|
2017-08-03 11:27:17 +00:00
|
|
|
# apperently openssl returns 'IP address' not 'IP' as specifier when converting the subjectAltName to string
|
|
|
|
# although it won't accept this specifier when generating the CSR. (https://github.com/openssl/openssl/issues/4004)
|
|
|
|
altnames = [name if not name.startswith('IP Address:') else "IP:" + name.split(':', 1)[1] for name in altnames]
|
|
|
|
if self.subjectAltName:
|
2017-08-15 08:29:29 +00:00
|
|
|
if set(altnames) != set(self.subjectAltName) or altnames_ext.get_critical() != self.subjectAltName_critical:
|
2017-08-03 11:27:17 +00:00
|
|
|
return False
|
|
|
|
else:
|
|
|
|
if altnames:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return True
|
|
|
|
|
2017-09-14 16:03:00 +00:00
|
|
|
def _check_keyUsage_(extensions, extName, expected, critical):
|
2017-08-15 08:29:29 +00:00
|
|
|
usages_ext = [ext for ext in extensions if ext.get_short_name() == extName]
|
2017-08-03 11:27:17 +00:00
|
|
|
if (not usages_ext and expected) or (usages_ext and not expected):
|
|
|
|
return False
|
|
|
|
elif not usages_ext and not expected:
|
|
|
|
return True
|
2017-04-06 16:09:07 +00:00
|
|
|
else:
|
2017-09-14 16:03:00 +00:00
|
|
|
current = [OpenSSL._util.lib.OBJ_txt2nid(to_bytes(usage.strip())) for usage in str(usages_ext[0]).split(',')]
|
|
|
|
expected = [OpenSSL._util.lib.OBJ_txt2nid(to_bytes(usage)) for usage in expected]
|
2017-08-16 12:35:25 +00:00
|
|
|
return set(current) == set(expected) and usages_ext[0].get_critical() == critical
|
2017-08-03 11:27:17 +00:00
|
|
|
|
|
|
|
def _check_keyUsage(extensions):
|
2019-01-03 11:34:24 +00:00
|
|
|
usages_ext = [ext for ext in extensions if ext.get_short_name() == b'keyUsage']
|
|
|
|
if (not usages_ext and self.keyUsage) or (usages_ext and not self.keyUsage):
|
|
|
|
return False
|
|
|
|
elif not usages_ext and not self.keyUsage:
|
|
|
|
return True
|
|
|
|
else:
|
|
|
|
# OpenSSL._util.lib.OBJ_txt2nid() always returns 0 for all keyUsage values
|
|
|
|
# (since keyUsage has a fixed bitfield for these values and is not extensible).
|
|
|
|
# Therefore, we create an extension for the wanted values, and compare the
|
|
|
|
# data of the extensions (which is the serialized bitfield).
|
|
|
|
expected_ext = crypto.X509Extension(b"keyUsage", False, ', '.join(self.keyUsage).encode('ascii'))
|
|
|
|
return usages_ext[0].get_data() == expected_ext.get_data() and usages_ext[0].get_critical() == self.keyUsage_critical
|
2017-08-03 11:27:17 +00:00
|
|
|
|
|
|
|
def _check_extenededKeyUsage(extensions):
|
2017-09-14 16:03:00 +00:00
|
|
|
return _check_keyUsage_(extensions, b'extendedKeyUsage', self.extendedKeyUsage, self.extendedKeyUsage_critical)
|
2017-08-03 11:27:17 +00:00
|
|
|
|
2017-11-30 13:50:45 +00:00
|
|
|
def _check_basicConstraints(extensions):
|
|
|
|
return _check_keyUsage_(extensions, b'basicConstraints', self.basicConstraints, self.basicConstraints_critical)
|
|
|
|
|
2018-02-08 12:03:28 +00:00
|
|
|
def _check_ocspMustStaple(extensions):
|
2019-01-21 17:19:05 +00:00
|
|
|
oms_ext = [ext for ext in extensions if to_bytes(ext.get_short_name()) == OPENSSL_MUST_STAPLE_NAME and to_bytes(ext) == OPENSSL_MUST_STAPLE_VALUE]
|
2018-02-08 12:03:28 +00:00
|
|
|
if OpenSSL.SSL.OPENSSL_VERSION_NUMBER < 0x10100000:
|
|
|
|
# Older versions of libssl don't know about OCSP Must Staple
|
|
|
|
oms_ext.extend([ext for ext in extensions if ext.get_short_name() == b'UNDEF' and ext.get_data() == b'\x30\x03\x02\x01\x05'])
|
|
|
|
if self.ocspMustStaple:
|
|
|
|
return len(oms_ext) > 0 and oms_ext[0].get_critical() == self.ocspMustStaple_critical
|
|
|
|
else:
|
|
|
|
return len(oms_ext) == 0
|
|
|
|
|
2017-08-03 11:27:17 +00:00
|
|
|
def _check_extensions(csr):
|
|
|
|
extensions = csr.get_extensions()
|
2017-11-30 13:50:45 +00:00
|
|
|
return (_check_subjectAltName(extensions) and _check_keyUsage(extensions) and
|
2018-02-08 12:03:28 +00:00
|
|
|
_check_extenededKeyUsage(extensions) and _check_basicConstraints(extensions) and
|
|
|
|
_check_ocspMustStaple(extensions))
|
2017-08-03 11:27:17 +00:00
|
|
|
|
|
|
|
def _check_signature(csr):
|
|
|
|
try:
|
|
|
|
return csr.verify(self.privatekey)
|
|
|
|
except crypto.Error:
|
|
|
|
return False
|
|
|
|
|
|
|
|
csr = crypto_utils.load_certificate_request(self.path)
|
|
|
|
|
|
|
|
return _check_subject(csr) and _check_extensions(csr) and _check_signature(csr)
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
class CertificateSigningRequestCryptography(CertificateSigningRequestBase):
|
2019-01-14 13:33:51 +00:00
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
def __init__(self, module):
|
|
|
|
super(CertificateSigningRequestCryptography, self).__init__(module)
|
|
|
|
self.cryptography_backend = cryptography.hazmat.backends.default_backend()
|
|
|
|
|
|
|
|
def _get_name_oid(self, id):
|
|
|
|
if id in ('CN', 'commonName'):
|
|
|
|
return cryptography.x509.oid.NameOID.COMMON_NAME
|
|
|
|
if id in ('C', 'countryName'):
|
|
|
|
return cryptography.x509.oid.NameOID.COUNTRY_NAME
|
|
|
|
if id in ('L', 'localityName'):
|
|
|
|
return cryptography.x509.oid.NameOID.LOCALITY_NAME
|
|
|
|
if id in ('ST', 'stateOrProvinceName'):
|
|
|
|
return cryptography.x509.oid.NameOID.STATE_OR_PROVINCE_NAME
|
|
|
|
if id in ('street', 'streetAddress'):
|
|
|
|
return cryptography.x509.oid.NameOID.STREET_ADDRESS
|
|
|
|
if id in ('O', 'organizationName'):
|
|
|
|
return cryptography.x509.oid.NameOID.ORGANIZATION_NAME
|
|
|
|
if id in ('OU', 'organizationalUnitName'):
|
|
|
|
return cryptography.x509.oid.NameOID.ORGANIZATIONAL_UNIT_NAME
|
|
|
|
if id in ('serialNumber', ):
|
|
|
|
return cryptography.x509.oid.NameOID.SERIAL_NUMBER
|
|
|
|
if id in ('SN', 'surname'):
|
|
|
|
return cryptography.x509.oid.NameOID.SURNAME
|
|
|
|
if id in ('GN', 'givenName'):
|
|
|
|
return cryptography.x509.oid.NameOID.GIVEN_NAME
|
|
|
|
if id in ('title', ):
|
|
|
|
return cryptography.x509.oid.NameOID.TITLE
|
|
|
|
if id in ('generationQualifier', ):
|
|
|
|
return cryptography.x509.oid.NameOID.GENERATION_QUALIFIER
|
|
|
|
if id in ('x500UniqueIdentifier', ):
|
|
|
|
return cryptography.x509.oid.NameOID.X500_UNIQUE_IDENTIFIER
|
|
|
|
if id in ('dnQualifier', ):
|
|
|
|
return cryptography.x509.oid.NameOID.DN_QUALIFIER
|
|
|
|
if id in ('pseudonym', ):
|
|
|
|
return cryptography.x509.oid.NameOID.PSEUDONYM
|
|
|
|
if id in ('UID', 'userId'):
|
|
|
|
return cryptography.x509.oid.NameOID.USER_ID
|
|
|
|
if id in ('DC', 'domainComponent'):
|
|
|
|
return cryptography.x509.oid.NameOID.DOMAIN_COMPONENT
|
|
|
|
if id in ('emailAddress', ):
|
|
|
|
return cryptography.x509.oid.NameOID.EMAIL_ADDRESS
|
|
|
|
if id in ('jurisdictionC', 'jurisdictionCountryName'):
|
|
|
|
return cryptography.x509.oid.NameOID.JURISDICTION_COUNTRY_NAME
|
|
|
|
if id in ('jurisdictionL', 'jurisdictionLocalityName'):
|
|
|
|
return cryptography.x509.oid.NameOID.JURISDICTION_LOCALITY_NAME
|
|
|
|
if id in ('jurisdictionST', 'jurisdictionStateOrProvinceName'):
|
|
|
|
return cryptography.x509.oid.NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME
|
|
|
|
if id in ('businessCategory', ):
|
|
|
|
return cryptography.x509.oid.NameOID.BUSINESS_CATEGORY
|
|
|
|
if id in ('postalAddress', ):
|
|
|
|
return cryptography.x509.oid.NameOID.POSTAL_ADDRESS
|
|
|
|
if id in ('postalCode', ):
|
|
|
|
return cryptography.x509.oid.NameOID.POSTAL_CODE
|
|
|
|
raise CertificateSigningRequestError('Unknown subject field identifier "{0}"'.format(id))
|
|
|
|
|
|
|
|
def _get_san(self, name):
|
|
|
|
if name.startswith('DNS:'):
|
|
|
|
return cryptography.x509.DNSName(to_text(name[4:]))
|
|
|
|
if name.startswith('IP:'):
|
|
|
|
return cryptography.x509.IPAddress(to_text(name[3:]))
|
|
|
|
if name.startswith('email:'):
|
|
|
|
return cryptography.x509.RFC822Name(to_text(name[6:]))
|
|
|
|
if name.startswith('URI:'):
|
|
|
|
return cryptography.x509.UniformResourceIdentifier(to_text(name[4:]))
|
|
|
|
if name.startswith('DirName:'):
|
|
|
|
return cryptography.x509.DirectoryName(to_text(name[8:]))
|
|
|
|
if ':' not in name:
|
|
|
|
raise CertificateSigningRequestError('Cannot parse Subject Alternative Name "{0}" (forgot "DNS:" prefix?)'.format(name))
|
|
|
|
raise CertificateSigningRequestError('Cannot parse Subject Alternative Name "{0}" (potentially unsupported by cryptography backend)'.format(name))
|
|
|
|
|
|
|
|
def _get_keyusage(self, usage):
|
|
|
|
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 CertificateSigningRequestError('Unknown key usage "{0}"'.format(usage))
|
|
|
|
|
|
|
|
def _get_ext_keyusage(self, usage):
|
|
|
|
if usage in ('serverAuth', 'TLS Web Server Authentication'):
|
|
|
|
return cryptography.x509.oid.ExtendedKeyUsageOID.SERVER_AUTH
|
|
|
|
if usage in ('clientAuth', 'TLS Web Client Authentication'):
|
|
|
|
return cryptography.x509.oid.ExtendedKeyUsageOID.CLIENT_AUTH
|
|
|
|
if usage in ('codeSigning', 'Code Signing'):
|
|
|
|
return cryptography.x509.oid.ExtendedKeyUsageOID.CODE_SIGNING
|
|
|
|
if usage in ('emailProtection', 'E-mail Protection'):
|
|
|
|
return cryptography.x509.oid.ExtendedKeyUsageOID.EMAIL_PROTECTION
|
|
|
|
if usage in ('timeStamping', 'Time Stamping'):
|
|
|
|
return cryptography.x509.oid.ExtendedKeyUsageOID.TIME_STAMPING
|
|
|
|
if usage in ('OCSPSigning', 'OCSP Signing'):
|
|
|
|
return cryptography.x509.oid.ExtendedKeyUsageOID.OCSP_SIGNING
|
|
|
|
if usage in ('anyExtendedKeyUsage', 'Any Extended Key Usage'):
|
|
|
|
return cryptography.x509.oid.ExtendedKeyUsageOID.ANY_EXTENDED_KEY_USAGE
|
|
|
|
if usage in ('qcStatements', ):
|
|
|
|
return cryptography.x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.1.3")
|
|
|
|
if usage in ('DVCS', ):
|
|
|
|
return cryptography.x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.3.10")
|
|
|
|
if usage in ('IPSec User', 'ipsecUser'):
|
|
|
|
return cryptography.x509.oid.ObjectIdentifier("1.3.6.1.5.5.7.3.7")
|
|
|
|
if usage in ('Biometric Info', 'biometricInfo'):
|
|
|
|
return cryptography.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 CertificateSigningRequestError('Unknown extended key usage "{0}"'.format(usage))
|
|
|
|
|
|
|
|
def _get_basic_constraints(self, constraints):
|
|
|
|
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 CertificateSigningRequestError('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 CertificateSigningRequestError('Cannot parse path length constraint "{0}" ({1})'.format(v, e))
|
|
|
|
else:
|
|
|
|
raise CertificateSigningRequestError('Unknown basic constraint "{0}"'.format(constraint))
|
|
|
|
return ca, path_length
|
|
|
|
|
|
|
|
def _parse_key_usage(self):
|
|
|
|
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 self.keyUsage:
|
|
|
|
params[self._get_keyusage(usage)] = True
|
|
|
|
return params
|
|
|
|
|
|
|
|
def _generate_csr(self):
|
|
|
|
csr = cryptography.x509.CertificateSigningRequestBuilder()
|
|
|
|
csr = csr.subject_name(cryptography.x509.Name([
|
|
|
|
cryptography.x509.NameAttribute(self._get_name_oid(entry[0]), to_text(entry[1])) for entry in self.subject
|
|
|
|
]))
|
|
|
|
|
|
|
|
if self.subjectAltName:
|
|
|
|
csr = csr.add_extension(cryptography.x509.SubjectAlternativeName([
|
|
|
|
self._get_san(name) for name in self.subjectAltName
|
|
|
|
]), critical=self.subjectAltName_critical)
|
|
|
|
|
|
|
|
if self.keyUsage:
|
|
|
|
params = self._parse_key_usage()
|
|
|
|
csr = csr.add_extension(cryptography.x509.KeyUsage(**params), critical=self.keyUsage_critical)
|
|
|
|
|
|
|
|
if self.extendedKeyUsage:
|
|
|
|
usages = [self._get_ext_keyusage(usage) for usage in self.extendedKeyUsage]
|
|
|
|
csr = csr.add_extension(cryptography.x509.ExtendedKeyUsage(usages), critical=self.extendedKeyUsage_critical)
|
|
|
|
|
|
|
|
if self.basicConstraints:
|
|
|
|
params = {}
|
|
|
|
ca, path_length = self._get_basic_constraints(self.basicConstraints)
|
|
|
|
csr = csr.add_extension(cryptography.x509.BasicConstraints(ca, path_length), critical=self.basicConstraints_critical)
|
|
|
|
|
|
|
|
if self.ocspMustStaple:
|
|
|
|
try:
|
|
|
|
# This only works with cryptography >= 2.1
|
|
|
|
csr = csr.add_extension(cryptography.x509.TLSFeature([cryptography.x509.TLSFeatureType.status_request]), critical=self.ocspMustStaple_critical)
|
|
|
|
except AttributeError as dummy:
|
|
|
|
csr = csr.add_extension(
|
|
|
|
cryptography.x509.UnrecognizedExtension(CRYPTOGRAPHY_MUST_STAPLE_NAME, CRYPTOGRAPHY_MUST_STAPLE_VALUE),
|
|
|
|
critical=self.ocspMustStaple_critical
|
|
|
|
)
|
|
|
|
|
|
|
|
digest = None
|
|
|
|
if self.digest == 'sha256':
|
|
|
|
digest = cryptography.hazmat.primitives.hashes.SHA256()
|
|
|
|
elif self.digest == 'sha384':
|
|
|
|
digest = cryptography.hazmat.primitives.hashes.SHA384()
|
|
|
|
elif self.digest == 'sha512':
|
|
|
|
digest = cryptography.hazmat.primitives.hashes.SHA512()
|
|
|
|
elif self.digest == 'sha1':
|
|
|
|
digest = cryptography.hazmat.primitives.hashes.SHA1()
|
|
|
|
elif self.digest == 'md5':
|
|
|
|
digest = cryptography.hazmat.primitives.hashes.MD5()
|
|
|
|
# FIXME
|
|
|
|
else:
|
|
|
|
raise CertificateSigningRequestError('Unsupported digest "{0}"'.format(self.digest))
|
|
|
|
self.request = csr.sign(self.privatekey, digest, self.cryptography_backend)
|
|
|
|
|
|
|
|
return self.request.public_bytes(cryptography.hazmat.primitives.serialization.Encoding.PEM)
|
|
|
|
|
|
|
|
def _load_private_key(self):
|
|
|
|
try:
|
|
|
|
with open(self.privatekey_path, 'rb') as f:
|
|
|
|
self.privatekey = cryptography.hazmat.primitives.serialization.load_pem_private_key(
|
|
|
|
f.read(),
|
|
|
|
None if self.privatekey_passphrase is None else to_bytes(self.privatekey_passphrase),
|
|
|
|
backend=self.cryptography_backend
|
|
|
|
)
|
|
|
|
except Exception as e:
|
|
|
|
raise CertificateSigningRequestError(e)
|
|
|
|
|
|
|
|
def _check_csr(self):
|
|
|
|
def _check_subject(csr):
|
|
|
|
subject = [(self._get_name_oid(entry[0]), entry[1]) for entry in self.subject]
|
|
|
|
current_subject = [(sub.oid, sub.value) for sub in csr.subject]
|
|
|
|
return set(subject) == set(current_subject)
|
|
|
|
|
|
|
|
def _find_extension(extensions, type):
|
|
|
|
return next(
|
|
|
|
(ext for ext in extensions if isinstance(ext.value, type)),
|
|
|
|
None
|
|
|
|
)
|
|
|
|
|
|
|
|
def _check_subjectAltName(extensions):
|
|
|
|
current_altnames_ext = _find_extension(extensions, cryptography.x509.SubjectAlternativeName)
|
|
|
|
current_altnames = [str(altname) for altname in current_altnames_ext.value] if current_altnames_ext else []
|
|
|
|
altnames = [str(self._get_san(altname)) for altname in self.subjectAltName]
|
|
|
|
if set(altnames) != set(current_altnames):
|
|
|
|
return False
|
|
|
|
if altnames:
|
|
|
|
if current_altnames_ext.critical != self.subjectAltName_critical:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _check_keyUsage(extensions):
|
|
|
|
current_keyusage_ext = _find_extension(extensions, cryptography.x509.KeyUsage)
|
|
|
|
if not self.keyUsage:
|
|
|
|
return current_keyusage_ext is None
|
|
|
|
elif current_keyusage_ext is None:
|
|
|
|
return False
|
|
|
|
params = self._parse_key_usage()
|
|
|
|
for param in params:
|
|
|
|
if getattr(current_keyusage_ext.value, '_' + param) != params[param]:
|
|
|
|
return False
|
|
|
|
if current_keyusage_ext.critical != self.keyUsage_critical:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _check_extenededKeyUsage(extensions):
|
|
|
|
current_usages_ext = _find_extension(extensions, cryptography.x509.ExtendedKeyUsage)
|
|
|
|
current_usages = [str(usage) for usage in current_usages_ext.value] if current_usages_ext else []
|
|
|
|
usages = [str(self._get_ext_keyusage(usage)) for usage in self.extendedKeyUsage] if self.extendedKeyUsage else []
|
|
|
|
if set(current_usages) != set(usages):
|
|
|
|
return False
|
|
|
|
if usages:
|
|
|
|
if current_usages_ext.critical != self.extendedKeyUsage_critical:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _check_basicConstraints(extensions):
|
|
|
|
bc_ext = _find_extension(extensions, cryptography.x509.BasicConstraints)
|
|
|
|
current_ca = bc_ext.ca if bc_ext else False
|
|
|
|
current_path_length = bc_ext.path_length if bc_ext else None
|
|
|
|
ca, path_length = self._get_basic_constraints(self.basicConstraints)
|
|
|
|
# Check CA flag
|
|
|
|
if ca != current_ca:
|
|
|
|
return False
|
|
|
|
# Check path length
|
|
|
|
if path_length != current_path_length:
|
|
|
|
return False
|
|
|
|
# Check criticality
|
|
|
|
if self.basicConstraints:
|
|
|
|
if bc_ext.critical != self.basicConstraints_critical:
|
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def _check_ocspMustStaple(extensions):
|
|
|
|
try:
|
|
|
|
# This only works with cryptography >= 2.1
|
|
|
|
tlsfeature_ext = _find_extension(extensions, cryptography.x509.TLSFeature)
|
|
|
|
has_tlsfeature = True
|
|
|
|
except AttributeError as dummy:
|
|
|
|
tlsfeature_ext = next(
|
|
|
|
(ext for ext in extensions if ext.value.oid == CRYPTOGRAPHY_MUST_STAPLE_NAME),
|
|
|
|
None
|
|
|
|
)
|
|
|
|
has_tlsfeature = False
|
|
|
|
if self.ocspMustStaple:
|
|
|
|
if not tlsfeature_ext or tlsfeature_ext.critical != self.ocspMustStaple_critical:
|
|
|
|
return False
|
|
|
|
if has_tlsfeature:
|
|
|
|
return cryptography.x509.TLSFeatureType.status_request in tlsfeature_ext.value
|
|
|
|
else:
|
|
|
|
return tlsfeature_ext.value.value == CRYPTOGRAPHY_MUST_STAPLE_VALUE
|
|
|
|
else:
|
|
|
|
return tlsfeature_ext is None
|
|
|
|
|
|
|
|
def _check_extensions(csr):
|
|
|
|
extensions = csr.extensions
|
|
|
|
return (_check_subjectAltName(extensions) and _check_keyUsage(extensions) and
|
|
|
|
_check_extenededKeyUsage(extensions) and _check_basicConstraints(extensions) and
|
|
|
|
_check_ocspMustStaple(extensions))
|
|
|
|
|
|
|
|
def _check_signature(csr):
|
|
|
|
if not csr.is_signature_valid:
|
|
|
|
return False
|
|
|
|
# To check whether public key of CSR belongs to private key,
|
|
|
|
# encode both public keys and compare PEMs.
|
|
|
|
key_a = csr.public_key().public_bytes(
|
|
|
|
cryptography.hazmat.primitives.serialization.Encoding.PEM,
|
|
|
|
cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo
|
|
|
|
)
|
|
|
|
key_b = self.privatekey.public_key().public_bytes(
|
|
|
|
cryptography.hazmat.primitives.serialization.Encoding.PEM,
|
|
|
|
cryptography.hazmat.primitives.serialization.PublicFormat.SubjectPublicKeyInfo
|
|
|
|
)
|
|
|
|
return key_a == key_b
|
|
|
|
|
|
|
|
try:
|
|
|
|
with open(self.path, 'rb') as f:
|
|
|
|
csr = cryptography.x509.load_pem_x509_csr(f.read(), self.cryptography_backend)
|
|
|
|
except Exception as dummy:
|
|
|
|
return False
|
|
|
|
|
|
|
|
return _check_subject(csr) and _check_extensions(csr) and _check_signature(csr)
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
def main():
|
|
|
|
module = AnsibleModule(
|
2017-04-06 17:41:18 +00:00
|
|
|
argument_spec=dict(
|
2017-04-06 16:09:07 +00:00
|
|
|
state=dict(default='present', choices=['present', 'absent'], type='str'),
|
|
|
|
digest=dict(default='sha256', type='str'),
|
|
|
|
privatekey_path=dict(require=True, type='path'),
|
2017-07-19 10:02:29 +00:00
|
|
|
privatekey_passphrase=dict(type='str', no_log=True),
|
2017-09-14 13:21:32 +00:00
|
|
|
version=dict(default='1', type='int'),
|
2017-04-06 16:09:07 +00:00
|
|
|
force=dict(default=False, type='bool'),
|
|
|
|
path=dict(required=True, type='path'),
|
2017-12-12 12:35:22 +00:00
|
|
|
subject=dict(type='dict'),
|
2017-09-11 19:05:15 +00:00
|
|
|
countryName=dict(aliases=['C', 'country_name'], type='str'),
|
|
|
|
stateOrProvinceName=dict(aliases=['ST', 'state_or_province_name'], type='str'),
|
|
|
|
localityName=dict(aliases=['L', 'locality_name'], type='str'),
|
|
|
|
organizationName=dict(aliases=['O', 'organization_name'], type='str'),
|
|
|
|
organizationalUnitName=dict(aliases=['OU', 'organizational_unit_name'], type='str'),
|
|
|
|
commonName=dict(aliases=['CN', 'common_name'], type='str'),
|
|
|
|
emailAddress=dict(aliases=['E', 'email_address'], type='str'),
|
2018-11-26 15:17:25 +00:00
|
|
|
subjectAltName=dict(aliases=['subject_alt_name'], type='list', elements='str'),
|
2017-09-11 19:05:15 +00:00
|
|
|
subjectAltName_critical=dict(aliases=['subject_alt_name_critical'], default=False, type='bool'),
|
2019-01-21 17:19:05 +00:00
|
|
|
useCommonNameForSAN=dict(type='bool', default=True),
|
2018-11-26 15:17:25 +00:00
|
|
|
keyUsage=dict(aliases=['key_usage'], type='list', elements='str'),
|
2017-09-11 19:05:15 +00:00
|
|
|
keyUsage_critical=dict(aliases=['key_usage_critical'], default=False, type='bool'),
|
2019-01-09 14:10:17 +00:00
|
|
|
extendedKeyUsage=dict(aliases=['extKeyUsage', 'extended_key_usage'], type='list', elements='str'),
|
|
|
|
extendedKeyUsage_critical=dict(aliases=['extKeyUsage_critical', 'extended_key_usage_critical'], default=False, type='bool'),
|
2018-11-26 15:17:25 +00:00
|
|
|
basicConstraints=dict(aliases=['basic_constraints'], type='list', elements='str'),
|
2017-11-30 13:50:45 +00:00
|
|
|
basicConstraints_critical=dict(aliases=['basic_constraints_critical'], default=False, type='bool'),
|
2018-02-08 12:03:28 +00:00
|
|
|
ocspMustStaple=dict(aliases=['ocsp_must_staple'], default=False, type='bool'),
|
|
|
|
ocspMustStaple_critical=dict(aliases=['ocsp_must_staple_critical'], default=False, type='bool'),
|
2019-01-21 17:19:05 +00:00
|
|
|
select_crypto_backend=dict(required=False, choices=['auto', 'pyopenssl', 'cryptography'], default='auto', type='str'),
|
2017-04-06 16:09:07 +00:00
|
|
|
),
|
2017-04-06 17:41:18 +00:00
|
|
|
add_file_common_args=True,
|
|
|
|
supports_check_mode=True,
|
2017-04-06 16:09:07 +00:00
|
|
|
)
|
|
|
|
|
2019-01-03 11:34:46 +00:00
|
|
|
base_dir = os.path.dirname(module.params['path']) or '.'
|
2017-04-06 16:09:07 +00:00
|
|
|
if not os.path.isdir(base_dir):
|
2017-08-03 11:27:17 +00:00
|
|
|
module.fail_json(name=base_dir, msg='The directory %s does not exist or the file is not a directory' % base_dir)
|
2017-04-06 16:09:07 +00:00
|
|
|
|
2019-01-21 17:19:05 +00:00
|
|
|
backend = module.params['select_crypto_backend']
|
|
|
|
if backend == 'auto':
|
|
|
|
# Detection what is possible
|
|
|
|
can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(MINIMAL_CRYPTOGRAPHY_VERSION)
|
|
|
|
can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >= LooseVersion(MINIMAL_PYOPENSSL_VERSION)
|
|
|
|
|
|
|
|
# First try cryptography, then pyOpenSSL
|
|
|
|
if can_use_cryptography:
|
|
|
|
backend = 'cryptography'
|
|
|
|
elif can_use_pyopenssl:
|
|
|
|
backend = 'pyopenssl'
|
|
|
|
|
|
|
|
# Success?
|
|
|
|
if backend == 'auto':
|
|
|
|
module.fail_json(msg=('Can detect none of the Python libraries '
|
|
|
|
'cryptography (>= {0}) and pyOpenSSL (>= {1})').format(
|
|
|
|
MINIMAL_CRYPTOGRAPHY_VERSION,
|
|
|
|
MINIMAL_PYOPENSSL_VERSION))
|
|
|
|
if backend == 'pyopenssl':
|
|
|
|
if not PYOPENSSL_FOUND:
|
|
|
|
module.fail_json(msg='The Python pyOpenSSL library is required')
|
|
|
|
try:
|
|
|
|
getattr(crypto.X509Req, 'get_extensions')
|
|
|
|
except AttributeError:
|
|
|
|
module.fail_json(msg='You need to have PyOpenSSL>=0.15 to generate CSRs')
|
|
|
|
csr = CertificateSigningRequestPyOpenSSL(module)
|
|
|
|
elif backend == 'cryptography':
|
|
|
|
if not CRYPTOGRAPHY_FOUND:
|
|
|
|
module.fail_json(msg='The Python cryptography library is required')
|
|
|
|
csr = CertificateSigningRequestCryptography(module)
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
if module.params['state'] == 'present':
|
|
|
|
|
|
|
|
if module.check_mode:
|
|
|
|
result = csr.dump()
|
2017-08-03 11:27:17 +00:00
|
|
|
result['changed'] = module.params['force'] or not csr.check(module)
|
2017-04-06 16:09:07 +00:00
|
|
|
module.exit_json(**result)
|
|
|
|
|
|
|
|
try:
|
|
|
|
csr.generate(module)
|
2017-08-03 11:27:17 +00:00
|
|
|
except (CertificateSigningRequestError, crypto_utils.OpenSSLObjectError) as exc:
|
2017-07-03 10:07:42 +00:00
|
|
|
module.fail_json(msg=to_native(exc))
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
else:
|
|
|
|
|
|
|
|
if module.check_mode:
|
|
|
|
result = csr.dump()
|
2017-08-03 11:27:17 +00:00
|
|
|
result['changed'] = os.path.exists(module.params['path'])
|
2017-04-06 16:09:07 +00:00
|
|
|
module.exit_json(**result)
|
|
|
|
|
|
|
|
try:
|
|
|
|
csr.remove()
|
2017-08-03 11:27:17 +00:00
|
|
|
except (CertificateSigningRequestError, crypto_utils.OpenSSLObjectError) as exc:
|
2017-07-03 10:07:42 +00:00
|
|
|
module.fail_json(msg=to_native(exc))
|
2017-04-06 16:09:07 +00:00
|
|
|
|
|
|
|
result = csr.dump()
|
|
|
|
|
|
|
|
module.exit_json(**result)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
main()
|