Debian Codegraph @

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

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright (c) 2017 Will Thames
5 # Copyright (c) 2015 Mike Mochan
6 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
7
8 DOCUMENTATION = r"""
9 module: waf_rule
10 short_description: Create and delete WAF Rules
11 version_added: 1.0.0
12 description:
13 - Read the AWS documentation for WAF
14 U(https://aws.amazon.com/documentation/waf/).
15 - Prior to release 5.0.0 this module was called C(community.aws.aws_waf_rule).
16 The usage did not change.
17
18 author:
19 - Mike Mochan (@mmochan)
20 - Will Thames (@willthames)
21
22 deprecated:
23 removed_in: 12.0.0
24 why: Amazon has retired the "WAF Classic" service.
25 alternative: Please use the "AWS WAF (WAFv2)" service and modules instead.
26
27 options:
28 name:
29 description: Name of the Web Application Firewall rule.
30 required: true
31 type: str
32 metric_name:
33 description:
34 - A friendly name or description for the metrics for the rule.
35 - The name can contain only alphanumeric characters (A-Z, a-z, 0-9); the name may not contain whitespace.
36 - You can't change I(metric_name) after you create the rule.
37 - Defaults to the same as I(name) with disallowed characters removed.
38 type: str
39 state:
40 description: Whether the rule should be present or absent.
41 choices: ['present', 'absent']
42 default: present
43 type: str
44 conditions:
45 description: >
46 List of conditions used in the rule. M(community.aws.waf_condition) can be used to create new conditions.
47 type: list
48 elements: dict
49 suboptions:
50 type:
51 required: true
52 type: str
53 choices: ['byte','geo','ip','size','sql','xss']
54 description: The type of rule to match.
55 negated:
56 required: true
57 type: bool
58 description: Whether the condition should be negated.
59 condition:
60 required: true
61 type: str
62 description: The name of the condition. The condition must already exist.
63 purge_conditions:
64 description:
65 - Whether or not to remove conditions that are not passed when updating I(conditions).
66 default: false
67 type: bool
68 waf_regional:
69 description: Whether to use C(waf-regional) module.
70 default: false
71 required: false
72 type: bool
73
74 extends_documentation_fragment:
75 - amazon.aws.common.modules
76 - amazon.aws.region.modules
77 - amazon.aws.boto3
78 """
79
80 EXAMPLES = r"""
81 - name: create WAF rule
82 community.aws.waf_rule:
83 name: my_waf_rule
84 conditions:
85 - name: my_regex_condition
86 type: regex
87 negated: false
88 - name: my_geo_condition
89 type: geo
90 negated: false
91 - name: my_byte_condition
92 type: byte
93 negated: true
94
95 - name: remove WAF rule
96 community.aws.waf_rule:
97 name: "my_waf_rule"
98 state: absent
99 """
100
101 RETURN = r"""
102 rule:
103 description: WAF rule contents
104 returned: always
105 type: complex
106 contains:
107 metric_name:
108 description: Metric name for the rule.
109 returned: always
110 type: str
111 sample: ansibletest1234rule
112 name:
113 description: Friendly name for the rule.
114 returned: always
115 type: str
116 sample: ansible-test-1234_rule
117 predicates:
118 description: List of conditions used in the rule.
119 returned: always
120 type: complex
121 contains:
122 data_id:
123 description: ID of the condition.
124 returned: always
125 type: str
126 sample: 8251acdb-526c-42a8-92bc-d3d13e584166
127 negated:
128 description: Whether the sense of the condition is negated.
129 returned: always
130 type: bool
131 sample: false
132 type:
133 description: type of the condition.
134 returned: always
135 type: str
136 sample: ByteMatch
137 rule_id:
138 description: ID of the WAF rule.
139 returned: always
140 type: str
141 sample: 15de0cbc-9204-4e1f-90e6-69b2f415c261
142 """
143
144 import re
145
146 try:
147 import botocore
148 except ImportError:
149 pass # handled by AnsibleAWSModule
150
151 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
152
153 from ansible_collections.amazon.aws.plugins.module_utils.waf import MATCH_LOOKUP
154 from ansible_collections.amazon.aws.plugins.module_utils.waf import get_web_acl_with_backoff
155 from ansible_collections.amazon.aws.plugins.module_utils.waf import list_regional_rules_with_backoff
156 from ansible_collections.amazon.aws.plugins.module_utils.waf import list_regional_web_acls_with_backoff
157 from ansible_collections.amazon.aws.plugins.module_utils.waf import list_rules_with_backoff
158 from ansible_collections.amazon.aws.plugins.module_utils.waf import list_web_acls_with_backoff
159 from ansible_collections.amazon.aws.plugins.module_utils.waf import run_func_with_change_token_backoff
160
161 from ansible_collections.community.aws.plugins.module_utils.modules import AnsibleCommunityAWSModule as AnsibleAWSModule
162
163
164 def get_rule_by_name(client, module, name):
165 rules = [d["RuleId"] for d in list_rules(client, module) if d["Name"] == name]
166 if rules:
167 return rules[0]
168
169
170 def get_rule(client, module, rule_id):
171 try:
172 return client.get_rule(RuleId=rule_id)["Rule"]
173 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
174 module.fail_json_aws(e, msg="Could not get WAF rule")
175
176
177 def list_rules(client, module):
178 if client.__class__.__name__ == "WAF":
179 try:
180 return list_rules_with_backoff(client)
181 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
182 module.fail_json_aws(e, msg="Could not list WAF rules")
183 elif client.__class__.__name__ == "WAFRegional":
184 try:
185 return list_regional_rules_with_backoff(client)
186 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
187 module.fail_json_aws(e, msg="Could not list WAF Regional rules")
188
189
190 def list_regional_rules(client, module):
191 try:
192 return list_regional_rules_with_backoff(client)
193 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
194 module.fail_json_aws(e, msg="Could not list WAF rules")
195
196
197 def find_and_update_rule(client, module, rule_id):
198 rule = get_rule(client, module, rule_id)
199 rule_id = rule["RuleId"]
200
201 existing_conditions = dict((condition_type, dict()) for condition_type in MATCH_LOOKUP)
202 desired_conditions = dict((condition_type, dict()) for condition_type in MATCH_LOOKUP)
203 all_conditions = dict()
204
205 for condition_type in MATCH_LOOKUP:
206 method = "list_" + MATCH_LOOKUP[condition_type]["method"] + "s"
207 all_conditions[condition_type] = dict()
208 try:
209 paginator = client.get_paginator(method)
210 func = paginator.paginate().build_full_result
211 except (KeyError, botocore.exceptions.OperationNotPageableError):
212 # list_geo_match_sets and list_regex_match_sets do not have a paginator
213 # and throw different exceptions
214 func = getattr(client, method)
215 try:
216 pred_results = func()[MATCH_LOOKUP[condition_type]["conditionset"] + "s"]
217 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
218 module.fail_json_aws(e, msg=f"Could not list {condition_type} conditions")
219 for pred in pred_results:
220 pred["DataId"] = pred[MATCH_LOOKUP[condition_type]["conditionset"] + "Id"]
221 all_conditions[condition_type][pred["Name"]] = camel_dict_to_snake_dict(pred)
222 all_conditions[condition_type][pred["DataId"]] = camel_dict_to_snake_dict(pred)
223
224 for condition in module.params["conditions"]:
225 desired_conditions[condition["type"]][condition["name"]] = condition
226
227 reverse_condition_types = dict((v["type"], k) for (k, v) in MATCH_LOOKUP.items())
228 for condition in rule["Predicates"]:
229 existing_conditions[reverse_condition_types[condition["Type"]]][condition["DataId"]] = camel_dict_to_snake_dict(
230 condition
231 )
232
233 insertions = list()
234 deletions = list()
235
236 for condition_type in desired_conditions:
237 for condition_name, condition in desired_conditions[condition_type].items():
238 if condition_name not in all_conditions[condition_type]:
239 module.fail_json(msg=f"Condition {condition_name} of type {condition_type} does not exist")
240 condition["data_id"] = all_conditions[condition_type][condition_name]["data_id"]
241 if condition["data_id"] not in existing_conditions[condition_type]:
242 insertions.append(format_for_insertion(condition))
243
244 if module.params["purge_conditions"]:
245 for condition_type in existing_conditions:
246 deletions.extend(
247 [
248 format_for_deletion(condition)
249 for condition in existing_conditions[condition_type].values()
250 if all_conditions[condition_type][condition["data_id"]]["name"]
251 not in desired_conditions[condition_type]
252 ]
253 )
254
255 changed = bool(insertions or deletions)
256 update = {"RuleId": rule_id, "Updates": insertions + deletions}
257 if changed:
258 try:
259 run_func_with_change_token_backoff(client, module, update, client.update_rule, wait=True)
260 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
261 module.fail_json_aws(e, msg="Could not update rule conditions")
262
263 return changed, get_rule(client, module, rule_id)
264
265
266 def format_for_insertion(condition):
267 return dict(
268 Action="INSERT",
269 Predicate=dict(
270 Negated=condition["negated"], Type=MATCH_LOOKUP[condition["type"]]["type"], DataId=condition["data_id"]
271 ),
272 )
273
274
275 def format_for_deletion(condition):
276 return dict(
277 Action="DELETE",
278 Predicate=dict(Negated=condition["negated"], Type=condition["type"], DataId=condition["data_id"]),
279 )
280
281
282 def remove_rule_conditions(client, module, rule_id):
283 conditions = get_rule(client, module, rule_id)["Predicates"]
284 updates = [format_for_deletion(camel_dict_to_snake_dict(condition)) for condition in conditions]
285 try:
286 run_func_with_change_token_backoff(client, module, {"RuleId": rule_id, "Updates": updates}, client.update_rule)
287 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
288 module.fail_json_aws(e, msg="Could not remove rule conditions")
289
290
291 def ensure_rule_present(client, module):
292 name = module.params["name"]
293 rule_id = get_rule_by_name(client, module, name)
294 params = dict()
295 if rule_id:
296 return find_and_update_rule(client, module, rule_id)
297 else:
298 params["Name"] = module.params["name"]
299 metric_name = module.params["metric_name"]
300 if not metric_name:
301 metric_name = re.sub(r"[^a-zA-Z0-9]", "", module.params["name"])
302 params["MetricName"] = metric_name
303 try:
304 new_rule = run_func_with_change_token_backoff(client, module, params, client.create_rule)["Rule"]
305 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
306 module.fail_json_aws(e, msg="Could not create rule")
307 return find_and_update_rule(client, module, new_rule["RuleId"])
308
309
310 def find_rule_in_web_acls(client, module, rule_id):
311 web_acls_in_use = []
312 try:
313 if client.__class__.__name__ == "WAF":
314 all_web_acls = list_web_acls_with_backoff(client)
315 elif client.__class__.__name__ == "WAFRegional":
316 all_web_acls = list_regional_web_acls_with_backoff(client)
317 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
318 module.fail_json_aws(e, msg="Could not list Web ACLs")
319 for web_acl in all_web_acls:
320 try:
321 web_acl_details = get_web_acl_with_backoff(client, web_acl["WebACLId"])
322 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
323 module.fail_json_aws(e, msg="Could not get Web ACL details")
324 if rule_id in [rule["RuleId"] for rule in web_acl_details["Rules"]]:
325 web_acls_in_use.append(web_acl_details["Name"])
326 return web_acls_in_use
327
328
329 def ensure_rule_absent(client, module):
330 rule_id = get_rule_by_name(client, module, module.params["name"])
331 in_use_web_acls = find_rule_in_web_acls(client, module, rule_id)
332 if in_use_web_acls:
333 web_acl_names = ", ".join(in_use_web_acls)
334 module.fail_json(msg=f"Rule {module.params['name']} is in use by Web ACL(s) {web_acl_names}")
335 if rule_id:
336 remove_rule_conditions(client, module, rule_id)
337 try:
338 return True, run_func_with_change_token_backoff(
339 client, module, {"RuleId": rule_id}, client.delete_rule, wait=True
340 )
341 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
342 module.fail_json_aws(e, msg="Could not delete rule")
343 return False, {}
344
345
346 def main():
347 argument_spec = dict(
348 name=dict(required=True),
349 metric_name=dict(),
350 state=dict(default="present", choices=["present", "absent"]),
351 conditions=dict(type="list", elements="dict"),
352 purge_conditions=dict(type="bool", default=False),
353 waf_regional=dict(type="bool", default=False),
354 )
355 module = AnsibleAWSModule(argument_spec=argument_spec)
356 state = module.params.get("state")
357
358 resource = "waf" if not module.params["waf_regional"] else "waf-regional"
359 client = module.client(resource)
360 if state == "present":
361 (changed, results) = ensure_rule_present(client, module)
362 else:
363 (changed, results) = ensure_rule_absent(client, module)
364
365 module.exit_json(changed=changed, rule=camel_dict_to_snake_dict(results))
366
367
368 if __name__ == "__main__":
369 main()