Debian Codegraph @

ansible_collections/amazon/aws/plugins/module_utils/waf.py

raw
1 # -*- coding: utf-8 -*-
2
3 # Copyright (c) 2017 Will Thames
4 #
5 # This code is part of Ansible, but is an independent component.
6 # This particular file snippet, and this file snippet only, is BSD licensed.
7 # Modules you write using this snippet, which is embedded dynamically by Ansible
8 # still belong to the author of the module, and may assign their own license
9 # to the complete work.
10 #
11 # Redistribution and use in source and binary forms, with or without modification,
12 # are permitted provided that the following conditions are met:
13 #
14 # * Redistributions of source code must retain the above copyright
15 # notice, this list of conditions and the following disclaimer.
16 # * Redistributions in binary form must reproduce the above copyright notice,
17 # this list of conditions and the following disclaimer in the documentation
18 # and/or other materials provided with the distribution.
19 #
20 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
21 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
24 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
28 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 """
31 This module adds shared support for Web Application Firewall modules
32 """
33
34 try:
35 import botocore
36 except ImportError:
37 pass # caught by imported HAS_BOTO3
38
39 from ansible.module_utils.common.dict_transformations import camel_dict_to_snake_dict
40
41 from .retries import AWSRetry
42 from .waiters import get_waiter
43
44 MATCH_LOOKUP = {
45 "byte": {
46 "method": "byte_match_set",
47 "conditionset": "ByteMatchSet",
48 "conditiontuple": "ByteMatchTuple",
49 "type": "ByteMatch",
50 },
51 "geo": {
52 "method": "geo_match_set",
53 "conditionset": "GeoMatchSet",
54 "conditiontuple": "GeoMatchConstraint",
55 "type": "GeoMatch",
56 },
57 "ip": {"method": "ip_set", "conditionset": "IPSet", "conditiontuple": "IPSetDescriptor", "type": "IPMatch"},
58 "regex": {
59 "method": "regex_match_set",
60 "conditionset": "RegexMatchSet",
61 "conditiontuple": "RegexMatchTuple",
62 "type": "RegexMatch",
63 },
64 "size": {
65 "method": "size_constraint_set",
66 "conditionset": "SizeConstraintSet",
67 "conditiontuple": "SizeConstraint",
68 "type": "SizeConstraint",
69 },
70 "sql": {
71 "method": "sql_injection_match_set",
72 "conditionset": "SqlInjectionMatchSet",
73 "conditiontuple": "SqlInjectionMatchTuple",
74 "type": "SqlInjectionMatch",
75 },
76 "xss": {
77 "method": "xss_match_set",
78 "conditionset": "XssMatchSet",
79 "conditiontuple": "XssMatchTuple",
80 "type": "XssMatch",
81 },
82 }
83
84
85 @AWSRetry.jittered_backoff(delay=5)
86 def get_rule_with_backoff(client, rule_id):
87 return client.get_rule(RuleId=rule_id)["Rule"]
88
89
90 @AWSRetry.jittered_backoff(delay=5)
91 def get_byte_match_set_with_backoff(client, byte_match_set_id):
92 return client.get_byte_match_set(ByteMatchSetId=byte_match_set_id)["ByteMatchSet"]
93
94
95 @AWSRetry.jittered_backoff(delay=5)
96 def get_ip_set_with_backoff(client, ip_set_id):
97 return client.get_ip_set(IPSetId=ip_set_id)["IPSet"]
98
99
100 @AWSRetry.jittered_backoff(delay=5)
101 def get_size_constraint_set_with_backoff(client, size_constraint_set_id):
102 return client.get_size_constraint_set(SizeConstraintSetId=size_constraint_set_id)["SizeConstraintSet"]
103
104
105 @AWSRetry.jittered_backoff(delay=5)
106 def get_sql_injection_match_set_with_backoff(client, sql_injection_match_set_id):
107 return client.get_sql_injection_match_set(SqlInjectionMatchSetId=sql_injection_match_set_id)["SqlInjectionMatchSet"]
108
109
110 @AWSRetry.jittered_backoff(delay=5)
111 def get_xss_match_set_with_backoff(client, xss_match_set_id):
112 return client.get_xss_match_set(XssMatchSetId=xss_match_set_id)["XssMatchSet"]
113
114
115 def get_rule(client, module, rule_id):
116 try:
117 rule = get_rule_with_backoff(client, rule_id)
118 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
119 module.fail_json_aws(e, msg="Couldn't obtain waf rule")
120
121 match_sets = {
122 "ByteMatch": get_byte_match_set_with_backoff,
123 "IPMatch": get_ip_set_with_backoff,
124 "SizeConstraint": get_size_constraint_set_with_backoff,
125 "SqlInjectionMatch": get_sql_injection_match_set_with_backoff,
126 "XssMatch": get_xss_match_set_with_backoff,
127 }
128 if "Predicates" in rule:
129 for predicate in rule["Predicates"]:
130 if predicate["Type"] in match_sets:
131 predicate.update(match_sets[predicate["Type"]](client, predicate["DataId"]))
132 # replaced by Id from the relevant MatchSet
133 del predicate["DataId"]
134 return rule
135
136
137 @AWSRetry.jittered_backoff(delay=5)
138 def get_web_acl_with_backoff(client, web_acl_id):
139 return client.get_web_acl(WebACLId=web_acl_id)["WebACL"]
140
141
142 def get_web_acl(client, module, web_acl_id):
143 try:
144 web_acl = get_web_acl_with_backoff(client, web_acl_id)
145 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
146 module.fail_json_aws(e, msg="Couldn't obtain web acl")
147
148 if web_acl:
149 try:
150 for rule in web_acl["Rules"]:
151 rule.update(get_rule(client, module, rule["RuleId"]))
152 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
153 module.fail_json_aws(e, msg="Couldn't obtain web acl rule")
154 return camel_dict_to_snake_dict(web_acl)
155
156
157 @AWSRetry.jittered_backoff(delay=5)
158 def list_rules_with_backoff(client):
159 paginator = client.get_paginator("list_rules")
160 return paginator.paginate().build_full_result()["Rules"]
161
162
163 @AWSRetry.jittered_backoff(delay=5)
164 def list_regional_rules_with_backoff(client):
165 resp = client.list_rules()
166 rules = []
167 while resp:
168 rules += resp["Rules"]
169 resp = client.list_rules(NextMarker=resp["NextMarker"]) if "NextMarker" in resp else None
170 return rules
171
172
173 @AWSRetry.jittered_backoff(delay=5)
174 def list_web_acls_with_backoff(client):
175 paginator = client.get_paginator("list_web_acls")
176 return paginator.paginate().build_full_result()["WebACLs"]
177
178
179 @AWSRetry.jittered_backoff(delay=5)
180 def list_regional_web_acls_with_backoff(client):
181 resp = client.list_web_acls()
182 acls = []
183 while resp:
184 acls += resp["WebACLs"]
185 resp = client.list_web_acls(NextMarker=resp["NextMarker"]) if "NextMarker" in resp else None
186 return acls
187
188
189 def list_web_acls(client, module):
190 try:
191 if client.__class__.__name__ == "WAF":
192 return list_web_acls_with_backoff(client)
193 elif client.__class__.__name__ == "WAFRegional":
194 return list_regional_web_acls_with_backoff(client)
195 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
196 module.fail_json_aws(e, msg="Couldn't obtain web acls")
197
198
199 def get_change_token(client, module):
200 try:
201 token = client.get_change_token()
202 return token["ChangeToken"]
203 except (botocore.exceptions.ClientError, botocore.exceptions.BotoCoreError) as e:
204 module.fail_json_aws(e, msg="Couldn't obtain change token")
205
206
207 @AWSRetry.jittered_backoff(backoff=2, catch_extra_error_codes=["WAFStaleDataException"])
208 def run_func_with_change_token_backoff(client, module, params, func, wait=False):
209 params["ChangeToken"] = get_change_token(client, module)
210 result = func(**params)
211 if wait:
212 get_waiter(
213 client,
214 "change_token_in_sync",
215 ).wait(ChangeToken=result["ChangeToken"])
216 return result