如何配置防火墙 - 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

相关文章

如何配置Spring Boot中的Jackson序列化

《如何配置SpringBoot中的Jackson序列化》在开发基于SpringBoot的应用程序时,Jackson是默认的JSON序列化和反序列化工具,本文将详细介绍如何在SpringBoot中配置... 目录配置Spring Boot中的Jackson序列化1. 为什么需要自定义Jackson配置?2.

鸿蒙中Axios数据请求的封装和配置方法

《鸿蒙中Axios数据请求的封装和配置方法》:本文主要介绍鸿蒙中Axios数据请求的封装和配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1.配置权限 应用级权限和系统级权限2.配置网络请求的代码3.下载在Entry中 下载AxIOS4.封装Htt

Spring中配置ContextLoaderListener方式

《Spring中配置ContextLoaderListener方式》:本文主要介绍Spring中配置ContextLoaderListener方式,具有很好的参考价值,希望对大家有所帮助,如有错误... 目录Spring中配置ContextLoaderLishttp://www.chinasem.cntene

浅谈配置MMCV环境,解决报错,版本不匹配问题

《浅谈配置MMCV环境,解决报错,版本不匹配问题》:本文主要介绍浅谈配置MMCV环境,解决报错,版本不匹配问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录配置MMCV环境,解决报错,版本不匹配错误示例正确示例总结配置MMCV环境,解决报错,版本不匹配在col

Nginx中配置HTTP/2协议的详细指南

《Nginx中配置HTTP/2协议的详细指南》HTTP/2是HTTP协议的下一代版本,旨在提高性能、减少延迟并优化现代网络环境中的通信效率,本文将为大家介绍Nginx配置HTTP/2协议想详细步骤,需... 目录一、HTTP/2 协议概述1.HTTP/22. HTTP/2 的核心特性3. HTTP/2 的优

Python 安装和配置flask, flask_cors的图文教程

《Python安装和配置flask,flask_cors的图文教程》:本文主要介绍Python安装和配置flask,flask_cors的图文教程,本文通过图文并茂的形式给大家介绍的非常详细,... 目录一.python安装:二,配置环境变量,三:检查Python安装和环境变量,四:安装flask和flas

SpringCloud动态配置注解@RefreshScope与@Component的深度解析

《SpringCloud动态配置注解@RefreshScope与@Component的深度解析》在现代微服务架构中,动态配置管理是一个关键需求,本文将为大家介绍SpringCloud中相关的注解@Re... 目录引言1. @RefreshScope 的作用与原理1.1 什么是 @RefreshScope1.

SpringBoot日志配置SLF4J和Logback的方法实现

《SpringBoot日志配置SLF4J和Logback的方法实现》日志记录是不可或缺的一部分,本文主要介绍了SpringBoot日志配置SLF4J和Logback的方法实现,文中通过示例代码介绍的非... 目录一、前言二、案例一:初识日志三、案例二:使用Lombok输出日志四、案例三:配置Logback一

springboot security之前后端分离配置方式

《springbootsecurity之前后端分离配置方式》:本文主要介绍springbootsecurity之前后端分离配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的... 目录前言自定义配置认证失败自定义处理登录相关接口匿名访问前置文章总结前言spring boot secu

一文详解SpringBoot响应压缩功能的配置与优化

《一文详解SpringBoot响应压缩功能的配置与优化》SpringBoot的响应压缩功能基于智能协商机制,需同时满足很多条件,本文主要为大家详细介绍了SpringBoot响应压缩功能的配置与优化,需... 目录一、核心工作机制1.1 自动协商触发条件1.2 压缩处理流程二、配置方案详解2.1 基础YAML