如何配置防火墙 - OpenWrt Wiki

2024-05-28 12:48
文章标签 配置 openwrt 防火墙 wiki

本文主要是介绍如何配置防火墙 - OpenWrt Wiki,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

如何配置防火墙
You are here:  OpenWrt Wiki ?  OpenWrt简体中文Wiki ?  文档 ?  UCI系统 ?  如何配置防火墙
?Table of Contents
  • 从软件包的角度看 Openwrt 的 iptables 是如何组织的
  • Sections
    • Defaults
    • Zones
    • 转发
    • 重定向
    • 规则
    • 包括
  • 举例
    • 开放端口
    • 端口转发(NAT/DNAT)
源NAT (SNAT)
    • 实际端口转发
    • 限制指定机器
    • 通过MAC限制访问互联网
    • 转发规则限制
    • 透明代理规则(同一主机)
    • 透明代理规则(外部)
    • 简单DMZ规则
    • IPSec passthrough
    • IPv6隧道转发
    • 关于 iptables 的规则文件
  • 防火墙管理
  • Hotplug hooks (8.09.2+)
  • Implications of DROP vs. REJECT
  • Note on connection tracking (NOTRACK)
    • 如何删除规则
  • 进一步学习
    • 如何理解 iptables/netfilter框架
    • 参考资料

----------------------------------------------------------------------------------------------------------------------

如何配置防火墙

     首先我们要明白,Openwrt 是一个 GNU/Linux 的发行版, 和其他大多数的发行版一样,Openwrt 的防火墙同样也是基于 iptables .

  其次,Openwrt支持两种途径配置 iptables ,一种就是 Openwrt 自己的 UCI 方式,另一种就是传统的 Linux 方式.

     本文要探讨的是如何通过 UCI 方式来配置 iptables , UCI 的方式就是通过配置 /etc/config/firewall 这个文件来完成的.

  至于传统的 Linux 方式,请参考篇文章,netfilter.

   

  firewall 文件的结构

   default  这是 firewall 文件的第一个小节 zone 可以有数个 zone , zone 又可以包含数个 networ interfaces  forwarding 位于的 zone 下面, 主要作用是允许数据封包的流动  rule 以及 redirect 可以看作是 zone 子集, 用来扩展进一步的封包限制.


从软件包的角度看 Openwrt 的 iptables 是如何组织的

  我们随便打开一个 Openwrt 的分支版本软件包下载页面,例如 http://downloads.openwrt.org//backfire/10.03.1/brcm63xx/packages/, 我们会发现有很多相关的软件包.

  • iptables_1.4.6-3.1_brcm63xx.ipk

   这个软件包是 iptables 本身,其实 iptables 早已被大多数官方打包好并公开发行的 firmware 之中.

  • kmod-ipt-*

   这个开头的软件包,是 kernel space 层级的模块 vanilla)

  • iptables-mod-*

   这种开头的软件包,是 user space 层级的模块,有一部分也被包含进官方打包好并公开发行的 firmware 之中. 比如 iptables-mod-nat_1.4.6-3.1_brcm63xx.ipk 这个软件就是为了提供基本的NAT功能,针对 SNAT DNAT MASQUERADE 这三个 Targets,以及针对 nat 这个 Tables 的.

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.

Defaults

The defaults section declares global firewall settings which do not belong to specific zones.The following options are defined within this section:

名称 类型 是否必需 缺省 描述
syn_flood boolean no 1 Enable SYN flood protection
drop_invalid boolean no 1 Drop packets not matching any active connection
disable_ipv6 boolean no 0 Disables IPv6 firewall rules if set to1 (Firewall v2 and later)
input string no DROP Default policy (ACCEPT, REJECT, DROP) for the INPUT chain
forward string no DROP Default policy (ACCEPT, REJECT, DROP) for the FORWARD chain
output string no DROP Default policy (ACCEPT, REJECT, DROP) for the OUTPUT chain

Zones

A zone section groups one more interfaces and serves as a source or destination for forwardingsrules and redirects. Masquerading (NAT) of outgoing traffic is controlled on a per-zone basis.

The options below are defined within zone sections:

