| 1 |
#!/usr/bin/python |
| 2 |
|
| 3 |
# (c) 2020, NetApp, Inc |
| 4 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 5 |
from __future__ import absolute_import, division, print_function |
| 6 |
__metaclass__ = type |
| 7 |
|
| 8 |
|
| 9 |
DOCUMENTATION = """ |
| 10 |
module: na_santricity_server_certificate |
| 11 |
short_description: NetApp E-Series manage the storage system's server SSL certificates. |
| 12 |
description: Manage NetApp E-Series storage system's server SSL certificates. |
| 13 |
author: |
| 14 |
- Nathan Swartz (@swartzn) |
| 15 |
- Vu Tran (@VuTran007) |
| 16 |
extends_documentation_fragment: |
| 17 |
- netapp_eseries.santricity.santricity.santricity_doc |
| 18 |
options: |
| 19 |
controller: |
| 20 |
description: |
| 21 |
- The controller that owns the port you want to configure. |
| 22 |
- Controller names are represented alphabetically, with the first controller as A, the second as B, and so on. |
| 23 |
- Current hardware models have either 1 or 2 available controllers, but that is not a guaranteed hard limitation and could change in the future. |
| 24 |
- I(controller) must be specified unless managing SANtricity Web Services Proxy (ie I(ssid="proxy")) |
| 25 |
choices: |
| 26 |
- A |
| 27 |
- B |
| 28 |
type: str |
| 29 |
required: false |
| 30 |
certificates: |
| 31 |
description: |
| 32 |
- Unordered list of all server certificate files which include PEM and DER encoded certificates as well as private keys. |
| 33 |
- When I(certificates) is not defined then a self-signed certificate will be expected. |
| 34 |
type: list |
| 35 |
elements: str |
| 36 |
required: false |
| 37 |
passphrase: |
| 38 |
description: |
| 39 |
- Passphrase for PEM encoded private key encryption. |
| 40 |
- If I(passphrase) is not supplied then Ansible will prompt for private key certificate. |
| 41 |
type: str |
| 42 |
required: false |
| 43 |
notes: |
| 44 |
- Set I(ssid=='0') or I(ssid=='proxy') to specifically reference SANtricity Web Services Proxy. |
| 45 |
- Certificates can be the following filetypes - PEM (.pem, .crt, .cer, or .key) or DER (.der or .cer) |
| 46 |
- When I(certificates) is not defined then a self-signed certificate will be expected. |
| 47 |
requirements: |
| 48 |
- cryptography |
| 49 |
""" |
| 50 |
EXAMPLES = """ |
| 51 |
- name: Ensure signed certificate is installed. |
| 52 |
na_santricity_server_certificate: |
| 53 |
ssid: 1 |
| 54 |
api_url: https://192.168.1.100:8443/devmgr/v2 |
| 55 |
api_username: admin |
| 56 |
api_password: adminpass |
| 57 |
controller: A |
| 58 |
certificates: |
| 59 |
- 'root_auth_cert.pem' |
| 60 |
- 'intermediate_auth1_cert.pem' |
| 61 |
- 'intermediate_auth2_cert.pem' |
| 62 |
- 'public_cert.pem' |
| 63 |
- 'private_key.pem' |
| 64 |
passphrase: keypass |
| 65 |
- name: Ensure signed certificate bundle is installed. |
| 66 |
na_santricity_server_certificate: |
| 67 |
ssid: 1 |
| 68 |
api_url: https://192.168.1.100:8443/devmgr/v2 |
| 69 |
api_username: admin |
| 70 |
api_password: adminpass |
| 71 |
controller: B |
| 72 |
certificates: |
| 73 |
- 'cert_bundle.pem' |
| 74 |
passphrase: keypass |
| 75 |
- name: Ensure storage system generated self-signed certificate is installed. |
| 76 |
na_santricity_server_certificate: |
| 77 |
ssid: 1 |
| 78 |
api_url: https://192.168.1.100:8443/devmgr/v2 |
| 79 |
api_username: admin |
| 80 |
api_password: adminpass |
| 81 |
controller: A |
| 82 |
""" |
| 83 |
RETURN = """ |
| 84 |
changed: |
| 85 |
description: Whether changes have been made. |
| 86 |
type: bool |
| 87 |
returned: always |
| 88 |
sample: true |
| 89 |
signed_server_certificate: |
| 90 |
description: Whether the public server certificate is signed. |
| 91 |
type: bool |
| 92 |
returned: always |
| 93 |
sample: true |
| 94 |
added_certificates: |
| 95 |
description: Any SSL certificates that were added. |
| 96 |
type: list |
| 97 |
returned: always |
| 98 |
sample: ['added_certificiate.crt'] |
| 99 |
removed_certificates: |
| 100 |
description: Any SSL certificates that were removed. |
| 101 |
type: list |
| 102 |
returned: always |
| 103 |
sample: ['removed_certificiate.crt'] |
| 104 |
""" |
| 105 |
|
| 106 |
import binascii |
| 107 |
import random |
| 108 |
import re |
| 109 |
|
| 110 |
from ansible.module_utils import six |
| 111 |
from ansible_collections.netapp_eseries.santricity.plugins.module_utils.santricity import NetAppESeriesModule |
| 112 |
from ansible.module_utils._text import to_native |
| 113 |
from time import sleep |
| 114 |
|
| 115 |
try: |
| 116 |
import cryptography |
| 117 |
from cryptography import x509 |
| 118 |
from cryptography.hazmat.primitives import serialization |
| 119 |
from cryptography.hazmat.backends import default_backend |
| 120 |
except ImportError: |
| 121 |
HAS_CRYPTOGRAPHY = False |
| 122 |
else: |
| 123 |
HAS_CRYPTOGRAPHY = True |
| 124 |
|
| 125 |
|
| 126 |
def create_multipart_formdata(file_details): |
| 127 |
"""Create the data for a multipart/form request for a certificate.""" |
| 128 |
boundary = "---------------------------" + "".join([str(random.randint(0, 9)) for x in range(30)]) |
| 129 |
data_parts = list() |
| 130 |
data = None |
| 131 |
|
| 132 |
if six.PY2: # Generate payload for Python 2 |
| 133 |
newline = "\r\n" |
| 134 |
for name, filename, content in file_details: |
| 135 |
data_parts.extend(["--%s" % boundary, |
| 136 |
'Content-Disposition: form-data; name="%s"; filename="%s"' % (name, filename), |
| 137 |
"Content-Type: application/octet-stream", |
| 138 |
"", |
| 139 |
content]) |
| 140 |
data_parts.extend(["--%s--" % boundary, ""]) |
| 141 |
data = newline.join(data_parts) |
| 142 |
|
| 143 |
else: |
| 144 |
newline = six.b("\r\n") |
| 145 |
for name, filename, content in file_details: |
| 146 |
data_parts.extend([six.b("--%s" % boundary), |
| 147 |
six.b('Content-Disposition: form-data; name="%s"; filename="%s"' % (name, filename)), |
| 148 |
six.b("Content-Type: application/octet-stream"), |
| 149 |
six.b(""), |
| 150 |
content]) |
| 151 |
data_parts.extend([six.b("--%s--" % boundary), b""]) |
| 152 |
data = newline.join(data_parts) |
| 153 |
|
| 154 |
headers = { |
| 155 |
"Content-Type": "multipart/form-data; boundary=%s" % boundary, |
| 156 |
"Content-Length": str(len(data))} |
| 157 |
|
| 158 |
return headers, data |
| 159 |
|
| 160 |
|
| 161 |
class NetAppESeriesServerCertificate(NetAppESeriesModule): |
| 162 |
RESET_SSL_CONFIG_TIMEOUT_SEC = 3 * 60 |
| 163 |
|
| 164 |
def __init__(self): |
| 165 |
ansible_options = dict(controller=dict(type="str", required=False, choices=["A", "B"]), |
| 166 |
certificates=dict(type="list", elements="str", required=False), |
| 167 |
passphrase=dict(type="str", required=False, no_log=True)) |
| 168 |
|
| 169 |
super(NetAppESeriesServerCertificate, self).__init__(ansible_options=ansible_options, |
| 170 |
web_services_version="05.00.0000.0000", |
| 171 |
supports_check_mode=True) |
| 172 |
args = self.module.params |
| 173 |
self.controller = args["controller"] |
| 174 |
self.certificates = args["certificates"] if "certificates" in args.keys() else list() |
| 175 |
self.passphrase = args["passphrase"] if "passphrase" in args.keys() else None |
| 176 |
|
| 177 |
# Check whether request needs to be forwarded on to the controller web services rest api. |
| 178 |
self.url_path_prefix = "" |
| 179 |
self.url_path_suffix = "" |
| 180 |
if self.is_proxy(): |
| 181 |
if self.ssid.lower() in ["0", "proxy"]: |
| 182 |
self.url_path_suffix = "?controller=auto" |
| 183 |
elif self.controller is not None: |
| 184 |
self.url_path_prefix = "storage-systems/%s/forward/devmgr/v2/" % self.ssid |
| 185 |
self.url_path_suffix = "?controller=%s" % self.controller.lower() |
| 186 |
else: |
| 187 |
self.module.fail_json(msg="Invalid options! You must specify which controller's certificates to modify. Array [%s]." % self.ssid) |
| 188 |
elif self.controller is None: |
| 189 |
self.module.fail_json(msg="Invalid options! You must specify which controller's certificates to modify. Array [%s]." % self.ssid) |
| 190 |
|
| 191 |
self.cache_get_current_certificates = None |
| 192 |
self.cache_is_controller_alternate = None |
| 193 |
self.cache_is_public_server_certificate_signed = None |
| 194 |
|
| 195 |
def get_controllers(self): |
| 196 |
"""Retrieve a mapping of controller labels to their controller slot.""" |
| 197 |
controllers_dict = {} |
| 198 |
controllers = [] |
| 199 |
try: |
| 200 |
rc, controllers = self.request("storage-systems/%s/controllers" % self.ssid) |
| 201 |
except Exception as error: |
| 202 |
self.module.fail_json(msg="Failed to retrieve the controller settings. Array Id [%s]. Error [%s]." % (self.ssid, to_native(error))) |
| 203 |
|
| 204 |
for controller in controllers: |
| 205 |
slot = controller['physicalLocation']['slot'] |
| 206 |
letter = chr(slot + 64) |
| 207 |
controllers_dict.update({letter: slot}) |
| 208 |
|
| 209 |
return controllers_dict |
| 210 |
|
| 211 |
def check_controller(self): |
| 212 |
"""Is the effected controller the alternate controller.""" |
| 213 |
controllers_info = self.get_controllers() |
| 214 |
try: |
| 215 |
rc, about = self.request("utils/about", rest_api_path=self.DEFAULT_BASE_PATH) |
| 216 |
self.url_path_suffix = "?alternate=%s" % ("true" if controllers_info[self.controller] != about["controllerPosition"] else "false") |
| 217 |
except Exception as error: |
| 218 |
self.module.fail_json(msg="Failed to retrieve accessing controller slot information. Array [%s]." % self.ssid) |
| 219 |
|
| 220 |
@staticmethod |
| 221 |
def sanitize_distinguished_name(dn): |
| 222 |
"""Generate a sorted distinguished name string to account for different formats/orders.""" |
| 223 |
dn = re.sub(" *= *", "=", dn).lower() |
| 224 |
dn = re.sub(", *(?=[a-zA-Z]+={1})", "---SPLIT_MARK---", dn) |
| 225 |
dn_parts = dn.split("---SPLIT_MARK---") |
| 226 |
dn_parts.sort() |
| 227 |
return ",".join(dn_parts) |
| 228 |
|
| 229 |
def certificate_info_from_file(self, path): |
| 230 |
"""Determine the certificate info from the provided filepath.""" |
| 231 |
certificates_info = {} |
| 232 |
try: |
| 233 |
# Treat file as PEM encoded file. |
| 234 |
with open(path, "r") as fh: |
| 235 |
line = fh.readline() |
| 236 |
while line != "": |
| 237 |
|
| 238 |
# Add public certificates to bundle_info. |
| 239 |
if re.search("^-+BEGIN CERTIFICATE-+$", line): |
| 240 |
certificate = line |
| 241 |
line = fh.readline() |
| 242 |
while not re.search("^-+END CERTIFICATE-+$", line): |
| 243 |
if line == "": |
| 244 |
self.module.fail_json(msg="Invalid certificate! Path [%s]. Array [%s]." % (path, self.ssid)) |
| 245 |
certificate += line |
| 246 |
line = fh.readline() |
| 247 |
certificate += line |
| 248 |
if not six.PY2: |
| 249 |
certificate = six.b(certificate) |
| 250 |
info = x509.load_pem_x509_certificate(certificate, default_backend()) |
| 251 |
certificates_info.update(self.certificate_info(info, certificate, path)) |
| 252 |
|
| 253 |
# Add private key to self.private_key. |
| 254 |
elif re.search("^-+BEGIN.*PRIVATE KEY-+$", line): |
| 255 |
pkcs8 = "BEGIN PRIVATE KEY" in line |
| 256 |
pkcs8_encrypted = "BEGIN ENCRYPTED PRIVATE KEY" in line |
| 257 |
key = line |
| 258 |
line = fh.readline() |
| 259 |
while not re.search("^-+END.*PRIVATE KEY-+$", line): |
| 260 |
if line == "": |
| 261 |
self.module.fail_json(msg="Invalid certificate! Array [%s]." % self.ssid) |
| 262 |
key += line |
| 263 |
line = fh.readline() |
| 264 |
key += line |
| 265 |
if not six.PY2: |
| 266 |
key = six.b(key) |
| 267 |
if self.passphrase: |
| 268 |
self.passphrase = six.b(self.passphrase) |
| 269 |
|
| 270 |
# Check for PKCS8 PEM encoding. |
| 271 |
if pkcs8 or pkcs8_encrypted: |
| 272 |
try: |
| 273 |
if pkcs8: |
| 274 |
crypto_key = serialization.load_pem_private_key(key, password=None, backend=default_backend()) |
| 275 |
else: |
| 276 |
crypto_key = serialization.load_pem_private_key(key, password=self.passphrase, backend=default_backend()) |
| 277 |
except ValueError as error: |
| 278 |
self.module.fail_json(msg="Failed to load%sPKCS8 encoded private key. %s" |
| 279 |
" Error [%s]." % (" encrypted " if pkcs8_encrypted else " ", |
| 280 |
"Check passphrase." if pkcs8_encrypted else "", error)) |
| 281 |
|
| 282 |
key = crypto_key.private_bytes(encoding=serialization.Encoding.PEM, |
| 283 |
format=serialization.PrivateFormat.TraditionalOpenSSL, |
| 284 |
encryption_algorithm=serialization.NoEncryption()) |
| 285 |
|
| 286 |
# Check whether multiple private keys have been provided and fail if different |
| 287 |
if "private_key" in certificates_info.keys() and certificates_info["private_key"] != key: |
| 288 |
self.module.fail_json(msg="Multiple private keys have been provided! Array [%s]" % self.ssid) |
| 289 |
else: |
| 290 |
certificates_info.update({"private_key": key}) |
| 291 |
|
| 292 |
line = fh.readline() |
| 293 |
|
| 294 |
# Throw exception when no PEM certificates have been discovered. |
| 295 |
if len(certificates_info) == 0: |
| 296 |
raise Exception("Failed to discover a valid PEM encoded certificate or private key!") |
| 297 |
|
| 298 |
except Exception as error: |
| 299 |
# Treat file as DER encoded certificate |
| 300 |
try: |
| 301 |
with open(path, "rb") as fh: |
| 302 |
cert_info = x509.load_der_x509_certificate(fh.read(), default_backend()) |
| 303 |
cert_data = cert_info.public_bytes(serialization.Encoding.PEM) |
| 304 |
certificates_info.update(self.certificate_info(cert_info, cert_data, path)) |
| 305 |
|
| 306 |
# Throw exception when no DER encoded certificates have been discovered. |
| 307 |
if len(certificates_info) == 0: |
| 308 |
raise Exception("Failed to discover a valid DER encoded certificate!") |
| 309 |
except Exception as error: |
| 310 |
|
| 311 |
# Treat file as DER encoded private key |
| 312 |
try: |
| 313 |
with open(path, "rb") as fh: |
| 314 |
crypto_key = serialization.load_der_public_key(fh.read(), backend=default_backend()) |
| 315 |
key = crypto_key.private_bytes(encoding=serialization.Encoding.PEM, |
| 316 |
format=serialization.PrivateFormat.TraditionalOpenSSL, |
| 317 |
encryption_algorithm=serialization.NoEncryption()) |
| 318 |
certificates_info.update({"private_key": key}) |
| 319 |
except Exception as error: |
| 320 |
self.module.fail_json(msg="Invalid file type! File is neither PEM or DER encoded certificate/private key." |
| 321 |
" Path [%s]. Array [%s]. Error [%s]." % (path, self.ssid, to_native(error))) |
| 322 |
|
| 323 |
return certificates_info |
| 324 |
|
| 325 |
def certificate_info(self, info, data, path): |
| 326 |
"""Load x509 certificate that is either encoded DER or PEM encoding and return the certificate fingerprint.""" |
| 327 |
fingerprint = binascii.hexlify(info.fingerprint(info.signature_hash_algorithm)).decode("utf-8") |
| 328 |
return {self.sanitize_distinguished_name(info.subject.rfc4514_string()): {"alias": fingerprint, "fingerprint": fingerprint, |
| 329 |
"certificate": data, "path": path, |
| 330 |
"issuer": self.sanitize_distinguished_name(info.issuer.rfc4514_string())}} |
| 331 |
|
| 332 |
def get_current_certificates(self): |
| 333 |
"""Determine the server certificates that exist on the storage system.""" |
| 334 |
if self.cache_get_current_certificates is None: |
| 335 |
current_certificates = [] |
| 336 |
try: |
| 337 |
rc, current_certificates = self.request(self.url_path_prefix + "certificates/server%s" % self.url_path_suffix) |
| 338 |
except Exception as error: |
| 339 |
self.module.fail_json(msg="Failed to retrieve server certificates. Array [%s]." % self.ssid) |
| 340 |
|
| 341 |
self.cache_get_current_certificates = {} |
| 342 |
for certificate in current_certificates: |
| 343 |
certificate.update({"issuer": self.sanitize_distinguished_name(certificate["issuerDN"])}) |
| 344 |
self.cache_get_current_certificates.update({self.sanitize_distinguished_name(certificate["subjectDN"]): certificate}) |
| 345 |
|
| 346 |
return self.cache_get_current_certificates |
| 347 |
|
| 348 |
def is_public_server_certificate_signed(self): |
| 349 |
"""Return whether the public server certificate is signed.""" |
| 350 |
if self.cache_is_public_server_certificate_signed is None: |
| 351 |
current_certificates = self.get_current_certificates() |
| 352 |
|
| 353 |
for certificate in current_certificates: |
| 354 |
if current_certificates[certificate]["alias"] == "jetty": |
| 355 |
self.cache_is_public_server_certificate_signed = current_certificates[certificate]["type"] == "caSigned" |
| 356 |
break |
| 357 |
|
| 358 |
return self.cache_is_public_server_certificate_signed |
| 359 |
|
| 360 |
def get_expected_certificates(self): |
| 361 |
"""Determine effected certificates and return certificate list in the required submission order.""" |
| 362 |
certificates_info = {} |
| 363 |
existing_certificates = self.get_current_certificates() |
| 364 |
|
| 365 |
private_key = None |
| 366 |
if self.certificates: |
| 367 |
for path in self.certificates: |
| 368 |
info = self.certificate_info_from_file(path) |
| 369 |
if "private_key" in info.keys(): |
| 370 |
if private_key is not None and info["private_key"] != private_key: |
| 371 |
self.module.fail_json(msg="Multiple private keys have been provided! Array [%s]" % self.ssid) |
| 372 |
else: |
| 373 |
private_key = info.pop("private_key") |
| 374 |
certificates_info.update(info) |
| 375 |
|
| 376 |
# Determine bundle certificate ordering. |
| 377 |
ordered_certificates_info = [dict] * len(certificates_info) |
| 378 |
ordered_certificates_info_index = len(certificates_info) - 1 |
| 379 |
while certificates_info: |
| 380 |
for certificate_subject in certificates_info.keys(): |
| 381 |
|
| 382 |
# Determine all remaining issuers. |
| 383 |
remaining_issuer_list = [info["issuer"] for subject, info in existing_certificates.items()] |
| 384 |
for subject, info in certificates_info.items(): |
| 385 |
remaining_issuer_list.append(info["issuer"]) |
| 386 |
|
| 387 |
# Search for the next certificate that is not an issuer of the remaining certificates in certificates_info dictionary. |
| 388 |
if certificate_subject not in remaining_issuer_list: |
| 389 |
ordered_certificates_info[ordered_certificates_info_index] = certificates_info[certificate_subject] |
| 390 |
certificates_info.pop(certificate_subject) |
| 391 |
ordered_certificates_info_index -= 1 |
| 392 |
break |
| 393 |
else: # Add remaining root certificate if one exists. |
| 394 |
for certificate_subject in certificates_info.keys(): |
| 395 |
ordered_certificates_info[ordered_certificates_info_index] = certificates_info[certificate_subject] |
| 396 |
ordered_certificates_info_index -= 1 |
| 397 |
break |
| 398 |
return {"private_key": private_key, "certificates": ordered_certificates_info} |
| 399 |
|
| 400 |
def determine_changes(self): |
| 401 |
"""Determine certificates that need to be added or removed from storage system's server certificates database.""" |
| 402 |
if not self.is_proxy(): |
| 403 |
self.check_controller() |
| 404 |
existing_certificates = self.get_current_certificates() |
| 405 |
expected = self.get_expected_certificates() |
| 406 |
certificates = expected["certificates"] |
| 407 |
|
| 408 |
changes = {"change_required": False, |
| 409 |
"signed_cert": True if certificates else False, |
| 410 |
"private_key": expected["private_key"], |
| 411 |
"public_cert": None, |
| 412 |
"add_certs": [], |
| 413 |
"remove_certs": []} |
| 414 |
|
| 415 |
# Determine whether any expected certificates are missing from the storage system's database. |
| 416 |
if certificates: |
| 417 |
|
| 418 |
# Create a initial remove_cert list. |
| 419 |
for existing_certificate_subject, existing_certificate in existing_certificates.items(): |
| 420 |
changes["remove_certs"].append(existing_certificate["alias"]) |
| 421 |
|
| 422 |
# Determine expected certificates |
| 423 |
last_certificate_index = len(certificates) - 1 |
| 424 |
for certificate_index, certificate in enumerate(certificates): |
| 425 |
for existing_certificate_subject, existing_certificate in existing_certificates.items(): |
| 426 |
|
| 427 |
if certificate_index == last_certificate_index: |
| 428 |
if existing_certificate["alias"] == "jetty": |
| 429 |
if (certificate["fingerprint"] != existing_certificate["shaFingerprint"] and |
| 430 |
certificate["fingerprint"] != existing_certificate["sha256Fingerprint"]): |
| 431 |
changes["change_required"] = True |
| 432 |
changes["public_cert"] = certificate |
| 433 |
changes["remove_certs"].remove(existing_certificate["alias"]) |
| 434 |
break |
| 435 |
|
| 436 |
elif certificate["alias"] == existing_certificate["alias"]: |
| 437 |
if (certificate["fingerprint"] != existing_certificate["shaFingerprint"] and |
| 438 |
certificate["fingerprint"] != existing_certificate["sha256Fingerprint"]): |
| 439 |
changes["add_certs"].append(certificate) |
| 440 |
changes["change_required"] = True |
| 441 |
changes["remove_certs"].remove(existing_certificate["alias"]) |
| 442 |
break |
| 443 |
|
| 444 |
else: |
| 445 |
changes["add_certs"].append(certificate) |
| 446 |
changes["change_required"] = True |
| 447 |
|
| 448 |
# Determine whether new self-signed certificate needs to be generated. |
| 449 |
elif self.is_public_server_certificate_signed(): |
| 450 |
changes["change_required"] = True |
| 451 |
|
| 452 |
return changes |
| 453 |
|
| 454 |
def apply_self_signed_certificate(self): |
| 455 |
"""Install self-signed server certificate which is generated by the storage system itself.""" |
| 456 |
try: |
| 457 |
rc, resp = self.request(self.url_path_prefix + "certificates/reset%s" % self.url_path_suffix, method="POST") |
| 458 |
except Exception as error: |
| 459 |
self.module.fail_json(msg="Failed to reset SSL configuration back to a self-signed certificate! Array [%s]. Error [%s]." % (self.ssid, error)) |
| 460 |
|
| 461 |
def apply_signed_certificate(self, public_cert, private_key): |
| 462 |
"""Install authoritative signed server certificate whether csr is generated by storage system or not.""" |
| 463 |
if private_key is None: |
| 464 |
headers, data = create_multipart_formdata([("file", "signed_server_certificate", public_cert["certificate"])]) |
| 465 |
else: |
| 466 |
headers, data = create_multipart_formdata([("file", "signed_server_certificate", public_cert["certificate"]), |
| 467 |
("privateKey", "private_key", private_key)]) |
| 468 |
|
| 469 |
try: |
| 470 |
rc, resp = self.request(self.url_path_prefix + "certificates/server%s&replaceMainServerCertificate=true" % self.url_path_suffix, |
| 471 |
method="POST", headers=headers, data=data) |
| 472 |
except Exception as error: |
| 473 |
self.module.fail_json(msg="Failed to upload signed server certificate! Array [%s]. Error [%s]." % (self.ssid, error)) |
| 474 |
|
| 475 |
def upload_authoritative_certificates(self, certificate): |
| 476 |
"""Install all authoritative certificates.""" |
| 477 |
headers, data = create_multipart_formdata([["file", certificate["alias"], certificate["certificate"]]]) |
| 478 |
|
| 479 |
try: |
| 480 |
rc, resp = self.request(self.url_path_prefix + "certificates/server%s&alias=%s" % (self.url_path_suffix, certificate["alias"]), |
| 481 |
method="POST", headers=headers, data=data) |
| 482 |
except Exception as error: |
| 483 |
self.module.fail_json(msg="Failed to upload certificate authority! Array [%s]. Error [%s]." % (self.ssid, error)) |
| 484 |
|
| 485 |
def remove_authoritative_certificates(self, alias): |
| 486 |
"""Delete all authoritative certificates.""" |
| 487 |
try: |
| 488 |
rc, resp = self.request(self.url_path_prefix + "certificates/server/%s%s" % (alias, self.url_path_suffix), method="DELETE") |
| 489 |
except Exception as error: |
| 490 |
self.module.fail_json(msg="Failed to delete certificate authority! Array [%s]. Error [%s]." % (self.ssid, error)) |
| 491 |
|
| 492 |
def reload_ssl_configuration(self): |
| 493 |
"""Asynchronously reloads the SSL configuration.""" |
| 494 |
self.request(self.url_path_prefix + "certificates/reload%s" % self.url_path_suffix, method="POST", ignore_errors=True) |
| 495 |
|
| 496 |
for retry in range(int(self.RESET_SSL_CONFIG_TIMEOUT_SEC / 3)): |
| 497 |
try: |
| 498 |
rc, current_certificates = self.request(self.url_path_prefix + "certificates/server%s" % self.url_path_suffix) |
| 499 |
except Exception as error: |
| 500 |
sleep(3) |
| 501 |
continue |
| 502 |
break |
| 503 |
else: |
| 504 |
self.module.fail_json(msg="Failed to retrieve server certificates. Array [%s]." % self.ssid) |
| 505 |
|
| 506 |
def apply(self): |
| 507 |
"""Apply state changes to the storage array's truststore.""" |
| 508 |
if not HAS_CRYPTOGRAPHY: |
| 509 |
self.module.fail_json(msg="Python cryptography package are missing!") |
| 510 |
|
| 511 |
major, minor, patch = [int(item) for item in str(cryptography.__version__).split(".")] |
| 512 |
if major < 2 or (major == 2 and minor < 5): |
| 513 |
self.module.fail_json(msg="Python cryptography package version must greater than version 2.5! Version [%s]." % cryptography.__version__) |
| 514 |
|
| 515 |
changes = self.determine_changes() |
| 516 |
if changes["change_required"] and not self.module.check_mode: |
| 517 |
|
| 518 |
if changes["signed_cert"]: |
| 519 |
for certificate in changes["add_certs"]: |
| 520 |
self.upload_authoritative_certificates(certificate) |
| 521 |
for certificate_alias in changes["remove_certs"]: |
| 522 |
self.remove_authoritative_certificates(certificate_alias) |
| 523 |
if changes["public_cert"]: |
| 524 |
self.apply_signed_certificate(changes["public_cert"], changes["private_key"]) |
| 525 |
self.reload_ssl_configuration() |
| 526 |
else: |
| 527 |
self.apply_self_signed_certificate() |
| 528 |
self.reload_ssl_configuration() |
| 529 |
|
| 530 |
self.module.exit_json(changed=changes["change_required"], |
| 531 |
signed_server_certificate=changes["signed_cert"], |
| 532 |
added_certificates=[cert["alias"] for cert in changes["add_certs"]], |
| 533 |
removed_certificates=changes["remove_certs"]) |
| 534 |
|
| 535 |
|
| 536 |
def main(): |
| 537 |
client_certs = NetAppESeriesServerCertificate() |
| 538 |
client_certs.apply() |
| 539 |
|
| 540 |
|
| 541 |
if __name__ == "__main__": |
| 542 |
main() |