Debian Codegraph @

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

raw
1 #!/usr/bin/python
2
3 # Copyright (c) 2020, quidame <[email protected]>
4 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
5 # SPDX-License-Identifier: GPL-3.0-or-later
6
7 from __future__ import annotations
8
9 DOCUMENTATION = r"""
10 module: iptables_state
11 short_description: Save iptables state into a file or restore it from a file
12 version_added: '1.1.0'
13 author: quidame (@quidame)
14 extends_documentation_fragment:
15 - community.general._attributes
16 - community.general._attributes.flow
17 description:
18 - C(iptables) is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel.
19 - This module handles the saving and/or loading of rules. This is the same as the behaviour of the C(iptables-save) and
20 C(iptables-restore) (or C(ip6tables-save) and C(ip6tables-restore) for IPv6) commands which this module uses internally.
21 - Modifying the state of the firewall remotely may lead to loose access to the host in case of mistake in new ruleset. This
22 module embeds a rollback feature to avoid this, by telling the host to restore previous rules if a cookie is still there
23 after a given delay, and all this time telling the controller to try to remove this cookie on the host through a new connection.
24 notes:
25 - The rollback feature is not a module option and depends on task's attributes. To enable it, the module must be played
26 asynchronously, in other words by setting task attributes C(poll) to V(0), and C(async) to a value less or equal to C(ANSIBLE_TIMEOUT).
27 If C(async) is greater, the rollback still happens when needed, but you experience a connection timeout instead of more
28 relevant info returned by the module after its failure.
29 attributes:
30 check_mode:
31 support: full
32 diff_mode:
33 support: none
34 action:
35 support: full
36 async:
37 support: full
38 options:
39 counters:
40 description:
41 - Save or restore the values of all packet and byte counters.
42 - When V(true), the module is not idempotent.
43 type: bool
44 default: false
45 ip_version:
46 description:
47 - Which version of the IP protocol this module should apply to.
48 type: str
49 choices: [ipv4, ipv6]
50 default: ipv4
51 modprobe:
52 description:
53 - Specify the path to the C(modprobe) program internally used by iptables related commands to load kernel modules.
54 - By default, V(/proc/sys/kernel/modprobe) is inspected to determine the executable's path.
55 type: path
56 noflush:
57 description:
58 - For O(state=restored), ignored otherwise.
59 - If V(false), restoring iptables rules from a file flushes (deletes) all previous contents of the respective table(s).
60 If V(true), the previous rules are left untouched (but policies are updated anyway, for all built-in chains).
61 type: bool
62 default: false
63 path:
64 description:
65 - The file the iptables state should be saved to.
66 - The file the iptables state should be restored from.
67 type: path
68 required: true
69 state:
70 description:
71 - Whether the firewall state should be saved (into a file) or restored (from a file).
72 type: str
73 choices: [saved, restored]
74 required: true
75 table:
76 description:
77 - When O(state=restored), restore only the named table even if the input file contains other tables. Fail if the named
78 table is not declared in the file.
79 - When O(state=saved), restrict output to the specified table. If not specified, output includes all active tables.
80 type: str
81 choices: [filter, nat, mangle, raw, security]
82 wait:
83 description:
84 - Wait N seconds for the xtables lock to prevent instant failure in case multiple instances of the program are running
85 concurrently.
86 type: int
87 requirements: [iptables, ip6tables]
88 """
89
90 EXAMPLES = r"""
91 # This will apply to all loaded/active IPv4 tables.
92 - name: Save current state of the firewall in system file
93 community.general.iptables_state:
94 state: saved
95 path: /etc/sysconfig/iptables
96
97 # This will apply only to IPv6 filter table.
98 - name: save current state of the firewall in system file
99 community.general.iptables_state:
100 ip_version: ipv6
101 table: filter
102 state: saved
103 path: /etc/iptables/rules.v6
104
105 # This will load a state from a file, with a rollback in case of access loss
106 - name: restore firewall state from a file
107 community.general.iptables_state:
108 state: restored
109 path: /run/iptables.apply
110 async: "{{ ansible_timeout }}"
111 poll: 0
112
113 # This will load new rules by appending them to the current ones
114 - name: restore firewall state from a file
115 community.general.iptables_state:
116 state: restored
117 path: /run/iptables.apply
118 noflush: true
119 async: "{{ ansible_timeout }}"
120 poll: 0
121
122 # This will only retrieve information
123 - name: get current state of the firewall
124 community.general.iptables_state:
125 state: saved
126 path: /tmp/iptables
127 check_mode: true
128 changed_when: false
129 register: iptables_state
130
131 - name: show current state of the firewall
132 ansible.builtin.debug:
133 var: iptables_state.initial_state
134 """
135
136 RETURN = r"""
137 applied:
138 description: Whether or not the wanted state has been successfully restored.
139 type: bool
140 returned: always
141 sample: true
142 initial_state:
143 description: The current state of the firewall when module starts.
144 type: list
145 elements: str
146 returned: always
147 sample:
148 [
149 "# Generated by xtables-save v1.8.2",
150 "*filter",
151 ":INPUT ACCEPT [0:0]",
152 ":FORWARD ACCEPT [0:0]",
153 ":OUTPUT ACCEPT [0:0]",
154 "COMMIT",
155 "# Completed"
156 ]
157 restored:
158 description: The state the module restored, whenever it is finally applied or not.
159 type: list
160 elements: str
161 returned: always
162 sample:
163 [
164 "# Generated by xtables-save v1.8.2",
165 "*filter",
166 ":INPUT DROP [0:0]",
167 ":FORWARD DROP [0:0]",
168 ":OUTPUT ACCEPT [0:0]",
169 "-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT",
170 "-A INPUT -m conntrack --ctstate INVALID -j DROP",
171 "-A INPUT -i lo -j ACCEPT",
172 "-A INPUT -p icmp -j ACCEPT",
173 "-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT",
174 "COMMIT",
175 "# Completed"
176 ]
177 saved:
178 description: The iptables state the module saved.
179 type: list
180 elements: str
181 returned: always
182 sample:
183 [
184 "# Generated by xtables-save v1.8.2",
185 "*filter",
186 ":INPUT ACCEPT [0:0]",
187 ":FORWARD DROP [0:0]",
188 ":OUTPUT ACCEPT [0:0]",
189 "COMMIT",
190 "# Completed"
191 ]
192 tables:
193 description:
194 - The iptables on the system before the module has run, separated by table.
195 - If the option O(table) is used, only this table is included.
196 type: dict
197 contains:
198 table:
199 description: Policies and rules for all chains of the named table.
200 type: list
201 elements: str
202 sample: |-
203 {
204 "filter": [
205 ":INPUT ACCEPT",
206 ":FORWARD ACCEPT",
207 ":OUTPUT ACCEPT",
208 "-A INPUT -i lo -j ACCEPT",
209 "-A INPUT -p icmp -j ACCEPT",
210 "-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT",
211 "-A INPUT -j REJECT --reject-with icmp-host-prohibited"
212 ],
213 "nat": [
214 ":PREROUTING ACCEPT",
215 ":INPUT ACCEPT",
216 ":OUTPUT ACCEPT",
217 ":POSTROUTING ACCEPT"
218 ]
219 }
220 returned: always
221 """
222
223
224 import os
225 import re
226 import time
227
228 from ansible.module_utils.basic import AnsibleModule
229 from ansible.module_utils.common.text.converters import to_bytes, to_native
230
231 IPTABLES = dict(
232 ipv4="iptables",
233 ipv6="ip6tables",
234 )
235
236 SAVE = dict(
237 ipv4="iptables-save",
238 ipv6="ip6tables-save",
239 )
240
241 RESTORE = dict(
242 ipv4="iptables-restore",
243 ipv6="ip6tables-restore",
244 )
245
246 TABLES = ["filter", "mangle", "nat", "raw", "security"]
247
248
249 def read_state(b_path):
250 """
251 Read a file and store its content in a variable as a list.
252 """
253 with open(b_path) as f:
254 text = f.read()
255 return [t for t in text.splitlines() if t != ""]
256
257
258 def get_file_contents(b_path: bytes) -> bytes | None:
259 try:
260 with open(b_path, "rb") as f:
261 return f.read()
262 except FileNotFoundError:
263 return None
264
265
266 def write_state(module: AnsibleModule, b_path: bytes, lines: list[str], changed: bool) -> bool:
267 """
268 Write given contents to the given path, and return changed status.
269 """
270 joined_lines = "\n".join(lines)
271 content = f"{joined_lines}\n".encode("utf-8")
272
273 existing_contents = get_file_contents(b_path)
274 if existing_contents == content:
275 return changed
276
277 changed = True
278
279 if existing_contents is None:
280 b_destdir = os.path.dirname(b_path)
281 destdir = to_native(b_destdir, errors="surrogate_or_strict")
282 if b_destdir and not os.path.exists(b_destdir) and not module.check_mode:
283 try:
284 os.makedirs(b_destdir)
285 except Exception as err:
286 module.fail_json(msg=f"Error creating {destdir}: {err}", initial_state=lines)
287
288 if not module.check_mode:
289 try:
290 with open(b_path, "wb") as f:
291 f.write(content)
292 except Exception as err:
293 path = to_native(b_path, errors="surrogate_or_strict")
294 module.fail_json(msg=f"Error saving state into {path}: {err}", initial_state=lines)
295
296 return changed
297
298
299 def initialize_from_null_state(module: AnsibleModule, initializer, initcommand, fallbackcmd, table):
300 """
301 This ensures iptables-state output is suitable for iptables-restore to roll
302 back to it, i.e. iptables-save output is not empty. This also works for the
303 iptables-nft-save alternative.
304 """
305 if table is None:
306 table = "filter"
307
308 commandline = list(initializer)
309 commandline += ["-t", table]
310 dummy = module.run_command(commandline, check_rc=True)
311 (rc, out, err) = module.run_command(initcommand, check_rc=True)
312 if f"*{table}" not in out.splitlines():
313 # The last resort.
314 iptables_input = f"*{table}\n:OUTPUT ACCEPT\nCOMMIT\n"
315 dummy = module.run_command(fallbackcmd, data=iptables_input, check_rc=True)
316 (rc, out, err) = module.run_command(initcommand, check_rc=True)
317
318 return rc, out, err
319
320
321 def filter_and_format_state(module: AnsibleModule, string: str) -> list[str]:
322 """
323 Remove timestamps to ensure idempotence between runs. Also remove counters
324 by default. And return the result as a list.
325 """
326 string = re.sub(r"((^|\n)# (Generated|Completed)[^\n]*) on [^\n]*", r"\1", string)
327 if not module.params["counters"]:
328 string = re.sub(r"\[[0-9]+:[0-9]+\]", r"[0:0]", string)
329 lines = [line for line in string.splitlines() if line != ""]
330 return lines
331
332
333 def parse_per_table_state(module: AnsibleModule, all_states_dump) -> dict[str, list[str]]:
334 """
335 Convert raw iptables-save output into usable datastructure, for reliable
336 comparisons between initial and final states.
337 """
338 lines = filter_and_format_state(module, all_states_dump)
339 tables: dict[str, list[str]] = {}
340 current_table = ""
341 current_list: list[str] = []
342 for line in lines:
343 if re.match(r"^[*](filter|mangle|nat|raw|security)$", line):
344 current_table = line[1:]
345 continue
346 if line == "COMMIT":
347 tables[current_table] = current_list
348 current_table = ""
349 current_list = []
350 continue
351 if line.startswith("# "):
352 continue
353 current_list.append(line)
354 return tables
355
356
357 def main() -> None:
358 module = AnsibleModule(
359 argument_spec=dict(
360 path=dict(type="path", required=True),
361 state=dict(type="str", choices=["saved", "restored"], required=True),
362 table=dict(type="str", choices=["filter", "nat", "mangle", "raw", "security"]),
363 noflush=dict(type="bool", default=False),
364 counters=dict(type="bool", default=False),
365 modprobe=dict(type="path"),
366 ip_version=dict(type="str", choices=["ipv4", "ipv6"], default="ipv4"),
367 wait=dict(type="int"),
368 _timeout=dict(type="int"),
369 _back=dict(type="path"),
370 ),
371 required_together=[
372 ["_timeout", "_back"],
373 ],
374 supports_check_mode=True,
375 )
376
377 # We'll parse iptables-restore stderr
378 module.run_command_environ_update = dict(LANGUAGE="C", LC_ALL="C")
379
380 path = module.params["path"]
381 state = module.params["state"]
382 table = module.params["table"]
383 noflush = module.params["noflush"]
384 counters = module.params["counters"]
385 modprobe = module.params["modprobe"]
386 ip_version = module.params["ip_version"]
387 wait = module.params["wait"]
388 _timeout = module.params["_timeout"]
389 _back = module.params["_back"]
390
391 bin_iptables = module.get_bin_path(IPTABLES[ip_version], True)
392 bin_iptables_save = module.get_bin_path(SAVE[ip_version], True)
393 bin_iptables_restore = module.get_bin_path(RESTORE[ip_version], True)
394
395 os.umask(0o077)
396 changed = False
397 COMMANDARGS = []
398 INITCOMMAND = [bin_iptables_save]
399 INITIALIZER = [bin_iptables, "-L", "-n"]
400 TESTCOMMAND = [bin_iptables_restore, "--test"]
401 FALLBACKCMD = [bin_iptables_restore]
402
403 if counters:
404 COMMANDARGS.append("--counters")
405
406 if table is not None:
407 COMMANDARGS.extend(["--table", table])
408
409 if wait is not None:
410 TESTCOMMAND.extend(["--wait", f"{wait}"])
411
412 if modprobe is not None:
413 b_modprobe = to_bytes(modprobe, errors="surrogate_or_strict")
414 if not os.path.exists(b_modprobe):
415 module.fail_json(msg=f"modprobe {modprobe} not found")
416 if not os.path.isfile(b_modprobe):
417 module.fail_json(msg=f"modprobe {modprobe} not a file")
418 if not os.access(b_modprobe, os.R_OK):
419 module.fail_json(msg=f"modprobe {modprobe} not readable")
420 if not os.access(b_modprobe, os.X_OK):
421 module.fail_json(msg=f"modprobe {modprobe} not executable")
422 COMMANDARGS.extend(["--modprobe", modprobe])
423 INITIALIZER.extend(["--modprobe", modprobe])
424 INITCOMMAND.extend(["--modprobe", modprobe])
425 TESTCOMMAND.extend(["--modprobe", modprobe])
426 FALLBACKCMD.extend(["--modprobe", modprobe])
427
428 SAVECOMMAND = list(COMMANDARGS)
429 SAVECOMMAND.insert(0, bin_iptables_save)
430
431 b_path = to_bytes(path, errors="surrogate_or_strict")
432
433 if state == "restored":
434 if not os.path.exists(b_path):
435 module.fail_json(msg=f"Source {path} not found")
436 if not os.path.isfile(b_path):
437 module.fail_json(msg=f"Source {path} not a file")
438 if not os.access(b_path, os.R_OK):
439 module.fail_json(msg=f"Source {path} not readable")
440 state_to_restore = read_state(b_path)
441 cmd = None
442 else:
443 cmd = " ".join(SAVECOMMAND)
444
445 (rc, stdout, stderr) = module.run_command(INITCOMMAND, check_rc=True)
446
447 # The issue comes when wanting to restore state from empty iptable-save's
448 # output... what happens when, say:
449 # - no table is specified, and iptables-save's output is only nat table;
450 # - we give filter's ruleset to iptables-restore, that locks ourselves out
451 # of the host;
452 # then trying to roll iptables state back to the previous (working) setup
453 # doesn't override current filter table because no filter table is stored
454 # in the backup ! So we have to ensure tables to be restored have a backup
455 # in case of rollback.
456 if table is None:
457 if state == "restored":
458 for t in TABLES:
459 if f"*{t}" in state_to_restore:
460 if len(stdout) == 0 or f"*{t}" not in stdout.splitlines():
461 (rc, stdout, stderr) = initialize_from_null_state(
462 module, INITIALIZER, INITCOMMAND, FALLBACKCMD, t
463 )
464 elif len(stdout) == 0:
465 (rc, stdout, stderr) = initialize_from_null_state(module, INITIALIZER, INITCOMMAND, FALLBACKCMD, "filter")
466
467 elif state == "restored" and f"*{table}" not in state_to_restore:
468 module.fail_json(msg=f"Table {table} to restore not defined in {path}")
469
470 elif len(stdout) == 0 or f"*{table}" not in stdout.splitlines():
471 (rc, stdout, stderr) = initialize_from_null_state(module, INITIALIZER, INITCOMMAND, FALLBACKCMD, table)
472
473 initial_state = filter_and_format_state(module, stdout)
474 if initial_state is None:
475 module.fail_json(msg="Unable to initialize firewall from NULL state.")
476
477 # Depending on the value of 'table', initref_state may differ from
478 # initial_state.
479 (rc, stdout, stderr) = module.run_command(SAVECOMMAND, check_rc=True)
480 tables_before = parse_per_table_state(module, stdout)
481 initref_state = filter_and_format_state(module, stdout)
482
483 if state == "saved":
484 changed = write_state(module, b_path, initref_state, changed)
485 module.exit_json(
486 changed=changed, cmd=cmd, tables=tables_before, initial_state=initial_state, saved=initref_state
487 )
488
489 #
490 # All remaining code is for state=restored
491 #
492
493 MAINCOMMAND = list(COMMANDARGS)
494 MAINCOMMAND.insert(0, bin_iptables_restore)
495
496 if wait is not None:
497 MAINCOMMAND.extend(["--wait", f"{wait}"])
498
499 if _back is not None:
500 b_back = to_bytes(_back, errors="surrogate_or_strict")
501 dummy = write_state(module, b_back, initref_state, changed)
502 BACKCOMMAND = list(MAINCOMMAND)
503 BACKCOMMAND.append(_back)
504
505 if noflush:
506 MAINCOMMAND.append("--noflush")
507
508 MAINCOMMAND.append(path)
509 cmd = " ".join(MAINCOMMAND)
510
511 TESTCOMMAND = list(MAINCOMMAND)
512 TESTCOMMAND.insert(1, "--test")
513 error_msg = f"Source {path} is not suitable for input to {os.path.basename(bin_iptables_restore)}"
514
515 # Due to a bug in iptables-nft-restore --test, we have to validate tables
516 # one by one (https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=960003).
517 for t in tables_before:
518 testcommand = list(TESTCOMMAND)
519 testcommand.extend(["--table", t])
520 (rc, stdout, stderr) = module.run_command(testcommand)
521
522 if "Another app is currently holding the xtables lock" in stderr:
523 error_msg = stderr
524
525 if rc != 0:
526 cmd = " ".join(testcommand)
527 module.fail_json(
528 msg=error_msg,
529 cmd=cmd,
530 rc=rc,
531 stdout=stdout,
532 stderr=stderr,
533 tables=tables_before,
534 initial_state=initial_state,
535 restored=state_to_restore,
536 applied=False,
537 )
538
539 if module.check_mode:
540 joined_initial_state = "\n".join(initial_state)
541 if get_file_contents(b_path) == f"{joined_initial_state}\n".encode("utf-8"):
542 restored_state = initial_state
543 else:
544 restored_state = state_to_restore
545
546 else:
547 # Let time enough to the plugin to retrieve async status of the module
548 # in case of bad option type/value and the like.
549 if _back is not None:
550 b_starter = to_bytes(f"{_back}.starter", errors="surrogate_or_strict")
551 while True:
552 if os.path.exists(b_starter):
553 os.remove(b_starter)
554 break
555 time.sleep(0.01)
556
557 (rc, stdout, stderr) = module.run_command(MAINCOMMAND)
558 if "Another app is currently holding the xtables lock" in stderr:
559 module.fail_json(
560 msg=stderr,
561 cmd=cmd,
562 rc=rc,
563 stdout=stdout,
564 stderr=stderr,
565 tables=tables_before,
566 initial_state=initial_state,
567 restored=state_to_restore,
568 applied=False,
569 )
570
571 (rc, stdout, stderr) = module.run_command(SAVECOMMAND, check_rc=True)
572 restored_state = filter_and_format_state(module, stdout)
573 tables_after = parse_per_table_state(module, "\n".join(restored_state))
574 if restored_state not in (initref_state, initial_state):
575 for table_name, table_content in tables_after.items():
576 if table_name not in tables_before:
577 # Would initialize a table, which doesn't exist yet
578 changed = True
579 break
580 if tables_before[table_name] != table_content:
581 # Content of some table changes
582 changed = True
583 break
584
585 if _back is None or module.check_mode:
586 module.exit_json(
587 changed=changed,
588 cmd=cmd,
589 tables=tables_before,
590 initial_state=initial_state,
591 restored=restored_state,
592 applied=True,
593 )
594
595 # The rollback implementation currently needs:
596 # Here:
597 # * test existence of the backup file, exit with success if it doesn't exist
598 # * otherwise, restore iptables from this file and return failure
599 # Action plugin:
600 # * try to remove the backup file
601 # * wait async task is finished and retrieve its final status
602 # * modify it and return the result
603 # Task:
604 # * task attribute 'async' set to the same value (or lower) than ansible
605 # timeout
606 # * task attribute 'poll' equals 0
607 #
608 for dummy2 in range(_timeout):
609 if os.path.exists(b_back):
610 time.sleep(1)
611 continue
612 module.exit_json(
613 changed=changed,
614 cmd=cmd,
615 tables=tables_before,
616 initial_state=initial_state,
617 restored=restored_state,
618 applied=True,
619 )
620
621 # Here we are: for whatever reason, but probably due to the current ruleset,
622 # the action plugin (i.e. on the controller) was unable to remove the backup
623 # cookie, so we restore initial state from it.
624 (rc, stdout, stderr) = module.run_command(BACKCOMMAND, check_rc=True)
625 os.remove(b_back)
626
627 (rc, stdout, stderr) = module.run_command(SAVECOMMAND, check_rc=True)
628 tables_rollback = parse_per_table_state(module, stdout)
629
630 msg = f"Failed to confirm state restored from {path} after {_timeout}s. Firewall has been rolled back to its initial state."
631
632 module.fail_json(
633 changed=(tables_before != tables_rollback),
634 msg=msg,
635 cmd=cmd,
636 tables=tables_before,
637 initial_state=initial_state,
638 restored=restored_state,
639 applied=False,
640 )
641
642
643 if __name__ == "__main__":
644 main()