0%

nginx拒绝恶意域名解析设置

前段时间,nginx的访问日志里有很多/otsmobile/app/mgs/mgw.htm?operationType mobile.12306.cn 这样的404报错。后来通过实践,通过正确设置nginx的listen的值,可以有效规避这问题。

什么是恶意域名解析?

因为IP地址不方便记忆,我们通常上网一般都是通过域名发出请求,通过DNS系统来转换成具体IP地址。
当然,也可以更改客户端的hosts文件(优先级比DNS更高), 于是也有攻击者,把其他网站域名和被攻击IP关联,比如:
120.79.66.66 www.abc.com,最终,从这台电脑上发出到www.abc.com任意请求都会被解析到120.79.66.66上。

最终导致带宽被占满,正常服务受影响。

nginx的listen设置

关于listen中的default_server,官网是这样解释的:The default_server parameter, if present, will cause the server to become the default server for the specified address:port pair. If none of the directives have the default_server parameter then the first server with the address:port pair will be the default server for this pair. 也就是说,如果设置了default_server,可以配合server_name _ (匹配没找到有效的server_name)

下方配置放在nginx配置文件的最后,当请求$host没有在nginx中匹配到时,交给default_server,最后返回444状态码(不返回信息,直接关闭连接)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
return 444;
access_log /var/log/opsping.com_deny.log;
error_log /var/log/opsping.com_deny.log;
}

server {
listen 443 http2 default_server;
listen [::]:443 http2 default_server;
server_name _;
ssl_certificate "ssl/3635348_opsping.com.pem";
ssl_certificate_key "ssl/3635348_opsping.com.key";
ssl_session_cache shared:SSL:1m;
ssl_session_timeout 10m;
ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP;
ssl_prefer_server_ciphers on;
return 444;
access_log /var/log/opsping.com_deny.log;
error_log /var/log/opsping.com_deny.log;
}

实际效果

reload nginx后,访问http://www.abc.com可以在访问日志中看到,请求已经被关闭
# tail -f /var/log/opsping.com_deny.log

1
2
3
4
113.87.227.235 - - [21/Mar/2020:14:07:43 +0800] "GET /favicon.ico HTTP/1.1" 444 0 "http://www.abc.com/" "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"
80.82.70.187 - - [21/Mar/2020:16:52:35 +0800] "GET http://www.baidu.com/cache/global/img/gs.gif HTTP/1.1" 444 0 "-" "Mozilla"
80.82.70.187 - - [21/Mar/2020:16:52:37 +0800] "GET http://www.baidu.com/cache/global/img/gs.gif HTTP/1.1" 444 0 "-" "Mozilla"
139.162.88.63 - - [21/Mar/2020:17:16:14 +0800] "GET http://clientapi.ipip.net/echo.php?info=1234567890 HTTP/1.1" 444 0 "-" "Go-http-client/1.1"

参考资料

http://nginx.org/en/docs/http/ngx_http_core_module.html