centos7下nginx安全配置
Linux服务器下nginx的安全配置
1、一些常识
- 
linux下,要读取一个文件,首先需要具有对文件所在文件夹的执行权限,然后需要对文件的读取权限。 
- 
php文件的执行不需要文件的执行权限,只需要nginx和php-fpm运行账户的读取权限。 
- 
上传木马后,能不能列出一个文件夹的内容,跟php-fpm的运行账户对文件夹的读取权限有关,木马执行命令的权限跟php-fpm的账户权限有关。 
- 
如果木马要执行命令,需要php-fpm的账户对相应的sh有执行权限。 
- 
读取一个文件夹内的文件,是不需要对文件夹有读取权限的,只需要对文件夹有执行权限。 
1、顶部配置
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #定义 Nginx 运行的用户和用户组user nginx;#进程文件pid /var/run/nginx.pid;#错误日志位置和级别,debug、info、notice、warn、error、criterror_log  /var/log/nginx/error.log warn;#Nginx worker 的进程数,一般可设置为可用的CPU内核数。worker_processes 8;#每个 worker 打开文件描述符的最大数量限制。理论值应该是最多打开文件数(系统的值ulimit -n)与 nginx 进程数相除,但是 nginx 分配请求并不均匀,所以建议与ulimit -n的值保持一致。worker_rlimit_nofile 65535; | 
2、Events 模块
| 1 2 3 4 5 6 7 8 9 10 | events {    #设置一个worker进程同时打开的最大连接数    worker_connections 2048;    #告诉nginx收到一个新连接通知后接受尽可能多的连接    multi_accept on;    #设置用于复用客户端线程的轮询方法。如果你使用Linux 2.6+,你应该使用epoll。如果你使用*BSD,你应该使用kqueue。    use epoll;} | 
3、HTTP 模块
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | http {    #隐藏 Nginx 的版本号,提高安全性。    server_tokens off;    #开启高效文件传输模式,sendfile 指令指定 Nginx 是否调用sendfile 函数来输出文件,对于普通应用设为 on,如果用来进行下载等应用磁盘 IO 重负载应用,可设置为 off,以平衡磁盘与网络 I/O 处理速度,降低系统的负载。    sendfile on;    #是否开启目录列表访问,默认关闭。    autoindex off;    #告诉 Nginx 在一个数据包里发送所有头文件,而不一个接一个的发送    tcp_nopush on;    #告诉 Nginx 不要缓存数据,而是一段一段的发送--当需要及时发送数据时,就应该给应用设置这个属性,这样发送一小块数据信息时就不能立即得到返回值。Nginx 默认会始终工作在 tcp nopush 状态下。但是当开启前面的 sendfile on; 时,它的工作特点是 nopush 的最后一个包会自动转转换到 nopush off。为了减小那200ms的延迟,开启 nodelay on; 将其很快传送出去。结论就是 sendfile on; 开启时,tcp_nopush 和 tcp_nodelay 都是on 是可以的。    tcp_nodelay on;    #日志格式设定    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '    '$status $body_bytes_sent "$http_referer" '    '"$http_user_agent" "$http_x_forwarded_for"';    #定义访问日志,设置为 off 可以关闭日志,提高性能    access_log /var/log/nginx/access.log main;    #连接超时时间,单位是秒    keepalive_timeout 120;    #读取HTTP头部的超时时间,默认值 60。客户端与服务器建立连接后将开始接收HTTP头部,在这个过程中,如果在一个时间间隔(超时时间)内没有读取到客户端发来的字节,则认为超时,并向客户端返回408 ("Request timed out")响应。    client_header_timeout 60;    #默认值 60。与client_header_timeout相似,只是这个超时时间只在读取HTTP包体时才有效。    client_body_timeout 10;    #发送响应的超时时间,默认值 60。即Nginx服务器向客户端发送了数据包,但客户端一直没有去接收这个数据包。如果某个连接超过send_timeout定义的超时时间,那么Nginx将会关闭这个连接。    send_timeout 60;    #连接超时后将通过向客户端发送RST包来直接重置连接。这个选项打开后,Nginx会在某个连接超时后,不是使用正常情形下的四次握手关闭TCP连接,而是直接向用户发送RST重置包,不再等待用户的应答,直接释放Nginx服务器上关于这个套接字使用的所有缓存(如TCP滑动窗口)。相比正常的关闭方式,它使得服务器避免产生许多处于FIN_WAIT_1、FIN_WAIT_2、TIME_WAIT状态的TCP连接。注意,使用RST重置包关闭连接会带来一些问题,默认情况下不会开启。    reset_timedout_connection off;    #要限制连接,必须先有一个容器对连接进行计数,"zone=" 是给它一个名字,可以随便叫,这个名字要跟下面的 limit_conn 一致。$binary_remote_addr 用二进制来储存客户端的地址,1m 可以储存 32000 个并发会话。    limit_conn_zone $binary_remote_addr zone=addr:5m;    #给定的key设置最大连接数。这里key是addr,我们设置的值是100,也就是说我们允许每一个IP地址最多同时打开有100个连接。    limit_conn addr 100;    #对每个连接限速100k。这如果一个IP允许两个并发连接,那么这个IP就是限速200K。    limit_rate 100k;    #include 是一个在当前文件中包含另一个文件内容的指令。这里我们使用它来加载文件扩展名与文件类型映射表。nginx根据映射关系,设置http请求响应头的Content-Type值。当在映射表找不到时,使用nginx.conf中default-type指定的默认值。    include /etc/nginx/mime.types;    #设置文件使用的默认的MIME-type    default_type text/html;    #默认编码    charset UTF-8;    #该模块可以读取预先压缩的gz文件,这样可以减少每次请求进行gzip压缩的CPU资源消耗。该模块启用后,nginx首先检查是否存在请求静态文件的gz结尾的文件,如果有则直接返回该gz文件内容。    gzip_static off;     #开启 gzip 压缩。    gzipon;    # 禁用客户端为 IE6 时的 gzip功能。    gzip_disable "msie6";    #Nginx做为反向代理的时候启用。可选值:off|expired|no-cache|no-sotre|private|no_last_modified|no_etag|auth|any    gzip_proxied any;    #设置允许压缩的页面最小字节数,页面字节数从header头中的Content-Length中进行获取。建议设置成大于1k的字节数,小于1k可能会越压越大。    gzip_min_length 1024;    #设置数据的压缩等级。这个等级可以是1-9之间的任意数值,9是最慢但是压缩比最大的。    gzip_comp_level 5;    #设置系统获取几个单位的缓存用于存储gzip的压缩结果数据流。 例如 4 4k 代表以4k为单位,按照原始数据大小以4k为单位的4倍申请内存。如果没有设置,默认值是申请跟原始数据相同大小的内存空间去存储gzip压缩结果。    gzip_buffers 4 16k;    #设置需要压缩的数据格式。Nginx默认只对text/html进行压缩。    gzip_types text/plaintext/cssapplication/jsonapplication/x-javascripttext/xmlapplication/xmlapplication/xml+rss text/javascript;    #为打开文件指定缓存,默认是没有启用的,max 指定缓存数量,建议和打开文件数一致,inactive 是指经过多长时间文件没被请求后删除缓存。    open_file_cache max=65535 inactive=30s;    #多长时间检查一次缓存的有效信息    open_file_cache_valid 30s;    #open_file_cache指令中的inactive参数时间内文件的最少使用次数,如果超过这个数字,文件描述符一直是在缓存中打开的。出现 Last-Modified 不变的情况,就是因为当nginx对一个静态文件缓存后,如果30s内还在访问它,那么它的缓存就一直存在,直到30s内你不访问了为止。    open_file_cache_min_uses 2;    #是否记录cache错误    open_file_cache_errors on;    include /etc/nginx/conf.d/*.conf;    include /etc/nginx/sites-enabled/*;} | 
4、SERVER 模块
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | server {    #监听端口,nginx 会根据请求的 HOST 来决定使用哪个 SERVER 段的配置。如果没有匹配的 server_name,则默认使用配置文件中第一个。加上 default_server 则可以以指定没有匹配时的默认规则。    #listen 80;    listen 80 default_server;    #域名可以有多个,用空格隔开    server_name www.test.com test.com;    root /user/share/nginx/html/test;    #404页面配置    error_page   404   /404.html;    #配置 ssl,有需要时开启。    ssl on;    ssl_certificate /etc/nginx/ssl/server.crt;    ssl_certificate_key /etc/nginx/ssl/server.key;    location / {        index   index.html index.php;    }    #图片缓存时间设置    location ~ .*.(gif|jpg|jpeg|png|bmp|swf)$ {        expires 10d;    }    #JS和CSS缓存时间设置    location ~ .*.(js|css)?$ {        expires 1h;    }    location ~ [^/]\.php(/|$) {        fastcgi_index   index.php;        #开启 PATH_INFO 支持,作用就是把参数按照给定的正则表达式分割成 $fastcgi_script_name 和 $fastcgi_path_info。        #例如:请求 index.php/id/1 不加此行配置时,fastcgi_script_name 是 /index.php/id/1,fastcgi_path_info 是空。        #加上之后,fastcgi_script_name 是 index.php,fastcgi_path_info 是 /id/1        fastcgi_split_path_info ^(.+\.php)(.*)$;        #此值即是 PHP 中 $_SERVER['SCRIPT_FILENAME'] 的值        fastcgi_param   SCRIPT_FILENAME $document_root$fastcgi_script_name;        fastcgi_param   PATH_INFO               $fastcgi_path_info;        fastcgi_param   PATH_TRANSLATED $document_root$fastcgi_path_info;        #指定FastCGI服务器监听端口与地址。须和 PHP-FPM 的设置相同。        #fastcgi_pass   127.0.0.1:9000;        fastcgi_pass    unix:/var/run/php5-fpm.sock;        include fastcgi_params;    }} | 
2、常见的方式
1. 让木马上传后不能执行:针对上传目录,在nginx配置文件中加入配置,使此目录无法解析php
2. 让木马执行后看不到非网站目录文件:取消php-fpm运行账户对于其他目录的读取权限
3. 木马执行后命令不能执行:取消php-fpm账户对于sh的执行权限
4. 命令执行后权限不能过高:php-fpm账户不要用root或者加入root组
3、具体的配置
1、禁止php文件的访问及执行
| 1 2 3 | location ~  /(attachments|upload)/.*\.(php|php5)?$ {    deny all;} | 
2、禁止IP的访问
| 1 2 3 4 5 6 | //禁止的写法deny 10.0.0.0/24;//允许的写法allow 10.0.0.0/24; deny all; | 
3、根据用户的真实 IP 做连接限制
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | ## 这里取得原始用户的IP地址map $http_x_forwarded_for  $clientRealIp {    ""$remote_addr;    ~^(?P<firstAddr>[0-9\.]+),?.*$    $firstAddr;}## 针对原始用户 IP 地址做限制limit_conn_zone $clientRealIp zone=TotalConnLimitZone:20m ;limit_conn  TotalConnLimitZone  50;limit_conn_log_level notice;## 针对原始用户 IP 地址做限制limit_req_zone $clientRealIp zone=ConnLimitZone:20m  rate=10r/s;#limit_req zone=ConnLimitZone burst=10 nodelay;limit_req_log_level notice;## 具体服务器配置server {    listen   80;    location ~ \.php$ {                ## 最多 5 个排队, 由于每秒处理 10 个请求 + 5个排队,你一秒最多发送 15 个请求过来,再多就直接返回 503 错误给你了        limit_req zone=ConnLimitZone burst=5 nodelay;        fastcgi_pass   127.0.0.1:9000;        fastcgi_index  index.php;        include fastcgi_params;    }  } | 
4、 经过多层CDN之后取得原始用户的IP地址,nginx 配置
| 1 2 3 4 5 6 7 8 9 10 11 | map $http_x_forwarded_for  $clientRealIp {        ## 没有通过代理,直接用 remote_addr    ""$remote_addr;         ## 用正则匹配,从 x_forwarded_for 中取得用户的原始IP        ## 例如   X-Forwarded-For: 202.123.123.11, 208.22.22.234, 192.168.2.100,...        ## 这里第一个 202.123.123.11 是用户的真实 IP,后面其它都是经过的 CDN 服务器    ~^(?P<firstAddr>[0-9\.]+),?.*$    $firstAddr;}## 通过 map 指令,我们为 nginx 创建了一个变量 $clientRealIp ,这个就是 原始用户的真实 IP 地址,## 不论用户是直接访问,还是通过一串 CDN 之后的访问,我们都能取得正确的原始IP地址 | 
5、隐藏版本信息
| 1 2 3 | server_tokens   off;proxy_hide_header        X-Powered-By;//或者编译的时候修改源代码 | 
6、禁用非必要的方法
| 1 2 3 | if($request_method !~ ^(GET|HEAD|POST)$ ) {    return444;} | 
7、禁用扩展名
| 1 2 3 | location ~* .(txt|doc|sql|gz|svn|git)$ {   deny all;} | 
8、合理配置响应头
| 1 2 3 4 | add_header  Strict-Transport-Security  "max-age=31536000";add_header  X-Frame-Options  deny;add_header  X-Content-Type-Options  nosniff;add_header  Content-Security-Policy  "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval' https://a.disquscdn.com; img-src 'self' data: https://www.google-analytics.com; style-src 'self' 'unsafe-inline'; frame-src https://disqus.com"; | 
Strict-Transport-Security(简称为 HSTS)可以告诉浏览器,在指定的 max-age 内,始终通过 HTTPS 访问
X-Frame-Options 用来指定此网页是否允许被 iframe 嵌套,deny 就是不允许任何嵌套发生
9、拒绝一些User-Agents
| 1 2 3 | if($http_user_agent ~* LWP::Simple|BBBike|wget) {    return403;} | 
10、防止图片盗链
| 1 2 3 4 | 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} | 
11、控制缓冲区溢出攻击
| 1 2 3 4 5 6 7 8 9 | client_body_buffer_size  1K;client_header_buffer_size 1k;client_max_body_size 1k;large_client_header_buffers 2 1k;client_body_timeout   10;client_header_timeout 10;keepalive_timeout     5 5;send_timeout          10; | 
解释说明
1、client_body_buffer_size 1k-(默认8k或16k)这个指令可以指定连接请求实体的缓冲区大小。如果连接请求超过缓存区指定的值,那么这些请求实体的整体或部分将尝试写入一个临时文件。
2、client_header_buffer_size 1k-指令指定客户端请求头部的缓冲区大小。绝大多数情况下一个请求头不会大于1k,不过如果有来自于wap客户端的较大的cookie它可能会大于1k,Nginx将分配给它一个更大的缓冲区,这个值可以在large_client_header_buffers里面设置。
3、client_max_body_size 1k-指令指定允许客户端连接的最大请求实体大小,它出现在请求头部的Content-Length字段。如果请求大于指定的值,客户端将收到一个”Request Entity Too Large” (413)错误。记住,浏览器并不知道怎样显示这个错误。
4、large_client_header_buffers-指定客户端一些比较大的请求头使用的缓冲区数量和大小。请求字段不能大于一个缓冲区大小,如果客户端发送一个比较大的头,nginx将返回”Request URI too large” (414)1、client_body_timeout 10;-指令指定读取请求实体的超时时间。这里的超时是指一个请求实体没有进入读取步骤,如果连接超过这个时间而客户端没有任何响应,Nginx将返回一个”Request time out” (408)错误。
2、client_header_timeout 10;-指令指定读取客户端请求头标题的超时时间。这里的超时是指一个请求头没有进入读取步骤,如果连接超过这个时间而客户端没有任何响应,Nginx将返回一个”Request time out” (408)错误。
3、keepalive_timeout 5 5; – 参数的第一个值指定了客户端与服务器长连接的超时时间,超过这个时间,服务器将关闭连接。参数的第二个值(可选)指定了应答头中Keep-Alive: timeout=time的time值,这个值可以使一些浏览器知道什么时候关闭连接,以便服务器不用重复关闭,如果不指定这个参数,nginx不会在应答头中发送Keep-Alive信息。(但这并不是指怎样将一个连接“Keep-Alive”)参数的这两个值可以不相同。
4、send_timeout 10; 指令指定了发送给客户端应答后的超时时间,Timeout是指没有进入完整established状态,只完成了两次握手,如果超过这个时间客户端没有任何响应,nginx将关闭连接。
12、控制并发连接
| 1 2 | limit_zone slimits $binary_remote_addr 5m;limit_conn slimits 5; | 
13、sysctl.conf配置
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | # Avoid a smurf attacknet.ipv4.icmp_echo_ignore_broadcasts = 1 # Turn on protection for bad icmp error messagesnet.ipv4.icmp_ignore_bogus_error_responses = 1 # Turn on syncookies for SYN flood attack protectionnet.ipv4.tcp_syncookies = 1 # Turn on and log spoofed, source routed, and redirect packetsnet.ipv4.conf.all.log_martians = 1net.ipv4.conf.default.log_martians = 1 # No source routed packets herenet.ipv4.conf.all.accept_source_route = 0net.ipv4.conf.default.accept_source_route = 0 # Turn on reverse path filteringnet.ipv4.conf.all.rp_filter = 1net.ipv4.conf.default.rp_filter = 1 # Make sure no one can alter the routing tablesnet.ipv4.conf.all.accept_redirects = 0net.ipv4.conf.default.accept_redirects = 0net.ipv4.conf.all.secure_redirects = 0net.ipv4.conf.default.secure_redirects = 0 # Don't act as a routernet.ipv4.ip_forward = 0net.ipv4.conf.all.send_redirects = 0net.ipv4.conf.default.send_redirects = 0 # Turn on execshildkernel.exec-shield = 1kernel.randomize_va_space = 1 # Tuen IPv6net.ipv6.conf.default.router_solicitations = 0net.ipv6.conf.default.accept_ra_rtr_pref = 0net.ipv6.conf.default.accept_ra_pinfo = 0net.ipv6.conf.default.accept_ra_defrtr = 0net.ipv6.conf.default.autoconf = 0net.ipv6.conf.default.dad_transmits = 0net.ipv6.conf.default.max_addresses = 1 # Optimization for port usefor LBs# Increase system file descriptor limitfs.file-max = 65535 # Allow for more PIDs (to reduce rollover problems); may break some programs 32768kernel.pid_max = 65536 # Increase system IP port limitsnet.ipv4.ip_local_port_range = 2000 65000 # Increase TCP max buffer size setable using setsockopt()net.ipv4.tcp_rmem = 4096 87380 8388608net.ipv4.tcp_wmem = 4096 87380 8388608 # Increase Linux auto tuning TCP buffer limits# min, default, and max number of bytes to use# set max to at least 4MB, or higher if you use very high BDP paths# Tcp Windows etcnet.core.rmem_max = 8388608net.core.wmem_max = 8388608net.core.netdev_max_backlog = 5000net.ipv4.tcp_window_scaling = 1 | 
14、在防火墙级限制每个IP的连接数
| 1 2 | /sbin/iptables-A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --set/sbin/iptables-A INPUT -p tcp --dport 80 -i eth0 -m state --state NEW -m recent --update --seconds 60  --hitcount 15 -j DROP | 
15、限制Nginx连接传出
| 1 | /sbin/iptables-A OUTPUT -o eth0 -m owner --uid-owner vivek -p tcp --dport 80 -m state --state NEW,ESTABLISHED  -j ACCEPT | 
。。。
参考链接
http://www.bzfshop.net/article/176.html
http://nginx.org/en/docs/
http://www.oschina.net/translate/nginx-setup
http://www.ha97.com/5194.html
https://www.cnblogs.com/chenpingzhao/p/5785416.html
- 作者:踏雪无痕
- 出处:http://www.cnblogs.com/chenpingzhao/
- 本文版权归作者和博客园共有,如需转载,请联系 pingzhao1990#163.com
 
                    
                     
                    
                 
                    
                 
 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号