iptables ansible
Документация по модулю iptables
Писать буду простой файрвол. Блокируем вход и разрешаем подключение по SSH и PING
Основная суть это очистка правил и таблицы nat а затем применение конфигурации. Это полезно при начальной настройке
Когда на всех хостах одинаковые настройки то это уже можно не делать, зависит от ситуации
Так же политика INPUT, FORWARD, OUTPUT меняется на ACCEPT. Если просто сбросить таблицы, то при политиках INPUT, OUTPUT в режиме DROP подключение потеряется
Вконце INPUT блокируется не политикой а цепочкой, можно изменить на политику по желанию
--- - hosts: - iptables tasks: # Set Polycy - iptables: chain: ">" policy: ACCEPT with_items: ["INPUT", "FORWARD", "OUTPUT"] # Flush all - iptables: chain: ">" flush: yes with_items: ["INPUT", "FORWARD", "OUTPUT"] # Flush nat - iptables: chain: ">" flush: yes table: nat with_items: ["INPUT", "FORWARD", "OUTPUT"] # Allow input - iptables: chain: INPUT ctstate: ESTABLISHED,RELATED jump: ACCEPT comment: Allow related and established connections # PING - iptables: chain: INPUT protocol: icmp jump: ACCEPT comment: Allow icmp Ping # SSH - iptables: chain: INPUT protocol: tcp destination_port: "22" jump: ACCEPT comment: Allow SSH # Drop others input - iptables: chain: INPUT jump: DROP comment: Drop all
Перенос правил iptables на новый сервер
При смене сервера часто возникает необходимость перенести правила iptables. Данное руководство продемонстрирует простой способ переноса активных правил фаервола с одного сервера на другой.
Требования
Для выполнения руководства нужно иметь два сервера. Исходный сервер, на котором находятся правила фаервола, называется в руководстве сервером A; целевой сервер – B.
Также нужно иметь права sudo.
Просмотр правил iptables
Прежде чем приступить к переносу правил брандмауэра, нужно просмотреть их. Для этого выполните следующую команду на сервере A:
sudo iptables -S
Example output:
-P INPUT ACCEPT
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -m conntrack —ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp —dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp —dport 80 -j ACCEPT
-A INPUT -s 15.15.15.51/32 -j DROP
Теперь нужно перенести эти правила на другой сервер.
Экспорт правил Iptables
Команда iptables-save сохранит текущие правила брандмауэра в stdout, после чего его можно будет сохранить в файл.
Используйте эту команду на сервере А, чтобы экспортировать правила в файл iptables-export.
cd ~
sudo iptables-save > iptables-export
После этого в домашнем каталоге появится файл iptables-export, при помощи которого можно перенести правила фаервола на другой сервер.
Просмотр файла (опционально)
Проверьте, содержит ли новый файл все необходимые данные:
cat iptables-export
# Generated by iptables-save v1.4.21 on Tue Sep 1 17:32:29 2015
*filter
:INPUT ACCEPT [135:10578] :FORWARD ACCEPT [0:0] :OUTPUT ACCEPT [8364:1557108] -A INPUT -m conntrack —ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp —dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp —dport 80 -j ACCEPT
-A INPUT -s 15.15.15.51/32 -j DROP
COMMIT
# Completed on Tue Sep 1 17:32:29 2015
Как видите, данный файл содержит все текущие правила iptables, и теперь можно скопировать этот файл на целевой сервер.
Перенос правил на целевой сервер
Проще всего для этого использовать scp или же просто скопировать и вставить содержимое файла в новый файл на целевом сервере.
Ниже показано, как при помощи scp скопировать файл по сети в каталог /tmp.
Итак, запустите команду scp на сервере А, указав логин и IP-адрес сервера.
scp iptables-export user@server_b_ip_address:/tmp
Пройдя авторизацию, файл будет скопирован в каталог /tmp на сервер В.
Примечание: Содержимое каталога /tmp будет удалено при перезагрузке системы. Не забудьте переместить файл в более надёжный каталог.
Импорт правил
Теперь можно загрузить перенесённые правила.
Примечание: В случае необходимости сейчас можно обновить их, добавив данные нового сервера; отредактируйте файл /tmp/iptables-export, внеся всё необходимое.
Когда правила будут соответствовать требованиям данного сервера, загрузите их из файла iptables-export при помощи команды iptables-restore.
На сервере В запустите:
Чтобы убедиться, что правила загружены успешно, используйте:
sudo iptables -S
Сохранение правил
Несохранённые правила фаервола действительны только в течение одной сессии; чтобы сделать набор правил постоянным, нужно его сохранить. Убедитесь, что вы на сервере В, и следуйте соответствующему разделу.
Сохранение правил в Ubuntu
Для сохранения правил брандмауэра система Ubuntu предлагает пакет iptables-persistent. Чтобы установить этот пакет, введите команду:
sudo apt-get install iptables-persistent
Во время установки программа предложит сохранить текущие правила iptables. Выберите yes.
В дальнейшем для сохранения новых или обновлённых правил используйте команду:
sudo invoke-rc.d iptables-persistent save
Сохранение правил в CentOS 6 и 7
По умолчанию системы CentOS 6 и 7 используют фаервол FirewallD; чтобы сохранить правила iptables, используйте:
sudo service iptables save
Это сохранит текущие правила iptables в файл /etc/sysconfig/iptables, который загрузится после перезапуска системы.
Перенос правил брандмауэра успешно завершён!
Инструкция по настройке iptables файрвола для ОС Linux
Iptables представляет собой вспомогательную программу, которая работает как межсетевой экран. Настраивается конфигурация утилиты посредствам командной строки, определенный набор правил позволит разрешить или заблокировать передачу трафика. В момент установки интернет-соединения с устройством (компьютером ил ноутбуком), программа сканирует выставленный список правил и выполняет команды в соответствии с записями. Когда правило отсутствует, команда исполняется по умолчанию. Установка iptables стандартно выполняется на всех ОС Linux. Для обновления или повторной установки программы предназначена команда: sudo apt-get install iptables Для пользователей, не привыкших к работе с командной строкой, выпущены графические интерфейсы (в том числе программа Firestarter). Но если настраивать утилиту через специализированные программы и удаленные ssh-соединения, необходимо соблюдение осторожности, так как неверно введенная команда несет риск блокировки интернет-подключения. Система не сможет осуществить подключение к удаленной машине, для решения данной проблемы придется физическим путем корректировать настройки компьютера.
Правила iptables
- Правило Input применяется для мониторинга всех входящих пакетов. Если человек захочет сделать подключение к серверу по зашифрованной технологии SSH, то утилита произведет сравнение IP пользователя с данными из своего списка и решит, позволить сделать соединение или заблокировать.
- Правило категории Forward обрабатывает входящие сообщения и пакеты, чьей конечной точкой отправки текущий сервер не становится. Если рассматривать функционирование маршрутизатора, можно заметить, что к роутеру запрашивают подключения многие приложения и пользователи, при этом пакеты направляются маршрутизатору только для того, чтобы быть перенаправленными следующему адресату. Если вам не нужно настраивать NAT и маршрутизацию, то в повседневных командах Forward применяться не будет.
- Тип Output применяется, чтобы контролировать исходящий трафик с соединениями. Если юзер хочет запинговать любой на выбор веб-сайт, утилита iptables просканирует имеющиеся правила для определения своих действий и дальше решит, блокировать или разрешить соединение.
При пинге стороннего сайта необходимо отправить к нему пакет и дождаться ответной реакции. Работая с файрволом iptables, следует учитывать – множество протоколов передачи нуждаются в двусторонних коммуникациях. Именно по этой причине важно внимательно проводить настройку утилиты – ошибки новичков при включении разрешения работы машины с сервером путем передачи SSH не такие уж редкие.
Настройка поведения
Перед тем, как садиться за настройку файрвола, необходимо продумать и включить по умолчанию цепочку правил, на которой должна строиться работа межсетевого экрана. То есть, пользователю надо определиться, что должна делать программа iptables, когда для запрашиваемого соединения не создано ни правило, ни исключение.
Для нахождения стандартных и актуальных настроек утилиты нужна команда iptables –L:

