Debian Codegraph @

ansible_collections/community/general/plugins/modules/ufw.py

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2014, Ahti Kitsik <[email protected]>
4 # Copyright (c) 2014, Jarno Keskikangas <[email protected]>
5 # Copyright (c) 2013, Aleksey Ovcharenko <[email protected]>
6 # Copyright (c) 2013, James Martin <[email protected]>
7 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
8 # SPDX-License-Identifier: GPL-3.0-or-later
9
10 from __future__ import annotations
11
12 DOCUMENTATION = r"""
13 module: ufw
14 short_description: Manage firewall with UFW
15 description:
16 - Manage firewall with UFW.
17 author:
18 - Aleksey Ovcharenko (@ovcharenko)
19 - Jarno Keskikangas (@pyykkis)
20 - Ahti Kitsik (@ahtik)
21 notes:
22 - See C(man ufw) for more examples.
23 - B(Warning:) Whilst the module itself can be run using concurrent strategies, C(ufw) does not support concurrency, as firewall
24 rules are meant to be ordered and parallel executions do not guarantee order. B(Do not use concurrency:) The results are
25 unpredictable and the module may fail silently if you do.
26 requirements:
27 - C(ufw) package
28 extends_documentation_fragment:
29 - community.general._attributes
30 attributes:
31 check_mode:
32 support: full
33 diff_mode:
34 support: none
35 options:
36 state:
37 description:
38 - V(enabled) reloads firewall and enables firewall on boot.
39 - V(disabled) unloads firewall and disables firewall on boot.
40 - V(reloaded) reloads firewall.
41 - V(reset) disables and resets firewall to installation defaults.
42 type: str
43 choices: [disabled, enabled, reloaded, reset]
44 default:
45 description:
46 - Change the default policy for incoming or outgoing traffic.
47 type: str
48 choices: [allow, deny, reject]
49 aliases: [policy]
50 direction:
51 description:
52 - Select direction for a rule or default policy command. Mutually exclusive with O(interface_in) and O(interface_out).
53 type: str
54 choices: [in, incoming, out, outgoing, routed]
55 logging:
56 description:
57 - Toggles logging. Logged packets use the LOG_KERN syslog facility.
58 type: str
59 choices: ['on', 'off', low, medium, high, full]
60 insert:
61 description:
62 - Insert the corresponding rule as rule number NUM.
63 - Note that ufw numbers rules starting with 1.
64 - If O(delete=true) and a value is provided for O(insert), then O(insert) is ignored.
65 type: int
66 insert_relative_to:
67 description:
68 - Allows to interpret the index in O(insert) relative to a position.
69 - V(zero) interprets the rule number as an absolute index (that is, 1 is the first rule).
70 - V(first-ipv4) interprets the rule number relative to the index of the first IPv4 rule, or relative to the position
71 where the first IPv4 rule would be if there is currently none.
72 - V(last-ipv4) interprets the rule number relative to the index of the last IPv4 rule, or relative to the position where
73 the last IPv4 rule would be if there is currently none.
74 - V(first-ipv6) interprets the rule number relative to the index of the first IPv6 rule, or relative to the position
75 where the first IPv6 rule would be if there is currently none.
76 - V(last-ipv6) interprets the rule number relative to the index of the last IPv6 rule, or relative to the position where
77 the last IPv6 rule would be if there is currently none.
78 type: str
79 choices: [first-ipv4, first-ipv6, last-ipv4, last-ipv6, zero]
80 default: zero
81 rule:
82 description:
83 - Add firewall rule.
84 type: str
85 choices: [allow, deny, limit, reject]
86 log:
87 description:
88 - Log new connections matched to this rule.
89 type: bool
90 default: false
91 from_ip:
92 description:
93 - Source IP address.
94 type: str
95 default: any
96 aliases: [from, src]
97 from_port:
98 description:
99 - Source port.
100 type: str
101 to_ip:
102 description:
103 - Destination IP address.
104 type: str
105 default: any
106 aliases: [dest, to]
107 to_port:
108 description:
109 - Destination port.
110 type: str
111 aliases: [port]
112 proto:
113 description:
114 - TCP/IP protocol.
115 - The value V(vrrp) is supported since community.general 10.3.0.
116 type: str
117 choices: [any, tcp, udp, ipv6, esp, ah, gre, igmp, vrrp]
118 aliases: [protocol]
119 name:
120 description:
121 - Use profile located in C(/etc/ufw/applications.d).
122 type: str
123 aliases: [app]
124 delete:
125 description:
126 - Delete rule.
127 - If O(delete=true) and a value is provided for O(insert), then O(insert) is ignored.
128 type: bool
129 default: false
130 interface:
131 description:
132 - Specify interface for the rule. The direction (in or out) used for the interface depends on the value of O(direction).
133 See O(interface_in) and O(interface_out) for routed rules that needs to supply both an input and output interface.
134 Mutually exclusive with O(interface_in) and O(interface_out).
135 type: str
136 aliases: [if]
137 interface_in:
138 description:
139 - Specify input interface for the rule. This is mutually exclusive with O(direction) and O(interface). However, it is
140 compatible with O(interface_out) for routed rules.
141 type: str
142 aliases: [if_in]
143 version_added: '0.2.0'
144 interface_out:
145 description:
146 - Specify output interface for the rule. This is mutually exclusive with O(direction) and O(interface). However, it
147 is compatible with O(interface_in) for routed rules.
148 type: str
149 aliases: [if_out]
150 version_added: '0.2.0'
151 route:
152 description:
153 - Apply the rule to routed/forwarded packets.
154 type: bool
155 default: false
156 comment:
157 description:
158 - Add a comment to the rule. Requires UFW version >=0.35.
159 type: str
160 """
161
162 EXAMPLES = r"""
163 - name: Allow everything and enable UFW
164 community.general.ufw:
165 state: enabled
166 policy: allow
167
168 - name: Set logging
169 community.general.ufw:
170 logging: 'on'
171
172 # Sometimes it is desirable to let the sender know when traffic is
173 # being denied, rather than simply ignoring it. In these cases, use
174 # reject instead of deny. In addition, log rejected connections:
175 - community.general.ufw:
176 rule: reject
177 port: auth
178 log: true
179
180 # ufw supports connection rate limiting, which is useful for protecting
181 # against brute-force login attacks. ufw will deny connections if an IP
182 # address has attempted to initiate 6 or more connections in the last
183 # 30 seconds. See http://www.debian-administration.org/articles/187
184 # for details. Typical usage is:
185 - community.general.ufw:
186 rule: limit
187 port: ssh
188 proto: tcp
189
190 # Allow OpenSSH. (Note that as ufw manages its own state, simply removing
191 # a rule=allow task can leave those ports exposed. Either use delete=true
192 # or a separate state=reset task)
193 - community.general.ufw:
194 rule: allow
195 name: OpenSSH
196
197 - name: Delete OpenSSH rule
198 community.general.ufw:
199 rule: allow
200 name: OpenSSH
201 delete: true
202
203 - name: Deny all access to port 53
204 community.general.ufw:
205 rule: deny
206 port: '53'
207
208 - name: Allow port range 60000-61000
209 community.general.ufw:
210 rule: allow
211 port: 60000:61000
212 proto: tcp
213
214 - name: Allow all access to tcp port 80
215 community.general.ufw:
216 rule: allow
217 port: '80'
218 proto: tcp
219
220 - name: Allow all access from RFC1918 networks to this host
221 community.general.ufw:
222 rule: allow
223 src: '{{ item }}'
224 loop:
225 - 10.0.0.0/8
226 - 172.16.0.0/12
227 - 192.168.0.0/16
228
229 - name: Deny access to udp port 514 from host 1.2.3.4 and include a comment
230 community.general.ufw:
231 rule: deny
232 proto: udp
233 src: 1.2.3.4
234 port: '514'
235 comment: Block syslog
236
237 - name: Allow incoming access to eth0 from 1.2.3.5 port 5469 to 1.2.3.4 port 5469
238 community.general.ufw:
239 rule: allow
240 interface: eth0
241 direction: in
242 proto: udp
243 src: 1.2.3.5
244 from_port: '5469'
245 dest: 1.2.3.4
246 to_port: '5469'
247
248 # Note that IPv6 must be enabled in /etc/default/ufw for IPv6 firewalling to work.
249 - name: Deny all traffic from the IPv6 2001:db8::/32 to tcp port 25 on this host
250 community.general.ufw:
251 rule: deny
252 proto: tcp
253 src: 2001:db8::/32
254 port: '25'
255
256 - name: Deny all IPv6 traffic to tcp port 20 on this host
257 # this should be the first IPv6 rule
258 community.general.ufw:
259 rule: deny
260 proto: tcp
261 port: '20'
262 to_ip: "::"
263 insert: 0
264 insert_relative_to: first-ipv6
265
266 - name: Deny all IPv4 traffic to tcp port 20 on this host
267 # This should be the third to last IPv4 rule
268 # (insert: -1 addresses the second to last IPv4 rule;
269 # so the new rule will be inserted before the second
270 # to last IPv4 rule, and will be come the third to last
271 # IPv4 rule.)
272 community.general.ufw:
273 rule: deny
274 proto: tcp
275 port: '20'
276 to_ip: "::"
277 insert: -1
278 insert_relative_to: last-ipv4
279
280 # Can be used to further restrict a global FORWARD policy set to allow
281 - name: Deny forwarded/routed traffic from subnet 1.2.3.0/24 to subnet 4.5.6.0/24
282 community.general.ufw:
283 rule: deny
284 route: true
285 src: 192.0.2.0/24
286 dest: 198.51.100.0/24
287 """
288
289 import re
290 from operator import itemgetter
291
292 from ansible.module_utils.basic import AnsibleModule
293
294
295 def compile_ipv4_regexp():
296 r = r"((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}"
297 r += r"(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])"
298 return re.compile(r)
299
300
301 def compile_ipv6_regexp():
302 """
303 validation pattern provided by :
304 https://stackoverflow.com/questions/53497/regular-expression-that-matches-
305 valid-ipv6-addresses#answer-17871737
306 """
307 r = r"(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:"
308 r += r"|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}"
309 r += r"(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4})"
310 r += r"{1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]"
311 r += r"{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]"
312 r += r"{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4})"
313 r += r"{0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]"
314 r += r"|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}"
315 r += r"[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}"
316 r += r"[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))"
317 return re.compile(r)
318
319
320 def main():
321 command_keys = ["state", "default", "rule", "logging"]
322
323 module = AnsibleModule(
324 argument_spec=dict(
325 state=dict(type="str", choices=["enabled", "disabled", "reloaded", "reset"]),
326 default=dict(type="str", aliases=["policy"], choices=["allow", "deny", "reject"]),
327 logging=dict(type="str", choices=["full", "high", "low", "medium", "off", "on"]),
328 direction=dict(type="str", choices=["in", "incoming", "out", "outgoing", "routed"]),
329 delete=dict(type="bool", default=False),
330 route=dict(type="bool", default=False),
331 insert=dict(type="int"),
332 insert_relative_to=dict(
333 choices=["zero", "first-ipv4", "last-ipv4", "first-ipv6", "last-ipv6"], default="zero"
334 ),
335 rule=dict(type="str", choices=["allow", "deny", "limit", "reject"]),
336 interface=dict(type="str", aliases=["if"]),
337 interface_in=dict(type="str", aliases=["if_in"]),
338 interface_out=dict(type="str", aliases=["if_out"]),
339 log=dict(type="bool", default=False),
340 from_ip=dict(type="str", default="any", aliases=["from", "src"]),
341 from_port=dict(type="str"),
342 to_ip=dict(type="str", default="any", aliases=["dest", "to"]),
343 to_port=dict(type="str", aliases=["port"]),
344 proto=dict(
345 type="str",
346 aliases=["protocol"],
347 choices=["ah", "any", "esp", "ipv6", "tcp", "udp", "gre", "igmp", "vrrp"],
348 ),
349 name=dict(type="str", aliases=["app"]),
350 comment=dict(type="str"),
351 ),
352 supports_check_mode=True,
353 mutually_exclusive=[
354 ["name", "proto", "logging"],
355 # Mutual exclusivity with `interface` implied by `required_by`.
356 ["direction", "interface_in"],
357 ["direction", "interface_out"],
358 ],
359 required_one_of=([command_keys]),
360 required_by=dict(
361 interface=("direction",),
362 ),
363 )
364
365 cmds = []
366
367 ipv4_regexp = compile_ipv4_regexp()
368 ipv6_regexp = compile_ipv6_regexp()
369
370 def filter_line_that_not_start_with(pattern, content):
371 return "".join([line for line in content.splitlines(True) if line.startswith(pattern)])
372
373 def filter_line_that_contains(pattern, content):
374 return [line for line in content.splitlines(True) if pattern in line]
375
376 def filter_line_that_not_contains(pattern, content):
377 return "".join([line for line in content.splitlines(True) if not line.contains(pattern)])
378
379 def filter_line_that_match_func(match_func, content):
380 return "".join([line for line in content.splitlines(True) if match_func(line) is not None])
381
382 def filter_line_that_contains_ipv4(content):
383 return filter_line_that_match_func(ipv4_regexp.search, content)
384
385 def filter_line_that_contains_ipv6(content):
386 return filter_line_that_match_func(ipv6_regexp.search, content)
387
388 def is_starting_by_ipv4(ip):
389 return ipv4_regexp.match(ip) is not None
390
391 def is_starting_by_ipv6(ip):
392 return ipv6_regexp.match(ip) is not None
393
394 def execute(cmd, ignore_error=False):
395 cmd = " ".join(map(itemgetter(-1), filter(itemgetter(0), cmd)))
396
397 cmds.append(cmd)
398 (rc, out, err) = module.run_command(cmd, environ_update={"LANGUAGE": "C", "LC_ALL": "C"})
399
400 if rc != 0 and not ignore_error:
401 module.fail_json(msg=err or out, commands=cmds)
402
403 return out
404
405 def get_current_rules():
406 user_rules_files = [
407 "/lib/ufw/user.rules",
408 "/lib/ufw/user6.rules",
409 "/etc/ufw/user.rules",
410 "/etc/ufw/user6.rules",
411 "/var/lib/ufw/user.rules",
412 "/var/lib/ufw/user6.rules",
413 ]
414
415 cmd = [[grep_bin], ["-h"], ["'^### tuple'"]]
416
417 cmd.extend([[f] for f in user_rules_files])
418 return execute(cmd, ignore_error=True)
419
420 def ufw_version():
421 """
422 Returns the major and minor version of ufw installed on the system.
423 """
424 out = execute([[ufw_bin], ["--version"]])
425
426 lines = [x for x in out.split("\n") if x.strip() != ""]
427 if len(lines) == 0:
428 module.fail_json(msg="Failed to get ufw version.", rc=0, out=out)
429
430 matches = re.search(r"^ufw.+(\d+)\.(\d+)(?:\.(\d+))?.*$", lines[0])
431 if matches is None:
432 module.fail_json(msg="Failed to get ufw version.", rc=0, out=out)
433
434 # Convert version to numbers
435 major = int(matches.group(1))
436 minor = int(matches.group(2))
437 rev = 0
438 if matches.group(3) is not None:
439 rev = int(matches.group(3))
440
441 return major, minor, rev
442
443 params = module.params
444
445 commands = {key: params[key] for key in command_keys if params[key]}
446
447 # Ensure ufw is available
448 ufw_bin = module.get_bin_path("ufw", True)
449 grep_bin = module.get_bin_path("grep", True)
450
451 # Save the pre state and rules in order to recognize changes
452 pre_state = execute([[ufw_bin], ["status verbose"]])
453 pre_rules = get_current_rules()
454
455 changed = False
456
457 # Execute filter
458 for command, value in commands.items():
459 cmd = [[ufw_bin], [module.check_mode, "--dry-run"]]
460
461 if command == "state":
462 states = {"enabled": "enable", "disabled": "disable", "reloaded": "reload", "reset": "reset"}
463
464 if value in ["reloaded", "reset"]:
465 changed = True
466
467 if module.check_mode:
468 # "active" would also match "inactive", hence the space
469 ufw_enabled = pre_state.find(" active") != -1
470 if (value == "disabled" and ufw_enabled) or (value == "enabled" and not ufw_enabled):
471 changed = True
472 else:
473 execute(cmd + [["-f"], [states[value]]])
474
475 elif command == "logging":
476 extract = re.search(r"Logging: (on|off)(?: \(([a-z]+)\))?", pre_state)
477 if extract:
478 current_level = extract.group(2)
479 current_on_off_value = extract.group(1)
480 if value != "off":
481 if current_on_off_value == "off":
482 changed = True
483 elif value != "on" and value != current_level:
484 changed = True
485 elif current_on_off_value != "off":
486 changed = True
487 else:
488 changed = True
489
490 if not module.check_mode:
491 execute(cmd + [[command], [value]])
492
493 elif command == "default":
494 if params["direction"] not in ["outgoing", "incoming", "routed", None]:
495 module.fail_json(
496 msg='For default, direction must be one of "outgoing", "incoming" and "routed", or direction must not be specified.'
497 )
498 if module.check_mode:
499 regexp = r"Default: (deny|allow|reject) \(incoming\), (deny|allow|reject) \(outgoing\), (deny|allow|reject|disabled) \(routed\)"
500 extract = re.search(regexp, pre_state)
501 if extract is not None:
502 current_default_values = {}
503 current_default_values["incoming"] = extract.group(1)
504 current_default_values["outgoing"] = extract.group(2)
505 current_default_values["routed"] = extract.group(3)
506 v = current_default_values[params["direction"] or "incoming"]
507 if v not in (value, "disabled"):
508 changed = True
509 else:
510 changed = True
511 else:
512 execute(cmd + [[command], [value], [params["direction"]]])
513
514 elif command == "rule":
515 if params["direction"] not in ["in", "out", None]:
516 module.fail_json(
517 msg='For rules, direction must be one of "in" and "out", or direction must not be specified.'
518 )
519 if not params["route"] and params["interface_in"] and params["interface_out"]:
520 module.fail_json(msg="Only route rules can combine interface_in and interface_out")
521 # Rules are constructed according to the long format
522 #
523 # ufw [--dry-run] [route] [delete | insert NUM] allow|deny|reject|limit [in|out on INTERFACE] [log|log-all] \
524 # [from ADDRESS [port PORT]] [to ADDRESS [port PORT]] \
525 # [proto protocol] [app application] [comment COMMENT]
526 cmd.append([module.boolean(params["route"]), "route"])
527 cmd.append([module.boolean(params["delete"]), "delete"])
528 if params["insert"] is not None and not params["delete"]:
529 relative_to_cmd = params["insert_relative_to"]
530 if relative_to_cmd == "zero":
531 insert_to = params["insert"]
532 else:
533 (dummy, numbered_state, dummy) = module.run_command([ufw_bin, "status", "numbered"])
534 numbered_line_re = re.compile(R"^\[ *([0-9]+)\] ")
535 lines = [(numbered_line_re.match(line), "(v6)" in line) for line in numbered_state.splitlines()]
536 lines = [(int(matcher.group(1)), ipv6) for (matcher, ipv6) in lines if matcher]
537 last_number = max([no for (no, ipv6) in lines]) if lines else 0
538 has_ipv4 = any(not ipv6 for (no, ipv6) in lines)
539 has_ipv6 = any(ipv6 for (no, ipv6) in lines)
540 if relative_to_cmd == "first-ipv4":
541 relative_to = 1
542 elif relative_to_cmd == "last-ipv4":
543 relative_to = max([no for (no, ipv6) in lines if not ipv6]) if has_ipv4 else 1
544 elif relative_to_cmd == "first-ipv6":
545 relative_to = max([no for (no, ipv6) in lines if not ipv6]) + 1 if has_ipv4 else 1
546 elif relative_to_cmd == "last-ipv6":
547 relative_to = last_number if has_ipv6 else last_number + 1
548 insert_to = params["insert"] + relative_to
549 if insert_to > last_number:
550 # ufw does not like it when the insert number is larger than the
551 # maximal rule number for IPv4/IPv6.
552 insert_to = None
553 cmd.append([insert_to is not None, f"insert {insert_to}"])
554 cmd.append([value])
555 cmd.append([params["direction"], params["direction"]])
556 cmd.append([params["interface"], f"on {params['interface']}"])
557 cmd.append([params["interface_in"], f"in on {params['interface_in']}"])
558 cmd.append([params["interface_out"], f"out on {params['interface_out']}"])
559 cmd.append([module.boolean(params["log"]), "log"])
560
561 for key, template in [
562 ("from_ip", "from %s"),
563 ("from_port", "port %s"),
564 ("to_ip", "to %s"),
565 ("to_port", "port %s"),
566 ("proto", "proto %s"),
567 ("name", "app '%s'"),
568 ]:
569 value = params[key]
570 cmd.append([value, template % (value)])
571
572 ufw_major, ufw_minor, dummy = ufw_version()
573 # comment is supported only in ufw version after 0.35
574 if (ufw_major == 0 and ufw_minor >= 35) or ufw_major > 0:
575 cmd.append([params["comment"], f"comment '{params['comment']}'"])
576
577 rules_dry = execute(cmd)
578
579 if module.check_mode:
580 nb_skipping_line = len(filter_line_that_contains("Skipping", rules_dry))
581
582 if not (nb_skipping_line > 0 and nb_skipping_line == len(rules_dry.splitlines(True))):
583 rules_dry = filter_line_that_not_start_with("### tuple", rules_dry)
584 # ufw dry-run doesn't send all rules so have to compare ipv4 or ipv6 rules
585 if is_starting_by_ipv4(params["from_ip"]) or is_starting_by_ipv4(params["to_ip"]):
586 if filter_line_that_contains_ipv4(pre_rules) != filter_line_that_contains_ipv4(rules_dry):
587 changed = True
588 elif is_starting_by_ipv6(params["from_ip"]) or is_starting_by_ipv6(params["to_ip"]):
589 if filter_line_that_contains_ipv6(pre_rules) != filter_line_that_contains_ipv6(rules_dry):
590 changed = True
591 elif pre_rules != rules_dry:
592 changed = True
593
594 # Get the new state
595 if module.check_mode:
596 return module.exit_json(changed=changed, commands=cmds)
597 else:
598 post_state = execute([[ufw_bin], ["status"], ["verbose"]])
599 if not changed:
600 post_rules = get_current_rules()
601 changed = (pre_state != post_state) or (pre_rules != post_rules)
602 return module.exit_json(changed=changed, commands=cmds, msg=post_state.rstrip())
603
604
605 if __name__ == "__main__":
606 main()