一、概述

nginx作为当前最流行的开源web服务器之一,被无数公司或个人在使用。正因为开源,所以任何人都可以获取到它的源码,这其中就包含了世界各地的黑客。他们无时无刻不在想着如何找出nginx的漏洞,以至于在网上随便一搜都能找到无数nginx相关的漏洞:

默认情况下,http响应的Server头部都会携带上服务器的名字和版本信息:

> curl -I http://127.0.0.1
HTTP/1.1 502 Bad Gateway
Server: nginx/1.12.2   # 携带有服务端和版本号
Date: Mon, 12 Mar 2018 01:25:00 GMT
...

而一旦黑客知道了服务端软件的版本信息,很容易就能通过对应版本的漏洞来攻击服务器,引发安全问题。所以针对生产环境的服务器,有必要隐藏或者修改软件版本信息,以避免黑客的指向性攻击。

二、隐藏nginx版本号

nginx中隐藏版本号可以通过配置来解决,通过设置server_tokens变量控制版本号显示:

http {
    ...
    server_tokens off;
    ...
}

重新载入nginx,再次获取会发现版本号不见了,但是还能看出是nginx:

> curl http://127.0.0.1 -I
HTTP/1.1 502 Bad Gateway
Server: nginx   # 版本号已经不见
...

三、修改版本号

nginx的版本号在nginx-1.12.2/src/core/nginx.hNGINX_VERSION字段中定义,位于第13行左右:

> sed -n ''13,16p'' src/core/nginx.h 
#define NGINX_VERSION      "1.12.2" 
#define NGINX_VER          "nginx/" NGINX_VERSION

#ifdef NGX_BUILD
#define NGINX_VER_BUILD    NGINX_VER " (" NGX_BUILD ")"

修改第13行的NGINX_VERSION2.0.0,然后重新编译nginx,重启服务。

> make && make install
> service nginx restart # 不能使用reload
> curl http://127.0.0.1 -I
HTTP/1.1 502 Bad Gateway
Server: nginx/2.0.0
Date: Mon, 12 Mar 2018 01:49:39 GMT
...

四、修改服务端软件名

修改nginx/src/core/nginx.h中的NGINX_VER字段:

> sed -n ''14p'' src/core/nginx.h 
#define NGINX_VER          "nginx/" NGINX_VERSION  # 修改为Tomcat

修改nginx/src/http/ngx_http_header_filter_module.c的第49行:

> grep -n ''Server: nginx'' src/http/ngx_http_header_filter_module.c 
49:static u_char ngx_http_server_string[] = "Server: nginx" CRLF; 

改为Server: Tomcat

> sed -i ''s/Server: nginx/Server: tomcat/'' src/http/ngx_http_header_filter_module.c 
> sed -n ''49p'' src/http/ngx_http_header_filter_module.c 
static u_char ngx_http_server_string[] = "Server: tomcat" CRLF;

重新编译:

> curl http://localhost -I
HTTP/1.1 200 OK
Server: Tomcat/2.0.0
Date: Mon, 12 Mar 2018 02:05:53 GMT
...
最后修改:2020 年 03 月 13 日
如果觉得我的文章对你有用,请随意赞赏