名称 类型 是否必需 缺省 描述
name zone name yes (none) Unique zone name
network list no (none) List of interfaces attached to this zone, if ommitted, the value of nameis used by default
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. 
:!: Only supported by the Firewall v2 package, version 11 and above or Firewall v1, version 13 and above
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. 
:!: Only supported by the Firewall v2 package, version 11 and above or Firewall v1, version 13 and above
conntrack boolean no 1 if masquerading is used, 0 otherwise Force connection tracking for this zone (see Note on connection tracking)
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 Protocol family (ipv4, ipv6 or any) to generate iptables rules for.
:!: Only supported by the Firewall v2 package
log boolean no 0 Create log rules for rejected and dropped traffic in this zone. 
:!: Only supported by the Firewall v2 package, version 10 and above
log_limit string no 10/minute Limits the amount of log messages per interval. 
:!: Only supported by the Firewall v2 package, version 10 and above

转发

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:

名称 类型 是否必需 缺省 描述
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.
:!: Only supported by the Firewall v2 package

:!: 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.

重定向

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.

The options below are valid for redirects:

名称 类型 是否必需 缺省 描述
src zone name yes for DNAT target (none) Specifies the traffic source zone, must refer to one of the defined zone names. For typical port forwards this usually is wan
src_ip ip address no (none) Match incoming traffic from the specified source ip address
src_dip ip address yes for SNAT target (none) For DNAT, match incoming traffic directed at the given destination ip address. For SNAT rewrite the source address to the given address.
src_mac mac address no (none) Match incoming traffic from the specified mac address
src_port port or range no (none) Match incoming traffic originating from the given source port or port range on the client host
src_dport port or range no (none) For DNAT, match incoming traffic directed at the given destination port or port range on this host. For SNAT rewrite the source ports to the given value.
proto protocol name or number yes tcpudp Match incoming traffic using the givenprotocol
dest zone name yes for SNAT target (none) Specifies the traffic destination zone, must refer to one of the defined zone names.
dest_ip ip address yes for DNAT target (none) For DNAT, redirect matched incoming traffic to the specified internal host. For SNAT, match traffic directed at the given address.
dest_port port or range no (none) For DNAT, redirect matched incoming traffic to the given port on the internal host. For SNAT, match traffic directed at the given ports.
target string no DNAT NAT target (DNAT or SNAT) to use when generating the rule
:!: Only supported by the Firewall v2, version 12 and above or Firewall v1, version 15 and above
family string no any Protocol family (ipv4, ipv6 or any) to generate iptables rules for.
:!: Only supported by the Firewall v2 package
reflection boolean no 1 Disables NAT reflection for this redirect if set to 0 - applicable to DNAT targets.
:!: Only supported by the Firewall v2, version 11 and above or Firewall v1, version 13 and above

规则

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. Like redirects the rules are tied to the given source zone and match incoming traffic occuring there.

Valid options for this section are:

名称 类型 是否必需 缺省 描述
src zone name yes (none) Specifies the traffic source zone, must refer to one of the defined zone names.
src_ip ip address no (none) Match incoming traffic from the specified source ip address
src_mac mac address no (none) Match incoming traffic from the specified mac address
src_port port or range no (none) Match incoming traffic originating from the given source port or port range on the client host if tcp or udp is specified as protocol
proto protocol name or number no tcpudp Match incoming traffic using the given protocol. Can be one of tcp, udp, tcpudp, udplite, icmp, esp, ah, sctp, orall 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. The number 0 is equivalent to all.
dest zone name no (none) Specifies the traffic destination zone, must refer to one of the defined zone names. If specified, the rule applies to forwarded traffic else it is treated as input rule.
dest_ip ip address no (none) Match incoming traffic directed to the specified destination ip address
dest_port port or range no (none) Match incoming traffic directed at the given destination port or port range on this host if tcp or udp is specified as protocol
target string yes DROP Firewall action (ACCEPT, REJECT, DROP) for matched traffic
family string no any Protocol family (ipv4, ipv6 or any) to generate iptables rules for.
:!: Only supported by the Firewall v2 package

包括

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:

名称 类型 是否必需 缺省 描述
path file name yes /etc/firewall.user Specifies a shell script to execute on boot or firewall restarts

Included scripts may contain arbitary commands, for example advanced iptables rules or tc commands required for traffic shaping.

:!: When writing custom iptables rules remember to use -I (insert) instead of -A (append) to ensure that the created rules appear before the generic ones.


举例

开放端口

The default configuration accepts all LAN traffic, but blocks all incoming WAN traffic on ports not currently used for connections or NAT. To open a port for a service, add a rule section:

config rule        
   option src              wan        
   option dest_port        22        
   option target           ACCEPT        
   option proto            tcp

This example enables machines on the internet to use SSH to access your router.


端口转发(NAT/DNAT)