В командной строке применилась команда grep, она используется для получения более конкретного вывода. На картинке можно заметить, что по умолчанию 3 цепочки команд позволяют компьютеру принимать трафик. Такая реакция машины считается предпочтительной для обычного пользователя. Данное правило существует по умолчанию. Но если вы изменяли конфигурацию и желаете вернуть стандартные настройки, следует написать следующие команды:
iptables —policy INPUT ACCEPT
iptables —policy OUTPUT ACCEPT
iptables —policy FORWARD ACCEPT
Оптимальное поведение – сначала разрешить получение и отправку всех пакетов, а после этого создавать запреты соединений конкретным IP и на выбранный порт.
Также можно сделать противоположные действия: включить запрет на пересылку всего трафика, а после создать исключения на разрешения. Для этого имеются такие команды:
iptables —policy INPUT DROP
iptables —policy OUTPUT DROP
iptables —policy FORWARD DROP
Что можно делать с соединениями
Когда стандартная настройка поведения файрвола закончена, наступает время перехода к написанию правила по обработке пакетов трафика. Это необходимо, чтобы межсетевой экран понимал, как ему поступать с определенным интернет-соединением. Существует 3 разновидности действий:
- Разрешение соединения при помощи Accept;
- Игнорирование попыток коннекта командой Drop — это используется в случаях, в которых от источника трафика скрывается факт блокировки запросов;
- Полная блокировка соединения Reject и отправка отчетного сообщения об ошибке — это вариант для случаев, если пользователь дает ресурсам информацию об их блокировке своим файрволом.
Применяя каждый из перечисленных команд, можно увидеть следующий пинг.
Разрешенное соединение выглядит так:


