About iptables ban foreign IP method

0. Background description

The Tencent Cloud or Alibaba Cloud machines purchased by individuals deploy some application services, and "hackers" may maliciously attack, some using domestic IPs, and some simulating foreign IPs.
This article mainly focuses on the method of banning foreign IP.

1. Install dependent packages

yum -y install iptables
yum -y install ipset

2. Add collection

ipset create china hash:net maxelem 65536

3. Write the script

vim /home/china.sh

The content is as follows:

#!/usr/bin/env bash
##下载国内Ip网段并输入到~/cn.zone文件里面,可自定义(如不能访问该网址可自行百度找资源)。
wget --no-check-certificate -O- 'http://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest' | awk -F\| '/CN\|ipv4/ { printf("%s/%d\n", $4, 32-log($5)/log(2)) }' > /home/china.txt
##清空china集合
ipset flush china

ip=$(cat /home/china.txt)
for i in $ip
do
##批量将国内Ip网段添加进china集合。
ipset add china $i
done

4. Give the script executable permissions

chmod +x /home/china.sh

5. Execute the script

sh /home/china.sh

Wait for a while, you can view the domestic IP segment contained in the china.txt file, cat /home/china.txt

6. Check whether the domestic ip network segment is added to the china collection

ipset list china

7. Set crontab timing tasks


For example: update the IP set crontab -e every day at zero

Add a line of timed tasks, as follows:

0 0 * * * /home/china.sh

8. Configure iptables to restrict access

Add iptables rules, as follows:

iptables -A INPUT -m set --match-set china src -j ACCEPT
iptables -A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A INPUT -p icmp -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
iptables -A INPUT -j REJECT --reject-with icmp-host-prohibited
iptables -A FORWARD -j REJECT --reject-with icmp-host-prohibited

9. Query the ip information interacting with the external network

iftop

Guess you like

Origin blog.csdn.net/aikudexiaohai/article/details/130081305
Recommended