Debian Codegraph @

ansible_collections/cisco/meraki/plugins/modules/meraki_mr_l7_firewall.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: (c) 2022, Joshua Coronado (@joshuajcoronado) <[email protected]>
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
9 __metaclass__ = type
10
11 ANSIBLE_METADATA = {
12 "metadata_version": "1.1",
13 "status": ["deprecated"],
14 "supported_by": "community",
15 }
16
17 DOCUMENTATION = r"""
18 author:
19 - Joshua Coronado (@joshuajcoronado)
20 deprecated:
21 alternative: cisco.meraki.networks_appliance_firewall_l7_firewall_rules
22 removed_in: 3.0.0
23 why: Updated modules released with increased functionality
24 description:
25 - Allows for creation, management, and visibility into layer 7 firewalls implemented
26 on Meraki MR access points.
27 - Module assumes a complete list of firewall rules are passed as a parameter.
28 - If there is interest in this module allowing manipulation of a single firewall
29 rule, please submit an issue against this module.
30 extends_documentation_fragment: cisco.meraki.meraki
31 module: meraki_mr_l7_firewall
32 options:
33 categories:
34 description:
35 - When C(True), specifies that applications and application categories should
36 be queried instead of firewall rules.
37 type: bool
38 net_id:
39 description:
40 - ID of network containing access points.
41 type: str
42 net_name:
43 description:
44 - Name of network containing access points.
45 type: str
46 number:
47 aliases:
48 - ssid_number
49 description:
50 - Number of SSID to apply firewall rule to.
51 type: str
52 rules:
53 description:
54 - List of layer 7 firewall rules.
55 elements: dict
56 suboptions:
57 application:
58 description:
59 - Application to filter.
60 suboptions:
61 id:
62 description:
63 - URI of application as defined by Meraki.
64 type: str
65 name:
66 description:
67 - Name of application to filter as defined by Meraki.
68 type: str
69 type: dict
70 host:
71 description:
72 - FQDN of host to filter.
73 type: str
74 ip_range:
75 description:
76 - CIDR notation range of IP addresses to apply rule to.
77 - Port can be appended to range with a C(":").
78 type: str
79 policy:
80 choices:
81 - deny
82 default: deny
83 description:
84 - Policy to apply if rule is hit.
85 type: str
86 port:
87 description:
88 - TCP or UDP based port to filter.
89 type: str
90 type:
91 choices:
92 - application
93 - application_category
94 - host
95 - ip_range
96 - port
97 description:
98 - Type of policy to apply.
99 type: str
100 type: list
101 ssid_name:
102 aliases:
103 - ssid
104 description:
105 - Name of SSID to apply firewall rule to.
106 type: str
107 state:
108 choices:
109 - present
110 - query
111 default: present
112 description:
113 - Query or modify a firewall rule.
114 type: str
115 short_description: Manage MR access point layer 7 firewalls in the Meraki cloud
116 """
117
118 EXAMPLES = r"""
119 - name: Query firewall rules
120 meraki_mr_l7_firewall:
121 auth_key: abc123
122 org_name: YourOrg
123 net_name: YourNet
124 state: query
125 number: 1
126 delegate_to: localhost
127 - name: Query applications and application categories
128 meraki_mr_l7_firewall:
129 auth_key: abc123
130 org_name: YourOrg
131 net_name: YourNet
132 number: 1
133 categories: true
134 state: query
135 delegate_to: localhost
136 - name: Set firewall rules
137 meraki_mr_l7_firewall:
138 auth_key: abc123
139 org_name: YourOrg
140 net_name: YourNet
141 number: 1
142 state: present
143 rules:
144 - policy: deny
145 type: port
146 port: 8080
147 - type: port
148 port: 1234
149 - type: host
150 host: asdf.com
151 - type: application
152 application:
153 id: meraki:layer7/application/205
154 - type: application_category
155 application:
156 id: meraki:layer7/category/24
157 delegate_to: localhost
158 """
159
160 RETURN = r"""
161 data:
162 description: Firewall rules associated to network SSID.
163 returned: success
164 type: complex
165 contains:
166 rules:
167 description: Ordered list of firewall rules.
168 returned: success, when not querying applications
169 type: list
170 contains:
171 policy:
172 description: Action to apply when rule is hit.
173 returned: success
174 type: str
175 sample: deny
176 type:
177 description: Type of rule category.
178 returned: success
179 type: str
180 sample: applications
181 applications:
182 description: List of applications within a category.
183 type: list
184 contains:
185 id:
186 description: URI of application.
187 returned: success
188 type: str
189 sample: Gmail
190 name:
191 description: Descriptive name of application.
192 returned: success
193 type: str
194 sample: meraki:layer7/application/4
195 applicationCategory:
196 description: List of application categories within a category.
197 type: list
198 contains:
199 id:
200 description: URI of application.
201 returned: success
202 type: str
203 sample: Gmail
204 name:
205 description: Descriptive name of application.
206 returned: success
207 type: str
208 sample: meraki:layer7/application/4
209 port:
210 description: Port number in rule.
211 returned: success
212 type: str
213 sample: 23
214 ipRange:
215 description: Range of IP addresses in rule.
216 returned: success
217 type: str
218 sample: 1.1.1.0/23
219 application_categories:
220 description: List of application categories and applications.
221 type: list
222 returned: success, when querying applications
223 contains:
224 applications:
225 description: List of applications within a category.
226 type: list
227 contains:
228 id:
229 description: URI of application.
230 returned: success
231 type: str
232 sample: Gmail
233 name:
234 description: Descriptive name of application.
235 returned: success
236 type: str
237 sample: meraki:layer7/application/4
238 id:
239 description: URI of application category.
240 returned: success
241 type: str
242 sample: Email
243 name:
244 description: Descriptive name of application category.
245 returned: success
246 type: str
247 sample: layer7/category/1
248 """
249
250 import copy
251 from ansible.module_utils.basic import AnsibleModule, json
252 from ansible_collections.cisco.meraki.plugins.module_utils.network.meraki.meraki import (
253 MerakiModule,
254 meraki_argument_spec,
255 )
256
257
258 def get_applications(meraki, net_id):
259 path = meraki.construct_path("get_categories", net_id=net_id)
260 return meraki.request(path, method="GET")
261
262
263 def lookup_application(meraki, net_id, application):
264 response = get_applications(meraki, net_id)
265 for category in response["applicationCategories"]:
266 if category["name"].lower() == application.lower():
267 return category["id"]
268 for app in category["applications"]:
269 if app["name"].lower() == application.lower():
270 return app["id"]
271 meraki.fail_json(
272 msg="No application or category named {0} found".format(application)
273 )
274
275
276 def assemble_payload(meraki, net_id, rule):
277 new_rule = {}
278 if rule["type"] == "application":
279 new_rule = {
280 "policy": rule["policy"],
281 "type": "application",
282 }
283 if rule["application"]["id"]:
284 new_rule["value"] = {"id": rule["application"]["id"]}
285 elif rule["application"]["name"]:
286 new_rule["value"] = {
287 "id": lookup_application(meraki, net_id, rule["application"]["name"])
288 }
289 elif rule["type"] == "application_category":
290 new_rule = {
291 "policy": rule["policy"],
292 "type": "applicationCategory",
293 }
294 if rule["application"]["id"]:
295 new_rule["value"] = {"id": rule["application"]["id"]}
296 elif rule["application"]["name"]:
297 new_rule["value"] = {
298 "id": lookup_application(meraki, net_id, rule["application"]["name"])
299 }
300 elif rule["type"] == "ip_range":
301 new_rule = {
302 "policy": rule["policy"],
303 "type": "ipRange",
304 "value": rule["ip_range"],
305 }
306 elif rule["type"] == "host":
307 new_rule = {
308 "policy": rule["policy"],
309 "type": rule["type"],
310 "value": rule["host"],
311 }
312 elif rule["type"] == "port":
313 new_rule = {
314 "policy": rule["policy"],
315 "type": rule["type"],
316 "value": rule["port"],
317 }
318 return new_rule
319
320
321 def restructure_response(rules):
322 for rule in rules["rules"]:
323 type = rule["type"]
324 rule[type] = copy.deepcopy(rule["value"])
325 del rule["value"]
326 return rules
327
328
329 def get_ssid_number(name, data):
330 for ssid in data:
331 if name == ssid["name"]:
332 return ssid["number"]
333 return False
334
335
336 def get_ssids(meraki, net_id):
337 path = meraki.construct_path("get_ssids", net_id=net_id)
338 return meraki.request(path, method="GET")
339
340
341 def get_rules(meraki, net_id, number):
342 path = meraki.construct_path("get_all", net_id=net_id, custom={"number": number})
343 response = meraki.request(path, method="GET")
344 if meraki.status == 200:
345 return response
346
347
348 def main():
349 # define the available arguments/parameters that a user can pass to
350 # the module
351
352 application_arg_spec = dict(
353 id=dict(type="str"),
354 name=dict(type="str"),
355 )
356
357 rule_arg_spec = dict(
358 policy=dict(type="str", choices=["deny"], default="deny"),
359 type=dict(
360 type="str",
361 choices=["application", "application_category", "host", "ip_range", "port"],
362 ),
363 ip_range=dict(type="str"),
364 application=dict(type="dict", default=None, options=application_arg_spec),
365 host=dict(type="str"),
366 port=dict(type="str"),
367 )
368
369 argument_spec = meraki_argument_spec()
370 argument_spec.update(
371 state=dict(type="str", choices=["present", "query"], default="present"),
372 net_name=dict(type="str"),
373 net_id=dict(type="str"),
374 number=dict(type="str", aliases=["ssid_number"]),
375 ssid_name=dict(type="str", aliases=["ssid"]),
376 rules=dict(type="list", default=None, elements="dict", options=rule_arg_spec),
377 categories=dict(type="bool"),
378 )
379
380 # the AnsibleModule object will be our abstraction working with Ansible
381 # this includes instantiation, a couple of common attr would be the
382 # args/params passed to the execution, as well as if the module
383 # supports check mode
384 module = AnsibleModule(
385 argument_spec=argument_spec,
386 supports_check_mode=True,
387 )
388 meraki = MerakiModule(module, function="mr_l7_firewall")
389
390 # check for argument completeness
391 if meraki.params["rules"]:
392 for rule in meraki.params["rules"]:
393 if rule["type"] == "application" and rule["application"] is None:
394 meraki.fail_json(
395 msg="application argument is required when type is application."
396 )
397 elif rule["type"] == "application_category" and rule["application"] is None:
398 meraki.fail_json(
399 msg="application argument is required when type is application_category."
400 )
401 elif rule["type"] == "host" and rule["host"] is None:
402 meraki.fail_json(msg="host argument is required when type is host.")
403 elif rule["type"] == "port" and rule["port"] is None:
404 meraki.fail_json(msg="port argument is required when type is port.")
405
406 meraki.params["follow_redirects"] = "all"
407 query_ssids_urls = {"mr_l7_firewall": "/networks/{net_id}/wireless/ssids"}
408 query_urls = {
409 "mr_l7_firewall": "/networks/{net_id}/wireless/ssids/{number}/firewall/l7FirewallRules"
410 }
411 update_urls = {
412 "mr_l7_firewall": "/networks/{net_id}/wireless/ssids/{number}/firewall/l7FirewallRules"
413 }
414 query_category_urls = {
415 "mr_l7_firewall": "/networks/{net_id}/trafficShaping/applicationCategories"
416 }
417
418 meraki.url_catalog["get_all"].update(query_urls)
419 meraki.url_catalog["get_categories"] = query_category_urls
420 meraki.url_catalog["get_ssids"] = query_ssids_urls
421 meraki.url_catalog["update"] = update_urls
422
423 payload = None
424
425 # manipulate or modify the state as needed (this is going to be the
426 # part where your module will do what it needs to do)
427 org_id = meraki.params["org_id"]
428 orgs = None
429 if org_id is None:
430 orgs = meraki.get_orgs()
431 for org in orgs:
432 if org["name"] == meraki.params["org_name"]:
433 org_id = org["id"]
434 net_id = meraki.params["net_id"]
435 if net_id is None:
436 if orgs is None:
437 orgs = meraki.get_orgs()
438 net_id = meraki.get_net_id(
439 net_name=meraki.params["net_name"], data=meraki.get_nets(org_id=org_id)
440 )
441 number = meraki.params["number"]
442 if meraki.params["ssid_name"]:
443 ssids = get_ssids(meraki, net_id)
444 number = get_ssid_number(meraki.params["ssid_name"], ssids)
445
446 if meraki.params["state"] == "query":
447 if meraki.params["categories"] is True: # Output only applications
448 meraki.result["data"] = get_applications(meraki, net_id)
449 else:
450 meraki.result["data"] = restructure_response(
451 get_rules(meraki, net_id, number)
452 )
453 elif meraki.params["state"] == "present":
454 rules = get_rules(meraki, net_id, number)
455 path = meraki.construct_path(
456 "get_all", net_id=net_id, custom={"number": number}
457 )
458
459 # Detect if no rules are given, special case
460 if len(meraki.params["rules"]) == 0:
461 # Conditionally wrap parameters in rules makes it comparable
462 if isinstance(meraki.params["rules"], list):
463 param_rules = {"rules": meraki.params["rules"]}
464 else:
465 param_rules = meraki.params["rules"]
466 if meraki.is_update_required(rules, param_rules):
467 if meraki.module.check_mode is True:
468 meraki.result["data"] = meraki.params["rules"]
469 meraki.result["changed"] = True
470 meraki.exit_json(**meraki.result)
471 payload = {"rules": []}
472 response = meraki.request(
473 path, method="PUT", payload=json.dumps(payload)
474 )
475 meraki.result["data"] = response
476 meraki.result["changed"] = True
477 meraki.exit_json(**meraki.result)
478 else:
479 meraki.result["data"] = param_rules
480 meraki.exit_json(**meraki.result)
481 if meraki.params["rules"]:
482 payload = {"rules": []}
483 for rule in meraki.params["rules"]:
484 payload["rules"].append(assemble_payload(meraki, net_id, rule))
485 else:
486 payload = dict()
487 if meraki.is_update_required(rules, payload, force_include="id"):
488 if meraki.module.check_mode is True:
489 response = restructure_response(payload)
490 meraki.generate_diff(restructure_response(rules), response)
491 meraki.result["data"] = response
492 meraki.result["changed"] = True
493 meraki.exit_json(**meraki.result)
494 response = meraki.request(path, method="PUT", payload=json.dumps(payload))
495 response = restructure_response(response)
496 if meraki.status == 200:
497 meraki.generate_diff(restructure_response(rules), response)
498 meraki.result["data"] = response
499 meraki.result["changed"] = True
500 else:
501 if meraki.module.check_mode is True:
502 meraki.result["data"] = rules
503 meraki.result["changed"] = False
504 meraki.exit_json(**meraki.result)
505 meraki.result["data"] = payload
506
507 # in the event of a successful module execution, you will want to
508 # simple AnsibleModule.exit_json(), passing the key/value results
509 meraki.exit_json(**meraki.result)
510
511
512 if __name__ == "__main__":
513 main()