Debian Codegraph @

ansible_collections/dellemc/openmanage/plugins/modules/ome_application_certificate.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.12.4
7 # Copyright (C) 2020-2025 Dell Inc. or its subsidiaries. All Rights Reserved.
8
9 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
10 #
11
12
13 from __future__ import (absolute_import, division, print_function)
14
15 __metaclass__ = type
16
17 DOCUMENTATION = r'''
18 ---
19 module: ome_application_certificate
20 short_description: This module allows to generate a CSR and upload the certificate
21 version_added: "2.1.0"
22 description:
23 - This module allows the generation a new certificate signing request (CSR) and to upload the certificate
24 on OpenManage Enterprise.
25 notes:
26 - If a certificate is uploaded, which is identical to an already existing certificate, it is accepted by the module.
27 - This module does not support C(check_mode).
28 extends_documentation_fragment:
29 - dellemc.openmanage.ome_auth_options
30 options:
31 command:
32 description:
33 - C(generate_csr) allows the generation of a CSR.
34 - C(upload) uploads the certificate on OpenManage Enterprise.
35 - C(upload_cert_chain) uploads the certificate chain on OpenManage Enterprise.
36 type: str
37 default: generate_csr
38 choices: [generate_csr, upload, upload_cert_chain]
39 distinguished_name:
40 description: Name of the certificate issuer. This option is applicable for C(generate_csr).
41 type: str
42 department_name:
43 description: Name of the department that issued the certificate. This option is applicable for C(generate_csr).
44 type: str
45 business_name:
46 description: Name of the business that issued the certificate. This option is applicable for C(generate_csr).
47 type: str
48 locality:
49 description: Local address of the issuer of the certificate. This option is applicable for C(generate_csr).
50 type: str
51 country_state:
52 description: State in which the issuer resides. This option is applicable for C(generate_csr).
53 type: str
54 country:
55 description: Country in which the issuer resides. This option is applicable for C(generate_csr).
56 type: str
57 email:
58 description: Email associated with the issuer. This option is applicable for C(generate_csr).
59 type: str
60 subject_alternative_names:
61 description:
62 - Subject alternative name required for the certificate signing request generation.
63 - Supports up to 4 comma separated values starting from primary, secondary, Tertiary and Quaternary values.
64 type: str
65 version_added: 8.1.0
66 upload_file:
67 type: str
68 description: Local path of the certificate file to be uploaded. This option is applicable for C(upload) and C(upload_cert_chain).
69 Once the certificate is uploaded, OpenManage Enterprise cannot be accessed for a few seconds. The formats of the certificate
70 file are .crt, .cer, .ca-bundle, .p7b, .der, and .pem.
71 requirements:
72 - "python >= 3.9.6"
73 author:
74 - "Felix Stephen (@felixs88)"
75 - "Kritika Bhateja (@Kritika-Bhateja-03)"
76 - "Jennifer John (@Jennifer-John)"
77 - "Abhishek Sinha (@ABHISHEK-SINHA10)"
78 - "Saksham Nautiyal (@Saksham-Nautiyal)"
79 - "Sapana Gupta (@sapana05)"
80 '''
81
82 EXAMPLES = r'''
83 ---
84 - name: Generate a certificate signing request
85 dellemc.openmanage.ome_application_certificate:
86 hostname: "192.168.0.1"
87 username: "username"
88 password: "password"
89 ca_path: "/path/to/ca_cert.pem"
90 command: "generate_csr"
91 distinguished_name: "hostname.com"
92 department_name: "Remote Access Group"
93 business_name: "Dell Inc."
94 locality: "Round Rock"
95 country_state: "Texas"
96 country: "US"
97 email: "[email protected]"
98
99 - name: Generate a certificate signing request with subject alternative names
100 dellemc.openmanage.ome_application_certificate:
101 hostname: "192.168.0.1"
102 username: "username"
103 password: "password"
104 ca_path: "/path/to/ca_cert.pem"
105 command: "generate_csr"
106 distinguished_name: "hostname.com"
107 subject_alternative_names: "hostname1.chassis.com,hostname2.chassis.com"
108 department_name: "Remote Access Group"
109 business_name: "Dell Inc."
110 locality: "Round Rock"
111 country_state: "Texas"
112 country: "US"
113 email: "[email protected]"
114
115 - name: Upload the certificate
116 dellemc.openmanage.ome_application_certificate:
117 hostname: "192.168.0.1"
118 username: "username"
119 password: "password"
120 ca_path: "/path/to/ca_cert.pem"
121 command: "upload"
122 upload_file: "/path/certificate.cer"
123
124 - name: Upload the certificate chain
125 dellemc.openmanage.ome_application_certificate:
126 hostname: "192.168.0.1"
127 username: "username"
128 password: "password"
129 ca_path: "/path/to/ca_cert.pem"
130 command: "upload_cert_chain"
131 upload_file: "/path/certificate_chain.p7b"
132 '''
133
134 RETURN = r'''
135 ---
136 msg:
137 type: str
138 description: Overall status of the certificate signing request.
139 returned: always
140 sample: "Successfully generated certificate signing request."
141 csr_status:
142 type: dict
143 description: Details of the generated certificate.
144 returned: on success
145 sample:
146 {"CertificateData": "-----BEGIN CERTIFICATE REQUEST-----GHFSUEKLELE
147 af3u4h2rkdkfjasczjfefhkrr/frjrfrjfrxnvzklf/nbcvxmzvndlskmcvbmzkdk
148 kafhaksksvklhfdjtrhhffgeth/tashdrfstkm@kdjFGD/sdlefrujjfvvsfeikdf
149 yeufghdkatbavfdomehtdnske/tahndfavdtdfgeikjlagmdfbandfvfcrfgdtwxc
150 qwgfrteyupojmnsbajdkdbfs/ujdfgthedsygtamnsuhakmanfuarweyuiwruefjr
151 etwuwurefefgfgurkjkdmbvfmvfvfk==-----END CERTIFICATE REQUEST-----"
152 }
153 error_info:
154 description: Details of the HTTP error.
155 returned: on HTTP error
156 type: dict
157 sample:
158 {
159 "error": {
160 "code": "Base.1.0.GeneralError",
161 "message": "A general error has occurred. See ExtendedInfo for more information.",
162 "@Message.ExtendedInfo": [
163 {
164 "MessageId": "CSEC9002",
165 "RelatedProperties": [],
166 "Message": "Unable to upload the certificate because the certificate file provided is invalid.",
167 "MessageArgs": [],
168 "Severity": "Critical",
169 "Resolution": "Make sure the CA certificate and private key are correct and retry the operation."
170 }
171 ]
172 }
173 }
174 '''
175
176 import json
177 import os
178 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
179 from ansible_collections.dellemc.openmanage.plugins.module_utils.utils import get_ome_version
180 from urllib.error import URLError, HTTPError
181 from ansible.module_utils.urls import ConnectionError, SSLValidationError
182 from ansible.module_utils.compat.version import LooseVersion
183
184 UNSUPPORTED_OME = "This operation is not supported on OpenManage Enterprise version {ome_version}"
185 CERT_SIGN = "Successfully generated certificate signing request."
186 CERT_UPLOAD = "Successfully uploaded application certificate."
187
188
189 def generate_csr_payload(module):
190 return {
191 "DistinguishedName": module.params["distinguished_name"],
192 "DepartmentName": module.params["department_name"],
193 "BusinessName": module.params["business_name"],
194 "Locality": module.params["locality"],
195 "State": module.params["country_state"],
196 "Country": module.params["country"],
197 "Email": module.params["email"],
198 "San": get_san(module.params["subject_alternative_names"])
199 }
200
201
202 def read_file_payload(module):
203 file_path = module.params["upload_file"]
204 if os.path.exists(file_path):
205 with open(file_path, 'rb') as file:
206 return file.read()
207 else:
208 module.exit_json(msg="No such file or directory.", failed=True)
209
210
211 def get_resource_parameters(module):
212 command = module.params["command"]
213 csr_uri = "ApplicationService/Actions/ApplicationService.{0}"
214 method = "POST"
215 payload = None
216
217 # Mapping of command to their respective actions
218 command_map = {
219 "generate_csr": {
220 "uri": csr_uri.format("GenerateCSR"),
221 "payload_func": generate_csr_payload
222 },
223 "upload": {
224 "uri": csr_uri.format("UploadCertificate"),
225 "payload_func": read_file_payload
226 },
227 "upload_cert_chain": {
228 "uri": csr_uri.format("UploadCertChain"),
229 "payload_func": read_file_payload
230 }
231 }
232
233 command_details = command_map.get(command)
234 if not command_details:
235 module.exit_json(msg=f"Unknown command: {command}", failed=True)
236
237 uri = command_details["uri"]
238 payload = command_details["payload_func"](module)
239
240 return method, uri, payload
241
242
243 def get_san(subject_alternative_names):
244 if not subject_alternative_names:
245 return subject_alternative_names
246 return subject_alternative_names.replace(" ", "")
247
248
249 def format_csr_string(csr_string):
250 # Remove the header and footer
251 csr_string = csr_string.replace("-----BEGIN CERTIFICATE REQUEST-----", "")
252 csr_string = csr_string.replace("-----END CERTIFICATE REQUEST-----", "")
253 csr_string = csr_string.replace("\n", "")
254
255 # Format the remaining string with proper line breaks
256 formatted_csr = '\n'.join([csr_string[i:i + 64] for i in range(0, len(csr_string), 64)])
257
258 # Add the header and footer back
259 formatted_csr = "-----BEGIN CERTIFICATE REQUEST-----\n" + formatted_csr + "\n-----END CERTIFICATE REQUEST-----"
260
261 return formatted_csr
262
263
264 def main():
265 specs = {
266 "command": {"type": "str", "required": False,
267 "choices": ["generate_csr", "upload", "upload_cert_chain"], "default": "generate_csr"},
268 "distinguished_name": {"required": False, "type": "str"},
269 "department_name": {"required": False, "type": "str"},
270 "business_name": {"required": False, "type": "str"},
271 "locality": {"required": False, "type": "str"},
272 "country_state": {"required": False, "type": "str"},
273 "country": {"required": False, "type": "str"},
274 "email": {"required": False, "type": "str"},
275 "subject_alternative_names": {"required": False, "type": "str"},
276 "upload_file": {"required": False, "type": "str"}
277 }
278
279 module = OmeAnsibleModule(
280 argument_spec=specs,
281 required_if=[["command", "generate_csr", ["distinguished_name", "department_name",
282 "business_name", "locality", "country_state",
283 "country", "email"]],
284 ["command", "upload", ["upload_file"]],
285 ["command", "upload_cert_chain", ["upload_file"]]],
286 supports_check_mode=False
287 )
288
289 header = {"Content-Type": "application/octet-stream", "Accept": "application/octet-stream"}
290 try:
291 with RestOME(module.params, req_session=False) as rest_obj:
292 command = module.params.get("command")
293 if command == "upload_cert_chain":
294 ome_version = get_ome_version(rest_obj)
295 if LooseVersion(ome_version) < "3.10":
296 module.exit_json(msg=UNSUPPORTED_OME.format(ome_version=ome_version), skipped=True)
297
298 method, uri, payload = get_resource_parameters(module)
299 dump = False if command in ["upload", "upload_cert_chain"] else True
300 headers = header if command in ["upload", "upload_cert_chain"] else None
301 resp = rest_obj.invoke_request(method, uri, headers=headers, data=payload, dump=dump)
302 if resp.success:
303 if command == "generate_csr":
304 resp_copy = resp.json_data
305 formatted_csr = format_csr_string(resp_copy["CertificateData"])
306 resp_copy["CertificateData"] = formatted_csr
307 module.exit_json(msg=CERT_SIGN,
308 csr_status=resp_copy)
309 else:
310 module.exit_json(msg=CERT_UPLOAD, changed=True)
311 else:
312 module.exit_json(msg="Request failed", error_info=resp.json_data, failed=True)
313 except HTTPError as err:
314 if 400 == err.code:
315 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
316 module.exit_json(msg=str(err), failed=True)
317 except URLError as err:
318 module.exit_json(msg=str(err), unreachable=True)
319 except (IOError, ValueError, TypeError, ConnectionError, SSLValidationError, OSError) as err:
320 module.exit_json(msg=str(err), failed=True)
321
322
323 if __name__ == '__main__':
324 main()