测试环境:Ubuntu 20.04
修改默认 SSH 端口
cat <<EOF>> /etc/ssh/sshd_config
Port 45678
EOF
有防火墙的话先放行该端口
ufw allow 45678/tcp
重启服务生效
systemctl restart sshd
安装配置 fail2ban
apt install rsyslog fail2ban -y
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
编辑/etc/fail2ban/jail.local
,只需在如下位置中加入配置即可。
[sshd]
# To use more aggressive sshd modes set filter parameter "mode" in jail.local:
# normal (default), ddos, extra or aggressive (combines all).
# See "tests/files/logs/sshd" or "filter.d/sshd.conf" for usage example and details.
#mode = normal
enable = true
filter = sshd
maxretry = 5
findtime = 10m
bantime = 24h
重启服务生效配置并设置开机自启
systemctl start fail2ban && systemctl status fail2ban && systemctl enable fail2ban
查看已拦截 SSH 登录的IP信息
fail2ban-client status sshd
设置 tcp_wrappers
首先确认 sshd 是否编译了 tcp_wrappers 支持
ldd /usr/sbin/sshd | grep wrap
如果没有输出,说明 sshd 没有使用 libwrap,那 hosts.allow / hosts.deny 根本不会起作用。
cat /etc/hosts.allow
# /etc/hosts.allow: list of hosts that are allowed to access the system.
# See the manual pages hosts_access(5) and hosts_options(5).
#
# Example: ALL: LOCAL @some_netgroup
# ALL: .foobar.edu EXCEPT terminalserver.foobar.edu
#
# If you're going to protect the portmapper use the name "rpcbind" for the
# daemon name. See rpcbind(8) and rpc.mountd(8) for further information.
#
sshd:10.
sshd:192.168.1.0/255.255.255.0
sshd:111.111.111.0/24
sshd:[3ffe:505:2:1::]/64
sshd:.livejq.top
sshd:/opt/ip_allow.txt
注意:“sshd:192.168.1.*”这种写法已经不生效了,请用上面的掩码写法代替。
cat /etc/hosts.deny
# /etc/hosts.deny: list of hosts that are _not_ allowed to access the system.
# See the manual pages hosts_access(5) and hosts_options(5).
#
# Example: ALL: some.host.name, .some.domain
# ALL EXCEPT in.fingerd: other.host.name, .other.domain
#
# If you're going to protect the portmapper use the name "rpcbind" for the
# daemon name. See rpcbind(8) and rpc.mountd(8) for further information.
#
# The PARANOID wildcard matches any host whose name does not match its
# address.
#
# You may wish to enable this to ensure any programs that don't
# validate looked up hostnames still leave understandable logs. In past
# versions of Debian this has been the default.
# ALL: PARANOID
sshd:all
注意:请确保您当前主机已经包含在hosts.allow
允许访问的列表中再写入上述配置,否则可能会直接断开连接。
丢弃 ICMP
丢弃所有
通常直接用 sysctl 在内核层面禁掉 ICMP,是最“粗暴”的办法。
echo "net.ipv4.icmp_echo_ignore_all = 1" | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
或者启用了 ufw 的话
sudo ufw deny proto icmp from any
白名单版本
编辑 UFW 用户规则文件
nano /etc/ufw/before.rules
# Don't delete these required lines, otherwise there will be errors
*filter
:ufw-before-input - [0:0]
:ufw-before-output - [0:0]
:ufw-before-forward - [0:0]
:ufw-not-local - [0:0]
# End required lines
# Allow ICMP echo-request from whitelist
-A ufw-before-input -p icmp --icmp-type echo-request -s 1.2.3.4 -j ACCEPT
# Drop all other ICMP echo-request
-A ufw-before-input -p icmp --icmp-type echo-request -j DROP
添加“# End required lines”后面这些即可,1.2.3.4
换成你需要放行的源IP,通常是监控这台主机的IP地址。
重载配置生效
sudo ufw reload
评论区