MikroTik RouterOS 防火墙规则配置实战指南
本文详细介绍MikroTik RouterOS防火墙的核心概念与实战配置方法,包括Filter规则链、NAT配置、连接跟踪等关键知识点,帮助网络管理员快速掌握RouterOS防火墙的使用技巧,提升网络安全防护能力。
# MikroTik RouterOS 防火墙规则配置实战指南
MikroTik RouterOS 是一款功能强大的路由器操作系统,其内置的防火墙模块基于 Linux netfilter 框架,提供了灵活且高效的网络流量控制能力。本文将从基础概念出发,结合实际场景,带你掌握 RouterOS 防火墙的核心配置方法。
## 一、防火墙基础概念
RouterOS 防火墙主要由以下几个部分组成:
- **Filter 规则**:用于允许或拒绝数据包通过
- **NAT 规则**:用于网络地址转换(源NAT/目标NAT)
- **Mangle 规则**:用于标记和修改数据包
- **连接跟踪(Connection Tracking)**:追踪网络连接状态
### 规则链(Chain)
Filter 防火墙有三条默认规则链:
| 规则链 | 说明 |
|--------|------|
| input | 处理目标为路由器本身的数据包 |
| forward | 处理经过路由器转发的数据包 |
| output | 处理由路由器本身发出的数据包 |
## 二、基础防火墙配置
### 2.1 允许已建立的连接
```bash
/ip firewall filter
add chain=input connection-state=established,related action=accept comment="允许已建立连接"
add chain=forward connection-state=established,related action=accept comment="允许转发已建立连接"
```
### 2.2 丢弃无效连接
```bash
/ip firewall filter
add chain=input connection-state=invalid action=drop comment="丢弃无效连接"
add chain=forward connection-state=invalid action=drop comment="丢弃无效转发连接"
```
### 2.3 允许本地回环
```bash
/ip firewall filter
add chain=input in-interface=lo action=accept comment="允许本地回环"
```
## 三、保护路由器管理端口
为防止暴力破解,建议限制管理端口的访问来源:
```bash
/ip firewall filter
add chain=input protocol=tcp dst-port=22 src-address-list=admin_ips action=accept comment="允许SSH管理"
add chain=input protocol=tcp dst-port=8291 src-address-list=admin_ips action=accept comment="允许Winbox管理"
add chain=input protocol=tcp dst-port=22,8291 action=drop comment="拒绝其他SSH和Winbox访问"
```
定义管理员IP列表:
```bash
/ip firewall address-list
add list=admin_ips address=192.168.1.0/24 comment="内网管理段"
```
## 四、NAT 配置
### 4.1 源NAT(Masquerade)
让内网设备通过路由器访问互联网:
```bash
/ip firewall nat
add chain=srcnat out-interface=ether1 action=masquerade comment="内网访问互联网"
```
### 4.2 目标NAT(端口转发)
将外网访问转发到内网服务器:
```bash
/ip firewall nat
add chain=dstnat protocol=tcp dst-port=80 action=dst-nat to-addresses=192.168.1.100 to-ports=80 comment="转发HTTP到内网服务器"
```
## 五、防DDoS基础配置
```bash
/ip firewall filter
add chain=input protocol=tcp connection-limit=100,32 action=drop comment="限制单IP连接数"
add chain=input protocol=icmp limit=50,5:packet action=accept comment="限制ICMP速率"
add chain=input protocol=icmp action=drop comment="丢弃超限ICMP"
```
## 六、最终默认拒绝规则
所有规则的最后,添加默认拒绝规则:
```bash
/ip firewall filter
add chain=input action=drop comment="默认拒绝所有input"
add chain=forward action=drop comment="默认拒绝所有forward"
```
## 七、验证与调试
使用以下命令查看防火墙规则命中情况:
```bash
/ip firewall filter print stats
```
查看连接跟踪表:
```bash
/ip firewall connection print
```
## 总结
RouterOS 防火墙配置的核心原则是:**先放行已知安全流量,再拒绝其余所有流量**。合理利用连接跟踪、地址列表和规则链,可以构建出既安全又高效的网络防护体系。建议在生产环境变更前,先在测试环境验证规则的正确性,避免误操作导致网络中断。