This example forwards http (but not HTTPS) traffic to the webserver running on 192.168.1.10:

config redirect        
    option src       wan        
    option src_dport 80        
    option proto     tcp        
    option dest_ip   192.168.1.10


源NAT (SNAT)

Source NAT changes an outgoing packet outgoing packet destined for the system so that is looks as though the system is the source of the packet.

Define source NAT for UDP and TCP traffic directed to port 123 originating from the host with the IP address 10.55.34.85.The source address is rewritten to 63.240.161.99.

config redirect        
    option src              lan        
    option dest             wan        
    option src_ip           10.55.34.85        
    option src_dip          63.240.161.99        
    option dest_port        123        
    option target           SNAT


When used alone, Source NAT is used to restrict a computer's access to the internet, but allow a it to access a few services my manually forwarding what appear to be a few local services, e.g. NTP to the internet. While DNAT hides the local network from the internet, SNAT hides the internet from the local network.

Source NAT and destination NAT are combined and used dynamically in IP masquerading to make computers with private (192.168.x.x, etc.) IP address to appear on the internet with the system's public WAN ip address.


实际端口转发

Most users won't want this. It's usage is similar to SNAT, but as the the destination IP address isn't changed, machines on the destination network need to be aware that they'll receive and answer requests from a public IP address that isn't necessarily theirs. Port forwarding in this fashion is typically used for load balancing.

config redirect        
    option src              wan        
    option src_dport        80        
    option dest             lan        
    option dest_port        80        
    option proto            tcp


限制指定机器

The following rule blocks all connection attempts to the specified host address.

config rule        
    option src              lan       
    option dest             wan        
    option dest_ip          123.45.67.89        
    option target           REJECT


通过MAC限制访问互联网

The following rule blocks all connection attempts from the client to the Internet.

config rule        
     option src              lan        
     option dest             wan        
     option src_mac          00:00:00:00:00        
     option target           REJECT


转发规则限制

The example below creates a forward rule rejecting traffic from lan to wan on the ports 1000-1100.

config rule        
     option src              lan        
     option dest             wan        
     option dest_port        1000-1100        
     option proto            tcpudp        
     option target           REJECT


透明代理规则(同一主机)

The rule below redirects all outgoing HTTP traffic from lan through a proxy server listening at port 3128 on the router itself.

config redirect	
     option src              lan	
     option proto            tcp	
     option src_dport        80	
     option dest_port        3128


透明代理规则(外部)

The following rule redirects all outgoing HTTP traffic from lan through an external proxy at 192.168.1.100 listening on port 3128.

config redirect        
     option src              lan        
     option proto            tcp        
     option src_ip           !192.168.1.100        
     option src_dport        80        
     option dest_ip          192.168.1.100        
     option dest_port        3128


简单DMZ规则

The following rule redirects all WAN ports for all protocols to the internal host 192.168.1.2.

config redirect	
    option src              wan	
    option proto            all	
    option dest_ip          192.168.1.2


IPSec passthrough

This example enables proper forwarding of IPSec traffic through the wan.

# AH protocol
config rule        
    option src              wan        
    option dest             lan        
    option proto            ah        
    option target           ACCEPT# ESP protocolconfig rule        
    option src              wan        
    option dest             lan        
    option proto            esp        
    option target           ACCEPT


For some configurations you also have to open port 500/UDP.


# ISAKMP protocol
config rule        
    option src              wan        
    option dest             lan        
    option proto            udp        
    option src_port         500        
    option dest_port        500        
    option target           ACCEPT


IPv6隧道转发

:!: This example is for IPv6 tunnels only, and does not apply to native dual-stack interfaces.
:!: This example only applies to the firewall v2 package and later (only in Trunk, not yet in Backfire).

In order to be able to address the IPv6 tunnel interface with uci firewall rules, you need to cover it in the network configuration first.Assuming an established SixXs tunnel, the example below declares a logical interfacewan6 on top of the sixxs tunnel interface:

config interface wan6	
    option proto            none	
    option ifname           sixxs


IPv6 packets are by default not forwarded from lan to your wan6 interface, make sure to add net.ipv6.conf.all.forwarding=1 in /etc/sysctl.conf to enable it per名称nently.Add the following sections to the firewall config to cover the wan6 interface:

config zone	
    option name             wan6	
    option input            REJECT	
    option output           ACCEPT	
    option forward          REJECT	
    option family           ipv6	
    option mtu_fix          0config forwarding	
    option src              lan	 
    option dest             wan6


