debian

Debian防火墙如何定制个性化规则

小樊
36
2025-06-13 23:20:33
栏目: 智能运维

在Debian系统中,可以使用iptables或ufw(Uncomplicated Firewall)来定制个性化防火墙规则。以下是使用这两种工具的详细步骤:

使用iptables定制个性化规则

  1. 安装iptables(如果尚未安装):

    sudo apt update
    sudo apt install iptables
    
  2. 查看当前iptables规则

    sudo iptables -L -n -v
    
  3. 添加自定义规则

    • 允许特定IP访问:
      sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT
      
    • 拒绝特定IP访问:
      sudo iptables -A INPUT -s 192.168.1.101 -j DROP
      
    • 允许特定端口:
      sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT  # 允许HTTP
      sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT # 允许HTTPS
      
    • 拒绝所有入站连接:
      sudo iptables -P INPUT DROP
      
    • 允许SSH连接:
      sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW,ESTABLISHED -j ACCEPT
      sudo iptables -A OUTPUT -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
      
  4. 保存iptables规则

    • 使用iptables-persistent包保存和恢复规则:
      sudo apt install iptables-persistent
      sudo netfilter-persistent save
      sudo netfilter-persistent start
      
  5. 测试规则

    • 尝试从不同的IP地址或端口进行连接,确保规则按预期工作。
  6. 监控和调试

    • 使用以下命令查看iptables状态和规则:
      sudo iptables -L -n -v
      sudo iptables -t nat -L -n -v
      sudo iptables -t mangle -L -n -v
      

使用ufw定制个性化规则

  1. 安装ufw(如果尚未安装):

    sudo apt update
    sudo apt install ufw
    
  2. 启用ufw

    sudo ufw enable
    
  3. 查看当前ufw状态

    sudo ufw status
    
  4. 添加自定义规则

    • 允许SSH连接(默认端口22):
      sudo ufw allow ssh
      
    • 允许HTTP服务(端口80):
      sudo ufw allow http
      
    • 允许特定IP地址的SSH访问:
      sudo ufw allow from 192.168.1.100 to any port 22
      
    • 拒绝特定端口的FTP访问:
      sudo ufw deny 21/tcp
      
    • 允许特定端口范围(例如,打开从2290到2300的端口供TCP协议使用):
      sudo ufw allow 2290:2300/tcp
      
  5. 删除规则

    • 删除特定规则:
      sudo ufw delete allow 22/tcp
      
    • 删除所有规则:
      sudo ufw reset
      
  6. 保存规则

    • 确保系统重启后规则仍然有效:
      sudo ufw export > /etc/ufw/user.rules
      

通过以上步骤,您可以在Debian系统上定制个性化的防火墙规则,以确保系统的安全性和满足特定需求。

0
看了该问题的人还看了