Полное отклонение соединения:

Как разрешить/заблокировать соединение
В инструкции все поступающие соединения мы отклоняем, однако их также допустимо игнорировать и разрешать.
Для добавления новых правил к уже существующим, используется команда iptables –A. То есть межсетевой экран запускает сканирование по началу файла списка и последовательно проходит правила, ища совпадения.
При необходимости дополнить имеющиеся настройки, применяется выражение iptables -I [цепочка] [номер]. Здесь пользователь записывает номер места, куда помещается свежее правило.
Группа соединений, приходящие с одного IP-адреса
Выданная команда блокирует все попытки подключения, исходящие от IP-адреса 100.100.100.100:
iptables -A INPUT -s 100.100.100.100 -j DROP
Если имеется определенный диапазон IP, которые рекомендуется заблокировать, следует применить данную команду. Диапазон адресов здесь записывается через слеш после IP-адреса, его можно заменить на маску подсети:
iptables -A INPUT -s 100.100.100.0/24 -j DROP iptables -A INPUT -s 100.100.100.0/255.255.255.0 -j DROP
Соединения для конкретного порта
Для блокировки соединения типа SSH с адреса 100.100.100.100:
iptables -A INPUT -p tcp —dport ssh -s 100.100.100.100 -j DROP
В записанной команде допускается использование любого протокола, не только SSH, и номера порта. Выражение –p tcp является разновидностью соединений, применяемых протоколами. Чтобы заблокировать протокол, работающий с UDP, необходимо скорректировать выражение: –p udp.
Чтобы для любого IP блокировать соединения SSH типа, существует краткая команда:
iptables -A INPUT -p tcp —dport ssh -j DROP
Состояние интернет-соединения
Большинство современных протоколов нуждаются в двустороннем типе коммуникаций. Для разрешения машине SSH-соединения придется добавлять правило в обе категории output и input. Если возникает необходимость в разрешении доступа исключительно входящим и соединениям шифрованного типа SSH, будет приименяться состояние соединений. Эта функция опишет двустороннюю коммуникацию, для которой разрешено подключение соединение конкретного направления (входящего).
В написанной команде разрешается соединение SSH, которое поступило с IP-адреса 10.10.10.10. При этом, данный тип соединения к хосту заблокирован, но файрвол позволяет отправлять данные по SSH к установленным раннее сессиям, а это, в свою очередь, разрешает коммуникацию двух хостов:
iptables -A INPUT -p tcp —dport ssh -s 100.100.100.100 -m state —state NEW,ESTABLISHED -j ACCEPT iptables -A OUTPUT -p tcp —sport 22 -d 10.10.10.10 -m state —state ESTABLISHED -j ACCEPT
Как сохранить изменения
Если случайно перезапустить iptables, все изменения в командах и правилах исчезнут, поэтому их нужно заранее сохранять. Для этого имеется переделенная команда, меняющая вид в зависимости от вида Linux.
Для Ubuntu она выглядит следующим образом:
Варианты для Red Hat / CentOS:
=/sbin/service iptables save =/etc/init.d/iptables save
Прочие команды
Чтобы вывести и просмотреть созданные правила iptables применяется:
Если добавить –v, можно будет просмотреть данные о пакетах и байтах. Выражение –n предоставит цифровые сведения об именах хостов, протоколах, сетях.
Чтобы удалить все правила конфигурации утилиты, нужно написать:
На этом настройка iptables окончена. В нашей базе знаний вы найдёте ещё множество статей посвящённых различным аспектам работы в Linux, а если вы ищете надежный виртуальный сервер под управлением Linux, обратите внимания на нашу услугу — Аренда виртуального сервера на базе Linux.
Последнее обновление: 01.11.2023
Средняя оценка: 5,0 , всего оценок: 1 Спасибо за Вашу оценку! К сожалению, проголосовать не получилось. Попробуйте позже
ansible.builtin.iptables module – Modify iptables rules
This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name iptables even without specifying the collections keyword . However, we recommend you use the Fully Qualified Collection Name (FQCN) ansible.builtin.iptables for easy linking to the module documentation and to avoid conflicting with other collections that may have the same module name.
Synopsis
- ansible.builtin.iptables is used to set up, maintain, and inspect the tables of IP packet filter rules in the Linux kernel.
- This module does not handle the saving and/or loading of rules, but rather only manipulates the current rules that are present in memory. This is the same as the behaviour of the iptables and ip6tables command which this module uses internally.
Parameters
action
Whether the rule should be appended at the bottom or inserted at the top.
If the rule already exists the chain will not be modified.
Choices:
chain
Specify the iptables chain to modify.
This could be a user-defined chain or one of the standard iptables chains, like INPUT , FORWARD , OUTPUT , PREROUTING , POSTROUTING , SECMARK or CONNSECMARK .
chain_management
added in ansible-core 2.13
If true and state is present , the chain will be created if needed.
If true and state is absent , the chain will be deleted if the only other parameter passed are chain and optionally table .
Choices:
comment
This specifies a comment that will be added to the rule.
ctstate
A list of the connection states to match in the conntrack module.
Possible values are INVALID , NEW , ESTABLISHED , RELATED , UNTRACKED , SNAT , DNAT .
Default: []
destination
Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address.
Hostnames will be resolved once only, before the rule is submitted to the kernel. Please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea.
The mask can be either a network mask or a plain number, specifying the number of 1’s at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A ! argument before the address specification inverts the sense of the address.
destination_port
Destination port or port range specification. This can either be a service name or a port number. An inclusive range can also be specified, using the format first:last. If the first port is omitted, ‘0’ is assumed; if the last is omitted, ‘65535’ is assumed. If the first port is greater than the second one they will be swapped. This is only valid if the rule also specifies one of the following protocols: tcp, udp, dccp or sctp.
destination_ports
added in ansible-core 2.11
This specifies multiple destination port numbers or port ranges to match in the multiport module.
It can only be used in conjunction with the protocols tcp, udp, udplite, dccp and sctp.
Default: []
dst_range
added in Ansible 2.8
Specifies the destination IP range to match in the iprange module.
flush
Flushes the specified table and chain of all rules.
If no chain is specified then the entire table is purged.
Ignores all other parameters.
Choices:
fragment
This means that the rule only refers to second and further fragments of fragmented packets.
Since there is no way to tell the source or destination ports of such a packet (or ICMP type), such a packet will not match any rules which specify them.
When the “!” argument precedes fragment argument, the rule will only match head fragments, or unfragmented packets.
gateway
added in Ansible 2.8
This specifies the IP address of host to send the cloned packets.
This option is only valid when jump is set to TEE .
gid_owner
added in Ansible 2.9
Specifies the GID or group to use in match by owner rule.
goto
This specifies that the processing should continue in a user specified chain.
Unlike the jump argument return will not continue processing in this chain but instead in the chain that called us via jump.
icmp_type
This allows specification of the ICMP type, which can be a numeric ICMP type, type/code pair, or one of the ICMP type names shown by the command ‘iptables -p icmp -h’
in_interface
Name of an interface via which a packet was received (only for packets entering the INPUT , FORWARD and PREROUTING chains).
When the ! argument is used before the interface name, the sense is inverted.
If the interface name ends in a + , then any interface which begins with this name will match.
If this option is omitted, any interface name will match.
ip_version
Which version of the IP protocol this rule should apply to.
Choices:
jump
This specifies the target of the rule; i.e., what to do if the packet matches it.
The target can be a user-defined chain (other than the one this rule is in), one of the special builtin targets which decide the fate of the packet immediately, or an extension (see EXTENSIONS below).
If this option is omitted in a rule (and the goto parameter is not used), then matching the rule will have no effect on the packet’s fate, but the counters on the rule will be incremented.
limit
Specifies the maximum average number of matches to allow per second.
The number can specify units explicitly, using /second , /minute , /hour or /day , or parts of them (so 5/second is the same as 5/s ).
limit_burst
Specifies the maximum burst before the above limit kicks in.
log_level
added in Ansible 2.8
Logging level according to the syslogd-defined priorities.
The value can be strings or numbers from 1-8.
This parameter is only applicable if jump is set to LOG .
Choices:
log_prefix
Specifies a log text for the rule. Only make sense with a LOG jump.
match
Specifies a match to use, that is, an extension module that tests for a specific property.
The set of matches make up the condition under which a target is invoked.
Matches are evaluated first to last if specified as an array and work in short-circuit fashion, i.e. if one extension yields false, evaluation will stop.
Default: []
match_set
added in ansible-core 2.11
Specifies a set name which can be defined by ipset.
Must be used together with the match_set_flags parameter.
When the ! argument is prepended then it inverts the rule.
Uses the iptables set extension.
match_set_flags
added in ansible-core 2.11
Specifies the necessary flags for the match_set parameter.
Must be used together with the match_set parameter.
Uses the iptables set extension.
Choices:
numeric
added in ansible-core 2.15
This parameter controls the running of the list -action of iptables, which is used internally by the module
Does not affect the actual functionality. Use this if iptables hangs when creating chain or altering policy
If true , then iptables skips the DNS-lookup of the IP addresses in a chain when it uses the list -action
Listing is used internally for example when setting a policy or creting of a chain
Choices:
out_interface
Name of an interface via which a packet is going to be sent (for packets entering the FORWARD , OUTPUT and POSTROUTING chains).
When the ! argument is used before the interface name, the sense is inverted.
If the interface name ends in a + , then any interface which begins with this name will match.
If this option is omitted, any interface name will match.
policy
Set the policy for the chain to the given target.
Only built-in chains can have policies.
This parameter requires the chain parameter.
If you specify this parameter, all other parameters will be ignored.
This parameter is used to set default policy for the given chain . Do not confuse this with jump parameter.
Choices:
protocol
The protocol of the rule or of the packet to check.
The specified protocol can be one of tcp , udp , udplite , icmp , ipv6-icmp or icmpv6 , esp , ah , sctp or the special keyword all , or it can be a numeric value, representing one of these protocols or a different one.
A protocol name from /etc/protocols is also allowed.
A ! argument before the protocol inverts the test.
The number zero is equivalent to all.
all will match with all protocols and is taken as default when this option is omitted.
reject_with
Specifies the error packet type to return while rejecting. It implies “jump: REJECT”.
rule_num
Insert the rule as the given rule number.
This works only with action=insert .
set_counters
This enables the administrator to initialize the packet and byte counters of a rule (during INSERT , APPEND , REPLACE operations).
set_dscp_mark
This allows specifying a DSCP mark to be added to packets. It takes either an integer or hex value.
Mutually exclusive with set_dscp_mark_class .
set_dscp_mark_class
This allows specifying a predefined DiffServ class which will be translated to the corresponding DSCP mark.
Mutually exclusive with set_dscp_mark .
source
Address can be either a network name, a hostname, a network IP address (with /mask), or a plain IP address.
Hostnames will be resolved once only, before the rule is submitted to the kernel. Please note that specifying any name to be resolved with a remote query such as DNS is a really bad idea.
The mask can be either a network mask or a plain number, specifying the number of 1’s at the left side of the network mask. Thus, a mask of 24 is equivalent to 255.255.255.0. A ! argument before the address specification inverts the sense of the address.
source_port
Source port or port range specification.
This can either be a service name or a port number.
An inclusive range can also be specified, using the format first:last .
If the first port is omitted, 0 is assumed; if the last is omitted, 65535 is assumed.
If the first port is greater than the second one they will be swapped.
src_range
added in Ansible 2.8
Specifies the source IP range to match in the iprange module.
state
Whether the rule should be absent or present.
Choices:
syn
This allows matching packets that have the SYN bit set and the ACK and RST bits unset.
When negated, this matches all packets with the RST or the ACK bits set.
Choices:
table
This option specifies the packet matching table which the command should operate on.
If the kernel is configured with automatic module loading, an attempt will be made to load the appropriate module for that table if it is not already there.
Choices:
tcp_flags
TCP flags specification.
tcp_flags expects a dict with the two keys flags and flags_set .
flags
List of flags you want to examine.
flags_set
Flags to be set.
to_destination
This specifies a destination address to use with DNAT .
Without this, the destination address is never altered.
to_ports
This specifies a destination port or range of ports to use, without this, the destination port is never altered.
This is only valid if the rule also specifies one of the protocol tcp , udp , dccp or sctp .
to_source
This specifies a source address to use with SNAT .
Without this, the source address is never altered.
uid_owner
Specifies the UID or username to use in match by owner rule.
From Ansible 2.6 when the ! argument is prepended then the it inverts the rule to apply instead to all users except that one specified.
wait
added in ansible-base 2.10
Wait N seconds for the xtables lock to prevent multiple instances of the program from running concurrently.
Attributes
check_mode
Support: full
Can run in check_mode and return changed status prediction without modifying target
diff_mode
Support: none
Will return details on what has changed (or possibly needs changing in check_mode), when in diff mode
platform
Platform: linux
Target OS/families that can be operated against
Notes
- This module just deals with individual rules. If you need advanced chaining of rules the recommended way is to template the iptables restore file.
Examples
- name: Block specific IP ansible.builtin.iptables: chain: INPUT source: 8.8.8.8 jump: DROP become: yes - name: Forward port 80 to 8600 ansible.builtin.iptables: table: nat chain: PREROUTING in_interface: eth0 protocol: tcp match: tcp destination_port: 80 jump: REDIRECT to_ports: 8600 comment: Redirect web traffic to port 8600 become: yes - name: Allow related and established connections ansible.builtin.iptables: chain: INPUT ctstate: ESTABLISHED,RELATED jump: ACCEPT become: yes - name: Allow new incoming SYN packets on TCP port 22 (SSH) ansible.builtin.iptables: chain: INPUT protocol: tcp destination_port: 22 ctstate: NEW syn: match jump: ACCEPT comment: Accept new SSH connections. - name: Match on IP ranges ansible.builtin.iptables: chain: FORWARD src_range: 192.168.1.100-192.168.1.199 dst_range: 10.0.0.1-10.0.0.50 jump: ACCEPT - name: Allow source IPs defined in ipset "admin_hosts" on port 22 ansible.builtin.iptables: chain: INPUT match_set: admin_hosts match_set_flags: src destination_port: 22 jump: ALLOW - name: Tag all outbound tcp packets with DSCP mark 8 ansible.builtin.iptables: chain: OUTPUT jump: DSCP table: mangle set_dscp_mark: 8 protocol: tcp - name: Tag all outbound tcp packets with DSCP DiffServ class CS1 ansible.builtin.iptables: chain: OUTPUT jump: DSCP table: mangle set_dscp_mark_class: CS1 protocol: tcp # Create the user-defined chain ALLOWLIST - iptables: chain: ALLOWLIST chain_management: true # Delete the user-defined chain ALLOWLIST - iptables: chain: ALLOWLIST chain_management: true state: absent - name: Insert a rule on line 5 ansible.builtin.iptables: chain: INPUT protocol: tcp destination_port: 8080 jump: ACCEPT action: insert rule_num: 5 # Think twice before running following task as this may lock target system - name: Set the policy for the INPUT chain to DROP ansible.builtin.iptables: chain: INPUT policy: DROP - name: Reject tcp with tcp-reset ansible.builtin.iptables: chain: INPUT protocol: tcp reject_with: tcp-reset ip_version: ipv4 - name: Set tcp flags ansible.builtin.iptables: chain: OUTPUT jump: DROP protocol: tcp tcp_flags: flags: ALL flags_set: - ACK - RST - SYN - FIN - name: Iptables flush filter ansible.builtin.iptables: chain: " item >>" flush: yes with_items: [ 'INPUT', 'FORWARD', 'OUTPUT' ] - name: Iptables flush nat ansible.builtin.iptables: table: nat chain: ' item >>' flush: yes with_items: [ 'INPUT', 'OUTPUT', 'PREROUTING', 'POSTROUTING' ] - name: Log packets arriving into an user-defined chain ansible.builtin.iptables: chain: LOGGING action: append state: present limit: 2/second limit_burst: 20 log_prefix: "IPTABLES:INFO: " log_level: info - name: Allow connections on multiple ports ansible.builtin.iptables: chain: INPUT protocol: tcp destination_ports: - "80" - "443" - "8081:8083" jump: ACCEPT
Authors
- Linus Unnebäck (@LinusU)
- Sébastien DA ROCHA (@sebastiendarocha)
Collection links
- Issue Tracker
- Repository (Sources)
- Communication
© Copyright Ansible project contributors. Last updated on Jan 04, 2024.