| 1 |
# -*- coding: utf-8 -*- |
| 2 |
|
| 3 |
# Copyright: (c) 2015, Linus Unnebäck <[email protected]> |
| 4 |
# Copyright: (c) 2017, Sébastien DA ROCHA <[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 annotations |
| 8 |
|
| 9 |
|
| 10 |
DOCUMENTATION = r""" |
| 11 |
--- |
| 12 |
module: iptables |
| 13 |
short_description: Modify iptables rules |
| 14 |
version_added: "2.0" |
| 15 |
author: |
| 16 |
- Linus Unnebäck (@LinusU) <[email protected]> |
| 17 |
- Sébastien DA ROCHA (@sebastiendarocha) |
| 18 |
description: |
| 19 |
- M(ansible.builtin.iptables) is used to set up, maintain, and inspect the tables of IP packet |
| 20 |
filter rules in the Linux kernel. |
| 21 |
- This module does not handle the saving and/or loading of rules, but rather |
| 22 |
only manipulates the current rules that are present in memory. This is the |
| 23 |
same as the behaviour of the C(iptables) and C(ip6tables) command which |
| 24 |
this module uses internally. |
| 25 |
extends_documentation_fragment: action_common_attributes |
| 26 |
attributes: |
| 27 |
check_mode: |
| 28 |
support: full |
| 29 |
diff_mode: |
| 30 |
support: none |
| 31 |
platform: |
| 32 |
platforms: linux |
| 33 |
notes: |
| 34 |
- This module just deals with individual rules. If you need advanced |
| 35 |
chaining of rules the recommended way is to template the iptables restore |
| 36 |
file. |
| 37 |
options: |
| 38 |
table: |
| 39 |
description: |
| 40 |
- This option specifies the packet matching table on which the command should operate. |
| 41 |
- If the kernel is configured with automatic module loading, an attempt will be made |
| 42 |
to load the appropriate module for that table if it is not already there. |
| 43 |
type: str |
| 44 |
choices: [ filter, nat, mangle, raw, security ] |
| 45 |
default: filter |
| 46 |
state: |
| 47 |
description: |
| 48 |
- Whether the rule should be absent or present. |
| 49 |
type: str |
| 50 |
choices: [ absent, present ] |
| 51 |
default: present |
| 52 |
action: |
| 53 |
description: |
| 54 |
- Whether the rule should be appended at the bottom or inserted at the top. |
| 55 |
- If the rule already exists the chain will not be modified. |
| 56 |
type: str |
| 57 |
choices: [ append, insert ] |
| 58 |
default: append |
| 59 |
version_added: "2.2" |
| 60 |
rule_num: |
| 61 |
description: |
| 62 |
- Insert the rule as the given rule number. |
| 63 |
- This works only with O(action=insert). |
| 64 |
type: str |
| 65 |
version_added: "2.5" |
| 66 |
ip_version: |
| 67 |
description: |
| 68 |
- Which version of the IP protocol this rule should apply to. |
| 69 |
type: str |
| 70 |
choices: [ ipv4, ipv6, both ] |
| 71 |
default: ipv4 |
| 72 |
chain: |
| 73 |
description: |
| 74 |
- Specify the iptables chain to modify. |
| 75 |
- This could be a user-defined chain or one of the standard iptables chains, like |
| 76 |
V(INPUT), V(FORWARD), V(OUTPUT), V(PREROUTING), V(POSTROUTING), V(SECMARK) or V(CONNSECMARK). |
| 77 |
type: str |
| 78 |
protocol: |
| 79 |
description: |
| 80 |
- The protocol of the rule or of the packet to check. |
| 81 |
- The specified protocol can be one of V(tcp), V(udp), V(udplite), V(icmp), V(ipv6-icmp) or V(icmpv6), |
| 82 |
V(esp), V(ah), V(sctp) or the special keyword V(all), or it can be a numeric value, |
| 83 |
representing one of these protocols or a different one. |
| 84 |
- A protocol name from C(/etc/protocols) is also allowed. |
| 85 |
- A V(!) argument before the protocol inverts the test. |
| 86 |
- The number zero is equivalent to all. |
| 87 |
- V(all) will match with all protocols and is taken as default when this option is omitted. |
| 88 |
type: str |
| 89 |
source: |
| 90 |
description: |
| 91 |
- Source specification. |
| 92 |
- Address can be either a network name, a hostname, a network IP address |
| 93 |
(with /mask), or a plain IP address. |
| 94 |
- Hostnames will be resolved once only, before the rule is submitted to |
| 95 |
the kernel. Please note that specifying any name to be resolved with |
| 96 |
a remote query such as DNS is a really bad idea. |
| 97 |
- The mask can be either a network mask or a plain number, specifying |
| 98 |
the number of 1's at the left side of the network mask. Thus, a mask |
| 99 |
of 24 is equivalent to 255.255.255.0. A V(!) argument before the |
| 100 |
address specification inverts the sense of the address. |
| 101 |
type: str |
| 102 |
destination: |
| 103 |
description: |
| 104 |
- Destination specification. |
| 105 |
- Address can be either a network name, a hostname, a network IP address |
| 106 |
(with /mask), or a plain IP address. |
| 107 |
- Hostnames will be resolved once only, before the rule is submitted to |
| 108 |
the kernel. Please note that specifying any name to be resolved with |
| 109 |
a remote query such as DNS is a really bad idea. |
| 110 |
- The mask can be either a network mask or a plain number, specifying |
| 111 |
the number of 1's at the left side of the network mask. Thus, a mask |
| 112 |
of 24 is equivalent to 255.255.255.0. A V(!) argument before the |
| 113 |
address specification inverts the sense of the address. |
| 114 |
type: str |
| 115 |
tcp_flags: |
| 116 |
description: |
| 117 |
- TCP flags specification. |
| 118 |
- O(tcp_flags) expects a dict with the two keys C(flags) and C(flags_set). |
| 119 |
type: dict |
| 120 |
version_added: "2.4" |
| 121 |
suboptions: |
| 122 |
flags: |
| 123 |
description: |
| 124 |
- List of flags you want to examine. |
| 125 |
type: list |
| 126 |
elements: str |
| 127 |
flags_set: |
| 128 |
description: |
| 129 |
- Flags to be set. |
| 130 |
type: list |
| 131 |
elements: str |
| 132 |
match: |
| 133 |
description: |
| 134 |
- Specifies a match to use, that is, an extension module that tests for |
| 135 |
a specific property. |
| 136 |
- The set of matches makes up the condition under which a target is invoked. |
| 137 |
- Matches are evaluated first to last if specified as an array and work in short-circuit |
| 138 |
fashion, in other words if one extension yields false, the evaluation will stop. |
| 139 |
- The module automatically adds necessary extensions (for example, O(uid_owner=1) corresponds |
| 140 |
to the command flags C(-m owner --uid-owner 1)), so it is often unnecessary to use the O(match) argument. |
| 141 |
type: list |
| 142 |
elements: str |
| 143 |
default: [] |
| 144 |
jump: |
| 145 |
description: |
| 146 |
- This specifies the target of the rule; i.e., what to do if the packet matches it. |
| 147 |
- The target can be a user-defined chain (other than the one |
| 148 |
this rule is in), one of the special builtin targets that decide the |
| 149 |
fate of the packet immediately, or an extension (see EXTENSIONS |
| 150 |
below). |
| 151 |
- If this option is omitted in a rule (and the goto parameter |
| 152 |
is not used), then matching the rule will have no effect on the |
| 153 |
packet's fate, but the counters on the rule will be incremented. |
| 154 |
type: str |
| 155 |
gateway: |
| 156 |
description: |
| 157 |
- This specifies the IP address of the host to send the cloned packets. |
| 158 |
- This option is only valid when O(jump=TEE). |
| 159 |
type: str |
| 160 |
version_added: "2.8" |
| 161 |
log_prefix: |
| 162 |
description: |
| 163 |
- Specifies a log text for the rule. Only makes sense with a LOG jump. |
| 164 |
type: str |
| 165 |
version_added: "2.5" |
| 166 |
log_level: |
| 167 |
description: |
| 168 |
- Logging level according to the syslogd-defined priorities. |
| 169 |
- The value can be strings or numbers from 1-8. |
| 170 |
- This parameter is only applicable if O(jump=LOG). |
| 171 |
type: str |
| 172 |
version_added: "2.8" |
| 173 |
choices: [ '0', '1', '2', '3', '4', '5', '6', '7', 'emerg', 'alert', 'crit', 'error', 'warning', 'notice', 'info', 'debug' ] |
| 174 |
goto: |
| 175 |
description: |
| 176 |
- This specifies that the processing should continue in a user-specified chain. |
| 177 |
- Unlike the jump argument return will not continue processing in |
| 178 |
this chain but instead in the chain that called us via jump. |
| 179 |
type: str |
| 180 |
in_interface: |
| 181 |
description: |
| 182 |
- Name of an interface via which a packet was received (only for packets |
| 183 |
entering the V(INPUT), V(FORWARD) and V(PREROUTING) chains). |
| 184 |
- When the V(!) argument is used before the interface name, the sense is inverted. |
| 185 |
- If the interface name ends in a V(+), then any interface which begins with |
| 186 |
this name will match. |
| 187 |
- If this option is omitted, any interface name will match. |
| 188 |
type: str |
| 189 |
out_interface: |
| 190 |
description: |
| 191 |
- Name of an interface via which a packet is going to be sent (for |
| 192 |
packets entering the V(FORWARD), V(OUTPUT) and V(POSTROUTING) chains). |
| 193 |
- When the V(!) argument is used before the interface name, the sense is inverted. |
| 194 |
- If the interface name ends in a V(+), then any interface which begins |
| 195 |
with this name will match. |
| 196 |
- If this option is omitted, any interface name will match. |
| 197 |
type: str |
| 198 |
fragment: |
| 199 |
description: |
| 200 |
- This means that the rule only refers to second and further fragments |
| 201 |
of fragmented packets. |
| 202 |
- Since there is no way to tell the source or destination ports of such |
| 203 |
a packet (or ICMP type), such a packet will not match any rules which specify them. |
| 204 |
- When the "!" argument precedes the fragment argument, the rule will only match head fragments, |
| 205 |
or unfragmented packets. |
| 206 |
type: str |
| 207 |
set_counters: |
| 208 |
description: |
| 209 |
- This enables the administrator to initialize the packet and byte |
| 210 |
counters of a rule (during V(INSERT), V(APPEND), V(REPLACE) operations). |
| 211 |
type: str |
| 212 |
source_port: |
| 213 |
description: |
| 214 |
- Source port or port range specification. |
| 215 |
- This can either be a service name or a port number. |
| 216 |
- An inclusive range can also be specified, using the format C(first:last). |
| 217 |
- If the first port is omitted, V(0) is assumed; if the last is omitted, V(65535) is assumed. |
| 218 |
- If the first port is greater than the second one they will be swapped. |
| 219 |
type: str |
| 220 |
destination_port: |
| 221 |
description: |
| 222 |
- "Destination port or port range specification. This can either be |
| 223 |
a service name or a port number. An inclusive range can also be |
| 224 |
specified, using the format first:last. If the first port is omitted, |
| 225 |
'0' is assumed; if the last is omitted, '65535' is assumed. If the |
| 226 |
first port is greater than the second one they will be swapped. |
| 227 |
This is only valid if the rule also specifies one of the following |
| 228 |
protocols: tcp, udp, dccp or sctp." |
| 229 |
type: str |
| 230 |
destination_ports: |
| 231 |
description: |
| 232 |
- This specifies multiple destination port numbers or port ranges to match in the multiport module. |
| 233 |
- It can only be used in conjunction with the protocols tcp, udp, udplite, dccp and sctp. |
| 234 |
type: list |
| 235 |
elements: str |
| 236 |
default: [] |
| 237 |
version_added: "2.11" |
| 238 |
to_ports: |
| 239 |
description: |
| 240 |
- This specifies a destination port or range of ports to use, without |
| 241 |
this, the destination port is never altered. |
| 242 |
- This is only valid if the rule also specifies one of the protocol |
| 243 |
V(tcp), V(udp), V(dccp) or V(sctp). |
| 244 |
type: str |
| 245 |
to_destination: |
| 246 |
description: |
| 247 |
- This specifies a destination address to use with O(ctstate=DNAT). |
| 248 |
- Without this, the destination address is never altered. |
| 249 |
type: str |
| 250 |
version_added: "2.1" |
| 251 |
to_source: |
| 252 |
description: |
| 253 |
- This specifies a source address to use with O(ctstate=SNAT). |
| 254 |
- Without this, the source address is never altered. |
| 255 |
type: str |
| 256 |
version_added: "2.2" |
| 257 |
syn: |
| 258 |
description: |
| 259 |
- This allows matching packets that have the SYN bit set and the ACK |
| 260 |
and RST bits unset. |
| 261 |
- When negated, this matches all packets with the RST or the ACK bits set. |
| 262 |
type: str |
| 263 |
choices: [ ignore, match, negate ] |
| 264 |
default: ignore |
| 265 |
version_added: "2.5" |
| 266 |
set_dscp_mark: |
| 267 |
description: |
| 268 |
- This allows specifying a DSCP mark to be added to packets. |
| 269 |
It takes either an integer or hex value. |
| 270 |
- If the parameter is set, O(jump) is set to V(DSCP). |
| 271 |
- Mutually exclusive with O(set_dscp_mark_class). |
| 272 |
type: str |
| 273 |
version_added: "2.1" |
| 274 |
set_dscp_mark_class: |
| 275 |
description: |
| 276 |
- This allows specifying a predefined DiffServ class which will be |
| 277 |
translated to the corresponding DSCP mark. |
| 278 |
- If the parameter is set, O(jump) is set to V(DSCP). |
| 279 |
- Mutually exclusive with O(set_dscp_mark). |
| 280 |
type: str |
| 281 |
version_added: "2.1" |
| 282 |
comment: |
| 283 |
description: |
| 284 |
- This specifies a comment that will be added to the rule. |
| 285 |
type: str |
| 286 |
ctstate: |
| 287 |
description: |
| 288 |
- A list of the connection states to match in the conntrack module. |
| 289 |
- Possible values are V(INVALID), V(NEW), V(ESTABLISHED), V(RELATED), V(UNTRACKED), V(SNAT), V(DNAT). |
| 290 |
type: list |
| 291 |
elements: str |
| 292 |
default: [] |
| 293 |
src_range: |
| 294 |
description: |
| 295 |
- Specifies the source IP range to match the iprange module. |
| 296 |
type: str |
| 297 |
version_added: "2.8" |
| 298 |
dst_range: |
| 299 |
description: |
| 300 |
- Specifies the destination IP range to match in the iprange module. |
| 301 |
type: str |
| 302 |
version_added: "2.8" |
| 303 |
match_set: |
| 304 |
description: |
| 305 |
- Specifies a set name that can be defined by ipset. |
| 306 |
- Must be used together with the O(match_set_flags) parameter. |
| 307 |
- When the V(!) argument is prepended then it inverts the rule. |
| 308 |
- Uses the iptables set extension. |
| 309 |
type: str |
| 310 |
version_added: "2.11" |
| 311 |
match_set_flags: |
| 312 |
description: |
| 313 |
- Specifies the necessary flags for the match_set parameter. |
| 314 |
- Must be used together with the O(match_set) parameter. |
| 315 |
- Uses the iptables set extension. |
| 316 |
- Choices V(dst,dst) and V(src,src) added in version 2.17. |
| 317 |
type: str |
| 318 |
choices: [ "src", "dst", "src,dst", "dst,src", "dst,dst", "src,src" ] |
| 319 |
version_added: "2.11" |
| 320 |
limit: |
| 321 |
description: |
| 322 |
- Specifies the maximum average number of matches to allow per second. |
| 323 |
- The number can specify units explicitly, using C(/second), C(/minute), |
| 324 |
C(/hour) or C(/day), or parts of them (so V(5/second) is the same as |
| 325 |
V(5/s)). |
| 326 |
type: str |
| 327 |
limit_burst: |
| 328 |
description: |
| 329 |
- Specifies the maximum burst before the above limit kicks in. |
| 330 |
type: str |
| 331 |
version_added: "2.1" |
| 332 |
uid_owner: |
| 333 |
description: |
| 334 |
- Specifies the UID or username to use in the match by owner rule. |
| 335 |
- From Ansible 2.6 when the C(!) argument is prepended then the it inverts |
| 336 |
the rule to apply instead to all users except that one specified. |
| 337 |
type: str |
| 338 |
version_added: "2.1" |
| 339 |
gid_owner: |
| 340 |
description: |
| 341 |
- Specifies the GID or group to use in the match by owner rule. |
| 342 |
type: str |
| 343 |
version_added: "2.9" |
| 344 |
reject_with: |
| 345 |
description: |
| 346 |
- 'Specifies the error packet type to return while rejecting. It implies |
| 347 |
C(jump=REJECT).' |
| 348 |
type: str |
| 349 |
version_added: "2.1" |
| 350 |
icmp_type: |
| 351 |
description: |
| 352 |
- This allows specification of the ICMP type, which can be a numeric |
| 353 |
ICMP type, type/code pair, or one of the ICMP type names shown by the |
| 354 |
command C(iptables -p icmp -h). |
| 355 |
type: str |
| 356 |
version_added: "2.2" |
| 357 |
flush: |
| 358 |
description: |
| 359 |
- Flushes the specified table and chain of all rules. |
| 360 |
- If no chain is specified then the entire table is purged. |
| 361 |
- Ignores all other parameters. |
| 362 |
type: bool |
| 363 |
default: false |
| 364 |
version_added: "2.2" |
| 365 |
policy: |
| 366 |
description: |
| 367 |
- Set the policy for the chain to the given target. |
| 368 |
- Only built-in chains can have policies. |
| 369 |
- This parameter requires the O(chain) parameter. |
| 370 |
- If you specify this parameter, all other parameters will be ignored. |
| 371 |
- This parameter is used to set the default policy for the given O(chain). |
| 372 |
Do not confuse this with O(jump) parameter. |
| 373 |
type: str |
| 374 |
choices: [ ACCEPT, DROP, QUEUE, RETURN ] |
| 375 |
version_added: "2.2" |
| 376 |
wait: |
| 377 |
description: |
| 378 |
- Wait N seconds for the xtables lock to prevent multiple instances of |
| 379 |
the program from running concurrently. |
| 380 |
type: str |
| 381 |
version_added: "2.10" |
| 382 |
chain_management: |
| 383 |
description: |
| 384 |
- If V(true) and O(state) is V(present), the chain will be created if needed. |
| 385 |
- If V(true) and O(state) is V(absent), the chain will be deleted if the only |
| 386 |
other parameter passed are O(chain) and optionally O(table). |
| 387 |
type: bool |
| 388 |
default: false |
| 389 |
version_added: "2.13" |
| 390 |
numeric: |
| 391 |
description: |
| 392 |
- This parameter controls the running of the list -action of iptables, which is used internally by the module. |
| 393 |
- Does not affect the actual functionality. Use this if iptables hang when creating a chain or altering policy. |
| 394 |
- If V(true), then iptables skips the DNS-lookup of the IP addresses in a chain when it uses the list -action. |
| 395 |
- Listing is used internally for example when setting a policy or creating a chain. |
| 396 |
type: bool |
| 397 |
default: false |
| 398 |
version_added: "2.15" |
| 399 |
""" |
| 400 |
|
| 401 |
EXAMPLES = r""" |
| 402 |
- name: Block specific IP |
| 403 |
ansible.builtin.iptables: |
| 404 |
chain: INPUT |
| 405 |
source: 8.8.8.8 |
| 406 |
jump: DROP |
| 407 |
become: yes |
| 408 |
|
| 409 |
- name: Forward port 80 to 8600 |
| 410 |
ansible.builtin.iptables: |
| 411 |
table: nat |
| 412 |
chain: PREROUTING |
| 413 |
in_interface: eth0 |
| 414 |
protocol: tcp |
| 415 |
match: tcp |
| 416 |
destination_port: 80 |
| 417 |
jump: REDIRECT |
| 418 |
to_ports: 8600 |
| 419 |
comment: Redirect web traffic to port 8600 |
| 420 |
become: yes |
| 421 |
|
| 422 |
- name: Allow related and established connections |
| 423 |
ansible.builtin.iptables: |
| 424 |
chain: INPUT |
| 425 |
ctstate: ESTABLISHED,RELATED |
| 426 |
jump: ACCEPT |
| 427 |
become: yes |
| 428 |
|
| 429 |
- name: Allow new incoming SYN packets on TCP port 22 (SSH) |
| 430 |
ansible.builtin.iptables: |
| 431 |
chain: INPUT |
| 432 |
protocol: tcp |
| 433 |
destination_port: 22 |
| 434 |
ctstate: NEW |
| 435 |
syn: match |
| 436 |
jump: ACCEPT |
| 437 |
comment: Accept new SSH connections. |
| 438 |
|
| 439 |
- name: Match on IP ranges |
| 440 |
ansible.builtin.iptables: |
| 441 |
chain: FORWARD |
| 442 |
src_range: 192.168.1.100-192.168.1.199 |
| 443 |
dst_range: 10.0.0.1-10.0.0.50 |
| 444 |
jump: ACCEPT |
| 445 |
|
| 446 |
- name: Allow source IPs defined in ipset "admin_hosts" on port 22 |
| 447 |
ansible.builtin.iptables: |
| 448 |
chain: INPUT |
| 449 |
match_set: admin_hosts |
| 450 |
match_set_flags: src |
| 451 |
destination_port: 22 |
| 452 |
jump: ALLOW |
| 453 |
|
| 454 |
- name: Tag all outbound tcp packets with DSCP mark 8 |
| 455 |
ansible.builtin.iptables: |
| 456 |
chain: OUTPUT |
| 457 |
jump: DSCP |
| 458 |
table: mangle |
| 459 |
set_dscp_mark: 8 |
| 460 |
protocol: tcp |
| 461 |
|
| 462 |
- name: Tag all outbound tcp packets with DSCP DiffServ class CS1 |
| 463 |
ansible.builtin.iptables: |
| 464 |
chain: OUTPUT |
| 465 |
jump: DSCP |
| 466 |
table: mangle |
| 467 |
set_dscp_mark_class: CS1 |
| 468 |
protocol: tcp |
| 469 |
|
| 470 |
# Create the user-defined chain ALLOWLIST |
| 471 |
- iptables: |
| 472 |
chain: ALLOWLIST |
| 473 |
chain_management: true |
| 474 |
|
| 475 |
# Delete the user-defined chain ALLOWLIST |
| 476 |
- iptables: |
| 477 |
chain: ALLOWLIST |
| 478 |
chain_management: true |
| 479 |
state: absent |
| 480 |
|
| 481 |
- name: Insert a rule on line 5 |
| 482 |
ansible.builtin.iptables: |
| 483 |
chain: INPUT |
| 484 |
protocol: tcp |
| 485 |
destination_port: 8080 |
| 486 |
jump: ACCEPT |
| 487 |
action: insert |
| 488 |
rule_num: 5 |
| 489 |
|
| 490 |
# Think twice before running following task as this may lock target system |
| 491 |
- name: Set the policy for the INPUT chain to DROP |
| 492 |
ansible.builtin.iptables: |
| 493 |
chain: INPUT |
| 494 |
policy: DROP |
| 495 |
|
| 496 |
- name: Reject tcp with tcp-reset |
| 497 |
ansible.builtin.iptables: |
| 498 |
chain: INPUT |
| 499 |
protocol: tcp |
| 500 |
reject_with: tcp-reset |
| 501 |
ip_version: ipv4 |
| 502 |
|
| 503 |
- name: Set tcp flags |
| 504 |
ansible.builtin.iptables: |
| 505 |
chain: OUTPUT |
| 506 |
jump: DROP |
| 507 |
protocol: tcp |
| 508 |
tcp_flags: |
| 509 |
flags: ALL |
| 510 |
flags_set: |
| 511 |
- ACK |
| 512 |
- RST |
| 513 |
- SYN |
| 514 |
- FIN |
| 515 |
|
| 516 |
- name: Iptables flush filter |
| 517 |
ansible.builtin.iptables: |
| 518 |
chain: "{{ item }}" |
| 519 |
flush: yes |
| 520 |
with_items: [ 'INPUT', 'FORWARD', 'OUTPUT' ] |
| 521 |
|
| 522 |
- name: Iptables flush nat |
| 523 |
ansible.builtin.iptables: |
| 524 |
table: nat |
| 525 |
chain: '{{ item }}' |
| 526 |
flush: yes |
| 527 |
with_items: [ 'INPUT', 'OUTPUT', 'PREROUTING', 'POSTROUTING' ] |
| 528 |
|
| 529 |
- name: Log packets arriving into an user-defined chain |
| 530 |
ansible.builtin.iptables: |
| 531 |
chain: LOGGING |
| 532 |
action: append |
| 533 |
state: present |
| 534 |
limit: 2/second |
| 535 |
limit_burst: 20 |
| 536 |
log_prefix: "IPTABLES:INFO: " |
| 537 |
log_level: info |
| 538 |
|
| 539 |
- name: Allow connections on multiple ports |
| 540 |
ansible.builtin.iptables: |
| 541 |
chain: INPUT |
| 542 |
protocol: tcp |
| 543 |
destination_ports: |
| 544 |
- "80" |
| 545 |
- "443" |
| 546 |
- "8081:8083" |
| 547 |
jump: ACCEPT |
| 548 |
""" |
| 549 |
|
| 550 |
import re |
| 551 |
|
| 552 |
from ansible.module_utils.compat.version import LooseVersion |
| 553 |
|
| 554 |
from ansible.module_utils.basic import AnsibleModule |
| 555 |
|
| 556 |
|
| 557 |
IPTABLES_WAIT_SUPPORT_ADDED = '1.4.20' |
| 558 |
|
| 559 |
IPTABLES_WAIT_WITH_SECONDS_SUPPORT_ADDED = '1.6.0' |
| 560 |
|
| 561 |
BINS = dict( |
| 562 |
ipv4='iptables', |
| 563 |
ipv6='ip6tables', |
| 564 |
) |
| 565 |
|
| 566 |
ICMP_TYPE_OPTIONS = dict( |
| 567 |
ipv4='--icmp-type', |
| 568 |
ipv6='--icmpv6-type', |
| 569 |
both='--icmp-type --icmpv6-type', |
| 570 |
) |
| 571 |
|
| 572 |
|
| 573 |
def append_param(rule, param, flag, is_list): |
| 574 |
if is_list: |
| 575 |
for item in param: |
| 576 |
append_param(rule, item, flag, False) |
| 577 |
else: |
| 578 |
if param is not None: |
| 579 |
if param[0] == '!': |
| 580 |
rule.extend(['!', flag, param[1:]]) |
| 581 |
else: |
| 582 |
rule.extend([flag, param]) |
| 583 |
|
| 584 |
|
| 585 |
def append_tcp_flags(rule, param, flag): |
| 586 |
if param: |
| 587 |
if 'flags' in param and 'flags_set' in param: |
| 588 |
rule.extend([flag, ','.join(param['flags']), ','.join(param['flags_set'])]) |
| 589 |
|
| 590 |
|
| 591 |
def append_match_flag(rule, param, flag, negatable): |
| 592 |
if param == 'match': |
| 593 |
rule.extend([flag]) |
| 594 |
elif negatable and param == 'negate': |
| 595 |
rule.extend(['!', flag]) |
| 596 |
|
| 597 |
|
| 598 |
def append_csv(rule, param, flag): |
| 599 |
if param: |
| 600 |
rule.extend([flag, ','.join(param)]) |
| 601 |
|
| 602 |
|
| 603 |
def append_match(rule, param, match, loaded_extensions): |
| 604 |
if param and match not in loaded_extensions: |
| 605 |
rule.extend(['-m', match]) |
| 606 |
loaded_extensions.add(match) |
| 607 |
|
| 608 |
|
| 609 |
def append_jump(rule, param, jump): |
| 610 |
if param: |
| 611 |
rule.extend(['-j', jump]) |
| 612 |
|
| 613 |
|
| 614 |
def append_wait(rule, param, flag): |
| 615 |
if param: |
| 616 |
rule.extend([flag, param]) |
| 617 |
|
| 618 |
|
| 619 |
def construct_rule(params): |
| 620 |
rule = [] |
| 621 |
append_param(rule, params['protocol'], '-p', False) |
| 622 |
append_param(rule, params['source'], '-s', False) |
| 623 |
append_param(rule, params['destination'], '-d', False) |
| 624 |
append_param(rule, params['match'], '-m', True) |
| 625 |
loaded_extensions = set(params['match']) # Keep track of the above extensions |
| 626 |
append_tcp_flags(rule, params['tcp_flags'], '--tcp-flags') |
| 627 |
append_param(rule, params['jump'], '-j', False) |
| 628 |
if params.get('jump') and params['jump'].lower() == 'tee': |
| 629 |
append_param(rule, params['gateway'], '--gateway', False) |
| 630 |
append_param(rule, params['log_prefix'], '--log-prefix', False) |
| 631 |
append_param(rule, params['log_level'], '--log-level', False) |
| 632 |
append_param(rule, params['to_destination'], '--to-destination', False) |
| 633 |
append_match(rule, params['destination_ports'], 'multiport', loaded_extensions) |
| 634 |
append_csv(rule, params['destination_ports'], '--dports') |
| 635 |
append_param(rule, params['to_source'], '--to-source', False) |
| 636 |
append_param(rule, params['goto'], '-g', False) |
| 637 |
append_param(rule, params['in_interface'], '-i', False) |
| 638 |
append_param(rule, params['out_interface'], '-o', False) |
| 639 |
append_param(rule, params['fragment'], '-f', False) |
| 640 |
append_param(rule, params['set_counters'], '-c', False) |
| 641 |
append_param(rule, params['source_port'], '--source-port', False) |
| 642 |
append_param(rule, params['destination_port'], '--destination-port', False) |
| 643 |
append_param(rule, params['to_ports'], '--to-ports', False) |
| 644 |
append_param(rule, params['set_dscp_mark'], '--set-dscp', False) |
| 645 |
if params.get('set_dscp_mark') and params.get('jump').lower() != 'dscp': |
| 646 |
append_jump(rule, params['set_dscp_mark'], 'DSCP') |
| 647 |
|
| 648 |
append_param( |
| 649 |
rule, |
| 650 |
params['set_dscp_mark_class'], |
| 651 |
'--set-dscp-class', |
| 652 |
False) |
| 653 |
if params.get('set_dscp_mark_class') and params.get('jump').lower() != 'dscp': |
| 654 |
append_jump(rule, params['set_dscp_mark_class'], 'DSCP') |
| 655 |
append_match_flag(rule, params['syn'], '--syn', True) |
| 656 |
if 'conntrack' in params['match']: |
| 657 |
append_csv(rule, params['ctstate'], '--ctstate') |
| 658 |
elif 'state' in params['match']: |
| 659 |
append_csv(rule, params['ctstate'], '--state') |
| 660 |
elif params['ctstate']: |
| 661 |
append_match(rule, params['ctstate'], 'conntrack', loaded_extensions) |
| 662 |
append_csv(rule, params['ctstate'], '--ctstate') |
| 663 |
if 'iprange' in params['match']: |
| 664 |
append_param(rule, params['src_range'], '--src-range', False) |
| 665 |
append_param(rule, params['dst_range'], '--dst-range', False) |
| 666 |
elif params['src_range'] or params['dst_range']: |
| 667 |
append_match(rule, params['src_range'] or params['dst_range'], 'iprange', loaded_extensions) |
| 668 |
append_param(rule, params['src_range'], '--src-range', False) |
| 669 |
append_param(rule, params['dst_range'], '--dst-range', False) |
| 670 |
if 'set' in params['match']: |
| 671 |
append_param(rule, params['match_set'], '--match-set', False) |
| 672 |
append_match_flag(rule, 'match', params['match_set_flags'], False) |
| 673 |
elif params['match_set']: |
| 674 |
append_match(rule, params['match_set'], 'set', loaded_extensions) |
| 675 |
append_param(rule, params['match_set'], '--match-set', False) |
| 676 |
append_match_flag(rule, 'match', params['match_set_flags'], False) |
| 677 |
append_match(rule, params['limit'] or params['limit_burst'], 'limit', loaded_extensions) |
| 678 |
append_param(rule, params['limit'], '--limit', False) |
| 679 |
append_param(rule, params['limit_burst'], '--limit-burst', False) |
| 680 |
append_match(rule, params['uid_owner'], 'owner', loaded_extensions) |
| 681 |
append_match_flag(rule, params['uid_owner'], '--uid-owner', True) |
| 682 |
append_param(rule, params['uid_owner'], '--uid-owner', False) |
| 683 |
append_match(rule, params['gid_owner'], 'owner', loaded_extensions) |
| 684 |
append_match_flag(rule, params['gid_owner'], '--gid-owner', True) |
| 685 |
append_param(rule, params['gid_owner'], '--gid-owner', False) |
| 686 |
if params['jump'] is None: |
| 687 |
append_jump(rule, params['reject_with'], 'REJECT') |
| 688 |
append_jump(rule, params['set_dscp_mark_class'], 'DSCP') |
| 689 |
append_jump(rule, params['set_dscp_mark'], 'DSCP') |
| 690 |
|
| 691 |
append_param(rule, params['reject_with'], '--reject-with', False) |
| 692 |
append_param( |
| 693 |
rule, |
| 694 |
params['icmp_type'], |
| 695 |
ICMP_TYPE_OPTIONS[params['ip_version']], |
| 696 |
False) |
| 697 |
append_match(rule, params['comment'], 'comment', loaded_extensions) |
| 698 |
append_param(rule, params['comment'], '--comment', False) |
| 699 |
return rule |
| 700 |
|
| 701 |
|
| 702 |
def push_arguments(iptables_path, action, params, make_rule=True): |
| 703 |
cmd = [iptables_path] |
| 704 |
cmd.extend(['-t', params['table']]) |
| 705 |
cmd.extend([action, params['chain']]) |
| 706 |
if action == '-I' and params['rule_num']: |
| 707 |
cmd.extend([params['rule_num']]) |
| 708 |
if params['wait']: |
| 709 |
cmd.extend(['-w', params['wait']]) |
| 710 |
if make_rule: |
| 711 |
cmd.extend(construct_rule(params)) |
| 712 |
return cmd |
| 713 |
|
| 714 |
|
| 715 |
def check_rule_present(iptables_path, module, params): |
| 716 |
cmd = push_arguments(iptables_path, '-C', params) |
| 717 |
rc, stdout, stderr = module.run_command(cmd, check_rc=False) |
| 718 |
return (rc == 0) |
| 719 |
|
| 720 |
|
| 721 |
def append_rule(iptables_path, module, params): |
| 722 |
cmd = push_arguments(iptables_path, '-A', params) |
| 723 |
module.run_command(cmd, check_rc=True) |
| 724 |
|
| 725 |
|
| 726 |
def insert_rule(iptables_path, module, params): |
| 727 |
cmd = push_arguments(iptables_path, '-I', params) |
| 728 |
module.run_command(cmd, check_rc=True) |
| 729 |
|
| 730 |
|
| 731 |
def remove_rule(iptables_path, module, params): |
| 732 |
cmd = push_arguments(iptables_path, '-D', params) |
| 733 |
module.run_command(cmd, check_rc=True) |
| 734 |
|
| 735 |
|
| 736 |
def flush_table(iptables_path, module, params): |
| 737 |
cmd = push_arguments(iptables_path, '-F', params, make_rule=False) |
| 738 |
module.run_command(cmd, check_rc=True) |
| 739 |
|
| 740 |
|
| 741 |
def set_chain_policy(iptables_path, module, params): |
| 742 |
cmd = push_arguments(iptables_path, '-P', params, make_rule=False) |
| 743 |
cmd.append(params['policy']) |
| 744 |
module.run_command(cmd, check_rc=True) |
| 745 |
|
| 746 |
|
| 747 |
def get_chain_policy(iptables_path, module, params): |
| 748 |
cmd = push_arguments(iptables_path, '-L', params, make_rule=False) |
| 749 |
if module.params['numeric']: |
| 750 |
cmd.append('--numeric') |
| 751 |
rc, out, err = module.run_command(cmd, check_rc=True) |
| 752 |
chain_header = out.split("\n")[0] |
| 753 |
result = re.search(r'\(policy ([A-Z]+)\)', chain_header) |
| 754 |
if result: |
| 755 |
return result.group(1) |
| 756 |
return None |
| 757 |
|
| 758 |
|
| 759 |
def get_iptables_version(iptables_path, module): |
| 760 |
cmd = [iptables_path, '--version'] |
| 761 |
rc, out, err = module.run_command(cmd, check_rc=True) |
| 762 |
return out.split('v')[1].rstrip('\n') |
| 763 |
|
| 764 |
|
| 765 |
def create_chain(iptables_path, module, params): |
| 766 |
cmd = push_arguments(iptables_path, '-N', params, make_rule=False) |
| 767 |
module.run_command(cmd, check_rc=True) |
| 768 |
|
| 769 |
|
| 770 |
def check_chain_present(iptables_path, module, params): |
| 771 |
cmd = push_arguments(iptables_path, '-L', params, make_rule=False) |
| 772 |
if module.params['numeric']: |
| 773 |
cmd.append('--numeric') |
| 774 |
rc, out, err = module.run_command(cmd, check_rc=False) |
| 775 |
return (rc == 0) |
| 776 |
|
| 777 |
|
| 778 |
def delete_chain(iptables_path, module, params): |
| 779 |
cmd = push_arguments(iptables_path, '-X', params, make_rule=False) |
| 780 |
module.run_command(cmd, check_rc=True) |
| 781 |
|
| 782 |
|
| 783 |
def main(): |
| 784 |
module = AnsibleModule( |
| 785 |
supports_check_mode=True, |
| 786 |
argument_spec=dict( |
| 787 |
table=dict(type='str', default='filter', choices=['filter', 'nat', 'mangle', 'raw', 'security']), |
| 788 |
state=dict(type='str', default='present', choices=['absent', 'present']), |
| 789 |
action=dict(type='str', default='append', choices=['append', 'insert']), |
| 790 |
ip_version=dict(type='str', default='ipv4', choices=['ipv4', 'ipv6', 'both']), |
| 791 |
chain=dict(type='str'), |
| 792 |
rule_num=dict(type='str'), |
| 793 |
protocol=dict(type='str'), |
| 794 |
wait=dict(type='str'), |
| 795 |
source=dict(type='str'), |
| 796 |
to_source=dict(type='str'), |
| 797 |
destination=dict(type='str'), |
| 798 |
to_destination=dict(type='str'), |
| 799 |
match=dict(type='list', elements='str', default=[]), |
| 800 |
tcp_flags=dict(type='dict', |
| 801 |
options=dict( |
| 802 |
flags=dict(type='list', elements='str'), |
| 803 |
flags_set=dict(type='list', elements='str')) |
| 804 |
), |
| 805 |
jump=dict(type='str'), |
| 806 |
gateway=dict(type='str'), |
| 807 |
log_prefix=dict(type='str'), |
| 808 |
log_level=dict(type='str', |
| 809 |
choices=['0', '1', '2', '3', '4', '5', '6', '7', |
| 810 |
'emerg', 'alert', 'crit', 'error', |
| 811 |
'warning', 'notice', 'info', 'debug'], |
| 812 |
default=None, |
| 813 |
), |
| 814 |
goto=dict(type='str'), |
| 815 |
in_interface=dict(type='str'), |
| 816 |
out_interface=dict(type='str'), |
| 817 |
fragment=dict(type='str'), |
| 818 |
set_counters=dict(type='str'), |
| 819 |
source_port=dict(type='str'), |
| 820 |
destination_port=dict(type='str'), |
| 821 |
destination_ports=dict(type='list', elements='str', default=[]), |
| 822 |
to_ports=dict(type='str'), |
| 823 |
set_dscp_mark=dict(type='str'), |
| 824 |
set_dscp_mark_class=dict(type='str'), |
| 825 |
comment=dict(type='str'), |
| 826 |
ctstate=dict(type='list', elements='str', default=[]), |
| 827 |
src_range=dict(type='str'), |
| 828 |
dst_range=dict(type='str'), |
| 829 |
match_set=dict(type='str'), |
| 830 |
match_set_flags=dict( |
| 831 |
type='str', |
| 832 |
choices=['src', 'dst', 'src,dst', 'dst,src', 'src,src', 'dst,dst'] |
| 833 |
), |
| 834 |
limit=dict(type='str'), |
| 835 |
limit_burst=dict(type='str'), |
| 836 |
uid_owner=dict(type='str'), |
| 837 |
gid_owner=dict(type='str'), |
| 838 |
reject_with=dict(type='str'), |
| 839 |
icmp_type=dict(type='str'), |
| 840 |
syn=dict(type='str', default='ignore', choices=['ignore', 'match', 'negate']), |
| 841 |
flush=dict(type='bool', default=False), |
| 842 |
policy=dict(type='str', choices=['ACCEPT', 'DROP', 'QUEUE', 'RETURN']), |
| 843 |
chain_management=dict(type='bool', default=False), |
| 844 |
numeric=dict(type='bool', default=False), |
| 845 |
), |
| 846 |
mutually_exclusive=( |
| 847 |
['set_dscp_mark', 'set_dscp_mark_class'], |
| 848 |
['flush', 'policy'], |
| 849 |
), |
| 850 |
required_by=dict( |
| 851 |
set_dscp_mark=('jump',), |
| 852 |
set_dscp_mark_class=('jump',), |
| 853 |
), |
| 854 |
required_if=[ |
| 855 |
['jump', 'TEE', ['gateway']], |
| 856 |
['jump', 'tee', ['gateway']], |
| 857 |
['flush', False, ['chain']], |
| 858 |
] |
| 859 |
) |
| 860 |
args = dict( |
| 861 |
changed=False, |
| 862 |
failed=False, |
| 863 |
ip_version=module.params['ip_version'], |
| 864 |
table=module.params['table'], |
| 865 |
chain=module.params['chain'], |
| 866 |
flush=module.params['flush'], |
| 867 |
rule=' '.join(construct_rule(module.params)), |
| 868 |
state=module.params['state'], |
| 869 |
chain_management=module.params['chain_management'], |
| 870 |
wait=module.params['wait'], |
| 871 |
) |
| 872 |
|
| 873 |
ip_version = ['ipv4', 'ipv6'] if module.params['ip_version'] == 'both' else [module.params['ip_version']] |
| 874 |
iptables_path = [module.get_bin_path('iptables', True) if ip_version == 'ipv4' else module.get_bin_path('ip6tables', True) for ip_version in ip_version] |
| 875 |
|
| 876 |
both_changed = False |
| 877 |
|
| 878 |
for path in iptables_path: |
| 879 |
if module.params.get('log_prefix', None) or module.params.get('log_level', None): |
| 880 |
if module.params['jump'] is None: |
| 881 |
module.params['jump'] = 'LOG' |
| 882 |
elif module.params['jump'] != 'LOG': |
| 883 |
module.fail_json(msg="Logging options can only be used with the LOG jump target.") |
| 884 |
|
| 885 |
# Check if wait option is supported |
| 886 |
iptables_version = LooseVersion(get_iptables_version(path, module)) |
| 887 |
|
| 888 |
if iptables_version >= LooseVersion(IPTABLES_WAIT_SUPPORT_ADDED): |
| 889 |
if iptables_version < LooseVersion(IPTABLES_WAIT_WITH_SECONDS_SUPPORT_ADDED): |
| 890 |
module.params['wait'] = '' |
| 891 |
else: |
| 892 |
module.params['wait'] = None |
| 893 |
|
| 894 |
# Flush the table |
| 895 |
if args['flush'] is True: |
| 896 |
args['changed'] = True |
| 897 |
both_changed = True |
| 898 |
if not module.check_mode: |
| 899 |
flush_table(path, module, module.params) |
| 900 |
|
| 901 |
# Set the policy |
| 902 |
elif module.params['policy']: |
| 903 |
current_policy = get_chain_policy(path, module, module.params) |
| 904 |
if not current_policy: |
| 905 |
module.fail_json(msg='Can\'t detect current policy') |
| 906 |
|
| 907 |
changed = current_policy != module.params['policy'] |
| 908 |
args['changed'] = changed |
| 909 |
both_changed = both_changed or changed |
| 910 |
if changed and not module.check_mode: |
| 911 |
set_chain_policy(path, module, module.params) |
| 912 |
|
| 913 |
# Delete the chain if there is no rule in the arguments |
| 914 |
elif (args['state'] == 'absent') and not args['rule']: |
| 915 |
chain_is_present = check_chain_present( |
| 916 |
path, module, module.params |
| 917 |
) |
| 918 |
args['changed'] = chain_is_present |
| 919 |
both_changed = both_changed or chain_is_present |
| 920 |
|
| 921 |
if (chain_is_present and args['chain_management'] and not module.check_mode): |
| 922 |
delete_chain(path, module, module.params) |
| 923 |
|
| 924 |
else: |
| 925 |
# Create the chain if there are no rule arguments |
| 926 |
if (args['state'] == 'present') and not args['rule']: |
| 927 |
chain_is_present = check_chain_present( |
| 928 |
path, module, module.params |
| 929 |
) |
| 930 |
args['changed'] = not chain_is_present |
| 931 |
both_changed = both_changed or not chain_is_present |
| 932 |
|
| 933 |
if (not chain_is_present and args['chain_management'] and not module.check_mode): |
| 934 |
create_chain(path, module, module.params) |
| 935 |
|
| 936 |
else: |
| 937 |
insert = (module.params['action'] == 'insert') |
| 938 |
rule_is_present = check_rule_present( |
| 939 |
path, module, module.params |
| 940 |
) |
| 941 |
|
| 942 |
should_be_present = (args['state'] == 'present') |
| 943 |
# Check if target is up to date |
| 944 |
args['changed'] = (rule_is_present != should_be_present) |
| 945 |
both_changed = both_changed or (rule_is_present != should_be_present) |
| 946 |
if args['changed'] is False: |
| 947 |
# Target is already up to date |
| 948 |
continue |
| 949 |
|
| 950 |
# Modify if not check_mode |
| 951 |
if not module.check_mode: |
| 952 |
if should_be_present: |
| 953 |
if insert: |
| 954 |
insert_rule(path, module, module.params) |
| 955 |
else: |
| 956 |
append_rule(path, module, module.params) |
| 957 |
else: |
| 958 |
remove_rule(path, module, module.params) |
| 959 |
|
| 960 |
args['changed'] = both_changed |
| 961 |
|
| 962 |
module.exit_json(**args) |
| 963 |
|
| 964 |
|
| 965 |
if __name__ == '__main__': |
| 966 |
main() |