Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 #
5 # Dell OpenManage Ansible Modules
6 # Version 9.3.0
7 # Copyright (C) 2021-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_security_settings
20 short_description: Configure the login security properties
21 description: This module allows you to configure the login security properties on OpenManage Enterprise or OpenManage Enterprise Modular
22 version_added: "4.4.0"
23 extends_documentation_fragment:
24 - dellemc.openmanage.ome_auth_options
25 options:
26 restrict_allowed_ip_range:
27 description:
28 - Restrict to allow inbound connections only from the specified IP address range.
29 - This is mutually exclusive with I(fips_mode_enable).
30 - "C(NOTE) When I(restrict_allowed_ip_range) is configured on the appliance, any inbound connection to the appliance,
31 such as alert reception, firmware update, and network identities are blocked from the devices that are
32 outside the specified IP address range. However, any outbound connection from the appliance will work on all devices."
33 type: dict
34 suboptions:
35 enable_ip_range:
36 description: Allow connections based on the IP address range.
37 type: bool
38 required: true
39 ip_range:
40 description: "The IP address range in Classless Inter-Domain Routing (CIDR) format.
41 For example: 192.168.100.14/24 or 2001:db8::/24"
42 type: str
43 login_lockout_policy:
44 description:
45 - Locks the application after multiple unsuccessful login attempts.
46 - This is mutually exclusive with I(fips_mode_enable).
47 type: dict
48 suboptions:
49 by_user_name:
50 description: "Enable or disable lockout policy settings based on the user name. This restricts the number of
51 unsuccessful login attempts from a specific user for a specific time interval."
52 type: bool
53 by_ip_address:
54 description: "Enable or disable lockout policy settings based on the IP address. This restricts the number of
55 unsuccessful login attempts from a specific IP address for a specific time interval."
56 type: bool
57 lockout_fail_count:
58 description: "The number of unsuccessful login attempts that are allowed after which the appliance prevents log
59 in from the specific username or IP Address."
60 type: int
61 lockout_fail_window:
62 description: "Lockout fail window is the time in seconds within which the lockout fail count event must occur to
63 trigger the lockout penalty time. Enter the duration for which OpenManage Enterprise must display information
64 about a failed attempt."
65 type: int
66 lockout_penalty_time:
67 description: "The duration of time, in seconds, that login attempts from the specific user or IP address must
68 not be allowed."
69 type: int
70 job_wait:
71 description:
72 - Provides an option to wait for job completion.
73 type: bool
74 default: true
75 job_wait_timeout:
76 description:
77 - The maximum wait time of I(job_wait) in seconds. The job is tracked only for this duration.
78 - This option is applicable when I(job_wait) is C(true).
79 type: int
80 default: 120
81 fips_mode_enable:
82 description:
83 - "The FIPS mode is intended to meet the requirements of FIPS 140-2 level 1. For more information refer to the FIPS
84 user guide"
85 - This is applicable only for OpenManage Enterprise Modular only
86 - This is mutually exclusive with I(restrict_allowed_ip_range) and I(login_lockout_policy).
87 - "C(WARNING) Enabling or Disabling this option resets your chassis to default settings. This may cause change in
88 IP settings and loss of network connectivity."
89 - "C(WARNING) The FIPS mode cannot be enabled on a lead chassis in a multi-chassis management configuration. To toggle
90 enable FIPS on a lead chassis, delete the chassis group, enable FIPS and recreate the group."
91 - "C(WARNING) For a Standalone or member chassis, enabling the FIPS mode deletes any fabrics created. This may cause
92 loss of network connectivity and data paths to the compute sleds."
93 type: bool
94 author:
95 - Jagadeesh N V(@jagadeeshnv)
96 requirements:
97 - "python >= 3.9.6"
98 notes:
99 - Run this module from a system that has direct access to Dell OpenManage Enterprise or OpenManage Enterprise Modular.
100 - This module supports C(check_mode).
101 '''
102
103 EXAMPLES = r'''
104 ---
105 - name: Configure restricted allowed IP range
106 dellemc.openmanage.ome_application_security_settings:
107 hostname: "192.168.0.1"
108 username: "username"
109 password: "password"
110 ca_path: "/path/to/ca_cert.pem"
111 restrict_allowed_ip_range:
112 enable_ip_range: true
113 ip_range: 192.1.2.3/24
114
115 - name: Configure login lockout policy
116 dellemc.openmanage.ome_application_security_settings:
117 hostname: "192.168.0.1"
118 username: "username"
119 password: "password"
120 ca_path: "/path/to/ca_cert.pem"
121 login_lockout_policy:
122 by_user_name: true
123 by_ip_address: true
124 lockout_fail_count: 3
125 lockout_fail_window: 30
126 lockout_penalty_time: 900
127
128 - name: Configure restricted allowed IP range and login lockout policy with job wait time out of 60 seconds
129 dellemc.openmanage.ome_application_security_settings:
130 hostname: "192.168.0.1"
131 username: "username"
132 password: "password"
133 ca_path: "/path/to/ca_cert.pem"
134 restrict_allowed_ip_range:
135 enable_ip_range: true
136 ip_range: 192.1.2.3/24
137 login_lockout_policy:
138 by_user_name: true
139 by_ip_address: true
140 lockout_fail_count: 3
141 lockout_fail_window: 30
142 lockout_penalty_time: 900
143 job_wait_timeout: 60
144
145 - name: Enable FIPS mode
146 dellemc.openmanage.ome_application_security_settings:
147 hostname: "192.168.0.1"
148 username: "username"
149 password: "password"
150 ca_path: "/path/to/ca_cert.pem"
151 fips_mode_enable: true
152 '''
153
154 RETURN = r'''
155 ---
156 msg:
157 description: Overall status of the login security configuration.
158 returned: always
159 type: str
160 sample: "Successfully applied the security settings."
161 job_id:
162 description: Job ID of the security configuration task.
163 returned: When security configuration properties are provided
164 type: int
165 sample: 10123
166 error_info:
167 type: dict
168 description: Details of http error.
169 returned: on http error
170 sample: {
171 "error": {
172 "@Message.ExtendedInfo": [
173 {
174 "Message": "Unable to process the request because the domain information cannot be retrieved.",
175 "MessageArgs": [],
176 "MessageId": "CGEN8007",
177 "RelatedProperties": [],
178 "Resolution": "Verify the status of the database and domain configuration, and then retry the
179 operation.",
180 "Severity": "Critical"
181 }
182 ],
183 "code": "Base.1.0.GeneralError",
184 "message": "A general error has occurred. See ExtendedInfo for more information."
185 }
186 }
187 '''
188
189 GET_SETTINGS = "ApplicationService/Actions/ApplicationService.GetConfiguration"
190 SET_SETTINGS = "ApplicationService/Actions/ApplicationService.ApplyConfiguration"
191 FIPS_MODE = "ApplicationService/Security/SecurityConfiguration"
192 JOB_EXEC_HISTORY = "JobService/Jobs({job_id})/ExecutionHistories"
193 SEC_JOB_TRIGGERED = "Successfully triggered the job to apply security settings."
194 SEC_JOB_COMPLETE = "Successfully applied the security settings."
195 FIPS_TOGGLED = "Successfully {0} the FIPS mode."
196 FIPS_CONN_RESET = "The network connection may have changed. Verify the connection and try again."
197 NO_CHANGES_MSG = "No changes found to be applied."
198 CHANGES_FOUND = "Changes found to be applied."
199 TIMEOUT_NEGATIVE_OR_ZERO_MSG = "The value for the 'job_wait_timeout' parameter cannot be negative or zero."
200 SETTLING_TIME = 2
201 JOB_POLL_INTERVAL = 3
202
203 import json
204 import time
205 from ssl import SSLError
206 from ansible_collections.dellemc.openmanage.plugins.module_utils.ome import RestOME, OmeAnsibleModule
207 from ansible.module_utils.six.moves.urllib.error import URLError, HTTPError
208 from ansible.module_utils.urls import ConnectionError, SSLValidationError
209
210
211 def fips_mode_enable(module, rest_obj):
212 resp = rest_obj.invoke_request("GET", FIPS_MODE)
213 fips_payload = resp.json_data
214 curr_fips_mode = fips_payload.get("FipsMode")
215 if module.params.get("fips_mode_enable") is True:
216 fips_mode = "ON"
217 else:
218 fips_mode = "OFF"
219 if curr_fips_mode.lower() == fips_mode.lower():
220 module.exit_json(msg=NO_CHANGES_MSG)
221 if module.check_mode:
222 module.exit_json(msg=CHANGES_FOUND, changed=True)
223 payload = rest_obj.strip_substr_dict(fips_payload)
224 payload["FipsMode"] = fips_mode
225 rest_obj.invoke_request("PUT", FIPS_MODE, data=payload)
226 module.exit_json(msg=FIPS_TOGGLED.format("disabled" if fips_mode == "OFF" else "enabled"), changed=True)
227
228
229 def get_security_payload(rest_obj):
230 resp = rest_obj.invoke_request("POST", GET_SETTINGS, data={})
231 full_set = resp.json_data
232 comps = full_set.get("SystemConfiguration", {}).get("Components", [{"Attributes": []}])
233 attribs = comps[0].get("Attributes")
234 attr_dict = dict(
235 [(sys.get('Name'), sys.get("Value")) for sys in attribs if "loginsecurity" in sys.get('Name').lower()])
236 return full_set, attr_dict
237
238
239 def compare_merge(module, attr_dict):
240 val_map = {
241 "ip_range": "LoginSecurity.1#IPRangeAddr",
242 "enable_ip_range": "LoginSecurity.1#IPRangeEnable",
243 "by_ip_address": "LoginSecurity.1#LockoutByIPEnable",
244 "by_user_name": "LoginSecurity.1#LockoutByUsernameEnable",
245 "lockout_fail_count": "LoginSecurity.1#LockoutFailCount",
246 "lockout_fail_window": "LoginSecurity.1#LockoutFailCountTime",
247 "lockout_penalty_time": "LoginSecurity.1#LockoutPenaltyTime"
248 }
249 diff = 0
250 inp_dicts = ["restrict_allowed_ip_range", "login_lockout_policy"]
251 for d in inp_dicts:
252 inp_dict = module.params.get(d, {})
253 if inp_dict:
254 for k, v in inp_dict.items():
255 if v is not None:
256 if attr_dict[val_map[k]] != v:
257 attr_dict[val_map[k]] = v
258 diff = diff + 1
259 if attr_dict.get("LoginSecurity.1#IPRangeEnable") is False:
260 if attr_dict.get("LoginSecurity.1#IPRangeAddr") is not None:
261 attr_dict["LoginSecurity.1#IPRangeAddr"] = None
262 diff = diff - 1
263 if not diff:
264 module.exit_json(msg=NO_CHANGES_MSG)
265 if module.check_mode:
266 module.exit_json(msg=CHANGES_FOUND, changed=True)
267 return attr_dict
268
269
270 def get_execution_details(rest_obj, job_id, job_message):
271 try:
272 resp = rest_obj.invoke_request('GET', JOB_EXEC_HISTORY.format(job_id=job_id))
273 ex_hist = resp.json_data.get('value')
274 # Sorting based on startTime and to get latest execution instance.
275 tmp_dict = dict((x["StartTime"], x["Id"]) for x in ex_hist)
276 sorted_dates = sorted(tmp_dict.keys())
277 ex_url = JOB_EXEC_HISTORY.format(job_id=job_id) + "({0})/ExecutionHistoryDetails".format(tmp_dict[sorted_dates[-1]])
278 resp = rest_obj.invoke_request('GET', ex_url)
279 ex_hist = resp.json_data.get('value')
280 message = job_message
281 if len(ex_hist) > 0:
282 message = ex_hist[0].get("Value")
283 except Exception:
284 message = job_message
285 message = message.replace('\n', '. ')
286 return message
287
288
289 def exit_settings(module, rest_obj, job_id):
290 msg = SEC_JOB_TRIGGERED
291 time.sleep(SETTLING_TIME)
292 if module.params.get("job_wait") and module.params.get("job_wait_timeout") <= 0:
293 module.exit_json(msg=TIMEOUT_NEGATIVE_OR_ZERO_MSG, failed=True)
294 if module.params.get("job_wait"):
295 job_failed, job_message = rest_obj.job_tracking(
296 job_id=job_id, job_wait_sec=module.params["job_wait_timeout"], sleep_time=JOB_POLL_INTERVAL)
297 if job_failed is True:
298 job_message = get_execution_details(rest_obj, job_id, job_message)
299 module.exit_json(msg=job_message, failed=True, job_id=job_id)
300 msg = SEC_JOB_COMPLETE
301 module.exit_json(msg=msg, job_id=job_id, changed=True)
302
303
304 def login_security_setting(module, rest_obj):
305 security_set, attr_dict = get_security_payload(rest_obj)
306 new_attr_dict = compare_merge(module, attr_dict)
307 comps = security_set.get("SystemConfiguration", {}).get("Components", [{"Attributes": []}])
308 comps[0]["Attributes"] = [{"Name": k, "Value": v} for k, v in new_attr_dict.items()]
309 resp = rest_obj.invoke_request("POST", SET_SETTINGS, data=security_set)
310 job_id = resp.json_data.get("JobId")
311 exit_settings(module, rest_obj, job_id)
312
313
314 def main():
315 specs = {
316 "restrict_allowed_ip_range": {
317 "type": 'dict', "options": {
318 "enable_ip_range": {"type": 'bool', "required": True},
319 "ip_range": {"type": 'str'}
320 },
321 "required_if": [("enable_ip_range", True, ("ip_range",))]
322 },
323 "login_lockout_policy": {
324 "type": 'dict', "options": {
325 "by_user_name": {"type": 'bool'},
326 "by_ip_address": {"type": 'bool'},
327 "lockout_fail_count": {"type": 'int'},
328 "lockout_fail_window": {"type": 'int'},
329 "lockout_penalty_time": {"type": 'int'}
330 },
331 "required_one_of": [("by_user_name", "by_ip_address", "lockout_fail_count",
332 "lockout_fail_window", "lockout_penalty_time")]
333 },
334 "fips_mode_enable": {"type": 'bool'},
335 "job_wait": {"type": 'bool', "default": True},
336 "job_wait_timeout": {"type": 'int', "default": 120}
337 }
338
339 module = OmeAnsibleModule(
340 argument_spec=specs,
341 mutually_exclusive=[("fips_mode_enable", "login_lockout_policy"),
342 ("fips_mode_enable", "restrict_allowed_ip_range")],
343 required_one_of=[("restrict_allowed_ip_range", "login_lockout_policy", "fips_mode_enable")],
344 supports_check_mode=True)
345
346 try:
347 with RestOME(module.params, req_session=True) as rest_obj:
348 if module.params.get("fips_mode_enable") is not None:
349 fips_mode_enable(module, rest_obj)
350 else:
351 login_security_setting(module, rest_obj)
352 except HTTPError as err:
353 module.exit_json(msg=str(err), error_info=json.load(err), failed=True)
354 except URLError as err:
355 module.exit_json(msg=str(err), unreachable=True)
356 except (IOError, ValueError, TypeError, SSLError, ConnectionError, SSLValidationError, OSError) as err:
357 module.exit_json(msg=str(err), failed=True)
358
359
360 if __name__ == '__main__':
361 main()