侧边栏壁纸
博主头像
★街角晚灯★博主等级

博观而约取 厚积而薄发

  • 累计撰写 448 篇文章
  • 累计创建 183 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Nginx常规配置-安全加固

WinJay
2021-06-24 / 0 评论 / 0 点赞 / 212 阅读 / 17044 字 / 正在检测是否收录...
温馨提示:
文章发布较早,内容可能过时,阅读注意甄别。。。。

Nginx配置

一、隐藏版本号:

(操作后即只显示WebServ使用的是Nginx) image20210527104513849.png

1、进入nginx配置文件的目录(此目录根据安装时决定),用vim编辑打开

[root@LB-Master nginx]# vim /etc/nginx/nginx.conf

2、在http {—}里加上server_tokens off; 如:

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;
    server_tokens off;

    include /etc/nginx/conf.d/*.conf;

}

3、重新加载Nginx服务

[root@LB-Master nginx]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@LB-Master nginx]# nginx -s reload

这样就完全对外隐藏了nginx版本号了,就是出现404、501等页面也不会显示nginx版本。 image20210521110924904.pngimage20210527104940158.png

二、为客户端设置缓冲区大小限制:

设置自定义缓存以限制缓冲区溢出攻击。nginx.conf配置如下:

http{
    ... ...
    server{
        ... ...
        client_body_buffer_size  16K;
        client_header_buffer_size  1k;
        client_max_body_size  1m;
        large_client_header_buffers  4  8k;
        ... ...
        ... ...
        ... ...
    }
}

注:上述的参数不是最优参数,仅供参考。加固检查: 确保server模块中配置了上述标红的配置。

  • client_body_buffer_size 1k(默认8k或16k)这个指令可以指定连接请求实体的缓冲区大小。如果连接请求超过缓存区指定的值,那么这些请求实体的整体或部分将尝试写入一个临时文件。
  • client_header_buffer_size 1k 指令指定客户端请求头部的缓冲区大小。绝大多数情况下一个请求头不会大于1k,不过如果有来自于wap客户端的较大的cookie它可能会大于 1k,Nginx将分配给它一个更大的缓冲区,这个值可以在large_client_header_buffers里面设置。
  • client_max_body_size 1k 指令指定允许客户端连接的最大请求实体大小,它出现在请求头部的Content-Length字段。如果请求大于指定的值,客户端将收到一个”Request Entity Too Large” (413)错误。记住,浏览器并不知道怎样显示这个错误。
  • large_client_header_buffers 指定客户端一些比较大的请求头使用的缓冲区数量和大小。请求字段不能大于一个缓冲区大小,如果客户端发送一个比较大的头,nginx将返回”Request URI too large” (414)
  • 同样,请求的头部最长字段不能大于一个缓冲区,否则服务器将返回”Bad request” (400)。缓冲区只在需求时分开。默认一个缓冲区大小为操作系统中分页文件大小,通常是4k或8k,如果一个连接请求最终将状态转换为keep- alive,它所占用的缓冲区将被释放。

设置timeout

设置timeout设低来防御DOS攻击,nginx.conf配置如下:

http{
    ... ...
    server{
        ... ...
        client_body_timeout		10;
        client_header_timeout	30;
        keepalive_timeout		30  30;
        send_timeout			10;
        ... ...
        ... ...
        ... ...
    }
}
  • client_body_timeout 10;-指令指定读取请求实体的超时时间。这里的超时是指一个请求实体没有进入读取步骤,如果连接超过这个时间而客户端没有任何响应,Nginx将返回一个”Request time out” (408)错误。
  • client_header_timeout 10;-指令指定读取客户端请求头标题的超时时间。这里的超时是指一个请求头没有进入读取步骤,如果连接超过这个时间而客户端没有任何响应,Nginx将返回一个”Request time out” (408)错误。
  • keepalive_timeout 5 5; – 参数的第一个值指定了客户端与服务器长连接的超时时间,超过这个时间,服务器将关闭连接。参数的第二个值(可选)指定了应答头中Keep-Alive: timeout=time的time值,这个值可以使一些浏览器知道什么时候关闭连接,以便服务器不用重复关闭,如果不指定这个参数,nginx不会在应 答头中发送Keep-Alive信息。(但这并不是指怎样将一个连接“Keep-Alive”)参数的这两个值可以不相同。
  • send_timeout 10; 指令指定了发送给客户端应答后的超时时间,Timeout是指没有进入完整established状态,只完成了两次握手,如果超过这个时间客户端没有任何响应,nginx将关闭连接。

三、禁用所有不需要的 HTTP 方法

Http请求中8种请求方法

  • opions 返回服务器针对特定资源所支持的HTML请求方法 或web服务器发送测试服务器功能(允许客户端查看服务器性能)
  • Get 向特定资源发出请求(请求指定页面信息,并返回实体主体)
  • Post 向指定资源提交数据进行处理请求(提交表单、上传文件),又可能导致新的资源的建立或原有资源的修改
  • Put 向指定资源位置上上传其最新内容(从客户端向服务器传送的数据取代指定文档的内容)
  • Head 与服务器索与get请求一致的相应,响应体不会返回,获取包含在小消息头中的原信息(与get请求类似,返回的响应中没有具体内容,用于获取报头)
  • Delete 请求服务器删除request-URL所标示的资源(请求服务器删除页面)
  • Trace 回显服务器收到的请求,用于测试和诊断
  • Connect HTTP/1.1协议中能够将连接改为管道方式的代理服务器

​ http服务器至少能实现get、head、post方法,其他都是可选的;从安全防护角度考虑,一般我们要禁用不安全的 HTTP 方法,仅保留 GET、HEAD、POST 方法。过滤掉 DELETE 和 TRACE 等。

​ nginx 禁用不安全的http方法,既可以在nginx配置文件 server 下进行全局设置,也可以在某个location下进行设置。

1、全局设置方式一

        if ($request_method ~ ^(PUT|DELETE|TRACE|HEAD)$) {    #需要将所有不允许的请求方法都写到里面
            return 404;
        }
# ~ ^(PUT|DELETE|TRACE|HEAD)$ :匹配PUT|DELETE|TRACE|HEAD的请求方法

2、全局设置方式二

        if ($request_method !~ ^(GET|POST)$) {
            return 403;
        }

# 大概的意思就是,如果页面使用这二种(GET、POST)之外的方法,
# 网站直接返回403页面,无法获取更多信息,从而加强了服务器的安全性能,
# 添加完成后保存,重载nginx配置文件就行了。

# !~ ^(GET|POST)$ :匹配非GET|POST的请求方法

​ 比如:

server {
        listen       80;
        server_name  www.iwen.com;
        #return 301 https://$server_name$request_uri;
 
        if ($request_method !~ ^(GET|POST)$) {
            return 404;
        }
        .......
        .......
}

3、局部设置方式一:

location /knowlege_app {
        include /usr/local/nginx/allow_ip_list.conf;
        if ($request_method = PUT ) {
                return 404;
        } 
        if ($request_method = DELETE ) {
                return 404;
        }
        if ($request_method = OPTIONS ) {
                return 404;
        }
        if ($request_method = TRACE ) {
                return 404;
        }
        proxy_pass http://serverKnowlege_app;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

4、局部设置方式二:

location /knowlege_app {
	include /usr/local/nginx/allow_ip_list.conf;
	if ($request_method !~ ^(GET|POST|HEAD)$) {
		return 403;
	}
        proxy_pass http://serverKnowlege_app;
        proxy_redirect off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

​ 测试配置: image20210527105812787.png

四、Header头设置

server {
    listen       80;
    server_name xjbt.test.nercoa.com;
# X-Frame-Options头部可以保护你的网站内容
	add_header X-Frame-Options "SAMEORIGIN";
# XSS审计
	add_header X-XSS-Protection "1; mode=block";
# Content Type选项,设置X-Content-Type-Options为nosniff ,就是强迫浏览器尊重服务器端指定的文件类型。	
	add_header X-Content-Type-Options nosniff;
#阻止浏览器拒绝被黑客从HTTPS切换到HTTP等不安全的网址下载内容,HSTS头部选项会强迫用户开始通过HTTPS连接时,以后的连接都是通过HTTPS。	
	add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";

#激活内容安全策略Content Security Policy (CSP) ,大部分浏览器支持
# 告诉浏览器只能从本域名和你显式指定的网址下载脚本。
# http://www.html5rocks.com/en/tutorials/security/content-security-policy/#inline-code-considered-harmful
	add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://assets.zendesk.com; font-src 'self' https://themes.googleusercontent.com; frame-src https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";
	location / {
		...
	}
	...
}

五、添加location限制***----未配置***

不符合请示路径设置的外部请求,统一转到404报错页;首先要获取出允许访问的路径集合信息。

server {
    listen 80;
    listen 443 ssl;
    server_name www.nvic.edu.cn nvic.edu.cn;
	·····
	忽略信息
	·····
# 匹配允许访问的地址信息:
 	location  ~* ^/((\w+\.aspx)|(admin/)|(data/)|(download/)|(Libs/)|(Scripts/)|(Service/)|(staticFile/)|(Templates/)|(Web/)|(Content/)) {
       #只允许符合以上的路径(admin、data、download等)访问,
       proxy_pass http://127.0.0.1:8002;
       proxy_http_version 1.1;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      }

# 匹配首页地址信息:
    location  ~ ^/$ {
       proxy_pass http://127.0.0.1:8002;
       proxy_http_version 1.1;
       proxy_set_header X-Real-IP $remote_addr;
       proxy_set_header Host $host;
       proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

六、禁止文件被下载

zip|rar|sql|bak|7z等内部备份但忘记删除的文件。

#Deny Download
location ~ \.(zip|rar|sql|bak|gz|7z)$ {
  return 404;
}

image20210521162345671.png

七、屏蔽蜘蛛爬虫:

if ($http_user_agent ~* (SemrushBot|python|MJ12bot|AhrefsBot|AhrefsBot|hubspot|opensiteexplorer|leiki|webmeup)) {
     return 404;
}

image20210521162545377.png

八、拒绝一些User-Agents

可以很容易地阻止User-Agents,如soso、已知恶意代理、扫描器,机器人以及滥用你服务器的垃圾邮件发送者。

## Block download agents ##
if	($http_user_agent ~* LWP::Simple|BBBike|wget) {
  return 403;
}
### 阻止Soso和有道的机器人:
## Block some robots ##
if ($http_user_agent ~* Sosospider|YodaoBot) {
  return 403;
}

image20210521162844286.png

九、禁止上传文件夹及图片、样式等文件夹执行.net程序等等:

比如网站上传目录,通常存放的都是静态文件,如果因程序验证不严谨被上传木马程序,导致网站被黑。以下规则请根据自身情况改为您自己的目录,需要禁止的脚本后缀也可以自行添加。

#uploads|templets|data 这些目录禁止执行.net
location ~* ^/(uploads|templets|data)/.*.(exe|aspx)$ {
    return 404;
}

image20210521163348224.png

十、屏蔽某个IP或IP段***----未配置***

如果网站被恶意灌水或CC攻击,可从网站日志中分析特征IP,将其IP或IP段进行屏蔽。模块 ngx_http_access_module 允许限制某些IP地址的客户端访问。

location/ {
    deny  192.168.1.1;
    allow 192.168.1.0/24;
    allow 10.1.1.0/16;
    allow 2001:0db8::/32;
    deny  all;
}
##或者通过IP地址来限制访问目录/docs/:
location /docs/ {
  ## block one workstation
  deny  192.168.1.1;
  ## allow anyone in 192.168.1.0/24
  allow  192.168.1.0/24;
  ## drop rest of the world
  deny  all;
}

注:规则按照顺序依次检测,直到匹配到第一条规则。 在这个例子里,IPv4的网络中只有 10.1.1.0/16 和 192.168.1.0/24允许访问,但 192.168.1.1除外, 对于IPv6的网络,只有2001:0db8::/32允许访问。

上面大部分规则返回444状态码而不是403,因为444状态码在nginx中有特殊含义。nginx的444状态是直接由服务器中断连接,不会向客户端再返回任何消息,比返回403更加暴力。若有不足还请补充和指正。

十一、防止图片盗链***----未配置***

图片或HTML盗链的意思是有人直接用你网站的图片地址来显示在他的网站上。最终的结果,你需要支付额外的宽带费用。这通常是在论坛和博客。我强烈建议您封锁,并阻止盗链行为。

# Stop deep linking or hot linking
location /images/ {
  valid_referers none blocked www.example.com example.com;
  if ($invalid_referer) {
    return  403;
  }
}

例如:重定向并显示指定图片

valid_referers blocked www.example.com example.com;
  
if ($invalid_referer) {
  rewrite ^/images/uploads.*\.(gif|jpg|jpeg|png)$ http://www.examples.com/banned.jpg last
}
server {
    listen       80;
    server_name xjbt.test.nercoa.com;
# X-Frame-Options头部可以保护你的网站内容
	add_header X-Frame-Options "SAMEORIGIN";
# XSS审计
	add_header X-XSS-Protection "1; mode=block";
# Content Type选项,设置X-Content-Type-Options为nosniff ,就是强迫浏览器尊重服务器端指定的文件类型。	
	add_header X-Content-Type-Options nosniff;
#阻止浏览器拒绝被黑客从HTTPS切换到HTTP等不安全的网址下载内容,HSTS头部选项会强迫用户开始通过HTTPS连接时,以后的连接都是通过HTTPS。	
	add_header Strict-Transport-Security "max-age=31536000; includeSubdomains;";

#激活内容安全策略Content Security Policy (CSP) ,大部分浏览器支持
# 告诉浏览器只能从本域名和你显式指定的网址下载脚本。
# http://www.html5rocks.com/en/tutorials/security/content-security-policy/#inline-code-considered-harmful
	add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://ssl.google-analytics.com https://assets.zendesk.com https://connect.facebook.net; img-src 'self' https://ssl.google-analytics.com https://s-static.ak.facebook.com https://assets.zendesk.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com https://assets.zendesk.com; font-src 'self' https://themes.googleusercontent.com; frame-src https://assets.zendesk.com https://www.facebook.com https://s-static.ak.facebook.com https://tautt.zendesk.com; object-src 'none'";

	add_header Access-Control-Allow-Origin: * # 允许所有域请求
#	add_header Access-Control-Allow-Origin: http://someone.com # 允许特定域请求

#禁用所有不需要的 HTTP 方法
    if ($request_method !~ ^(GET|POST|HEAD)$) {
        return 404;
    }
    
#为客户端设置缓冲区大小限制
     client_body_buffer_size  16K;
     client_header_buffer_size  1k;
     client_max_body_size  1m;
     large_client_header_buffers  4  8k;
#    client_max_body_size 100M;

#设置超时时间
    client_body_timeout		10;
    client_header_timeout	30;
    keepalive_timeout		30  30;
    send_timeout		    10;

    location / {
       proxy_pass http://202.205.161.84:9332;
       proxy_set_header   Host             $host;
       proxy_set_header   X-Real-IP        $remote_addr;
       proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
#Proxy Settings
       proxy_redirect     off;
       proxy_set_header   Connection       close;
       proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
       proxy_max_temp_file_size 0;
       proxy_connect_timeout      90;
       proxy_send_timeout         90;
       proxy_read_timeout         90;
       proxy_buffer_size          4k;
       proxy_buffers              4 32k;
       proxy_busy_buffers_size    64k;

#屏蔽蜘蛛爬虫
       if ($http_user_agent ~* (SemrushBot|python|MJ12bot|AhrefsBot|AhrefsBot|hubspot|opensiteexplorer|leiki|webmeup)) {
             return 404;
     }
#拒绝一些User-Agents
       if ($http_user_agent ~* Sosospider|YodaoBot) {
             return 403;
     }
       if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
             return 403;
     }
  }

    location ~* \.(?:ico|css|js|gif|jpe?g|png|svg|woff|ttf|eot)$ {
       proxy_pass http://202.205.161.84:9332;
       proxy_set_header   Host             $host;
       proxy_set_header   X-Real-IP        $remote_addr;
       proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;
#Proxy Settings
       proxy_redirect     off;
       proxy_set_header   Connection       close;
       proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
       proxy_max_temp_file_size 0;
       proxy_connect_timeout      90;
       proxy_send_timeout         90;
       proxy_read_timeout         90;
       proxy_buffer_size          4k;
       proxy_buffers              4 32k;
       proxy_busy_buffers_size    64k;
       add_header Cache-Control "max-age=86400, public";
  }
    error_page   500 502 503 504  /50x.html;

    location = /50x.html {
        root   /usr/share/nginx/html;
  }

#禁止指定格式文件被下载
    location ~ \.(zip|rar|sql|bak|gz|7z)$ {
       return 404;
  }
  
#禁止上传文件夹及图片、样式等文件夹执行.net程序等等
    location ~* ^/(uploads|templets|data)/.*.(exe|aspx)$ {
        return 404;
  }
}


参考链接:

  1. Content Security Policy 入门教程

  2. Nginx提高安全与性能的最好配置

  3. HTTP 安全头配置

  4. 七种HTTP头部设置保护你的网站应用安全

0
  1. 支付宝打赏

    qrcode alipay
  2. 微信打赏

    qrcode weixin

评论区