封禁一些IPs的SSH登录,保护服务器安全

登录服务器的root用户时,可能会收到如下提示:

There were 3225 failed login attempts since the last successful login.

这表示有很黑客在尝试用一些用户和密码登录服务器。为了保障服务器安全,则可以在日志文件/var/log/secure中查看攻击的IPs来源和其失败登录的次数。例如:

Invalid user neisius from 211.144.12.75 port 34041
Failed password for invalid user server from 219.94.99.133 port 15139 ssh2
pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=106.12.217.39

若某个IP次数很高,则将其IP信息添加到/etc/hosts.deny文件中进行封禁。例如,修改/etc/hosts.deny文件内容:

sshd:101.109.83.140
sshd:103.27.238.202
sshd:104.236.94.202
sshd:106.12.200.13
sshd:106.12.217.39
sshd:106.54.19.67
sshd:111.230.73.133
sshd:117.50.45.254
sshd:118.24.38.53
sshd:122.155.223.119

为了能自动地封禁IPs,编写名为IP_denied_for_ssh_security.pl的perl程序:

#! /usr/bin/perl
use strict;

my $usage = <<USAGE;
Usage:
    $0 <num>

    运行程序后,程序读取/var/log/secure文件中信息。若存在某个IP登录失败(含有Invalid user|Failed password|authentication failure等信息)次数超过指定的次数,则是需要封禁的IP。此外,程序再读取/etc/hosts.deny文件中的IP信息,得到所有需要封禁的IP。然后程序将这些IP信息全部写入到/etc/hosts.deny文件中进行封禁。
    程序需要以root权限运行,因为只有root权限才能读取/var/log/secure文件,对/etc/hosts.deny进行写入。
    程序运行完毕后,会清空/var/log/secure文件内容。

USAGE
if(@ARGV==0){die $usage}

open IN, "/var/log/secure" or die "Can not open file /var/log/secure, $!";
my %num;
while (<IN>) {
    if (m/Invalid user/ or m/Failed password/ or m/authentication failure/) {
        $num{$1} ++ if m/(\d+\.\d+\.\d+\.\d+)/;
    }
}
close IN;

my %deny;
my $deny_num = 0;
foreach (keys %num) {
    if ($num{$_} >= $ARGV[0]) {
        $deny{$_} = 1;
        $deny_num ++;
    }
}
print STDERR "$deny_num IPs were detected for blocking from file /var/log/secure.\n";

open IN, "/etc/hosts.deny" or die "Can not open file /etc/hosts.deny, $!";
while (<IN>) {
    $deny{$1} = 1 if m/(\d+\.\d+\.\d+\.\d+)/;
};
close IN;

open OUT, ">", "/etc/hosts.deny" or die "Can not create file /etc/hosts.deny, $!";
my $total_num = 0;
foreach (sort keys %deny) {
    print OUT "sshd:$_\n";
    $total_num ++;
}
close OUT;
print STDERR "Total $total_num IPs were banned by file /etc/hosts.deny for SSH security.\n";

open OUT, ">", "/var/log/secure" or die "Can not  create file /var/log/secure, $!";
close OUT;

使用root用户执行该perl程序,若登录失败次数>=3次,则封禁对应的IP。

IP_denied_for_ssh_security.pl 3

发表评论

电子邮件地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据