Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2017, 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_policy
13 short_description: Manage AFM security firewall policies on a BIG-IP
14 description:
15 - Manages AFM (Advanced Firewall Manager) security firewall policies on a BIG-IP.
16 version_added: "1.0.0"
17 options:
18 name:
19 description:
20 - The name of the policy to create.
21 type: str
22 required: True
23 description:
24 description:
25 - The description to attach to the policy.
26 - This parameter is only supported on versions of BIG-IP >= 12.1.0. On earlier
27 versions it is simply ignored.
28 type: str
29 state:
30 description:
31 - When C(state) is C(present), ensures the policy exists.
32 - When C(state) is C(absent), ensures the policy is removed.
33 type: str
34 choices:
35 - present
36 - absent
37 default: present
38 rules:
39 description:
40 - Specifies a list of rules you want associated with this policy.
41 The order of this list is the order they will be evaluated by BIG-IP.
42 If the specified rules do not exist (for example when creating a new
43 policy), they will be created.
44 - Rules specified here, if they do not exist, will be created with "default deny"
45 behavior. It is expected that you follow-up after this module with the actual
46 configuration for these rules.
47 - The C(bigip_firewall_rule) module can also be used to create and
48 edit existing and new rules.
49 type: list
50 elements: str
51 partition:
52 description:
53 - Device partition to manage resources on.
54 type: str
55 default: Common
56 extends_documentation_fragment: f5networks.f5_modules.f5
57 author:
58 - Tim Rupp (@caphrim007)
59 '''
60
61 EXAMPLES = r'''
62 - name: Create a basic policy with some rule stubs
63 bigip_firewall_policy:
64 name: foo
65 rules:
66 - rule1
67 - rule2
68 - rule3
69 provider:
70 password: secret
71 server: lb.mydomain.com
72 user: admin
73 delegate_to: localhost
74 '''
75
76 RETURN = r'''
77 description:
78 description: The new description of the policy.
79 returned: changed
80 type: str
81 sample: My firewall policy
82 rules:
83 description: The list of rules, in the order that they are evaluated, on the device.
84 returned: changed
85 type: list
86 sample: ['rule1', 'rule2', 'rule3']
87 '''
88 from datetime import datetime
89 from ansible.module_utils.basic import (
90 AnsibleModule, env_fallback
91 )
92
93 from ..module_utils.bigip import F5RestClient
94 from ..module_utils.common import (
95 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec
96 )
97 from ..module_utils.icontrol import tmos_version
98 from ..module_utils.teem import send_teem
99
100
101 class Parameters(AnsibleF5Parameters):
102 api_map = {
103 'rulesReference': 'rules'
104 }
105
106 api_attributes = [
107 'description'
108 ]
109
110 returnables = [
111 'description',
112 'rules',
113 ]
114
115 updatables = [
116 'description',
117 'rules'
118 ]
119
120 def to_return(self):
121 result = {}
122 try:
123 for returnable in self.returnables:
124 result[returnable] = getattr(self, returnable)
125 result = self._filter_params(result)
126 except Exception:
127 raise
128 return result
129
130
131 class ModuleParameters(Parameters):
132 @property
133 def rules(self):
134 if self._values['rules'] is None:
135 return None
136 # In case rule values are unicode (as they may be coming from the API
137 result = [str(x) for x in self._values['rules']]
138 return result
139
140
141 class ApiParameters(Parameters):
142 @property
143 def rules(self):
144 result = []
145 if self._values['rules'] is None or 'items' not in self._values['rules']:
146 return []
147 for idx, item in enumerate(self._values['rules']['items']):
148 result.append(dict(item=item['fullPath'], order=idx))
149 result = [x['item'] for x in sorted(result, key=lambda k: k['order'])]
150 return result
151
152
153 class Changes(Parameters):
154 pass
155
156
157 class UsableChanges(Changes):
158 pass
159
160
161 class ReportableChanges(Changes):
162 pass
163
164
165 class Difference(object):
166 def __init__(self, want, have=None):
167 self.want = want
168 self.have = have
169
170 def compare(self, param):
171 try:
172 result = getattr(self, param)
173 return result
174 except AttributeError:
175 return self.__default(param)
176
177 def __default(self, param):
178 attr1 = getattr(self.want, param)
179 try:
180 attr2 = getattr(self.have, param)
181 if attr1 != attr2:
182 return attr1
183 except AttributeError:
184 return attr1
185
186 @property
187 def rules(self):
188 if self.want.rules is None:
189 return None
190 if self.have.rules is None:
191 return self.want.rules
192 if set(self.want.rules) != set(self.have.rules):
193 return self.want.rules
194
195
196 class ModuleManager(object):
197 def __init__(self, *args, **kwargs):
198 self.module = kwargs.get('module', None)
199 self.client = F5RestClient(**self.module.params)
200 self.want = ModuleParameters(params=self.module.params)
201 self.have = ApiParameters()
202 self.changes = UsableChanges()
203
204 def _set_changed_options(self):
205 changed = {}
206 for key in Parameters.returnables:
207 if getattr(self.want, key) is not None:
208 changed[key] = getattr(self.want, key)
209 if changed:
210 self.changes = Changes(params=changed)
211
212 def _update_changed_options(self):
213 diff = Difference(self.want, self.have)
214 updatables = Parameters.updatables
215 changed = dict()
216 for k in updatables:
217 change = diff.compare(k)
218 if change is None:
219 continue
220 else:
221 if isinstance(change, dict):
222 changed.update(change)
223 else:
224 changed[k] = change
225 if changed:
226 self.changes = Changes(params=changed)
227 return True
228 return False
229
230 def should_update(self):
231 result = self._update_changed_options()
232 if result:
233 return True
234 return False
235
236 def exec_module(self):
237 start = datetime.now().isoformat()
238 version = tmos_version(self.client)
239 changed = False
240 result = dict()
241 state = self.want.state
242
243 if state == "present":
244 changed = self.present()
245 elif state == "absent":
246 changed = self.absent()
247
248 changes = self.changes.to_return()
249 result.update(**changes)
250 result.update(dict(changed=changed))
251 self._announce_deprecations(result)
252 send_teem(start, self.client, self.module, version)
253 return result
254
255 def _announce_deprecations(self, result):
256 warnings = result.pop('__warnings', [])
257 for warning in warnings:
258 self.module.deprecate(
259 msg=warning['msg'],
260 version=warning['version']
261 )
262
263 def present(self):
264 if self.exists():
265 return self.update()
266 else:
267 return self.create()
268
269 def exists(self):
270 uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}".format(
271 self.client.provider['server'],
272 self.client.provider['server_port'],
273 transform_name(self.want.partition, self.want.name)
274 )
275 resp = self.client.api.get(uri)
276 try:
277 response = resp.json()
278 except ValueError as ex:
279 raise F5ModuleError(str(ex))
280
281 if resp.status == 404 or 'code' in response and response['code'] == 404:
282 return False
283 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
284 return True
285
286 errors = [401, 403, 409, 500, 501, 502, 503, 504]
287
288 if resp.status in errors or 'code' in response and response['code'] in errors:
289 if 'message' in response:
290 raise F5ModuleError(response['message'])
291 else:
292 raise F5ModuleError(resp.content)
293
294 def update(self):
295 self.have = self.read_current_from_device()
296 if not self.should_update():
297 return False
298 if self.module.check_mode:
299 return True
300 self.update_on_device()
301 return True
302
303 def remove(self):
304 if self.module.check_mode:
305 return True
306 self.remove_from_device()
307 if self.exists():
308 raise F5ModuleError("Failed to delete the resource.")
309 return True
310
311 def create(self):
312 self._set_changed_options()
313 if self.module.check_mode:
314 return True
315 self.create_on_device()
316 return True
317
318 def create_on_device(self):
319 params = self.changes.api_params()
320 params['name'] = self.want.name
321 params['partition'] = self.want.partition
322 uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/".format(
323 self.client.provider['server'],
324 self.client.provider['server_port']
325 )
326 resp = self.client.api.post(uri, json=params)
327 try:
328 response = resp.json()
329 except ValueError as ex:
330 raise F5ModuleError(str(ex))
331
332 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
333 if self.want.rules:
334 self._upsert_policy_rules_on_device()
335 return True
336 raise F5ModuleError(resp.content)
337
338 def update_on_device(self):
339 params = self.changes.api_params()
340 uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}".format(
341 self.client.provider['server'],
342 self.client.provider['server_port'],
343 transform_name(self.want.partition, self.want.name)
344 )
345 if params:
346 resp = self.client.api.patch(uri, json=params)
347 try:
348 response = resp.json()
349 except ValueError as ex:
350 raise F5ModuleError(str(ex))
351
352 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
353 return True
354 raise F5ModuleError(resp.content)
355
356 if self.changes.rules is not None:
357 self._upsert_policy_rules_on_device()
358
359 def absent(self):
360 if self.exists():
361 return self.remove()
362 return False
363
364 def remove_from_device(self):
365 uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}".format(
366 self.client.provider['server'],
367 self.client.provider['server_port'],
368 transform_name(self.want.partition, self.want.name)
369 )
370 response = self.client.api.delete(uri)
371 if response.status == 200:
372 return True
373 raise F5ModuleError(response.content)
374
375 def read_current_from_device(self):
376 uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/?expandSubcollections=true".format(
377 self.client.provider['server'],
378 self.client.provider['server_port'],
379 transform_name(self.want.partition, self.want.name)
380 )
381 resp = self.client.api.get(uri)
382 try:
383 response = resp.json()
384 except ValueError as ex:
385 raise F5ModuleError(str(ex))
386
387 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
388 return ApiParameters(params=response)
389 raise F5ModuleError(resp.content)
390
391 def rule_exists(self, rule):
392 uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/{3}".format(
393 self.client.provider['server'],
394 self.client.provider['server_port'],
395 transform_name(self.want.partition, self.want.name),
396 rule.replace('/', '_')
397 )
398 resp = self.client.api.get(uri)
399 try:
400 response = resp.json()
401 except ValueError as ex:
402 raise F5ModuleError(str(ex))
403
404 if resp.status == 404 or 'code' in response and response['code'] == 404:
405 return False
406 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
407 return True
408
409 errors = [401, 403, 409, 500, 501, 502, 503, 504]
410
411 if resp.status in errors or 'code' in response and response['code'] in errors:
412 if 'message' in response:
413 raise F5ModuleError(response['message'])
414 else:
415 raise F5ModuleError(resp.content)
416
417 def create_default_rule_on_device(self, rule):
418 params = dict(
419 name=rule.replace('/', '_'),
420 action='reject',
421 # Adding items to the end of the list causes the list of rules to match
422 # what the user specified in the original list.
423 placeAfter='last',
424 )
425 uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/".format(
426 self.client.provider['server'],
427 self.client.provider['server_port'],
428 transform_name(self.want.partition, self.want.name),
429 )
430 resp = self.client.api.post(uri, json=params)
431 try:
432 response = resp.json()
433 except ValueError as ex:
434 raise F5ModuleError(str(ex))
435
436 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
437 return True
438 raise F5ModuleError(resp.content)
439
440 def remove_rule_from_device(self, rule):
441 uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/{3}".format(
442 self.client.provider['server'],
443 self.client.provider['server_port'],
444 transform_name(self.want.partition, self.want.name),
445 rule.replace('/', '_'),
446 )
447 # this response returns no payload
448 resp = self.client.api.delete(uri)
449 if resp.status not in [200, 201]:
450 raise F5ModuleError(resp.content)
451
452 def move_rule_to_front(self, rule):
453 params = dict(
454 placeAfter='last'
455 )
456 uri = "https://{0}:{1}/mgmt/tm/security/firewall/policy/{2}/rules/{3}".format(
457 self.client.provider['server'],
458 self.client.provider['server_port'],
459 transform_name(self.want.partition, self.want.name),
460 rule.replace('/', '_')
461 )
462 resp = self.client.api.patch(uri, json=params)
463 try:
464 response = resp.json()
465 except ValueError as ex:
466 raise F5ModuleError(str(ex))
467
468 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
469 return True
470 raise F5ModuleError(resp.content)
471
472 def _upsert_policy_rules_on_device(self):
473 rules = self.changes.rules
474 if rules is None:
475 rules = []
476 self._remove_rule_difference(rules)
477
478 for idx, rule in enumerate(rules):
479 if not self.rule_exists(rule):
480 self.create_default_rule_on_device(rule)
481 for idx, rule in enumerate(rules):
482 self.move_rule_to_front(rule)
483
484 def _remove_rule_difference(self, rules):
485 if rules is None or self.have.rules is None:
486 return
487 have_rules = set(self.have.rules)
488 want_rules = set(rules)
489 removable = have_rules.difference(want_rules)
490 for remove in removable:
491 self.remove_rule_from_device(remove)
492
493
494 class ArgumentSpec(object):
495 def __init__(self):
496 self.supports_check_mode = True
497 argument_spec = dict(
498 name=dict(required=True),
499 description=dict(),
500 rules=dict(
501 type='list',
502 elements='str',
503 ),
504 partition=dict(
505 default='Common',
506 fallback=(env_fallback, ['F5_PARTITION'])
507 ),
508 state=dict(
509 default='present',
510 choices=['present', 'absent']
511 )
512 )
513 self.argument_spec = {}
514 self.argument_spec.update(f5_argument_spec)
515 self.argument_spec.update(argument_spec)
516
517
518 def main():
519 spec = ArgumentSpec()
520
521 module = AnsibleModule(
522 argument_spec=spec.argument_spec,
523 supports_check_mode=spec.supports_check_mode,
524 )
525
526 try:
527 mm = ModuleManager(module=module)
528 results = mm.exec_module()
529 module.exit_json(**results)
530 except F5ModuleError as ex:
531 module.fail_json(msg=str(ex))
532
533
534 if __name__ == '__main__':
535 main()