使用 Nginx 蜜罐并使用黑名单、防火墙阻止 ip 或 fail2ban

Using Nginx honeypot and using blacklist, firewall block ip or fail2ban

使用 Nginx 蜜罐并使用黑名单、防火墙阻止 ip 或 fail2ban

所以我们有这个服务器,我们每天都会看到 1000 个探测器。有趣的是他们都 'try' 至少有相同的基本 uri,比如 \admin\wp-admin\control\mysqladmin ....我们自己的人和用户会永远不要输入这些命令。

过去我们向这些 uri 位置匹配发送了全部拒绝,我们的块看起来像这样

location ~* ^/(admin|wp-admin|control)/?$
    deny all;
}

但是对于一些 uri 请求,我们 100% 确定这是一个网站 probe/hacker/crawler 正在抓取不存在的过度逻辑的不安全 uri 的...而不是使用 deny all; 我想要IP 被封锁...永久或至少 24 小时

问题:我如何像蜜罐一样匹配请求,然后通过 nginx conf 使用我们的防火墙阻止此 IP?

结果会是这样的

location ~* ^/(admin|wp-admin|control)/?$
    ban the ip permanently;
    or
    ban the ip 24hours;
}

谢谢!

如果 deny all 在您的 error.log 中产生错误条目,您可以使用 一个名为 nginx-http-auth 的 fail2ban 监狱,所以将其添加到您的 /etc/fail2ban/jail.local:

[nginx-http-auth]
enabled = true

重新启动 fail2ban(或 fail2ban-client reload fail2ban v.0.10 或更新版本)他们将被禁止。


如果你只有 access.log 中的条目,或者你想尝试更好的场景,你可以试试这个:

在 nginx 配置的 http 部分创建新的访问日志格式(nginx 默认值有点差):

log_format badlogfmt '$time_local : $remote_addr : $status : $body_bytes_sent : $request_method : $remote_user : '
                     '"$request" "$http_referer" "$http_user_agent"';

然后写入一个新条目,将所有 "bad" 请求记录在单独的日志文件中:

map $status $loggable {
    404     0; # ignore page not found (404).
    499     0; # ignore canceled/closed requests.
    ~^[45]  1; # all other requests with status starting with 4 or 5.
    default 0;
}

# log the bad requests: 
access_log /var/log/nginx/access_bad.log badlogfmt if=$loggable;
# all other requests:
access_log /var/log/nginx/access.log combined;

这将导致所有 "bad" 请求转到不同的日志,如下所示:

11/Jan/2020:06:27:59 +0100 : 192.0.2.1 : 403 : 154 : GET : - : "GET /admin/ HTTP/1.1" ...
11/Jan/2020:06:28:00 +0100 : 192.0.2.2 : 400 : 166 : - : - : "145.ll|'|'|SGFjS2...

你的监狱可以和这个类似:

[nginx-ban-bots]
port    = http,https
logpath = /var/log/nginx/access_bad.log
backend = auto
filter =
# ban all but ignore 401 Unauthorized for empty user (: - :) and 404 (and 499 cancel request)...
failregex = ^\s*: <HOST> :(?: (?!40[14]|499)[45]\d{2} :| 401 : \d+ : \S* (?!: - :))
enabled = true

重新加载 fail2ban,所有机器人都会消失。

有关 fail2ban/wiki/Best-practice#reduce-parasitic-log-traffic 的更多信息。

如果你的页面足够安全,那么你可以说 "there are no broken links on our page",那么你几乎没有 404 错误,一个聪明的技巧可能是禁止 large-scale 入侵者尝试访问每个不存在的页面。

因此您可以在 map $status ... 指令中注释或删除 404,以及从 failregex 的 [14] 中删除 4,并可能增加 maxretry (和 findtime)以避免一些误报。

使用此策略,您无需为任何人工 URL 创建所有 nginx 位置以匹配每个机器人尝试(如果有利可图的 URL 列表发生变化,明天它也可以工作)...


您也可以尝试我们最新的 fail2ban 版本 (0.11) 并逐步禁止,然后您可以启用 bantime.increment 并将初始 bantime 设置为一些较低的值,例如 30s (可能的误报),但是对被称为 "bad" 的入侵者的所有禁令都会随着下一次禁令的延长而延长(经过反复尝试)。