Debian Codegraph @

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

raw symbols SCIP
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 #
4 # Copyright: (c) 2019, 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_asm_dos_application
13 short_description: Manage application settings for a DOS profile
14 description:
15 - Manages Application settings for an ASM/AFM DOS profile.
16 version_added: "1.0.0"
17 options:
18 profile:
19 description:
20 - Specifies the name of the profile to manage application settings in.
21 type: str
22 required: True
23 rtbh_duration:
24 description:
25 - Specifies the duration of the RTBH BGP route advertisement, in seconds.
26 - The acceptable range is between 0 and 4294967295 inclusive.
27 type: int
28 rtbh_enable:
29 description:
30 - Specifies whether to enable Remote Triggered Black Hole C(RTBH) of attacking IPs by advertising BGP routes.
31 type: bool
32 scrubbing_duration:
33 description:
34 - Specifies the duration of the Traffic Scrubbing BGP route advertisement, in seconds.
35 - The acceptable range is between 0 and 4294967295 inclusive.
36 type: int
37 scrubbing_enable:
38 description:
39 - Specifies whether to enable Traffic Scrubbing during attacks by advertising BGP routes.
40 type: bool
41 single_page_application:
42 description:
43 - When C(true), specifies the system supports a Single Page Applications.
44 type: bool
45 trigger_irule:
46 description:
47 - When C(true), specifies the system activates an Application DoS iRule event.
48 type: bool
49 geolocations:
50 description:
51 - Manages the geolocations countries whitelist, blacklist.
52 type: dict
53 suboptions:
54 whitelist:
55 description:
56 - A list of countries to be put on the whitelist, must not have overlapping elements with C(blacklist).
57 type: list
58 elements: str
59 blacklist:
60 description:
61 - A list of countries to be put on the blacklist, must not have overlapping elements with C(whitelist).
62 type: list
63 elements: str
64 heavy_urls:
65 description:
66 - Manages Heavy URL protection.
67 - Heavy URLs are a small number of site URLs that might consume considerable server resources per request.
68 type: dict
69 suboptions:
70 auto_detect:
71 description:
72 - Enables or disables automatic heavy URL detection.
73 type: bool
74 latency_threshold:
75 description:
76 - Specifies the latency threshold for automatic heavy URL detection.
77 - The acceptable range is between 0 and 4294967295 miliseconds inclusive.
78 type: int
79 exclude:
80 description:
81 - Specifies a list of URLs or wildcards to exclude from the heavy URLs.
82 type: list
83 elements: str
84 include:
85 description:
86 - Configures additional URLs to include in the heavy URLs that were auto-detected.
87 type: list
88 elements: dict
89 suboptions:
90 url:
91 description:
92 - Specifies the URL to be added to the list of heavy URLs, in addition to those automatically detected.
93 type: str
94 required: True
95 threshold:
96 description:
97 - Specifies the threshold of requests per second, where the URL in question is considered under attack.
98 - The acceptable range is between 1 and 4294967295 inclusive, or C(auto).
99 type: str
100 mobile_detection:
101 description:
102 - Configures detection of mobile applications built with the Anti-Bot Mobile SDK and defines how requests
103 from these mobile application clients are handled.
104 type: dict
105 suboptions:
106 enabled:
107 description:
108 - When C(true), requests from mobile applications built with Anti-Bot Mobile SDK are detected and handled
109 according to the parameters set.
110 - When C(false), these requests are handled like any other request which may let attacks in, or cause false
111 positives.
112 type: bool
113 allow_android_rooted_device:
114 description:
115 - When C(true), the device allows traffic from rooted Android devices.
116 type: bool
117 allow_any_android_package:
118 description:
119 - When C(true), allows any application publisher.
120 - A publisher is identified by the certificate used to sign the application.
121 type: bool
122 allow_any_ios_package:
123 description:
124 - When C(true), allows any iOS package.
125 - A package name is the unique identifier of the mobile application.
126 type: bool
127 allow_jailbroken_devices:
128 description:
129 - When C(true), allows traffic from jailbroken iOS devices.
130 type: bool
131 allow_emulators:
132 description:
133 - When C(true), allows traffic from applications run on emulators.
134 type: bool
135 client_side_challenge_mode:
136 description:
137 - Action to take when a CAPTCHA or Client Side Integrity challenge needs to be presented.
138 - The mobile application user will not see a CAPTCHA challenge and the mobile application will not be
139 presented with the Client Side Integrity challenge. The such options for mobile applications are C(pass)
140 or C(cshui).
141 - When C(pass) the traffic is passed without incident.
142 - When C(cshui) the SDK checks for human interactions with the screen in the last few seconds.
143 If none are detected, the traffic is blocked.
144 type: str
145 choices:
146 - pass
147 - cshui
148 ios_allowed_package_names:
149 description:
150 - Specifies the names of iOS packages to allow traffic on.
151 - This option has no effect when C(allow_any_ios_package) is set to C(true).
152 type: list
153 elements: str
154 android_publishers:
155 description:
156 - This option has no effect when C(allow_any_android_package) is set to C(true).
157 - Specifies the allowed publisher certificates for android applications.
158 - The publisher certificate needs to be installed on the BIG-IP beforehand.
159 - "The certificate name located on a different partition than the one specified
160 in the C(partition) parameter needs to be provided in C(full_path) format, e.g. C(/Foo/cert.crt)."
161 type: list
162 elements: str
163 partition:
164 description:
165 - Device partition to manage resources on.
166 type: str
167 default: Common
168 state:
169 description:
170 - When C(state) is C(present), ensures that the Application object exists.
171 - When C(state) is C(absent), ensures that the Application object is removed.
172 type: str
173 choices:
174 - present
175 - absent
176 default: present
177 notes:
178 - Requires BIG-IP >= 13.1.0
179 extends_documentation_fragment: f5networks.f5_modules.f5
180 author:
181 - Wojciech Wypior (@wojtek0806)
182 '''
183
184 EXAMPLES = r'''
185 - name: Create an ASM dos application profile
186 bigip_asm_dos_application:
187 profile: dos_foo
188 geolocations:
189 blacklist:
190 - Afghanistan
191 - Andora
192 whitelist:
193 - Cuba
194 heavy_urls:
195 auto_detect: true
196 latency_threshold: 1000
197 rtbh_duration: 3600
198 rtbh_enable: true
199 single_page_application: true
200 provider:
201 password: secret
202 server: lb.mydomain.com
203 user: admin
204 delegate_to: localhost
205
206 - name: Update an ASM dos application profile
207 bigip_asm_dos_application:
208 profile: dos_foo
209 mobile_detection:
210 enabled: true
211 allow_any_ios_package: true
212 allow_emulators: true
213 provider:
214 password: secret
215 server: lb.mydomain.com
216 user: admin
217 delegate_to: localhost
218
219 - name: Remove an ASM dos application profile
220 bigip_asm_dos_application:
221 profile: dos_foo
222 state: absent
223 provider:
224 password: secret
225 server: lb.mydomain.com
226 user: admin
227 delegate_to: localhost
228 '''
229
230 RETURN = r'''
231 rtbh_enable:
232 description: Enables Remote Triggered Black Hole of attacking IPs.
233 returned: changed
234 type: bool
235 sample: false
236 rtbh_duration:
237 description: The duration of the RTBH BGP route advertisement.
238 returned: changed
239 type: int
240 sample: 3600
241 scrubbing_enable:
242 description: Enables Traffic Scrubbing during attacks.
243 returned: changed
244 type: bool
245 sample: true
246 scrubbing_duration:
247 description: The duration of the Traffic Scrubbing BGP route advertisement.
248 returned: changed
249 type: int
250 sample: 3600
251 single_page_application:
252 description: Enables support of Single Page Applications.
253 returned: changed
254 type: bool
255 sample: false
256 trigger_irule:
257 description: Activates an Application DoS iRule event.
258 returned: changed
259 type: bool
260 sample: true
261 geolocations:
262 description: Specifies geolocations countries whitelist, blacklist.
263 type: complex
264 returned: changed
265 contains:
266 whitelist:
267 description: A list of countries to be put on the whitelist.
268 returned: changed
269 type: list
270 sample: ['United States, United Kingdom']
271 blacklist:
272 description: A list of countries to be put on the blacklist.
273 returned: changed
274 type: list
275 sample: ['Russia', 'Germany']
276 sample: hash/dictionary of values
277 heavy_urls:
278 description: Manages Heavy URL protection.
279 type: complex
280 returned: changed
281 contains:
282 auto_detect:
283 description: Enables or disables automatic heavy URL detection.
284 returned: changed
285 type: bool
286 sample: true
287 latency_threshold:
288 description: Specifies the latency threshold for automatic heavy URL detection.
289 returned: changed
290 type: int
291 sample: 2000
292 exclude:
293 description: Specifies a list of URLs or wildcards to exclude from the heavy URLs.
294 returned: changed
295 type: list
296 sample: ['/exclude.html', '/exclude2.html']
297 include:
298 description: Configures additional URLs to include in the heavy URLs.
299 type: complex
300 returned: changed
301 contains:
302 url:
303 description: The URL to be added to the list of heavy URLs.
304 returned: changed
305 type: str
306 sample: /include.html
307 threshold:
308 description: The threshold of requests per second.
309 returned: changed
310 type: str
311 sample: auto
312 sample: hash/dictionary of values
313 sample: hash/dictionary of values
314 mobile_detection:
315 description: Configures detection of mobile applications built with the Anti-Bot Mobile SDK.
316 type: complex
317 returned: changed
318 contains:
319 enable:
320 description: Enables or disables automatic mobile detection.
321 returned: changed
322 type: bool
323 sample: true
324 allow_android_rooted_device:
325 description: Allows traffic from rooted Android devices.
326 returned: changed
327 type: bool
328 sample: false
329 allow_any_android_package:
330 description: Allows any application publisher.
331 returned: changed
332 type: bool
333 sample: false
334 allow_any_ios_package:
335 description: Allows any iOS package.
336 returned: changed
337 type: bool
338 sample: true
339 allow_jailbroken_devices:
340 description: Allows traffic from jailbroken iOS devices.
341 returned: changed
342 type: bool
343 sample: false
344 allow_emulators:
345 description: Allows traffic from applications run on emulators.
346 returned: changed
347 type: bool
348 sample: true
349 client_side_challenge_mode:
350 description: Action to take when a CAPTCHA or Client Side Integrity challenge needs to be presented.
351 returned: changed
352 type: str
353 sample: pass
354 ios_allowed_package_names:
355 description: The names of iOS packages to allow traffic on.
356 returned: changed
357 type: list
358 sample: ['package1','package2']
359 android_publishers:
360 description: The allowed publisher certificates for android applications.
361 returned: changed
362 type: list
363 sample: ['/Common/cert1.crt', '/Common/cert2.crt']
364 sample: hash/dictionary of values
365 '''
366
367 import traceback
368 from datetime import datetime
369
370 try:
371 from packaging.version import Version
372 except ImportError:
373 HAS_PACKAGING = False
374 Version = None
375 PACKAGING_IMPORT_ERROR = traceback.format_exc()
376 else:
377 HAS_PACKAGING = True
378 PACKAGING_IMPORT_ERROR = None
379
380 from ansible.module_utils.basic import (
381 AnsibleModule, missing_required_lib, env_fallback
382 )
383
384 from ..module_utils.bigip import F5RestClient
385 from ..module_utils.common import (
386 F5ModuleError, AnsibleF5Parameters, transform_name, f5_argument_spec, flatten_boolean, fq_name
387 )
388 from ..module_utils.compare import (
389 cmp_simple_list, compare_complex_list
390 )
391 from ..module_utils.icontrol import (
392 module_provisioned, tmos_version
393 )
394 from ..module_utils.teem import send_teem
395
396
397 class Parameters(AnsibleF5Parameters):
398 api_map = {
399 'rtbhDurationSec': 'rtbh_duration',
400 'rtbhEnable': 'rtbh_enable',
401 'scrubbingDurationSec': 'scrubbing_duration',
402 'scrubbingEnable': 'scrubbing_enable',
403 'singlePageApplication': 'single_page_application',
404 'triggerIrule': 'trigger_irule',
405 'heavyUrls': 'heavy_urls',
406 'mobileDetection': 'mobile_detection',
407 }
408
409 api_attributes = [
410 'geolocations',
411 'rtbhDurationSec',
412 'rtbhEnable',
413 'scrubbingDurationSec',
414 'scrubbingEnable',
415 'singlePageApplication',
416 'triggerIrule',
417 'heavyUrls',
418 'mobileDetection',
419 ]
420
421 returnables = [
422 'rtbh_duration',
423 'rtbh_enable',
424 'scrubbing_duration',
425 'scrubbing_enable',
426 'single_page_application',
427 'trigger_irule',
428 'enable_mobile_detection',
429 'allow_android_rooted_device',
430 'allow_any_android_package',
431 'allow_any_ios_package',
432 'allow_jailbroken_devices',
433 'allow_emulators',
434 'client_side_challenge_mode',
435 'ios_allowed_package_names',
436 'android_publishers',
437 'auto_detect',
438 'latency_threshold',
439 'hw_url_exclude',
440 'hw_url_include',
441 'geo_blacklist',
442 'geo_whitelist',
443 ]
444
445 updatables = [
446 'rtbh_duration',
447 'rtbh_enable',
448 'scrubbing_duration',
449 'scrubbing_enable',
450 'single_page_application',
451 'trigger_irule',
452 'enable_mobile_detection',
453 'allow_android_rooted_device',
454 'allow_any_android_package',
455 'allow_any_ios_package',
456 'allow_jailbroken_devices',
457 'allow_emulators',
458 'client_side_challenge_mode',
459 'ios_allowed_package_names',
460 'android_publishers',
461 'auto_detect',
462 'latency_threshold',
463 'hw_url_exclude',
464 'hw_url_include',
465 'geo_blacklist',
466 'geo_whitelist',
467 ]
468
469
470 class ApiParameters(Parameters):
471 @property
472 def enable_mobile_detection(self):
473 if self._values['mobile_detection'] is None:
474 return None
475 return self._values['mobile_detection']['enabled']
476
477 @property
478 def allow_android_rooted_device(self):
479 if self._values['mobile_detection'] is None:
480 return None
481 return self._values['mobile_detection']['allowAndroidRootedDevice']
482
483 @property
484 def allow_any_android_package(self):
485 if self._values['mobile_detection'] is None:
486 return None
487 return self._values['mobile_detection']['allowAnyAndroidPackage']
488
489 @property
490 def allow_any_ios_package(self):
491 if self._values['mobile_detection'] is None:
492 return None
493 return self._values['mobile_detection']['allowAnyIosPackage']
494
495 @property
496 def allow_jailbroken_devices(self):
497 if self._values['mobile_detection'] is None:
498 return None
499 return self._values['mobile_detection']['allowJailbrokenDevices']
500
501 @property
502 def allow_emulators(self):
503 if self._values['mobile_detection'] is None:
504 return None
505 return self._values['mobile_detection']['allowEmulators']
506
507 @property
508 def client_side_challenge_mode(self):
509 if self._values['mobile_detection'] is None:
510 return None
511 return self._values['mobile_detection']['clientSideChallengeMode']
512
513 @property
514 def ios_allowed_package_names(self):
515 if self._values['mobile_detection'] is None:
516 return None
517 return self._values['mobile_detection'].get('iosAllowedPackageNames', None)
518
519 @property
520 def android_publishers(self):
521 if self._values['mobile_detection'] is None or 'androidPublishers' not in self._values['mobile_detection']:
522 return None
523 result = [fq_name(publisher['partition'], publisher['name'])
524 for publisher in self._values['mobile_detection']['androidPublishers']]
525 return result
526
527 @property
528 def auto_detect(self):
529 if self._values['heavy_urls'] is None:
530 return None
531 return self._values['heavy_urls']['automaticDetection']
532
533 @property
534 def latency_threshold(self):
535 if self._values['heavy_urls'] is None:
536 return None
537 return self._values['heavy_urls']['latencyThreshold']
538
539 @property
540 def hw_url_exclude(self):
541 if self._values['heavy_urls'] is None:
542 return None
543 return self._values['heavy_urls'].get('exclude', None)
544
545 @property
546 def hw_url_include(self):
547 if self._values['heavy_urls'] is None:
548 return None
549 return self._values['heavy_urls'].get('includeList', None)
550
551 @property
552 def geo_blacklist(self):
553 if self._values['geolocations'] is None:
554 return None
555 result = list()
556 for item in self._values['geolocations']:
557 if 'blackListed' in item and item['blackListed'] is True:
558 result.append(item['name'])
559 if result:
560 return result
561
562 @property
563 def geo_whitelist(self):
564 if self._values['geolocations'] is None:
565 return None
566 result = list()
567 for item in self._values['geolocations']:
568 if 'whiteListed' in item and item['whiteListed'] is True:
569 result.append(item['name'])
570 if result:
571 return result
572
573
574 class ModuleParameters(Parameters):
575 @property
576 def rtbh_duration(self):
577 if self._values['rtbh_duration'] is None:
578 return None
579 if 0 <= self._values['rtbh_duration'] <= 4294967295:
580 return self._values['rtbh_duration']
581 raise F5ModuleError(
582 "Valid 'rtbh_duration' must be in range 0 - 4294967295 seconds."
583 )
584
585 @property
586 def rtbh_enable(self):
587 result = flatten_boolean(self._values['rtbh_enable'])
588 if result == 'yes':
589 return 'enabled'
590 if result == 'no':
591 return 'disabled'
592 return result
593
594 @property
595 def scrubbing_duration(self):
596 if self._values['scrubbing_duration'] is None:
597 return None
598 if 0 <= self._values['scrubbing_duration'] <= 4294967295:
599 return self._values['scrubbing_duration']
600 raise F5ModuleError(
601 "Valid 'scrubbing_duration' must be in range 0 - 4294967295 seconds."
602 )
603
604 @property
605 def scrubbing_enable(self):
606 result = flatten_boolean(self._values['scrubbing_enable'])
607 if result == 'yes':
608 return 'enabled'
609 if result == 'no':
610 return 'disabled'
611 return result
612
613 @property
614 def single_page_application(self):
615 result = flatten_boolean(self._values['single_page_application'])
616 if result == 'yes':
617 return 'enabled'
618 if result == 'no':
619 return 'disabled'
620 return result
621
622 @property
623 def trigger_irule(self):
624 result = flatten_boolean(self._values['trigger_irule'])
625 if result == 'yes':
626 return 'enabled'
627 if result == 'no':
628 return 'disabled'
629 return result
630
631 @property
632 def enable_mobile_detection(self):
633 if self._values['mobile_detection'] is None:
634 return None
635 result = flatten_boolean(self._values['mobile_detection']['enabled'])
636 if result == 'yes':
637 return 'enabled'
638 if result == 'no':
639 return 'disabled'
640 return result
641
642 @property
643 def allow_android_rooted_device(self):
644 if self._values['mobile_detection'] is None:
645 return None
646 result = flatten_boolean(self._values['mobile_detection']['allow_android_rooted_device'])
647 if result == 'yes':
648 return 'true'
649 if result == 'no':
650 return 'false'
651 return result
652
653 @property
654 def allow_any_android_package(self):
655 if self._values['mobile_detection'] is None:
656 return None
657 result = flatten_boolean(self._values['mobile_detection']['allow_any_android_package'])
658 if result == 'yes':
659 return 'true'
660 if result == 'no':
661 return 'false'
662 return result
663
664 @property
665 def allow_any_ios_package(self):
666 if self._values['mobile_detection'] is None:
667 return None
668 result = flatten_boolean(self._values['mobile_detection']['allow_any_ios_package'])
669 if result == 'yes':
670 return 'true'
671 if result == 'no':
672 return 'false'
673 return result
674
675 @property
676 def allow_jailbroken_devices(self):
677 if self._values['mobile_detection'] is None:
678 return None
679 result = flatten_boolean(self._values['mobile_detection']['allow_jailbroken_devices'])
680 if result == 'yes':
681 return 'true'
682 if result == 'no':
683 return 'false'
684 return result
685
686 @property
687 def allow_emulators(self):
688 if self._values['mobile_detection'] is None:
689 return None
690 result = flatten_boolean(self._values['mobile_detection']['allow_emulators'])
691 if result == 'yes':
692 return 'true'
693 if result == 'no':
694 return 'false'
695 return result
696
697 @property
698 def client_side_challenge_mode(self):
699 if self._values['mobile_detection'] is None:
700 return None
701 return self._values['mobile_detection']['client_side_challenge_mode']
702
703 @property
704 def ios_allowed_package_names(self):
705 if self._values['mobile_detection'] is None:
706 return None
707 return self._values['mobile_detection']['ios_allowed_package_names']
708
709 @property
710 def android_publishers(self):
711 if self._values['mobile_detection'] is None or self._values['mobile_detection']['android_publishers'] is None:
712 return None
713 result = [fq_name(self.partition, item) for item in self._values['mobile_detection']['android_publishers']]
714 return result
715
716 @property
717 def auto_detect(self):
718 if self._values['heavy_urls'] is None:
719 return None
720 result = flatten_boolean(self._values['heavy_urls']['auto_detect'])
721 if result == 'yes':
722 return 'enabled'
723 if result == 'no':
724 return 'disabled'
725 return result
726
727 @property
728 def latency_threshold(self):
729 if self._values['heavy_urls'] is None or self._values['heavy_urls']['latency_threshold'] is None:
730 return None
731 if 0 <= self._values['heavy_urls']['latency_threshold'] <= 4294967295:
732 return self._values['heavy_urls']['latency_threshold']
733 raise F5ModuleError(
734 "Valid 'latency_threshold' must be in range 0 - 4294967295 milliseconds."
735 )
736
737 @property
738 def hw_url_exclude(self):
739 if self._values['heavy_urls'] is None:
740 return None
741 return self._values['heavy_urls']['exclude']
742
743 @property
744 def hw_url_include(self):
745 if self._values['heavy_urls'] is None or self._values['heavy_urls']['include'] is None:
746 return None
747 result = list()
748 for item in self._values['heavy_urls']['include']:
749 element = dict()
750 element['url'] = self._correct_url(item['url'])
751 element['name'] = 'URL{0}'.format(self._correct_url(item['url']))
752 if 'threshold' in item:
753 element['threshold'] = self._validate_threshold(item['threshold'])
754 result.append(element)
755 return result
756
757 def _validate_threshold(self, item):
758 if item == 'auto':
759 return item
760 if 1 <= int(item) <= 4294967295:
761 return item
762 raise F5ModuleError(
763 "Valid 'url threshold' must be in range 1 - 4294967295 requests per second or 'auto'."
764 )
765
766 def _correct_url(self, item):
767 if item.startswith('/'):
768 return item
769 return "/{0}".format(item)
770
771 @property
772 def geo_blacklist(self):
773 if self._values['geolocations'] is None:
774 return None
775 whitelist = self.geo_whitelist
776 blacklist = self._values['geolocations']['blacklist']
777 if whitelist and blacklist:
778 if not set(whitelist).isdisjoint(set(blacklist)):
779 raise F5ModuleError('Cannot specify the same element in blacklist and whitelist.')
780 return blacklist
781
782 @property
783 def geo_whitelist(self):
784 if self._values['geolocations'] is None:
785 return None
786 return self._values['geolocations']['whitelist']
787
788
789 class Changes(Parameters):
790 def to_return(self):
791 result = {}
792 try:
793 for returnable in self.returnables:
794 result[returnable] = getattr(self, returnable)
795 result = self._filter_params(result)
796 except Exception:
797 raise
798 return result
799
800
801 class UsableChanges(Changes):
802 @property
803 def geolocations(self):
804 if self._values['geo_blacklist'] is None and self._values['geo_whitelist'] is None:
805 return None
806 result = list()
807 if self._values['geo_blacklist']:
808 for item in self._values['geo_blacklist']:
809 element = dict()
810 element['name'] = item
811 element['blackListed'] = True
812 result.append(element)
813 if self._values['geo_whitelist']:
814 for item in self._values['geo_whitelist']:
815 element = dict()
816 element['name'] = item
817 element['whiteListed'] = True
818 result.append(element)
819 if result:
820 return result
821
822 @property
823 def heavy_urls(self):
824 tmp = dict()
825 tmp['automaticDetection'] = self._values['auto_detect']
826 tmp['latencyThreshold'] = self._values['latency_threshold']
827 tmp['exclude'] = self._values['hw_url_exclude']
828 tmp['includeList'] = self._values['hw_url_include']
829 result = self._filter_params(tmp)
830 if result:
831 return result
832
833 @property
834 def mobile_detection(self):
835 tmp = dict()
836 tmp['enabled'] = self._values['enable_mobile_detection']
837 tmp['allowAndroidRootedDevice'] = self._values['allow_android_rooted_device']
838 tmp['allowAnyAndroidPackage'] = self._values['allow_any_android_package']
839 tmp['allowAnyIosPackage'] = self._values['allow_any_ios_package']
840 tmp['allowJailbrokenDevices'] = self._values['allow_jailbroken_devices']
841 tmp['allowEmulators'] = self._values['allow_emulators']
842 tmp['clientSideChallengeMode'] = self._values['client_side_challenge_mode']
843 tmp['iosAllowedPackageNames'] = self._values['ios_allowed_package_names']
844 tmp['androidPublishers'] = self._values['android_publishers']
845 result = self._filter_params(tmp)
846 if result:
847 return result
848
849
850 class ReportableChanges(Changes):
851 returnables = [
852 'rtbh_duration',
853 'rtbh_enable',
854 'scrubbing_duration',
855 'scrubbing_enable',
856 'single_page_application',
857 'trigger_irule',
858 'heavy_urls',
859 'mobile_detection',
860 'geolocations',
861 ]
862
863 def _convert_include_list(self, items):
864 if items is None:
865 return None
866 result = list()
867 for item in items:
868 element = dict()
869 element['url'] = item['url']
870 if 'threshold' in item:
871 element['threshold'] = item['threshold']
872 result.append(element)
873 if result:
874 return result
875
876 @property
877 def geolocations(self):
878 tmp = dict()
879 tmp['blacklist'] = self._values['geo_blacklist']
880 tmp['whitelist'] = self._values['geo_whitelist']
881 result = self._filter_params(tmp)
882 if result:
883 return result
884
885 @property
886 def heavy_urls(self):
887 tmp = dict()
888 tmp['auto_detect'] = flatten_boolean(self._values['auto_detect'])
889 tmp['latency_threshold'] = self._values['latency_threshold']
890 tmp['exclude'] = self._values['hw_url_exclude']
891 tmp['include'] = self._convert_include_list(self._values['hw_url_include'])
892 result = self._filter_params(tmp)
893 if result:
894 return result
895
896 @property
897 def mobile_detection(self):
898 tmp = dict()
899 tmp['enabled'] = flatten_boolean(self._values['enable_mobile_detection'])
900 tmp['allow_android_rooted_device'] = flatten_boolean(self._values['allow_android_rooted_device'])
901 tmp['allow_any_android_package'] = flatten_boolean(self._values['allow_any_android_package'])
902 tmp['allow_any_ios_package'] = flatten_boolean(self._values['allow_any_ios_package'])
903 tmp['allow_jailbroken_devices'] = flatten_boolean(self._values['allow_jailbroken_devices'])
904 tmp['allow_emulators'] = flatten_boolean(self._values['allow_emulators'])
905 tmp['client_side_challenge_mode'] = self._values['client_side_challenge_mode']
906 tmp['ios_allowed_package_names'] = self._values['ios_allowed_package_names']
907 tmp['android_publishers'] = self._values['android_publishers']
908 result = self._filter_params(tmp)
909 if result:
910 return result
911
912 @property
913 def rtbh_enable(self):
914 result = flatten_boolean(self._values['rtbh_enable'])
915 return result
916
917 @property
918 def scrubbing_enable(self):
919 result = flatten_boolean(self._values['scrubbing_enable'])
920 return result
921
922 @property
923 def single_page_application(self):
924 result = flatten_boolean(self._values['single_page_application'])
925 return result
926
927 @property
928 def trigger_irule(self):
929 result = flatten_boolean(self._values['trigger_irule'])
930 return result
931
932
933 class Difference(object):
934 def __init__(self, want, have=None):
935 self.want = want
936 self.have = have
937
938 def compare(self, param):
939 try:
940 result = getattr(self, param)
941 return result
942 except AttributeError:
943 return self.__default(param)
944
945 def __default(self, param):
946 attr1 = getattr(self.want, param)
947 try:
948 attr2 = getattr(self.have, param)
949 if attr1 != attr2:
950 return attr1
951 except AttributeError:
952 return attr1
953
954 @property
955 def hw_url_include(self):
956 if self.want.hw_url_include is None:
957 return None
958 if self.have.hw_url_include is None and self.want.hw_url_include == []:
959 return None
960 if self.have.hw_url_include is None:
961 return self.want.hw_url_include
962
963 wants = self.want.hw_url_include
964 haves = list()
965 # First we remove extra keys in have for the same elements
966 for want in wants:
967 for have in self.have.hw_url_include:
968 if want['url'] == have['url']:
969 entry = self._filter_have(want, have)
970 haves.append(entry)
971 # Next we do compare the lists as normal
972 result = compare_complex_list(wants, haves)
973 return result
974
975 def _filter_have(self, want, have):
976 to_check = set(want.keys()).intersection(set(have.keys()))
977 result = dict()
978 for k in list(to_check):
979 result[k] = have[k]
980 return result
981
982 @property
983 def hw_url_exclude(self):
984 result = cmp_simple_list(self.want.hw_url_exclude, self.have.hw_url_exclude)
985 return result
986
987 @property
988 def geo_blacklist(self):
989 result = cmp_simple_list(self.want.geo_blacklist, self.have.geo_blacklist)
990 return result
991
992 @property
993 def geo_whitelist(self):
994 result = cmp_simple_list(self.want.geo_whitelist, self.have.geo_whitelist)
995 return result
996
997 @property
998 def android_publishers(self):
999 result = cmp_simple_list(self.want.android_publishers, self.have.android_publishers)
1000 return result
1001
1002 @property
1003 def ios_allowed_package_names(self):
1004 result = cmp_simple_list(self.want.ios_allowed_package_names, self.have.ios_allowed_package_names)
1005 return result
1006
1007
1008 class ModuleManager(object):
1009 def __init__(self, *args, **kwargs):
1010 self.module = kwargs.get('module', None)
1011 self.client = F5RestClient(**self.module.params)
1012 self.want = ModuleParameters(params=self.module.params)
1013 self.have = ApiParameters()
1014 self.changes = UsableChanges()
1015
1016 def _set_changed_options(self):
1017 changed = {}
1018 for key in Parameters.returnables:
1019 if getattr(self.want, key) is not None:
1020 changed[key] = getattr(self.want, key)
1021 if changed:
1022 self.changes = UsableChanges(params=changed)
1023
1024 def _update_changed_options(self):
1025 diff = Difference(self.want, self.have)
1026 updatables = Parameters.updatables
1027 changed = dict()
1028 for k in updatables:
1029 change = diff.compare(k)
1030 if change is None:
1031 continue
1032 else:
1033 if isinstance(change, dict):
1034 changed.update(change)
1035 else:
1036 changed[k] = change
1037 if changed:
1038 self.changes = UsableChanges(params=changed)
1039 return True
1040 return False
1041
1042 def _announce_deprecations(self, result):
1043 warnings = result.pop('__warnings', [])
1044 for warning in warnings:
1045 self.client.module.deprecate(
1046 msg=warning['msg'],
1047 version=warning['version']
1048 )
1049
1050 def exec_module(self):
1051 start = datetime.now().isoformat()
1052 version = tmos_version(self.client)
1053 if not module_provisioned(self.client, 'asm'):
1054 raise F5ModuleError(
1055 "ASM must be provisioned to use this module."
1056 )
1057
1058 if self.version_less_than_13_1():
1059 raise F5ModuleError('Module supported on TMOS versions 13.1.x and above')
1060
1061 changed = False
1062 result = dict()
1063 state = self.want.state
1064
1065 if state == "present":
1066 changed = self.present()
1067 elif state == "absent":
1068 changed = self.absent()
1069
1070 reportable = ReportableChanges(params=self.changes.to_return())
1071 changes = reportable.to_return()
1072 result.update(**changes)
1073 result.update(dict(changed=changed))
1074 self._announce_deprecations(result)
1075 send_teem(start, self.client, self.module, version)
1076 return result
1077
1078 def version_less_than_13_1(self):
1079 version = tmos_version(self.client)
1080 if Version(version) < Version('13.1.0'):
1081 return True
1082 return False
1083
1084 def present(self):
1085 if self.exists():
1086 return self.update()
1087 else:
1088 return self.create()
1089
1090 def absent(self):
1091 if self.exists():
1092 return self.remove()
1093 return False
1094
1095 def should_update(self):
1096 result = self._update_changed_options()
1097 if result:
1098 return True
1099 return False
1100
1101 def update(self):
1102 self.have = self.read_current_from_device()
1103 if not self.should_update():
1104 return False
1105 if self.module.check_mode:
1106 return True
1107 self.update_on_device()
1108 return True
1109
1110 def remove(self):
1111 if self.module.check_mode:
1112 return True
1113 self.remove_from_device()
1114 if self.exists():
1115 raise F5ModuleError("Failed to delete the resource.")
1116 return True
1117
1118 def create(self):
1119 self._set_changed_options()
1120 if self.module.check_mode:
1121 return True
1122 self.create_on_device()
1123 return True
1124
1125 def profile_exists(self):
1126 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1127 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}/".format(
1128 self.client.provider['server'],
1129 self.client.provider['server_port'],
1130 transform_name(self.want.partition, self.want.profile),
1131 )
1132 resp = self.client.api.get(uri)
1133 try:
1134 response = resp.json()
1135 except ValueError as ex:
1136 raise F5ModuleError(str(ex))
1137
1138 if resp.status == 404 or 'code' in response and response['code'] == 404:
1139 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile".format(
1140 self.client.provider['server'],
1141 self.client.provider['server_port'],
1142 )
1143 payload = {'name': self.want.profile, 'partition': self.want.partition}
1144 resp = self.client.api.post(uri, json=payload)
1145 try:
1146 response = resp.json()
1147 except ValueError as ex:
1148 raise F5ModuleError(str(ex))
1149 # response = resp.json()
1150 if resp.status == 404 or 'code' in response and response['code'] == 404:
1151 return False
1152 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1153 return True
1154 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1155 return True
1156
1157 if resp.status in errors or 'code' in response and response['code'] in errors:
1158 if 'message' in response:
1159 raise F5ModuleError(response['message'])
1160 else:
1161 raise F5ModuleError(resp.content)
1162
1163 def exists(self):
1164 errors = [401, 403, 409, 500, 501, 502, 503, 504]
1165
1166 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}".format(
1167 self.client.provider['server'],
1168 self.client.provider['server_port'],
1169 transform_name(self.want.partition, self.want.profile),
1170 )
1171 resp = self.client.api.get(uri)
1172 try:
1173 response = resp.json()
1174 except ValueError as ex:
1175 raise F5ModuleError(str(ex))
1176
1177 if resp.status == 404 or 'code' in response and response['code'] == 404:
1178 return False
1179 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1180 return True
1181 if resp.status in errors or 'code' in response and response['code'] in errors:
1182 if 'message' in response:
1183 raise F5ModuleError(response['message'])
1184 else:
1185 raise F5ModuleError(resp.content)
1186
1187 def create_on_device(self):
1188 params = self.changes.api_params()
1189 params['name'] = self.want.profile
1190 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile".format(
1191 self.client.provider['server'],
1192 self.client.provider['server_port'],
1193 )
1194 payload = {'name': self.want.profile, 'partition': self.want.partition}
1195
1196 resp = self.client.api.post(uri, json=payload)
1197 try:
1198 response = resp.json()
1199 except ValueError as ex:
1200 raise F5ModuleError(str(ex))
1201 if resp.status == 404 or 'code' in response and response['code'] == 404:
1202 raise F5ModuleError(resp.content)
1203 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}/application/".format(
1204 self.client.provider['server'],
1205 self.client.provider['server_port'],
1206 transform_name(self.want.partition, self.want.profile),
1207 )
1208 resp = self.client.api.post(uri, json=params)
1209 try:
1210 response = resp.json()
1211 except ValueError as ex:
1212 raise F5ModuleError(str(ex))
1213
1214 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1215 return True
1216 raise F5ModuleError(resp.content)
1217
1218 def update_on_device(self):
1219 params = self.changes.api_params()
1220 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}/application/{3}".format(
1221 self.client.provider['server'],
1222 self.client.provider['server_port'],
1223 transform_name(self.want.partition, self.want.profile),
1224 self.want.profile
1225 )
1226 resp = self.client.api.patch(uri, json=params)
1227 try:
1228 response = resp.json()
1229 except ValueError as ex:
1230 raise F5ModuleError(str(ex))
1231
1232 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1233 return True
1234 raise F5ModuleError(resp.content)
1235
1236 def remove_from_device(self):
1237 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}/".format(
1238 self.client.provider['server'],
1239 self.client.provider['server_port'],
1240 transform_name(self.want.partition, self.want.profile),
1241 )
1242 response = self.client.api.delete(uri)
1243 if response.status == 200:
1244 return True
1245 raise F5ModuleError(response.content)
1246
1247 def read_current_from_device(self):
1248 uri = "https://{0}:{1}/mgmt/tm/security/dos/profile/{2}/application/{3}".format(
1249 self.client.provider['server'],
1250 self.client.provider['server_port'],
1251 transform_name(self.want.partition, self.want.profile),
1252 self.want.profile
1253 )
1254 resp = self.client.api.get(uri)
1255 try:
1256 response = resp.json()
1257 except ValueError as ex:
1258 raise F5ModuleError(str(ex))
1259
1260 if resp.status in [200, 201] or 'code' in response and response['code'] in [200, 201]:
1261 return ApiParameters(params=response)
1262 raise F5ModuleError(resp.content)
1263
1264
1265 class ArgumentSpec(object):
1266 def __init__(self):
1267 self.supports_check_mode = True
1268 argument_spec = dict(
1269 profile=dict(
1270 required=True,
1271 ),
1272 geolocations=dict(
1273 type='dict',
1274 options=dict(
1275 blacklist=dict(
1276 type='list',
1277 elements='str',
1278 ),
1279 whitelist=dict(
1280 type='list',
1281 elements='str',
1282 ),
1283 ),
1284 ),
1285 heavy_urls=dict(
1286 type='dict',
1287 options=dict(
1288 auto_detect=dict(type='bool'),
1289 latency_threshold=dict(type='int'),
1290 exclude=dict(
1291 type='list',
1292 elements='str',
1293 ),
1294 include=dict(
1295 type='list',
1296 elements='dict',
1297 options=dict(
1298 url=dict(required=True),
1299 threshold=dict(),
1300 ),
1301 )
1302 ),
1303 ),
1304 mobile_detection=dict(
1305 type='dict',
1306 options=dict(
1307 enabled=dict(type='bool'),
1308 allow_android_rooted_device=dict(type='bool'),
1309 allow_any_android_package=dict(type='bool'),
1310 allow_any_ios_package=dict(type='bool'),
1311 allow_jailbroken_devices=dict(type='bool'),
1312 allow_emulators=dict(type='bool'),
1313 client_side_challenge_mode=dict(choices=['cshui', 'pass']),
1314 ios_allowed_package_names=dict(
1315 type='list',
1316 elements='str',
1317 ),
1318 android_publishers=dict(
1319 type='list',
1320 elements='str',
1321 )
1322 )
1323 ),
1324 rtbh_duration=dict(type='int'),
1325 rtbh_enable=dict(type='bool'),
1326 scrubbing_duration=dict(type='int'),
1327 scrubbing_enable=dict(type='bool'),
1328 single_page_application=dict(type='bool'),
1329 trigger_irule=dict(type='bool'),
1330 partition=dict(
1331 default='Common',
1332 fallback=(env_fallback, ['F5_PARTITION'])
1333 ),
1334 state=dict(
1335 default='present',
1336 choices=['present', 'absent']
1337 )
1338 )
1339 self.argument_spec = {}
1340 self.argument_spec.update(f5_argument_spec)
1341 self.argument_spec.update(argument_spec)
1342
1343
1344 def main():
1345 spec = ArgumentSpec()
1346
1347 module = AnsibleModule(
1348 argument_spec=spec.argument_spec,
1349 supports_check_mode=spec.supports_check_mode,
1350 )
1351
1352 if not HAS_PACKAGING:
1353 module.fail_json(
1354 msg=missing_required_lib('packaging'),
1355 exception=PACKAGING_IMPORT_ERROR
1356 )
1357
1358 try:
1359 mm = ModuleManager(module=module)
1360 results = mm.exec_module()
1361 module.exit_json(**results)
1362 except F5ModuleError as ex:
1363 module.fail_json(msg=str(ex))
1364
1365
1366 if __name__ == '__main__':
1367 main()