Skip to content

iptables 命令:Linux 防火墙管理工具

1. 命令简介

iptables 是 Linux 系统中用于配置 IPv4 包过滤规则的命令行工具。它允许系统管理员配置内核防火墙提供的表、链和规则。iptables 是网络安全的重要组成部分,用于控制进出系统的网络流量。

2. 基本语法

bash
iptables [选项] 命令 [链] [规则匹配] [动作]

3. 常用选项和命令

  • -A:在链的末尾添加规则
  • -D:删除链中的规则
  • -I:在链的开头插入规则
  • -L:列出链中的规则
  • -F:清空所有规则
  • -P:设置链的默认策略
  • -t:指定表(filter、nat、mangle、raw)

4. 基础使用示例

  1. 列出所有规则:

    bash
    sudo iptables -L
  2. 添加一条规则允许 SSH 连接:

    bash
    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
  3. 阻止特定 IP 地址:

    bash
    sudo iptables -A INPUT -s 192.168.1.100 -j DROP
  4. 设置默认策略:

    bash
    sudo iptables -P INPUT DROP

5. 进阶使用技巧

  1. 端口转发:

    bash
    sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 8080
  2. 允许已建立的连接:

    bash
    sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
  3. 限制连接速率:

    bash
    sudo iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
  4. 记录被阻止的流量:

    bash
    sudo iptables -A INPUT -j LOG --log-prefix "IPTables-Dropped: "

6. 实用示例

  1. 基本的防火墙配置:

    bash
    # 清空所有规则
    sudo iptables -F
    
    # 设置默认策略
    sudo iptables -P INPUT DROP
    sudo iptables -P FORWARD DROP
    sudo iptables -P OUTPUT ACCEPT
    
    # 允许本地回环接口
    sudo iptables -A INPUT -i lo -j ACCEPT
    
    # 允许已建立的连接
    sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
    
    # 允许 SSH
    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
    
    # 允许 HTTP 和 HTTPS
    sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
  2. 防止 DoS 攻击:

    bash
    sudo iptables -A INPUT -p tcp --dport 80 -m limit --limit 25/minute --limit-burst 100 -j ACCEPT
  3. 封锁特定国家的 IP 范围:

    bash
    sudo iptables -A INPUT -m geoip --src-cc CN -j DROP

    注:需要安装 xtables-addons 和 GeoIP 数据库。

  4. 创建自定义链:

    bash
    sudo iptables -N CUSTOM_CHAIN
    sudo iptables -A INPUT -j CUSTOM_CHAIN
    sudo iptables -A CUSTOM_CHAIN -p tcp --dport 8080 -j ACCEPT

7. 注意事项

  • 修改 iptables 规则可能会导致网络中断,请谨慎操作。
  • 在远程服务器上修改防火墙规则时,确保不会意外阻止自己的访问。
  • iptables 规则在系统重启后默认不会保存,需要使用额外的工具或脚本来保存和恢复规则。
  • 使用 iptables 需要 root 权限。

8. 相关命令

  • ip6tables:用于 IPv6 的 iptables
  • ufw:Ubuntu 的简化防火墙配置工具
  • firewalld:CentOS/RHEL 的动态防火墙管理器
  • nftables:iptables 的现代替代品

9. 技巧与建议

  1. 使用 iptables-saveiptables-restore 来备份和恢复规则:

    bash
    sudo iptables-save > /etc/iptables.rules
    sudo iptables-restore < /etc/iptables.rules
  2. 在应用新规则前,先在一个测试环境中验证。

  3. 使用注释来记录规则的用途:

    bash
    sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT -m comment --comment "Allow HTTP"
  4. 考虑使用前端工具如 ufwfirewalld 来简化 iptables 的管理。

iptables 是 Linux 系统中强大的防火墙工具,它提供了灵活的网络流量控制能力。正确配置 iptables 可以显著提高系统的安全性。然而,由于其复杂性,不当的配置可能会导致严重的网络问题。因此,在使用 iptables 时,建议先在非生产环境中测试配置,并始终保持一个可靠的备份或回滚机制。