Debian Codegraph @

ansible_collections/f5networks/f5_modules/plugins/modules/bigip_firewall_dos_profile.py

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2018, F5 Networks Inc.
5 # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 from __future__ import absolute_import, division, print_function
8 __metaclass__ = type
9
10 DOCUMENTATION = r'''
11 ---
12 module: bigip_firewall_dos_profile
13 short_description: Manage AFM DoS profiles on a BIG-IP
14 description:
15 - Manages AFM (Advanced Firewall Manager) Denial of Service (DoS) profiles on a BIG-IP. To manage the vectors
16 associated with a DoS profile, refer to the C(bigip_firewall_dos_vector) module.
17 version_added: "1.0.0"
18 options:
19 name:
20 description:
21 - Specifies the name of the profile.
22 type: str
23 required: True
24 description:
25 description:
26 - The description of the DoS profile.
27 type: str
28 default_whitelist:
29 description:
30 - The default whitelist address list for the system to use to determine which
31 IP addresses are legitimate.
32 - The system does not examine traffic from the IP addresses in the list when
33 performing DoS prevention.
34 - To define a new whitelist, use the C(bigip_firewall_address_list) module.
35 type: str
36 threshold_sensitivity:
37 description:
38 - Specifies the threshold sensitivity for the DoS profile.
39 - Thresholds for detecting attacks are higher when sensitivity is C(low), and
40 lower when sensitivity is C(high).
41 - When creating a new profile, if this parameter is not specified, the default
42 is C(medium).
43 type: str
44 choices:
45 - low
46 - medium
47 - high
48 partition:
49 description:
50 - Device partition to manage resources on.
51 type: str
52 default: Common
53 state:
54 description:
55 - When C(present), ensures the resource exists.
56 - When C(absent), ensures the resource is removed.
57 type: str
58 choices:
59 - present
60 - absent
61 default: present
62 extends_documentation_fragment: f5networks.f5_modules.f5
63 author:
64 - Tim Rupp (@caphrim007)
65 '''
66
67 EXAMPLES = r'''
68 - name: Create a new DoS profile
69 bigip_firewall_dos_profile:
70 name: profile1
71 description: DoS profile 1
72 provider:
73 password: secret
74 server: lb.mydomain.com
75 user: admin
76 delegate_to: localhost
77 '''
78
79 RETURN = r'''
80 threshold_sensitivity:
81 description: The new threshold sensitivity of the profile.
82 returned: changed
83 type: str
84 sample: low
85 default_whitelist:
86 description: The new whitelist attached to the profile.
87 returned: changed
88 type: str
89 sample: /Common/whitelist1
90 description:
91 description: The description of the profile.
92 returned: changed
93 type: str
94 sample: New description
95 '''
96 from datetime import datetime
97
98 from ansible.module_utils.basic import (
99 AnsibleModule, env_fallback
100 )
101
102 from ..module_utils.bigip import F5RestClient
103 from ..module_utils.common import (
104 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, fq_name
105 )
106 from ..module_utils.icontrol import tmos_version
107 from ..module_utils.teem import send_teem
108
109
110 class Parameters(AnsibleF5Parameters):
111 api_map = {
112 'thresholdSensitivity': 'threshold_sensitivity',
113 'whitelist': 'default_whitelist',
114 }
115
116 api_attributes = [
117 'thresholdSensitivity',
118 'whitelist',
119 'description',
120 ]
121
122 returnables = [
123 'threshold_sensitivity',
124 'default_whitelist',
125 'description',
126 ]
127
128 updatables = [
129 'threshold_sensitivity',
130 'default_whitelist',
131 'description',
132 ]
133
134
135 class ApiParameters(Parameters):
136 pass
137
138
139 class ModuleParameters(Parameters):
140 @property
141 def default_whitelist(self):
142 if self._values['default_whitelist'] is None:
143 return None
144 return fq_name(self.partition, self._values['default_whitelist'])
145
146
147 class Changes(Parameters):
148 def to_return(self):
149 result = {}
150 try:
151 for returnable in self.returnables:
152 result[returnable] = getattr(self, returnable)
153 result = self._filter_params(result)
154 except Exception:
155 raise
156 return result
157
158
159 class UsableChanges(Changes):
160 pass
161
162
163 class ReportableChanges(Changes):
164 pass
165
166
167 class Difference(object):
168 def __init__(self, want, have=None):
169 self.want = want
170 self.have = have
171
172 def compare(self, param):
173 try:
174 result = getattr(self, param)
175 return result
176 except AttributeError:
177 return self.__default(param)
178
179 def __default(self, param):
180 attr1 = getattr(self.want, param)
181 try:
182 attr2 = getattr(self.have, param)
183 if attr1 != attr2:
184 return attr1
185 except AttributeError:
186 return attr1
187
188
189 class ModuleManager(object):
190 def __init__(self, *args, **kwargs):
191 self.module = kwargs.get('module', None)
192 self.client = F5RestClient(**self.module.params)
193 self.want = ModuleParameters(params=self.module.params)
194 self.have = ApiParameters()
195 self.changes = UsableChanges()
196
197 def _set_changed_options(self):
198 changed = {}
199 for key in Parameters.returnables:
200 if getattr(self.want, key) is not None:
201 changed[key] = getattr(self.want, key)
202 if changed:
203 self.changes = UsableChanges(params=changed)
204
205 def _update_changed_options(self):
206 diff = Difference(self.want, self.have)
207 updatables = Parameters.updatables
208 changed = dict()
209 for k in updatables:
210 change = diff.compare(k)
211 if change is None:
212 continue
213 else:
214 if isinstance(change, dict):
215 changed.update(change)
216 else:
217 changed[k] = change
218 if changed:
219 self.changes = UsableChanges(params=changed)
220 return True
221 return False
222
223 def should_update(self):
224 result = self._update_changed_options()
225 if result:
226 return True
227 return False
228
229 def exec_module(self):
230 start = datetime.now().isoformat()
231 version = tmos_version(self.client)
232 changed = False
233 result = dict()
234 state = self.want.state
235
236 if state == "present":
237 changed = self.present()
238 elif state == "absent":
239 changed = self.absent()
240
241 reportable = ReportableChanges(params=self.changes.to_return())
242 changes = reportable.to_return()
243 result.update(**changes)
244 result.update(dict(changed=changed))
245 self._announce_deprecations(result)
246 send_teem(start, self.client, self.module, version)
247 return result
248
249 def _announce_deprecations(self, result):
250 warnings = result.pop('__warnings', [])
251 for warning in warnings:
252 self.client.module.deprecate(
253 msg=warning['msg'],
254 version=warning['version']
255 )
256
257 def present(self):
258 if self.exists():
259 return self.update()
260 else:
261 return self.create()
262
263 def exists(self):
264 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}".format(
265 self.client.provider['server'],
266 self.client.provider['server_port'],
267 transform_name(self.want.partition, self.want.name)
268 )
269 resp = self.client.api.get(uri)
270 try:
271 response = resp.json()
272 except ValueError as ex:
273 raise F5ModuleError(str(ex))
274
275 if resp.status == 404 or 'code' in response and response['code'] == 404:
276 return False
277 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
278 return True
279
280 errors = [401, 403, 409, 500, 501, 502, 503, 504]
281
282 if resp.status in errors or 'code' in response and response['code'] in errors:
283 if 'message' in response:
284 raise F5ModuleError(response['message'])
285 else:
286 raise F5ModuleError(resp.content)
287
288 def update(self):
289 self.have = self.read_current_from_device()
290 if not self.should_update():
291 return False
292 if self.module.check_mode:
293 return True
294 self.update_on_device()
295 return True
296
297 def remove(self):
298 if self.module.check_mode:
299 return True
300 self.remove_from_device()
301 if self.exists():
302 raise F5ModuleError("Failed to delete the resource.")
303 return True
304
305 def create(self):
306 self._set_changed_options()
307 if self.module.check_mode:
308 return True
309 self.create_on_device()
310 return True
311
312 def create_on_device(self):
313 params = self.changes.api_params()
314 params['name'] = self.want.name
315 params['partition'] = self.want.partition
316 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/".format(
317 self.client.provider['server'],
318 self.client.provider['server_port']
319 )
320 resp = self.client.api.post(uri, json=params)
321 try:
322 response = resp.json()
323 except ValueError as ex:
324 raise F5ModuleError(str(ex))
325
326 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
327 return True
328 raise F5ModuleError(resp.content)
329
330 def update_on_device(self):
331 params = self.changes.api_params()
332 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}".format(
333 self.client.provider['server'],
334 self.client.provider['server_port'],
335 transform_name(self.want.partition, self.want.name)
336 )
337 resp = self.client.api.patch(uri, json=params)
338 try:
339 response = resp.json()
340 except ValueError as ex:
341 raise F5ModuleError(str(ex))
342
343 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
344 return True
345 raise F5ModuleError(resp.content)
346
347 def absent(self):
348 if self.exists():
349 return self.remove()
350 return False
351
352 def remove_from_device(self):
353 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}".format(
354 self.client.provider['server'],
355 self.client.provider['server_port'],
356 transform_name(self.want.partition, self.want.name)
357 )
358 resp = self.client.api.delete(uri)
359 if resp.status == 200:
360 return True
361 raise F5ModuleError(resp.content)
362
363 def read_current_from_device(self):
364 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}".format(
365 self.client.provider['server'],
366 self.client.provider['server_port'],
367 transform_name(self.want.partition, self.want.name)
368 )
369 resp = self.client.api.get(uri)
370 try:
371 response = resp.json()
372 except ValueError as ex:
373 raise F5ModuleError(str(ex))
374
375 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
376 return ApiParameters(params=response)
377 raise F5ModuleError(resp.content)
378
379
380 class ArgumentSpec(object):
381 def __init__(self):
382 self.supports_check_mode = True
383 argument_spec = dict(
384 name=dict(required=True),
385 description=dict(),
386 threshold_sensitivity=dict(
387 choices=['low', 'medium', 'high']
388 ),
389 default_whitelist=dict(),
390 state=dict(
391 default='present',
392 choices=['present', 'absent']
393 ),
394 partition=dict(
395 default='Common',
396 fallback=(env_fallback, ['F5_PARTITION'])
397 )
398 )
399 self.argument_spec = {}
400 self.argument_spec.update(f5_argument_spec)
401 self.argument_spec.update(argument_spec)
402
403
404 def main():
405 spec = ArgumentSpec()
406
407 module = AnsibleModule(
408 argument_spec=spec.argument_spec,
409 supports_check_mode=spec.supports_check_mode,
410 )
411
412 try:
413 mm = ModuleManager(module=module)
414 results = mm.exec_module()
415 module.exit_json(**results)
416 except F5ModuleError as ex:
417 module.fail_json(msg=str(ex))
418
419
420 if __name__ == '__main__':
421 main()