Debian Codegraph @

ansible_collections/community/aws/plugins/modules/wafv2_web_acl.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: wafv2_web_acl
10 version_added: 1.5.0
11 author:
12 - "Markus Bergholz (@markuman)"
13 short_description: Create and delete WAF Web ACLs
14 description:
15 - Create, modify or delete AWS WAF v2 web ACLs (not for classic WAF).
16 - See docs at U(https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html)
17 options:
18 state:
19 description:
20 - Whether the rule is present or absent.
21 choices: ["present", "absent"]
22 required: true
23 type: str
24 name:
25 description:
26 - The name of the web acl.
27 required: true
28 type: str
29 scope:
30 description:
31 - Geographical scope of the web acl.
32 required: true
33 choices: ["CLOUDFRONT", "REGIONAL"]
34 type: str
35 description:
36 description:
37 - Description of wafv2 web acl.
38 type: str
39 default_action:
40 description:
41 - Default action of the wafv2 web acl.
42 choices: ["Block", "Allow"]
43 type: str
44 sampled_requests:
45 description:
46 - Whether to store a sample of the web requests, true or false.
47 type: bool
48 default: false
49 cloudwatch_metrics:
50 description:
51 - Enable cloudwatch metric for wafv2 web acl.
52 type: bool
53 default: true
54 metric_name:
55 description:
56 - Name of cloudwatch metrics.
57 - If not given and cloudwatch_metrics is enabled, the name of the web acl itself will be taken.
58 type: str
59 rules:
60 description:
61 - The Rule statements used to identify the web requests that you want to allow, block, or count.
62 - For a list of managed rules see U(https://docs.aws.amazon.com/waf/latest/developerguide/aws-managed-rule-groups-list.html).
63 type: list
64 elements: dict
65 suboptions:
66 name:
67 description:
68 - The name of the wafv2 rule
69 type: str
70 priority:
71 description:
72 - The rule priority
73 type: int
74 action:
75 description:
76 - Wether a rule is blocked, allowed or counted.
77 type: dict
78 visibility_config:
79 description:
80 - Visibility of single wafv2 rule.
81 type: dict
82 statement:
83 description:
84 - Rule configuration.
85 type: dict
86 custom_response_bodies:
87 description:
88 - A map of custom response keys and content bodies. Define response bodies here and reference them in the rules by providing
89 - the key of the body dictionary element.
90 - Each element must have a unique dict key and in the dict two keys for I(content_type) and I(content).
91 type: dict
92 version_added: 3.1.0
93 purge_rules:
94 description:
95 - When set to C(no), keep the existing load balancer rules in place. Will modify and add, but will not delete.
96 default: true
97 type: bool
98
99 notes:
100 - Support for the I(purge_tags) parameter was added in release 4.0.0.
101
102 extends_documentation_fragment:
103 - amazon.aws.common.modules
104 - amazon.aws.region.modules
105 - amazon.aws.tags
106 - amazon.aws.boto3
107 """
108
109 EXAMPLES = r"""
110 - name: Create test web acl
111 community.aws.wafv2_web_acl:
112 name: test05
113 description: hallo eins
114 scope: REGIONAL
115 default_action: Allow
116 sampled_requests: false
117 cloudwatch_metrics: true
118 metric_name: test05-acl-metric
119 rules:
120 - name: zwei
121 priority: 0
122 action:
123 block: {}
124 visibility_config:
125 sampled_requests_enabled: true
126 cloud_watch_metrics_enabled: true
127 metric_name: ddos
128 statement:
129 xss_match_statement:
130 field_to_match:
131 body: {}
132 text_transformations:
133 - type: NONE
134 priority: 0
135 - name: admin_protect
136 priority: 1
137 override_action:
138 none: {}
139 visibility_config:
140 sampled_requests_enabled: true
141 cloud_watch_metrics_enabled: true
142 metric_name: fsd
143 statement:
144 managed_rule_group_statement:
145 vendor_name: AWS
146 name: AWSManagedRulesAdminProtectionRuleSet
147
148 # AWS Managed Bad Input Rule Set
149 # but allow PROPFIND_METHOD used e.g. by webdav
150 - name: bad_input_protect_whitelist_webdav
151 priority: 2
152 override_action:
153 none: {}
154 visibility_config:
155 sampled_requests_enabled: true
156 cloud_watch_metrics_enabled: true
157 metric_name: bad_input_protect
158 statement:
159 managed_rule_group_statement:
160 vendor_name: AWS
161 name: AWSManagedRulesKnownBadInputsRuleSet
162 excluded_rules:
163 - name: PROPFIND_METHOD
164
165 # Rate Limit example. 1500 req/5min
166 # counted for two domains via or_statement. login.mydomain.tld and api.mydomain.tld
167 - name: rate_limit_example
168 priority: 3
169 action:
170 block: {}
171 visibility_config:
172 sampled_requests_enabled: true
173 cloud_watch_metrics_enabled: true
174 metric_name: mydomain-ratelimit
175 statement:
176 rate_based_statement:
177 limit: 1500
178 aggregate_key_type: IP
179 scope_down_statement:
180 or_statement:
181 statements:
182 - byte_match_statement:
183 search_string: login.mydomain.tld
184 positional_constraint: CONTAINS
185 field_to_match:
186 single_header:
187 name: host
188 text_transformations:
189 - type: LOWERCASE
190 priority: 0
191 - byte_match_dtatement:
192 search_string: api.mydomain.tld
193 positional_constraint: CONTAINS
194 field_to_match:
195 single_header:
196 name: host
197 text_transformations:
198 - type: LOWERCASE
199 priority: 0
200 purge_rules: true
201 tags:
202 A: B
203 C: D
204 state: present
205
206 - name: Create IP filtering web ACL
207 community.aws.wafv2_web_acl:
208 name: ip-filtering-traffic
209 description: ACL that filters web traffic based on rate limits and whitelists some IPs
210 scope: REGIONAL
211 default_action: Allow
212 sampled_requests: true
213 cloudwatch_metrics: true
214 metric_name: ip-filtering-traffic
215 rules:
216 - name: whitelist-own-IPs
217 priority: 0
218 action:
219 allow: {}
220 statement:
221 ip_set_reference_statement:
222 arn: 'arn:aws:wafv2:us-east-1:123456789012:regional/ipset/own-public-ips/1c4bdfc4-0f77-3b23-5222-123123123'
223 visibility_config:
224 sampled_requests_enabled: true
225 cloud_watch_metrics_enabled: true
226 metric_name: waf-acl-rule-whitelist-own-IPs
227 - name: rate-limit-per-IP
228 priority: 1
229 action:
230 block:
231 custom_response:
232 response_code: 429
233 custom_response_body_key: too_many_requests
234 statement:
235 rate_based_statement:
236 limit: 5000
237 aggregate_key_type: IP
238 visibility_config:
239 sampled_requests_enabled: true
240 cloud_watch_metrics_enabled: true
241 metric_name: waf-acl-rule-rate-limit-per-IP
242 purge_rules: true
243 custom_response_bodies:
244 too_many_requests:
245 content_type: APPLICATION_JSON
246 content: '{ message: "Your request has been blocked due to too many HTTP requests coming from your IP" }'
247 region: us-east-1
248 state: present
249 """
250
251 RETURN = r"""
252 arn:
253 description: web acl arn
254 sample: arn:aws:wafv2:eu-central-1:123456789012:regional/webacl/test05/318c1ab9-fa74-4b3b-a974-f92e25106f61
255 type: str
256 returned: Always, as long as the web acl exists
257 description:
258 description: Description of the web acl
259 sample: Some web acl description
260 returned: Always, as long as the web acl exists
261 type: str
262 capacity:
263 description: Current capacity of the web acl
264 sample: 140
265 returned: Always, as long as the web acl exists
266 type: int
267 name:
268 description: Web acl name
269 sample: test02
270 returned: Always, as long as the web acl exists
271 type: str
272 default_action:
273 description: Default action of ACL
274 returned: Always, as long as the web acl exists
275 sample:
276 allow: {}
277 type: dict
278 rules:
279 description: Current rules of the web acl
280 returned: Always, as long as the web acl exists
281 type: list
282 sample:
283 - name: admin_protect
284 override_action:
285 none: {}
286 priority: 1
287 statement:
288 managed_rule_group_statement:
289 name: AWSManagedRulesAdminProtectionRuleSet
290 vendor_name: AWS
291 visibility_config:
292 cloud_watch_metrics_enabled: true
293 metric_name: admin_protect
294 sampled_requests_enabled: true
295 custom_response_bodies:
296 description: Custom response body configurations to be used in rules
297 type: dict
298 sample:
299 too_many_requests:
300 content_type: APPLICATION_JSON
301 content: '{ message: "Your request has been blocked due to too many HTTP requests coming from your IP" }'
302 returned: Always, as long as the web acl exists
303 visibility_config:
304 description: Visibility config of the web acl
305 returned: Always, as long as the web acl exists
306 type: dict
307 sample:
308 cloud_watch_metrics_enabled: true
309 metric_name: blub
310 sampled_requests_enabled: false
311 """
312
313 try:
314 from botocore.exceptions import BotoCoreError
315 from botocore.exceptions import ClientError
316 except ImportError:
317 pass # caught by AnsibleAWSModule
318
319 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
320 from ansible.module_utils.common.dict_transformations import snake_dict_to_camel_dict
321
322 from ansible_collections.amazon.aws.plugins.module_utils.tagging import ansible_dict_to_boto3_tag_list
323
324 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
325 from ansible_collections.community.aws.plugins.module_utils.wafv2 import compare_priority_rules
326 from ansible_collections.community.aws.plugins.module_utils.wafv2 import describe_wafv2_tags
327 from ansible_collections.community.aws.plugins.module_utils.wafv2 import ensure_wafv2_tags
328 from ansible_collections.community.aws.plugins.module_utils.wafv2 import wafv2_list_web_acls
329 from ansible_collections.community.aws.plugins.module_utils.wafv2 import wafv2_snake_dict_to_camel_dict
330
331
332 class WebACL:
333 def __init__(self, wafv2, name, scope, fail_json_aws):
334 self.wafv2 = wafv2
335 self.name = name
336 self.scope = scope
337 self.fail_json_aws = fail_json_aws
338 self.existing_acl, self.acl_id, self.locktoken = self.get_web_acl()
339
340 def update(
341 self,
342 default_action,
343 description,
344 rules,
345 sampled_requests,
346 cloudwatch_metrics,
347 metric_name,
348 custom_response_bodies,
349 ):
350 req_obj = {
351 "Name": self.name,
352 "Scope": self.scope,
353 "Id": self.acl_id,
354 "DefaultAction": default_action,
355 "Rules": rules,
356 "VisibilityConfig": {
357 "SampledRequestsEnabled": sampled_requests,
358 "CloudWatchMetricsEnabled": cloudwatch_metrics,
359 "MetricName": metric_name,
360 },
361 "LockToken": self.locktoken,
362 }
363
364 if description:
365 req_obj["Description"] = description
366
367 if custom_response_bodies:
368 req_obj["CustomResponseBodies"] = custom_response_bodies
369
370 try:
371 self.wafv2.update_web_acl(**req_obj)
372 except (BotoCoreError, ClientError) as e:
373 self.fail_json_aws(e, msg="Failed to update wafv2 web acl.")
374
375 self.existing_acl, self.acl_id, self.locktoken = self.get_web_acl()
376 return self.existing_acl
377
378 def remove(self):
379 try:
380 response = self.wafv2.delete_web_acl(
381 Name=self.name, Scope=self.scope, Id=self.acl_id, LockToken=self.locktoken
382 )
383 except (BotoCoreError, ClientError) as e:
384 self.fail_json_aws(e, msg="Failed to remove wafv2 web acl.")
385 return response
386
387 def get(self):
388 if self.existing_acl:
389 return self.existing_acl
390 return None
391
392 def get_web_acl(self):
393 acl_id = None
394 locktoken = None
395 arn = None
396 existing_acl = None
397 response = self.list()
398
399 for item in response.get("WebACLs"):
400 if item.get("Name") == self.name:
401 acl_id = item.get("Id")
402 locktoken = item.get("LockToken")
403 arn = item.get("ARN")
404
405 if acl_id:
406 try:
407 existing_acl = self.wafv2.get_web_acl(Name=self.name, Scope=self.scope, Id=acl_id)
408 except (BotoCoreError, ClientError) as e:
409 self.fail_json_aws(e, msg="Failed to get wafv2 web acl.")
410 tags = describe_wafv2_tags(self.wafv2, arn, self.fail_json_aws)
411 existing_acl["tags"] = tags
412 return existing_acl, acl_id, locktoken
413
414 def list(self):
415 return wafv2_list_web_acls(self.wafv2, self.scope, self.fail_json_aws)
416
417 def create(
418 self,
419 default_action,
420 rules,
421 sampled_requests,
422 cloudwatch_metrics,
423 metric_name,
424 tags,
425 description,
426 custom_response_bodies,
427 ):
428 req_obj = {
429 "Name": self.name,
430 "Scope": self.scope,
431 "DefaultAction": default_action,
432 "Rules": rules,
433 "VisibilityConfig": {
434 "SampledRequestsEnabled": sampled_requests,
435 "CloudWatchMetricsEnabled": cloudwatch_metrics,
436 "MetricName": metric_name,
437 },
438 }
439
440 if custom_response_bodies:
441 req_obj["CustomResponseBodies"] = custom_response_bodies
442 if description:
443 req_obj["Description"] = description
444 if tags:
445 req_obj["Tags"] = ansible_dict_to_boto3_tag_list(tags)
446
447 try:
448 self.wafv2.create_web_acl(**req_obj)
449 except (BotoCoreError, ClientError) as e:
450 self.fail_json_aws(e, msg="Failed to create wafv2 web acl.")
451
452 self.existing_acl, self.acl_id, self.locktoken = self.get_web_acl()
453 return self.existing_acl
454
455
456 def format_result(result):
457 # We were returning details of the Web ACL inside a "web_acl" parameter on
458 # creation, keep returning it to avoid breaking existing playbooks, but also
459 # return what the docs said we return (and returned when no change happened)
460 retval = dict(result)
461 if "WebACL" in retval:
462 retval.update(retval["WebACL"])
463
464 return camel_dict_to_snake_dict(retval, ignore_list=["tags"])
465
466
467 def main():
468 arg_spec = dict(
469 state=dict(type="str", required=True, choices=["present", "absent"]),
470 name=dict(type="str", required=True),
471 scope=dict(type="str", required=True, choices=["CLOUDFRONT", "REGIONAL"]),
472 description=dict(type="str"),
473 default_action=dict(type="str", choices=["Block", "Allow"]),
474 rules=dict(type="list", elements="dict"),
475 sampled_requests=dict(type="bool", default=False),
476 cloudwatch_metrics=dict(type="bool", default=True),
477 metric_name=dict(type="str"),
478 tags=dict(type="dict", aliases=["resource_tags"]),
479 purge_tags=dict(default=True, type="bool"),
480 custom_response_bodies=dict(type="dict"),
481 purge_rules=dict(default=True, type="bool"),
482 )
483
484 module = AnsibleAWSModule(
485 argument_spec=arg_spec,
486 supports_check_mode=True,
487 required_if=[["state", "present", ["default_action", "rules"]]],
488 )
489
490 state = module.params.get("state")
491 name = module.params.get("name")
492 scope = module.params.get("scope")
493 description = module.params.get("description")
494 default_action = module.params.get("default_action")
495 rules = module.params.get("rules")
496 sampled_requests = module.params.get("sampled_requests")
497 cloudwatch_metrics = module.params.get("cloudwatch_metrics")
498 metric_name = module.params.get("metric_name")
499 tags = module.params.get("tags")
500 purge_tags = module.params.get("purge_tags")
501 purge_rules = module.params.get("purge_rules")
502 check_mode = module.check_mode
503
504 custom_response_bodies = module.params.get("custom_response_bodies")
505 if custom_response_bodies:
506 custom_response_bodies = {}
507
508 for custom_name, body in module.params.get("custom_response_bodies").items():
509 custom_response_bodies[custom_name] = snake_dict_to_camel_dict(body, capitalize_first=True)
510
511 if default_action == "Block":
512 default_action = {"Block": {}}
513 elif default_action == "Allow":
514 default_action = {"Allow": {}}
515
516 if rules:
517 rules = []
518 for rule in module.params.get("rules"):
519 rules.append(wafv2_snake_dict_to_camel_dict(snake_dict_to_camel_dict(rule, capitalize_first=True)))
520
521 if not metric_name:
522 metric_name = name
523
524 wafv2 = module.client("wafv2")
525 web_acl = WebACL(wafv2, name, scope, module.fail_json_aws)
526 change = False
527 retval = {}
528
529 if state == "present":
530 if web_acl.get():
531 tags_changed = ensure_wafv2_tags(
532 wafv2, web_acl.get().get("WebACL").get("ARN"), tags, purge_tags, module.fail_json_aws, module.check_mode
533 )
534 change, rules = compare_priority_rules(web_acl.get().get("WebACL").get("Rules"), rules, purge_rules, state)
535 change = change or (description and web_acl.get().get("WebACL").get("Description") != description)
536 change = change or (default_action and web_acl.get().get("WebACL").get("DefaultAction") != default_action)
537
538 if change and not check_mode:
539 retval = web_acl.update(
540 default_action,
541 description,
542 rules,
543 sampled_requests,
544 cloudwatch_metrics,
545 metric_name,
546 custom_response_bodies,
547 )
548 elif tags_changed:
549 retval, acl_id, locktoken = web_acl.get_web_acl()
550 else:
551 retval = web_acl.get()
552
553 change |= tags_changed
554
555 else:
556 change = True
557 if not check_mode:
558 retval = web_acl.create(
559 default_action,
560 rules,
561 sampled_requests,
562 cloudwatch_metrics,
563 metric_name,
564 tags,
565 description,
566 custom_response_bodies,
567 )
568
569 elif state == "absent":
570 if web_acl.get():
571 if rules:
572 if len(rules) > 0:
573 change, rules = compare_priority_rules(
574 web_acl.get().get("WebACL").get("Rules"), rules, purge_rules, state
575 )
576 if change and not check_mode:
577 retval = web_acl.update(
578 default_action,
579 description,
580 rules,
581 sampled_requests,
582 cloudwatch_metrics,
583 metric_name,
584 custom_response_bodies,
585 )
586 else:
587 change = True
588 if not check_mode:
589 retval = web_acl.remove()
590
591 module.exit_json(changed=change, **format_result(retval))
592
593
594 if __name__ == "__main__":
595 main()