The family option ensures that the zone and all associated entries (rule, forwarding and redirect sections) are only added to ip6tables but not iptables.


关于 iptables 的规则文件

传统的 iptables 规则, 是指在 Shell 命令行模式下指定一个包含规则定义的外部文件, 其实可以在本配置文件中, 指定多个配置文件, 如下:

config include       
     option path /etc/firewall.userconfig include       
     option path /etc/firewall.vpn


需要注意的是, Openwrt 是以 UCI 方式来配置 iptables 的, 这与传统的 Linux 习惯是不一样的, 上面那两个指定的配置文件, 里面包含的规则写法必须与传统的 Linux 习惯一样. 那么如何配置上面那两个规则文件呢,请参考这篇文章 → netfilter.


防火墙管理

After a configuration change, firewall rules are rebuilt by executing /etc/init.d/firewall restart; calling /etc/init.d/firewall stop will flush all rules and set the policies to ACCEPT on all standard chains.To manually start the firewall, call /etc/init.d/firewall start.

The firewall can be permananently disabled by executing /etc/init.d/firewall disable.Note that disable does not flush the rules, so it might be required to issue a stop before.Use enable to activate the firewall again.

Hotplug hooks (8.09.2+)

In addition to includes it is possible to let the firewall execute hotplug handlers when interfaces are added to a zone or removed from it. This is useful to create rules for interfaces with dynamic ip configurations (dhcp, pppoe) on the fly.

Each time an interface is added or removed from a zone, all scripts in the /etc/hotplug.d/firewall/ directory are executed. Scripts must be named in the form NN-name with NN being a numeric index between 00 and 99. The name can be freely choosen.

Once a handler script is invoked, the informations about the event are passed through the environment.The table below lists defined variables and their meaning.

变量 描述
ACTION Type of the event, add if an interface was added, remove if it was removed
ZONE Name of the frewall zone the interface was added to
INTERFACE OpenWrt name of the interface, for example "lan" or "wan" - corresponds to the interfaces defined in /etc/config/network
DEVICE The physical interface involved, for example "eth0" or "ppp0"

Implications of DROP vs. REJECT

The decision whether to drop or to reject traffic should be done on a case-by-case basis. Many people see dropping traffic as a security advantage over rejecting it because it exposes less information to a hypothetical attacker.While dropping slightly increases security, it can also complicate the debugging of network issues or cause unwanted side-effects on client programs.

If traffic is rejected, the router will respond with an icmp error message ("destination port unreachable") causing the connection attempt to fail immediately. This also means that for each connection attempt a certain amount of response traffic is generated. This can actually harm if the firewall is "attacked" with many simultanous connection attempts, the resulting "backfire" of icmp responses can clog up all available upload and make the connection unusable (DoS).

When connection attempts are droppped the client is not aware of the blocking and will continue to re-transmit its packets until the connection eventually times out. Depending on the way the client software is implemented, this could result in frozen or hanging programs that need to wait until a timeout occurs before they're able to continue.

DROP

  • less information is exposed
  • less attack surface
  • client software may not cope well with it (hangs until connection times out)
  • may complicate network debugging (where was traffic dropped and why)

REJECT

  • may expose information (like the ip at which traffic was actually blocked)
  • client software can recover faster from rejected connection attempts
  • network debugging easier (routing and firewall issues clearly distinguishable)

Note on connection tracking (NOTRACK)

By default, the firewall will disable connection tracking for a zone if no masquerading is enabled. This is achieved by generating NOTRACKfirewall rules matching all traffic passing via interfaces referenced by the firewall zone. The purpose of NOTRACK is to speed up routing and save memory by circumventing resource intensive connection tracking in cases where it is not needed. You can check if connection tracking is disabled by issuing iptables -t raw -vnL, it will list all rules, check for NOTRACK target.

:!:NOTRACK will render certain ipables extensions unusable, for example the MASQUERADE target or the state match will not work!

If connection tracking is required, for example by custom rules in /etc/firewall.user, the conntrack option must be enabled in the corresponding zone to disable NOTRACK. It should appear as option 'conntrack' '1' in the right zone in /etc/config/firewall.For further information see http://security.maruhn.com/iptables-tutorial/x4772.html .

如何删除规则

If you make a mistake you can delete a rule this way. First, issue this command:


# iptables -L -t raw --line-numbers


Now to delete, e.g. the third rule from chain OUTPUTexecute:


# iptables -t raw -D OUTPUT 3


进一步学习

如何理解 iptables/netfilter框架

