#!/bin/sh
# Filename: ipfw.sh
# Function: 防护宝 Nginx 集群防火墙规则

IPTABLES=/sbin/iptables
MODPROBE=/sbin/modprobe
OSPF_INT=enp6s0f0                      # OSPF 网卡
EXT_INT=eno1                           # 管理网卡(公网)

### flush existing rules and set chain policy setting to DROP
echo "[+] Flushing existing iptables rules..."
$IPTABLES -F
$IPTABLES -F -t nat
$IPTABLES -X
$IPTABLES -P INPUT ACCEPT
$IPTABLES -P OUTPUT ACCEPT
$IPTABLES -A INPUT -i lo -j ACCEPT
$IPTABLES -A OUTPUT -o lo -j ACCEPT

### load connection-tracking modules
#
$MODPROBE ip_conntrack
$MODPROBE iptable_nat
$MODPROBE ip_conntrack_ftp

###### INPUT chain ######
#
echo "[+] Setting up INPUT chain..."

### make sure that OSPF traffic is accepted
$IPTABLES -A INPUT -i ${OSPF_INT} -j ACCEPT
#$IPTABLES -I INPUT -i ${OSPF_INT} -p ospf -j ACCEPT

### state tracking rules
#$IPTABLES -A INPUT -m conntrack --ctstate INVALID -j LOG --log-prefix "DROP INVALID " --log-ip-options --log-tcp-options
$IPTABLES -A INPUT -m conntrack --ctstate INVALID -j DROP
$IPTABLES -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

### ACCEPT rules for allowing connections out
$IPTABLES -A INPUT -i ${EXT_INT} -p tcp --dport 22 -m conntrack --ctstate NEW -m comment --comment "SSH rule" -j ACCEPT
$IPTABLES -A INPUT -i ${EXT_INT} -p tcp -m multiport --dport 80,443 -m conntrack --ctstate NEW -m comment --comment "Web rule" -j ACCEPT
$IPTABLES -A INPUT -i ${EXT_INT} -p tcp -m multiport --dport 54506,54505 -m conntrack --ctstate NEW -m comment --comment "SaltStack rule" -j ACCEPT

$IPTABLES -A INPUT -i ${EXT_INT} -p icmp --icmp-type 8 -m limit --limit 3/s --limit-burst 5 -j ACCEPT
$IPTABLES -A INPUT -i ${EXT_INT} -p icmp -j DROP

### Rules save
/sbin/service iptables save >/dev/null
echo "[+] Save rules..."
