Openwrt настройка firewall luci
Так бывает, что у вас два интернет канала или две сети, одна из которых подключается в интернет через VPN, а другая — напрямую. Соответственно, обе этих внутренних сети будут иметь разные публичные IP в интернет, что может быть полезно. Также вам может потребоваться разнести сети на два устройства, потому что пропускная способность одного не достаточна, но при этом пустить интернет трафик из обоих сетей через один интернет канал. Во всех случаях настройка сети штатными средствами заводской прошивки роутера для выполнения описанных задач чаще всего не возможна. Для этого надо использовать роутеры с прошивками OpenWrt, DD-WRT, LEDE и другими Linux-подобными. Мы рассмотрим решение раздач на OpenWrt как наиболее удобной и часто обновляемой.
Zone declaration for semi non-UCI interfaces, manually listed in the network config, and forwardings
First list the interfaces in /etc/config/network, for example, as written below. Be careful on the limits of interface naming in terms of name length, read more)
Then create the zone in /etc/config/firewall, for example one zone for all the vpn interfaces.
Then we want to communicate with the “lan” zone, therefore we need forwardings in both ways (from lan to wan and viceversa).
In general remember that forwardings are relying how routing rules are defined, and afterwards which zones are defined on which interfaces.
Forwardings
The forwarding sections control the traffic flow between zones, and may enable MSS clamping for specific directions.
Only one direction is covered by a forwarding rule. To allow bidirectional traffic flows between two zones, two forwardings are required, with src and dest reversed in each.
Options
Name | Type | Required | Default | Description |
---|---|---|---|---|
name | forward name | no | (none) | Unique forwarding name. |
src | zone name | yes | (none) | Specifies the traffic source zone. Refers to one of the defined zone names. For typical port forwards this usually is 'wan'. |
dest | zone name | yes | (none) | Specifies the traffic destination zone. Refers to one of the defined zone names |
mtu_fix | boolean | no | 0 | Enable MSS clamping for traffic flowing from the source zone to the destination zone (Deprecated and moved to zone sections in 8.09.2+) |
family | string | no | any | Protocol family ( ipv4 , ipv6 or any ) to generate iptables rules for. |
enabled | bool | no | yes | if set to 0 , forward is disabled |
The iptables rules generated for this section rely on the state match which needs connection tracking to work.
At least one of the src or dest zones needs to have connection tracking enabled through the masq option.
Rules
The rule section is used to define basic accept, drop, or reject rules to allow or restrict access to specific ports or hosts.
If neither src nor dest are given, the rule defaults to an outgoing traffic rule
Options
ICMP name types
address-mask-reply | host-redirect | pong | time-exceeded |
address-mask-request | host-unknown | port-unreachable | timestamp-reply |
any | host-unreachable | precedence-cutoff | timestamp-request |
communication-prohibited | ip-header-bad | protocol-unreachable | TOS-host-redirect |
destination-unreachable | network-prohibited | redirect | TOS-host-unreachable |
echo-reply | network-redirect | required-option-missing | TOS-network-redirect |
echo-request | network-unknown | router-advertisement | TOS-network-unreachable |
fragmentation-needed | network-unreachable | router-solicitation | ttl-exceeded |
host-precedence-violation | parameter-problem | source-quench | ttl-zero-during-reassembly |
host-prohibited | ping | source-route-failed | ttl-zero-during-transit |
IP Sets
The UCI firewall version 3 supports referencing or creating ipsets to simplify matching of huge address or port lists without the need for creating one rule per item to match,
The following options are defined for ipsets:
Name | Type | Required | Default | Description |
---|---|---|---|---|
enabled | boolean | no | 1 | Allows to disable the declaration fo the ipset without the need to delete the section. |
external | string | no | (none) | If the external option is set to a name, the firewall will simply reference an already existing ipset pointed to by the name. If the external option is unset, the firewall will create the ipset on start and destroy it on stop. |
name | string | yes if external is unset no if external is set | (none) if external is unset value of external if external is set | Specifies the firewall internal name of the ipset which is used to reference the set in rules or redirects. |
family | string | no | ipv4 | Protocol family ( ipv4 or ipv6 ) to create ipset for. Only applicable to storage types hash and list , the bitmap type implies ipv4 . |
storage | string | no | varies | Specifies the storage method ( bitmap , hash or list ) used by the ipset, the default varies depending on the used datatypes (see match option below). In most cases the storage method can be automatically inferred from the datatype combination but in some cases multiple choices are possible (e.g. bitmap:ip vs. hash:ip ). |
match | list of direction/type tuples | yes | (none) | Specifies the matched data types ( ip , port , mac , net or set ) and their direction ( src or dest ). The direction is joined with the datatype by an underscore to form a tuple, e.g. src_port to match source ports or dest_net to match destination CIDR ranges. |
iprange | IP range | yes for storage type bitmap with datatype ip | (none) | Specifies the IP range to cover, see ipset(8). Only applicable to the hash storage type. |
portrange | Port range | yes for storage type bitmap with datatype port | (none) | Specifies the port range to cover, see ipset(8). Only applicable to the hash storage type. |
netmask | integer | no | 32 | If specified, network addresses will be stored in the set instead of IP host addresses. Value must be between 1 and 32 , see ipset(8). Only applicable to the bitmap storage type with match ip or the hash storage type with match ip . |
maxelem | integer | no | 65536 | Limits the number of items that can be added to the set, only applicable to the hash and list storage types. |
hashsize | integer | no | 1024 | Specifies the initial hash size of the set, only applicable to the hash storage type. |
timeout | integer | no | 0 | Specifies the default timeout for entries added to the set. A value of 0 means no timeout. |
Possible Storage / Match Combinations
The table below outlines the possible combinations of storage methods and matched datatypes as well as the usable IP address family. The order of the datatype matches is significant.
Most of the information in this wiki will focus on the configuration files and content. The LuCI and UCI interfaces are user abstractions, ultimately modifying the configuration files.
Management
The main firewall config file is /etc/config/firewall , and this is edited to modify the firewall settings
Should changes cause a loss-of-connectivity to the router, you will need to access it in Failsafe Mode to restore the backup
Once the settings are changed, and after double checking changes, reload the firewall via /etc/init.d/firewall reload
This is a simple shell script calling fw3 reload , and will print diagnostics to the console as it parses the new firewall configuration. Check for errors!
The UCI firewall configuration in /etc/config/firewall covers a reasonable subset of NetFilter rules, but not all of them
To provide more functionality, an include section was added to the UCI firewall config that loads a file containing native iptables directives
This is processed as a shell script, allowing any shell command to be added to it, but the focus is working with the netfilter subsystem by adding iptables commands
Web interface instructions
LuCI is a good mechanism to view and modify the firewall configuration.
It takes a little longer to modify the firewall configuration, but has a higher level of organization than the config files.
Make changes and reload using the Save & Apply button.
Zone declaration for a specific protocol and port
This example declares a zone which maches any TCP stream from and to port 22 .
Includes
It is possible to include custom firewall scripts by specifying one or more include sections in the firewall configuration:
Options
Includes of type script may contain arbitrary commands, for example advanced iptables rules or tc commands required for traffic shaping.
Since custom iptables rules are meant to be more specific than the generic ones, be sure to use -I (insert), instead of -A (append), so that the rules appear before the default rules.
If the rule exists in iptables, it will not be re-added. A standard iptables -I or -A will add a duplicate rule.
- Last modified: 2021/12/16 10:28
- by paulfertser
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
Файрвол UCI объединяет один и более интерфейсов в специальные зоны, которые используются для для описания правил по-умолчанию для данного интерфейса, правил пересылки пакетов между интерфейсами, а также дополнительные правила, которые не подпадают под первые два типа. В конфигурационном файле правила по-умолчанию идут первыми, но вступают в силу последними. Система netfilter является системой фильтрации с последовательной обработкой, в которой пакеты последовательно, по цепочке, обрабатываются различными правилами. Первое совпавшее правило выполняется, но оно часто выполняет переход на другую цепочку правил, по которой движется пакет пока не встретит команды ACCEPT или DROP/REJECT. Правила с такими командами выполняются последними в цепочке правил, поэтому правила по-умолчанию вступят в силу последними, а более конкретные правила будут проверяться в первую очередь.
Конфигурация файрвола находится в файле /etc/config/firewall . При применения настроек в силу роутер перезагружать не надо. Командой ifconfig можно посмотреть названия интерфейсов для использования в конфигурации.
Требования
Includes
It is possible to include custom firewall scripts by specifying one or more include sections in the firewall configuration.
There is only one possible parameter for includes:
Includes of type script may contain arbitary commands, for example advanced iptables rules or tc commands required for traffic shaping.
Since custom iptables rules are meant to be more specific than the generic ones, you must make sure to use -I (insert) instead of -A (append) so that the rules appear before the default rules.
Block WAN-side networks and ports
When public-facing servers run behind the firewall (e.g. mail server), each is susceptible to attacks: SSH probing, SPAM, screen-scraping, etc.
Customers of the large overseas ISPs (particular China and Vietnam) have made spam attacks into an artform, generating blocks of prose to confuse spam filters, sprinkling emails across many source stations and many subnets. The best way to counter this is to block the main originating network sending the spam.
In this example, stations in a Beijing network are sending email spam in bursts of three with different content incrementing ipv4 addresses across subnets! This rule DROPS all incoming traffic on port 25 (SMTP ) from any station in their network. DROP silently discards the packet rather than REJECT which returns a response to the source.
IPSec passthrough
For some configurations you also have to open port 500/UDP for the ISAKMP protocol.
Ключевые понятия файрвола iptables
iptables — это утилита для настройки межсетевого экрана linux, которая предустанавливается по умолчанию во все сборки Linux, начиная с версии 2.4. Есть она и в OpenWrt. Как и все файрволлы, iptables оперирует некими правилами (rules), на основании которых решается судьба пакета, который поступил на интерфейс сетевого устройства (роутера). Каждое правило в iptables состоит из критерия (условие, под которое должны подпадать параметры пакета или текущее соединение, чтобы сработало действие), действия (операция, которую нужно проделать с пакетом или соединением) и счётчика (считает сколько пакетов было подвержено действию правила).
Набор правил формируется в цепочки (chains) . Существует 5 базовых цепочек и различаются они в зависимости от того, какое назначение имеет пакет. Имена базовых цепочек записываются в верхнем регистре.
- PREROUTING — правила в этой цепочке применяются ко всем пакетам, которые поступают на сетевой интерфейс извне;
- INPUT — применяются к пакетам, которые предназначаются для самого хоста или для локального процесса, запущенного на данном хосте. То есть не являются транзитными;
- FORWARD — правила, которые применяются к транзитным пакетам, проходящими через хост, не задерживаясь;
- OUTPUT — применяются к пакетам, которые сгенерированы самим хостом;
- POSTROUTING — применяются к пакетам, которые должны покинуть сетевой интерфейс.
В базовых цепочках обязательно устанавливается политика по умолчанию, как правило – принимать (ACCEPT) или сбрасывать (DROP) пакеты. Действует она только в цепочках INPUT, FORWARD и OUTPUT.
Таблицы — это набор базовых и пользовательских цепочек. В зависимости от того, в какой таблице находится цепочка правил, с пакетом или соединением производятся определённые действия. Существует 5 таблиц, основные из которых:
- filter — таблица, выполняющая функции фильтрации пакетов по определённым параметрам. В большинстве случаев вы будете использовать именно её. Содержит следующие встроенные цепочки: FORWARD, INPUT, OUTPUT;
- nat — таблица, предназначенная целиком по функции трансляции сетевых адресов. Содержит следующие встроенные цепочки: PREROUTING, OUTPUT, POSTROUTING;
- mangle — таблица, предназначенная для изменения различных заголовков пакета. Можно, например, изменить TTL, количество hop’ов и другое. Содержит следующие встроенные цепочки: PREROUTING, INPUT, FORWARD, OUTPUT, POSTROUTING;
Этот рисунок дает довольно ясное представление о порядке прохождения пакетов через различные цепочки. В первой точке принятия решения о маршрутизации (routing decision) все пакеты, предназначенные данному хосту направляются в цепочку INPUT, остальные – в цепочку FORWARD.
Обратите внимание также на тот факт, что пакеты, с адресом назначения на брандмауэр, могут претерпеть трансляцию сетевого адреса (DNAT) в цепочке PREROUTING таблицы nat и соответственно дальнейшая маршрутизация в первой точке будет выполняться в зависимости от произведенных изменений.
Наиболее используемые действия :
- ACCEPT — разрешить прохождение пакета;
- DROP — тихо выбросить пакет, не сообщая причин;
- QUEUE — отправляет пакет за пределы логики iptables, в стороннее приложение. Это может понадобиться, когда нужно обработать пакет в рамках другого процесса в другой программе;
- RETURN — остановить обработку правила и вернуться на одно правило назад. Это действие подобно break’у в языке программирования.
Помимо этих четырех, есть ещё масса других действий, которые называются расширенными (extension modules):
- REJECT — выбрасывает пакет и возвращает причину в виде ошибки, например: icmp unreachable;
- LOG — просто делает запись в логе, если пакет соответствует критериям правила;
Есть действия, которые доступны только в определенной цепочке и таблицах, например, только в таблице nat и цепочках OUTPUT и PREROUTING доступно действие DNAT, которое используется в NAT’ировании и меняет Destination IP пакета. В той же таблице, только в цепочке POSTRUNNING доступно действие SNAT, меняющее Source IP пакета.
Отдельно остановимся на действии MASQUERADE, которое делает то же самое что SNAT, только применяется на выходном интерфейсе, когда IP адрес может меняться, например, когда назначается по DHCP.
Реализация iptables в OpenWrt
Ключевое отличие — это добавление понятия зон. Зоны не могут быть использованы для конкретных сетей (подсетей), но генерируемые правила iptables работают исключительно с пакетами на интерфейсах. Минимальная конфигурация файрвола состоит из одной из секций defaults, в котрой как минимум 2 зоны ( lan и wan ) и одно forwarding , что разрешить трафик из lan в wan .
Внимание ! Маскирование задаётся на интерфейсе, из которого замаскированный трафик будет исходить.
Для зоны также есть правила:
правило INPUT для зоны описывает, что произойдёт с трафиком, входящим в роутер через интерфейсы этой зоны.
правило OUTPUT для зоны описывает, что произойдёт с трафиком, исходящим от самого роутера через интерфейсы этой зоны.
правило FORWARD для зоны описывает, что произойдёт с трафиком, проходящим между различными интерфейсами внутри этой зоны.
Цепочку FORWARD проходят ВСЕ пакеты, которые движутся через наш firewall/роутер. Не используйте цепочку INPUT для фильтрации транзитных пакетов, они туда просто не попадают! Через эту цепочку движутся только те пакеты, которые предназначены данному хосту.
Секция forwarding контролирует прохождение трафика между зонами и позволяет включить MSS clamping для отдельных адресов назначений (destination). В одном правиле forwarding можно указать только одно назначение. Чтобы разрешить трафик в обе стороны между зонами необходимо создать два forwardings с src и dest в каждом.
Именно поэтому в таблице Filter для зон присутствуют отдельные цепочки. Эти цепочки применяются при передачи трафика между зонами. Иначе говоря, обычный трафик от клиента в Интернет и обратно не попадает в эти цепочки, он виден только в базовой цепочке FORWARD, потому что хостом назначения не является ни интерфейс lan роутера, ни wan. При необходимости, цепочка FORWARD передает обработку в цепочки zone_lan_forward, zone_wan_forward, zone_uplink_forward.
Посмотрим на цепочки зон. Например, для lan имеются: Chain zone_lan_dest_ACCEPT, Chain zone_lan_forward, Chain zone_lan_input, Chain zone_lan_output, Chain zone_lan_src_ACCEPT. Такие же цепочки есть и для других зон, например, для wan. Как видно из скриншота, все, что попадает в цепочку по правилу input_lan_rule, пересылается в цепочку zone_lan_input, где принимается (ACCEPT). А маршрутизируемый трафик из цепочки zone_lan_forward передается в цепочки зон wan и uplink (это моя кастомная зона).
Зона zone_wan_dest — это те пакеты, которые адресованы непосредственно интерфейсу wan (10.54.192.1 в данном случае), а не в интернет.
Как трафик попадает в эти цепочки? Ну допустим, вы обращаетесь к роутеру самому или делаете трассировку трафика, когда на каждом хопе destination’ом у вас являются разные хосты. На скриншоте мы сначала попадаем в lan интерфейс (192.168.2.1) на первом хопе, а потом в wan (10.54.192.1) на втором:
Также в OpenWrt присутствуют и таблицы NAT с цепочками PREROUTING, POSTROUTING и цепочками пре- и построутинга между зонами. маскарадинг осуществляется непосредственно на цепочка построутинга зон.
Настройка файрвола OpenWrt
Общие настройки зон находятся в разделе UCI: Network -> Firewall -> General Settings:
Пересадресация портов (Port forwardings, DNAT) определяются в секции redirect . Весь входящий трафик в указанной source зоне, который подпадает под правила, будет направлен на указанный внутренний хост. Переадресация портов также известна как маппинг портов, port forwarding и virtual servers в других роутерах.
Настройка маппинга портов выпоняется в UCI в разделе Network -> Firewall -> Port Forward. По умолчанию там пусто.
Дополнительные правила вы можете посмотреть и добавить в Network -> Firewall -> Traffic Rules. Здесь, например, настраиваются правила для ICMP и IPSec трафика.
[Посещений: 4 851, из них сегодня: 1]
Block LAN-side access to a specific site
If the source or destination is the router itself then the option is not explicitly defined in a rule. For reference, these rules are added to the netfilter INPUT (to the router) and OUTPUT (from the router) chains.
This rule causes netfilter to reject any icmp echo from the router (OUTPUT chain) to the public google DNS server. This rule is not particularly useful but serves as an illustrative example.
Задача
Есть в 2 роутера, один в сети 192.168.1.0/24, другой — 192.168.2.0/24, необходимо их соединить и настроить маршрутизацию меду ними. Оба роутера TP-Link, один с заводской прошивкой (192.168.1.1), другой на OpenWrt 18.06 (192.168.2.1). Необходимо соединить сети, но обеспечить независимое подключение к Интернет пользователей из двух сетей.
Исходная информация: eth0 — встроенный свитч в OpenWrt; eth0.1 — порты, свитча, относящиеся к VLAN 1, eth0.2 — порты, свитча, относящиеся к VLAN 2,
IP sets
fw3 supports referencing or creating IP sets to simplify matching of large address or port lists without the need for creating one rule per item to match.
This needs the kmod-ipt-ipset kernel module installed.
Options
Name | Type | Required | Default | Description |
---|---|---|---|---|
enabled | boolean | no | 1 | Allows to disable the declaration of the ipset without the need to delete the section. |
external | string | no | (none) | If the external option is set to a name, the firewall will simply reference an already existing ipset pointed to by the name. If the external option is unset, the firewall will create the ipset on start and destroy it on stop. |
name | string | yes if external is unset no if external is set | (none) if external is unset value of external if external is set | Specifies the firewall internal name of the ipset which is used to reference the set in rules or redirects. |
family | string | no | ipv4 | Protocol family ( ipv4 or ipv6 ) to create ipset for. Only applicable to storage types hash and list , the bitmap type implies ipv4 . |
storage | string | no | varies | Specifies the storage method ( bitmap , hash or list ) used by the ipset, the default varies depending on the used datatypes (see match option below). In most cases the storage method can be automatically inferred from the datatype combination but in some cases multiple choices are possible (e.g. bitmap:ip vs. hash:ip ). |
match | list of direction/type tuples | yes | (none) | Specifies the matched data types ( ip , port , mac , net or set ) and their direction ( src or dest ). The direction is joined with the datatype by an underscore to form a tuple, e.g. src_port to match source ports or dest_net to match destination CIDR ranges. When using ipsets matching on multiple elements, e.g. hash:ip,port , specify the packet fields to match on in quotes or comma-separated (i.e. “match dest_ip dest_port”). |
iprange | IP range | yes for storage type bitmap with datatype ip | (none) | Specifies the IP range to cover, see ipset(8). Only applicable to the hash storage type. |
portrange | Port range | yes for storage type bitmap with datatype port | (none) | Specifies the port range to cover, see ipset(8). Only applicable to the hash storage type. |
netmask | integer | no | 32 | If specified, network addresses will be stored in the set instead of IP host addresses. Value must be between 1 and 32 , see ipset(8). Only applicable to the bitmap storage type with match ip or the hash storage type with match ip . |
maxelem | integer | no | 65536 | Limits the number of items that can be added to the set, only applicable to the hash and list storage types. |
hashsize | integer | no | 1024 | Specifies the initial hash size of the set, only applicable to the hash storage type. |
timeout | integer | no | 0 | Specifies the default timeout for entries added to the set. A value of 0 means no timeout. |
entry | setentry | no | ||
loadfile | string | no |
Storage / Match Options
The order of datatype matches is significant
Family | Storage | Match | Notes |
---|---|---|---|
ipv4 | bitmap | ip | Requires iprange option |
ipv4 | bitmap | ip mac | Requires iprange option |
ipv4 | bitmap | port | Requires portrange option |
any | hash | ip | - |
any | hash | net | - |
any | hash | ip port | - |
any | hash | net port | - |
any | hash | ip port ip | - |
any | hash | ip port net | - |
- | list | set | Meta type to create a set-of-sets |
Zones
правило INPUT для зоны описывает, что произойдёт с трафиком, входящим в роутер через интерфейсы этой зоны.
правило OUTPUT для зоны описывает, что произойдёт с трафиком, исходящим от самого роутера через интерфейсы этой зоны.
правило FORWARD для зоны описывает, что произойдёт с трафиком, проходящим между различными интерфейсами внутри этой зоны.
Ниже представлены параметры, используемые в секции zone :
Zone declaration for a specific subnet and protocol
This example declares a zone which maches any TCP stream in the 10.21.0.0/16 subnet.
Redirects
Port forwardings (DNAT) are defined by redirect sections. Port Redirects are also commonly known as “port forwarding” or “virtual servers”.
All incoming traffic on the specified source zone which matches the given rules will be directed to the specified internal host.
Destination NAT
If a src_dport is not included in the config section, packets matching the other config options, on any port, will be forwarded to the destination port specified in that config section. This could pose a security risk to the application running on the destination port the config section opens. One way to test for this issue, is to use Gibson Research Corporation's ShieldsUP! service, and probe the desired ports on your router. The response could be open, closed, or stealth (drop). In cases of open or closed ports, packets are reaching a destination host, and are sending ack/reply packets back. Whereas stealthed ports drop packets; from the perspective of the probing system (Gibson Research), that system cannot definitively know if those packets may, or may not be reaching the destination host.
Source NAT
Masquerade is the most common form of SNAT, changing the source of traffic to WAN to the router's public IP . SNAT can also be done manually:
Options
Config sections
Below is an overview of the section types that may be defined in the firewall configuration.
A minimal firewall configuration for a router usually consists of one defaults section, at least two zones ( lan and wan ), and one forwarding to allow traffic from lan to wan .
The forwarding section is not strictly required when there are no more than two zones, as the rule can then be set as the 'global default' for that zone.
Using ipset to block LAN-side networks
The example below creates a rule in the netfilter FORWARD chain, rejecting traffic from the LAN -side to the WAN -side on the ports 1000-1100.
Defaults
The defaults section declares global firewall settings which do not belong to specific zones:
Options
Opening ports for selected subnet/host
Use src_ip and dest_ip options to match on specific subnets.
Задача
Есть в 2 роутера, один в сети 192.168.1.0/24, другой — 192.168.2.0/24, необходимо их соединить и настроить маршрутизацию меду ними. Оба роутера TP-Link, один с заводской прошивкой (192.168.1.1), другой на OpenWrt 18.06 (192.168.2.1). Необходимо соединить сети, но обеспечить независимое подключение к Интернет пользователей из двух сетей.
Исходная информация: eth0 — встроенный свитч в OpenWrt; eth0.1 — порты, свитча, относящиеся к VLAN 1, eth0.2 — порты, свитча, относящиеся к VLAN 2,
Значения "по-умолчанию"
Секция defaults 12) определяет глобальные установки файрвола, которые не принадлежат каким-либо конкретным зонам. В этой секции определяются следующие опции:
Секции
Ниже обзор типов секций которые могут быть определены в конфигурации файрволла. Минимальная конфигурация файрволла A minimal firewall configuration for a router usually consists of one defaults section, at least two zones ( lan and wan ) and one forwarding to allow traffic from lan to wan . (The forwarding section is not strictly required when there are no more than two zones as the rule can then be set as the 'global default' for that zone.)
Zones
A zone section groups one or more interfaces and serves as a source or destination for forwardings, rules and redirects.
INPUT rules for a zone describe what happens to traffic trying to reach the router itself through an interface in that zone.
OUTPUT rules for a zone describe what happens to traffic originating from the router itself going through an interface in that zone.
FORWARD rules for a zone describe what happens to traffic passing between different interfaces belonging in the same zone.
Options
Name | Type | Required | Default | Description |
---|---|---|---|---|
name | zone name | yes | (none) | Unique zone name. 11 characters is the maximum working firewall zone name length. |
network | list | no | (none) | List of interfaces attached to this zone. If omitted and neither extra* options, subnets nor devices are given, the value of name is used by default. Alias interfaces defined in the network config cannot be used as valid 'standalone' networks. Use list syntax. |
masq | boolean | no | 0 | Specifies whether outgoing zone traffic should be masqueraded. This is typically enabled on the wan zone. |
masq_src | list of subnets | no | 0.0.0.0/0 | Limit masquerading to the given source subnets. Negation is possible by prefixing the subnet with ! ; multiple subnets are allowed. |
masq_dest | list of subnets | no | 0.0.0.0/0 | Limit masquerading to the given destination subnets. Negation is possible by prefixing the subnet with ! ; multiple subnets are allowed. |
masq_allow_invalid | boolean | no | 0 | Do not add DROP INVALID rules, if masquerading is used. The DROP rules are supposed to prevent NAT leakage (see commit in firewall3). |
mtu_fix | boolean | no | 0 | Enable MSS clamping for outgoing zone traffic. |
input | string | no | DROP | Default policy ( ACCEPT , REJECT , DROP ) for incoming zone traffic. |
forward | string | no | DROP | Default policy ( ACCEPT , REJECT , DROP ) for forwarded zone traffic. |
output | string | no | DROP | Default policy ( ACCEPT , REJECT , DROP ) for outgoing zone traffic. |
family | string | no | any | The protocol family ( ipv4 , ipv6 or any ) these iptables rules are for. Defaults to any , but automatically degrades to ipv4 or ipv6 if respective addresses are listed in the same section. |
log | int | no | 0 | Bit field to enable logging in the filter and/or mangle tables, bit 0 = filter, bit 1 = mangle. (Since r6397-7cc9914aae) |
log_limit | string | no | 10/minute | Limits the amount of log messages per interval. |
device | list | no | (none) | List of L3 network interface names attached to this zone, e.g. tun+ or ppp+ to match any TUN or PPP interface. This is specifically suitable for undeclared interfaces which lack built-in netifd support such as OpenVPN. Otherwise network is preferable and device should be avoided. |
subnet | list | no | (none) | List of IP subnets attached to this zone. |
extra | string | no | (none) | Extra arguments passed directly to iptables. Note that these options are passed to both source and destination classification rules, therefor direction-specific options like --dport should not be used here - in this case the extra_src and extra_dest options should be used instead. |
extra_src | string | no | Value of extra | Extra arguments passed directly to iptables for source classification rules. |
extra_dest | string | no | Value of extra | Extra arguments passed directly to iptables for destination classification rules. |
custom_chains | bool | no | 1 | Enable generation of custom rule chain hooks for user generated rules. Has no effect if disabled (0) in the defaults section (see above). |
enabled | bool | no | yes | if set to 0 , zone is disabled |
auto_helper | bool | no | 1 for non-masq zone | Add CT helpers for zone |
helper | cthelper | no | (none) | List of helpers to add to zone |
Block access to the Internet for a specific LAN station between certain times
The following rule can be used for parental access control.
These time/date matches use the netfilter xt_time kernel module, which is included in the release. Check /proc/modules to confirm it is loaded.
From LuCI this rule can be added by following “Firewall→Traffic Rules” and creating a new rule with the desired MAC address and an action of “block” or “reject.”
Remove the time and day options to always block WAN -side access for the station.
This rule can be created for a single MAC address, not a range.
this type of rule is very useful for mobile devices like smartphones and tablets. A lot can change in a smartphone but the wifi MAC is almost always programmed at the factory. The MAC can be modified by a sophisticated user by doing something similar to the Linux commands:
Zone declaration for non-UCI interfaces
This example declares a zone which matches any Linux network device whose name begins with “ppp”.
Решение
Исходная информация: eth0 — встроенный свитч в OpenWrt; eth0.1 — порты, свитча, относящиеся к VLAN 1, eth0.2 — порты, свитча, относящиеся к VLAN 2. eth1 — WAN интерфейс.
- Подключаем роутер 192.168.2.1 через WAN порт к Интернет и патч-кордом порт LAN4 с любым LAN портом роутера 192.168.1.1. Не обязательно использовать порт LAN4, но в данном случае настройка будет показана на его примере.
- В роутере на OpenWrt идем в Network -> Switch. Создаем VLAN с ID 2 (кнопка Add). Настраиваем порт LAN 4 таким образом, чтобы он относился к VLAN 2:
- Идем Network -> Interfaces. Выбираем интерфейс LAN (br-lan), нажимаем Edit. Переключаемся на закладку Physical Settings. Там в разделе Interface выбираем только eth0.1 и Wireless network:
- Создаем новый интерфейс Network -> Interfaces -> Add new interface, называем его Uplink (или как угодно).
- Присваиваем новому интерфейсу IPv4 адрес 192.168.1.98 и IP gateway 192.168.1.1. Указываем DNS сервера из сети 192.168.1.0. На закладке Physical Settings указываем использование интерфейса eth0.2. Тем самым мы выносим данный порт в отдельный VLAN 2, который относится к подсети другого роутера.
- На закладке Firewall settings нового интерфейса создаем новую firewall zone, назовем её uplink.
- Идем в Network -> Firewall. В Zones напротив зоны lan нажимаем Edit и редактируем Inter-Zone Forwarding, разрешив форвард трафика из lan в uplink и из uplink в lan. Это действие создает цепочку zone_lan_forward и zone_uplink_forward в таблице Filter файрвола:
- К сожалению, этого недостаточно, потому что forward пакетов будет происходить, а трансляция адресов между разными сетями — нет. Для трансляции адресов необходимо включить маскарадинг. В Network -> Firewall в Zones напротив зоны lan и uplink ставим галку Masquerading:
- Идем в Status -> Routes и проверяем Active IPv4 -Routes. Мы должны увидеть, что сеть 192.168.2.0/24 идет через интерфейс lan, 192.168.1.0/24 через uplink, а 0.0.0.0/0 (то есть все другие адреса Интернет) через wan. Если мы дополнительно хотим машрутизировать доступ в интернет через первый роутер, то необходимо или настроить интерфейс uplink на динамический IP адрес — в этом случае первый роутер будет присваивать адрес интерфейсу uplink самостоятельно, а в OpenWrt динамический адрес приоритет, поэтому он будет пересылать весь трафик в первый роутер.
- Второй вариант — добавить статический маршрут на роутере OpenWrt для сети 0.0.0.0/0. Для этого идем в Network -> Static Routes создаем маршрут в сеть 0.0.0.0/0.
Уточню, что для разрешения неполных имен из домена, который находится в сети 192.168.1.0/24, необходимо настроить DNS. Для этого в разделе Network -> DHCP and DNS необходимо отключить Domain required, настроить Local domain и в DNS forwardings указать DNS сервер домена, имена из которого вы хотите разрешать с помощью доменного контроллера.
Альтернативный вариант — настроить использование DNS серверов домена в свойствах DHCP. Для этого в интерфейсе lan перейдите в Network -> Interfaces -> LAN -> Edit. В разделе DHCP server на закладке Advanced Settings в окне DHCP-Options укажите 6,192.168.1.1, где 6 — это 6-я опция, указывающая на альтернативные DNS сервера, а 192.168.1.1 — это DNS сервер в первой сети.
Для маршрутизации из первой сети во вторую на первом роутере также необходимо добавить маршрут. В заводской прошивке TP-link это делается в разделе Дополнительные настройки маршрутизации -> Список статических маршрутов. Добавляем маршрут:
[Посещений: 6 482, из них сегодня: 1]
This section contains a collection of useful firewall3 configuration examples based on the UCI configuration files. All of these can be added on the LuCI Network → Firewall → Traffic Rules page.
In keeping with the underlying netfilter service, the first matching rule will run its target and (with a couple of exceptions) filtering stops; no subsequent rules are checked. LuCI has the capability to move rules up and down to sort them correctly.
See Reference Network Topology for a visual representation of the network used to test the examples here. These examples cover only IPv4 networks.
The term station is used to refer to any electronic device that can source or sink packets through, or to/from, the router. This can be a web server, mobile phone, tablet, laptop, IoT device on the LAN -side or the WAN -side. The netfilter rules match stations and traffic types to allow packets to continue through the network stack or not.
Unless otherwise noted, all rules have been tested mostly with netcat and curl. The enabled option in each rule is toggled between tests to verify the specific rule causes the expected behavior - on will cause packets to be accepted or not, off will cause the opposite behavior.
Before modifying rules, be sure to back-up your current /etc/config/firewall !
Block access to certain domains based on their names
Forwardings
The forwarding sections control the traffic flow between zones and may enable MSS clamping for specific directions. Only one direction is covered by a forwarding rule. To allow bidirectional traffic flows between two zones, two forwardings are required, with src and dest reversed in each.
Below is a listing of allowed option within forwardings:
Name | Type | Required | Default | Description |
---|---|---|---|---|
src | zone name | yes | (none) | Specifies the traffic source zone. Must refer to one of the defined zone names |
dest | zone name | yes | (none) | Specifies the traffic destination zone. Must refer to one of the defined zone names |
mtu_fix | boolean | no | 0 | Enable MSS clamping for traffic flowing from the source zone to the destination zone (Deprecated and moved to zone sections in 8.09.2+) |
family | string | no | any | Protocol family ( ipv4 , ipv6 or any ) to generate iptables rules for. |
The iptables rules generated for this section rely on the state match which needs connection tracking to work. At least one of the src or dest zones needs to have connection tracking enabled through either the masq or the conntrack option.
Rules
Sections of the type rule can be used to define basic accept or reject rules to allow or restrict access to specific ports or hosts.
Up to Firewall v2, version 57 and below the rules behave like redirects and are tied to the given source zone and match incoming traffic occuring there.
In later versions the rules are defined as follows:
Введение
Для пакетной фильтрации, NAT и искажения пакетов (mangling, манглинг) OpenWrt использует netfilter. с Для упрощения настройки файрволл UCI предоставляет абстрагированный от подсистемы ядра iptables интерфейс конфигурации, что является вполне достаточным в большинстве случаев, но в то же время этот интерфейс сохраняет возможность пользователю - когда это необходимо - самостоятельно определить необходимые нестандартные правила iptables . Файрволл UCI отображает один и более интерфейсов 2) в специальные зоны 3) , которые используются для для описания правил по-умолчанию для данного интерфейса, правил пересылки пакетов между интерфейсами 4) , а также дополнительные правила, которые не подпадают под первые два типа. В конфигурационном файле правила по-умолчанию идут первыми, но вступают в силу последними. Система netfilter является системой фильтрации с последовательной 5) обработкой, в которой пакеты последовательно, по цепочке, обрабатываются различными правилами. Первое совпавшее 6) правило выполняется, но оно часто выполняет переход на другую цепочку правил, по которой движется пакет пока не встретит команды ACCEPT 7) или DROP/REJECT 8) . Правила с такими командами выполняются последними в цепочке правил, поэтому правила по-умолчанию вступят в силу последними, а более конкретные правила будут проверяться в первую очередь. Зоны также используются для конфигурации маскарадинга 9) , также известного как NAT 10) , а также для конфигурации правил переадресации портов, более известных как редирект 11) .
Зоны должны всегда отображаться на один или несколько интерфейсов, что в конечном счете приводит к их отображению на физическое устройство; поэтому зоны не могут быть использованы для конкретных сетей (подсетей), и генерируемые правила iptables работают исключительно с пакетами на интерфейсах. The difference is that interfaces can be used to reach destinations not part of their own subnet, when their subnet contains another gateway. Usually however, forwarding is done between lan and wan interfaces, with the router serving as 'edge' gateway to the internet. The default configuration of UCI Firewall provides for such a common setup.
Opening ports on the OpenWrt router
Command-line instructions
UCI is a low-level abstraction to the configuration files and can be accessed remotely through SSH.
These would be presumed to be the final rules (each proto creates a rule) in the VPN → LAN forward chain, as all packets from VPN will be rejected.
Show firewall configuration:
UCI is useful to view the firewall configuration, but not to do any meaningful modifications for the following reasons:
Essential prior knowledge of where a firewall rule needs to go into the rule array in order to make it work (similar to iptables -I )
uci commit is necessary to save the changes, but still needs /etc/init.d/firewall reload to reload new tables.
Stateful firewall without NAT
I have not tested this, but it seems reasonable.
To do this, add the conntrack option to the WAN zone:
- Last modified: 2021/12/05 05:35
- by vgaetera
Self-registration in the wiki has been disabled.
If you want to contribute to the OpenWrt wiki, please post HERE in the forum or ask on IRC for access.
Except where otherwise noted, content on this wiki is licensed under the following license:
CC Attribution-Share Alike 4.0 International
Конфигурация межсетевого экрана 1) находится в файле /etc/config/firewall .
Redirects
Port forwardings (DNAT) are defined by redirect sections. All incoming traffic on the specified source zone which matches the given rules will be directed to the specified internal host.
Redirects are also commonly known as “port forwarding”, and “virtual servers”.
The options below are valid for redirects:
Читайте также: