背景知识
防攻击可以增加IP白名单/etc/hosts.allow和黑名单/etc/hosts.deny
①修改/etc/hosts.allow文件
# hosts.allow This file describes the names of the hosts which are
# allowed to use the local INET services, as decided
# by the ‘/usr/sbin/tcpd’ server.
#
sshd:210.13.218.*:allow
sshd:222.77.15.*:allow
以上写法表示允许210和222两个ip段连接sshd服务
当然如果管理员集中在一个IP那么这样写是比较省事的
all:218.24.129.110 //表示接受110这个ip的所有请求
②/etc/hosts.deny文件,此文件是拒绝服务列表,文件内容如下:
#
# hosts.deny This file describes the names of the hosts which are
# *not* allowed to use the local INET services, as decided
# by the ‘/usr/sbin/tcpd’ server.
#
# The portmap line is redundant, but it is left to remind you that
# the new secure portmap uses hosts.deny and hosts.allow. In particular
# you should know that NFS uses portmap!
sshd:all:deny
注意看:sshd:all:deny表示拒绝了所有sshd远程连接。:deny可以省略。
所以:当hosts.allow和 host.deny相冲突时,以hosts.allow设置为准。
Step1 将恶意IP地址写入黑名单
vim /root/secure_ssh.sh
每次执行该脚本时,它会自动去扫描/var/log/secure日志文件,并把登录失败次数大于5次的IP自动写入到/etc/hosts.deny文件中去。
脚本内容:
for i in $(grep "Failed password" /var/log/secure|awk '{print $(NF-3)}'|sort|uniq -c|sort -nr|awk '{if($1>=5) print $2}')
do
echo "sshd:$i:deny" >> /etc/hosts.deny
done
Step2 将脚本加入Crontab实现自动禁止恶意IP
设置定时任务,每天22:00自动执行secure_ssh.sh脚本
crontab -e
0 22 * * * sh /root/secure_ssh.sh
设计实验检验成果:
步骤:
使用ubuntu(ip192.168.248.131)远程登录centos7(ip192.168.248.132)服务器,在centos7上将ubuntu的ip写入黑名单,并自动禁止该恶意ip
查看centos7的ssh服务
rpm -qa|grep -E "openssh"
查看当前的centos是否安装了openssh-server服务。默认安装openssh-server服务。
显示结果含有这三个软件,则表示已经安装,可以直接进行远程连接。
如果缺失上面三个软件
yum install openssh-server -y安装openssh-server服务
service sshd restart重启OpenSSH服务。
如果不能登录连接,则是没有开放端口,开启防火墙的22端口:
sudo firewall-cmd --zone=public --add-port=22/tcp --permanent
sudo service firewalld restart
在ubuntu远程登录centos7服务器
ssh ‘登录目标机器的用户名’@’目标机器的ip地址’
故意输错密码。默认输错三次退出,我们重复登录几次,输错五次以上。
在centos7查看登录日志
a.首先查看安全日志文件
cat /var/log/secure
b.过滤其它ip,只看登录失败的ip地址
grep "Failed password" /var/log/secure
确实是是恶意的ubuntu的ip地址
第八次登录,我们输入正确密码,此时仍然可以登录centos7的shell
在centos7运行secure_ssh.sh脚本文件
. secure_ssh.sh运行
cat /etc/hosts.deny查看黑名单,验证恶意ip是否被写入:是
此时再在ubuntu中试图登录centos7,被禁止登录
如果想使ubuntu重新可以登录centos7,在白名单中写入ubuntu的ip或者删除黑名单中ubuntu的ip