79. iptables限制ssh链接服务器

linux服务器默认通过22端口用ssh协议登录,这种不安全. 今天想做限制,即允许部分来源ip连接服务器.

案例目标: 通过iptables规则限制对linux服务器的登录.

处理方法: 编写为sh脚本,以便多次执行. iptables.sh:

1
2
3
4
5
6
iptables -I INPUT -p tcp --dport 22 -j DROP -m comment --comment "ssh"
# 按ip范围区间开放
iptables -I INPUT -p tcp -m iprange --src-range 172.18.163.227-172.18.163.232 --dport 22 -j ACCEPT -m comment --comment "ssh"

# 按网段开放
iptables -I INPUT -p tcp -s 10.99.193.0/24 --dport 22 -j ACCEPT -m comment --comment "ssh"

简要说明: 这里默认使用filter表的INPUT链,使用 -I 插入方式,第一条DROP操作顺序不能错,必须是首条.

对于已经插入的规则,可以使用下面的命令进行查看:

1
iptables -t filter -nvL --line-number |grep ssh

如果后面需要删除规则,可以按照下面的方式处理:

1
iptables -t filter -D INPUT 3

说明一下: 这里删除iptables规则,指定了filter表的INPUT链,避免出错.
根据上一步查看的规则的行号来删除,查看到相应的规则编号之后,最好从最大的编号开始逐条删除.

示例: 禁止所有类型链接,允许特别定来源ip链接 iptables-myrules.sh

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#! /bin/bash
# author: xiongzaiqiren
# date: 2023-03-20
# usage: sh iptables-myrules.sh
# 设置服务器安全,允许特定来源ip访问请执行我.
# 每次改完需要执行iptables-save > /etc/iptables-myrules.conf 备份规则哦

#允许ping
iptables -A INPUT -p icmp -m icmp --icmp-type 8 -j ACCEPT

# 拒绝所有链接
iptables -P INPUT DROP;

# 指定ip及范围允许链接
iptables -A INPUT -s 10.99.193.243 -p tcp -j ACCEPT
iptables -A INPUT -s 10.90.5.0/24 -p tcp -j ACCEPT
iptables -A INPUT -s 10.99.193.0/24 -p tcp -j ACCEPT

iptables -nvL --line-numbers
#iptables -t filter -D INPUT 3 #表示删除filter表中的FORWARD链的第一条规则