iptables基础规则配置

设置默认规则

1
2
3
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

INPUT

  • 允许已建立的或相关连接的通行,即允许我发出去的数据包入站

    1
    iptables -I INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
  • 允许80(HTTP)/443(HTTPS)

    1
    iptables -A INPUT -p tcp -m state --state NEW -m multiport --dports 80,143 -m comment --comment HTTP -j ACCEPT
  • 允许访问NTP服务

    1
    iptables -A INPUT -p udp -m udp --dport 123 -j ACCEPT
  • 允许访问DNS服务

    1
    2
    iptables -A INPUT -p udp -m udp --sport 53 -j ACCEPT
    iptables -A INPUT -p tcp -m tcp --sport 53 -j ACCEPT
  • 允许回环网卡

    1
    iptables -A INPUT -i lo -j ACCEPT
  • 允许SSH端口的连接,脚本自动侦测目前的SSH端口,否则默认为22端口

    1
    2
    3
    4
    5
    6
    if grep "^Port" /etc/ssh/sshd_config>/dev/null;then
    sshdport=`grep "^Port" /etc/ssh/sshd_config | sed "s/Port\s//g" `
    else
    sshdport=22
    fi
    iptables -A INPUT -p tcp -m state --state NEW,ESTABLISHED -m tcp --dport ${sshdport} -m comment --comment SSH -j ACCEPT
  • 允许被ping

    1
    iptables -A INPUT -p icmp -j ACCEPT
  • 拒绝所有并且发送一条Destination Host Prohibited的消息给被拒绝的主机

    1
    iptables -A INPUT -j REJECT --reject-with icmp-host-prohibite

OUTPUT

  • 允许已建立的或相关连接的通行

    1
    iptables -I OUTPUT 1 -m state --state ESTABLISHED,RELATED -j ACCEPT
  • 允许回环网卡

    1
    iptables -A OUTPUT -o lo -j ACCEPT
  • 允许机器可以进行DNS查询

    1
    iptables -A OUTPUT -p udp -m udp -j ACCEPT

默认规则和保存

1
iptables -Z; iptables-save > /etc/sysconfig/iptables

脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/bin/bash
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT
iptables -F

iptables -I INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -p tcp -m state --state NEW -m multiport --dports 80,143 -m comment --comment HTTP -j ACCEPT
iptables -A INPUT -p udp -m udp --dport 123 -j ACCEPT
iptables -A INPUT -p udp -m udp --dport 53 -j ACCEPT
iptables -A INPUT -p tcp -m tcp --dport 53 -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT

if grep "^Port" /etc/ssh/sshd_config>/dev/null;then
sshdport=`grep "^Port" /etc/ssh/sshd_config | sed "s/Port\s//g" `
else
sshdport=22
fi
iptables -A INPUT -p tcp -m state --state NEW,ESTABLISHED -m tcp --dport ${sshdport} -m comment --comment SSH -j ACCEPT

iptables -A INPUT -p icmp -j ACCEPT
iptables -A INPUT -j REJECT --reject-with icmp-host-prohibited

iptables -I OUTPUT 1 -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
iptables -A OUTPUT -p udp -m udp -j ACCEPT
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2018-2024 Outsrkem
  • 访问人数: | 浏览次数:

      请我喝杯咖啡吧~

      支付宝
      微信