温馨提示×

Debian防火墙策略配置示例

小樊
33
2026-01-01 18:48:08
栏目: 智能运维

在Debian系统中,你可以使用iptablesnftables来配置防火墙策略。以下是使用这两种工具的示例。

使用 iptables 配置防火墙策略

  1. 更新系统

    sudo apt update && sudo apt upgrade -y
    
  2. 安装 iptables(如果尚未安装)

    sudo apt install iptables -y
    
  3. 设置默认策略

    sudo iptables -P INPUT DROP
    sudo iptables -P FORWARD DROP
    sudo iptables -P OUTPUT ACCEPT
    
  4. 允许本地回环接口的流量

    sudo iptables -A INPUT -i lo -j ACCEPT
    sudo iptables -A OUTPUT -o lo -j ACCEPT
    
  5. 允许已建立的连接

    sudo iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
    sudo iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
    
  6. 允许SSH连接(假设SSH运行在默认端口22)

    sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
    
  7. 允许HTTP和HTTPS连接

    sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
    sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT
    
  8. 允许特定IP地址访问(例如,允许IP地址为192.168.1.100的设备访问):

    sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
    
  9. 保存 iptables 规则

    sudo sh -c "iptables-save > /etc/iptables/rules.v4"
    

使用 nftables 配置防火墙策略

  1. 更新系统

    sudo apt update && sudo apt upgrade -y
    
  2. 安装 nftables(如果尚未安装)

    sudo apt install nftables -y
    
  3. 启用 nftables 服务

    sudo systemctl enable nftables
    sudo systemctl start nftables
    
  4. 设置默认策略

    sudo nft add table ip filter
    sudo nft add chain ip filter input { type filter hook input priority 0 \; }
    sudo nft add chain ip filter forward { type filter hook forward priority 0 \; }
    sudo nft add chain ip filter output { type filter hook output priority 0 \; }
    
    sudo nft add rule ip filter input drop
    sudo nft add rule ip filter forward drop
    sudo nft add rule ip filter output accept
    
  5. 允许本地回环接口的流量

    sudo nft add rule ip filter input iif lo accept
    sudo nft add rule ip filter output oif lo accept
    
  6. 允许已建立的连接

    sudo nft add rule ip filter input ct state established,related accept
    sudo nft add rule ip filter output ct state established,related accept
    
  7. 允许SSH连接(假设SSH运行在默认端口22)

    sudo nft add rule ip filter input tcp dport 22 accept
    
  8. 允许HTTP和HTTPS连接

    sudo nft add rule ip filter input tcp dport 80 accept
    sudo nft add rule ip filter input tcp dport 443 accept
    
  9. 允许特定IP地址访问(例如,允许IP地址为192.168.1.100的设备访问):

    sudo nft add rule ip filter input ip saddr 192.168.1.100 accept
    
  10. 保存 nftables 规则

    sudo nft list ruleset > /etc/nftables.conf
    

请注意,这些示例假设你有一个基本的Debian系统,并且你已经熟悉命令行操作。根据你的具体需求,你可能需要调整规则。

0