参考资料

1. http://www.netfilter.org/
  netfilter框架的官方主页

2. http://zh.wikipedia.org/zh/TCP/IP%E5%8D%8F%E8%AE%AE
  整个互联网的网络协议都以 TCP/IP 为基础,对这个协议簇有一般浅层的了解,会有助于掌握 iptables.



这篇关于如何配置防火墙 - OpenWrt Wiki的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1010611

相关文章

SpringBoot3.4配置校验新特性的用法详解

《SpringBoot3.4配置校验新特性的用法详解》SpringBoot3.4对配置校验支持进行了全面升级,这篇文章为大家详细介绍了一下它们的具体使用,文中的示例代码讲解详细,感兴趣的小伙伴可以参考... 目录基本用法示例定义配置类配置 application.yml注入使用嵌套对象与集合元素深度校验开发

IntelliJ IDEA 中配置 Spring MVC 环境的详细步骤及问题解决

《IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决》:本文主要介绍IntelliJIDEA中配置SpringMVC环境的详细步骤及问题解决,本文分步骤结合实例给大... 目录步骤 1:创建 Maven Web 项目步骤 2:添加 Spring MVC 依赖1、保存后执行2、将新的依赖

SpringBoot基于配置实现短信服务策略的动态切换

《SpringBoot基于配置实现短信服务策略的动态切换》这篇文章主要为大家详细介绍了SpringBoot在接入多个短信服务商(如阿里云、腾讯云、华为云)后,如何根据配置或环境切换使用不同的服务商,需... 目录目标功能示例配置(application.yml)配置类绑定短信发送策略接口示例:阿里云 & 腾

如何为Yarn配置国内源的详细教程

《如何为Yarn配置国内源的详细教程》在使用Yarn进行项目开发时,由于网络原因,直接使用官方源可能会导致下载速度慢或连接失败,配置国内源可以显著提高包的下载速度和稳定性,本文将详细介绍如何为Yarn... 目录一、查询当前使用的镜像源二、设置国内源1. 设置为淘宝镜像源2. 设置为其他国内源三、还原为官方

CentOS7更改默认SSH端口与配置指南

《CentOS7更改默认SSH端口与配置指南》SSH是Linux服务器远程管理的核心工具,其默认监听端口为22,由于端口22众所周知,这也使得服务器容易受到自动化扫描和暴力破解攻击,本文将系统性地介绍... 目录引言为什么要更改 SSH 默认端口?步骤详解:如何更改 Centos 7 的 SSH 默认端口1

Maven的使用和配置国内源的保姆级教程

《Maven的使用和配置国内源的保姆级教程》Maven是⼀个项目管理工具,基于POM(ProjectObjectModel,项目对象模型)的概念,Maven可以通过一小段描述信息来管理项目的构建,报告... 目录1. 什么是Maven?2.创建⼀个Maven项目3.Maven 核心功能4.使用Maven H

SpringBoot多数据源配置完整指南

《SpringBoot多数据源配置完整指南》在复杂的企业应用中,经常需要连接多个数据库,SpringBoot提供了灵活的多数据源配置方式,以下是详细的实现方案,需要的朋友可以参考下... 目录一、基础多数据源配置1. 添加依赖2. 配置多个数据源3. 配置数据源Bean二、JPA多数据源配置1. 配置主数据

Spring 基于XML配置 bean管理 Bean-IOC的方法

《Spring基于XML配置bean管理Bean-IOC的方法》:本文主要介绍Spring基于XML配置bean管理Bean-IOC的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录一. spring学习的核心内容二. 基于 XML 配置 bean1. 通过类型来获取 bean2. 通过

如何使用Nginx配置将80端口重定向到443端口

《如何使用Nginx配置将80端口重定向到443端口》这篇文章主要为大家详细介绍了如何将Nginx配置为将HTTP(80端口)请求重定向到HTTPS(443端口),文中的示例代码讲解详细,有需要的小伙... 目录1. 创建或编辑Nginx配置文件2. 配置HTTP重定向到HTTPS3. 配置HTTPS服务器

SpringBoot中配置Redis连接池的完整指南

《SpringBoot中配置Redis连接池的完整指南》这篇文章主要为大家详细介绍了SpringBoot中配置Redis连接池的完整指南,文中的示例代码讲解详细,具有一定的借鉴价值,感兴趣的小伙伴可以... 目录一、添加依赖二、配置 Redis 连接池三、测试 Redis 操作四、完整示例代码(一)pom.