Security configuration of Nginx under Linux server

Source: Internet
Author: User
Tags epoll fpm gz file sendfile nginx server

1, some common sense
    • Under Linux, to read a file, you first need to have execute permissions on the folder where the file is located, and then you need to read permissions on the file.

    • PHP file execution does not require file execution permissions, only the Nginx and PHP-FPM run account Read permissions.

    • After uploading the Trojan, can not list the contents of a folder, with the PHP-FPM running account of the folder Read permissions related to the Trojan to execute the command of the permissions and PHP-FPM account permissions.

    • If the Trojan to execute the command, need to PHP-FPM account to the corresponding SH have execute permission.

    • To read a file within a folder, you do not need to have Read permission to the folder, only the folder must have execute permissions.

1, the top of the configuration

#定义 nginx User and user group nginx, #进程文件pid/var/run/nginx.pid; #错误日志位置和级别, debug, info, notice, warn, error, Criterror_log  /var/log/nginx/error.log warn; the number of processes #Nginx worker, which can generally be set to the number of CPU cores available. Worker_processes 8; #每个 the maximum limit for the number of worker open file descriptors. The theoretical value should be the maximum number of open files (the value of the system ulimit-n) and the number of nginx processes, but the Nginx allocation request is not uniform, so the recommendation is consistent with the Ulimit-n value. Worker_rlimit_nofile 65535;

2. Events Module

Events {    #设置一个worker进程同时打开的最大连接数    worker_connections 2048;    #告诉nginx收到一个新连接通知后接受尽可能多的连接    multi_accept on;    #设置用于复用客户端线程的轮询方法. If you use Linux 2.6+, you should use Epoll. If you use *BSD, you should use Kqueue. Use    epoll;}

3. HTTP Module

HTTP {#隐藏 The version number of Nginx for increased security.    Server_tokens off; #开启高效文件传输模式, the sendfile instruction specifies whether Nginx calls the Sendfile function to output the file, and for normal applications to be set to ON, if it is used for downloading applications such as disk IO heavy load applications, can be off to balance disk and network I/O processing speed,    Reduce the load on the system.    Sendfile on;    #是否开启目录列表访问, the default is off.    AutoIndex off;    #告诉 Nginx sends all header files in one packet, not one by one send Tcp_nopush on; #告诉 Nginx does not cache data, but a paragraph of the send-when the need to send data in a timely manner, it should be set to the application of this property, so that a small piece of data can not be sent immediately after the return value. Nginx will always work in the TCP Nopush state by default. But when opening the front sendfile on; , it is characterized by the nopush that the last package will automatically convert to nopush off. To reduce the delay of that 200ms, turn on Nodelay; Send it out soon. The conclusion is sendfile on;    When turned on, Tcp_nopush and Tcp_nodelay are on.    Tcp_nodelay on; #日志格式设定 Log_format main ' $remote _addr-$remote _user [$time _local] "$request" "$status $body _bytes_sent" $http _r    Eferer "" "$http _user_agent" "$http _x_forwarded_for";    #定义访问日志, set to off to turn off logging and improve performance Access_log/var/log/nginx/access.log main;    #连接超时时间, Unit is seconds keepalive_timeout 120; #读取HTTP头部的超时时间, the default value is 60. After the client establishes a connection to the server, it begins to receive the HTTP header, in which case the bytes sent to the client are not read within a time interval (timeout), and the client is considered to be timed out and returned to the 408 ("Request timeD out ") response.    Client_header_timeout 60; #默认值 60.    Similar to Client_header_timeout, this time-out is only valid when the HTTP packet is read.    Client_body_timeout 10; #发送响应的超时时间, the default value is 60. That is, the Nginx server sends a packet to the client, but the client has never received the packet.    If a connection exceeds the timeout defined by Send_timeout, then Nginx will close the connection.    Send_timeout 60; #连接超时后将通过向客户端发送RST包来直接重置连接. When this option is turned on, Nginx will not use the normal four handshake to close the TCP connection after a connection time-out, but instead of waiting for the user to reply, the RST reset package is sent directly to the user, releasing all caches on the Nginx server (such as the TCP sliding window) that are used on the socket. It prevents the server from generating many TCP connections in the Fin_wait_1, fin_wait_2, time_wait states compared to the normal shutdown mode.    Note that closing a connection using the RST reset package can cause problems that are not turned on by default.    Reset_timedout_connection off; #要限制连接, you must first have a container to count the connection, "zone=" is to give it a name, can be called casually, the name should be consistent with the following limit_conn.    $binary _REMOTE_ADDR uses binary to store the address of the client, 1m can store 32,000 concurrent sessions.    Limit_conn_zone $binary _remote_addr zone=addr:5m; #给定的key设置最大连接数.    Here key is addr, we set the value is 100, that is to say we allow each IP address at most simultaneously open has 100 connections.    Limit_conn addr 100; #对每个连接限速100k.    This IP is a speed limit of 200K If an IP allows two concurrent connections.     Limit_rate 100k; #include is an instruction that contains the contents of another file in the current file. Here we use it to load the file name extension with the File Type mapping table. Nginx sets the Content-type value of the HTTP request response header based on the mapping relationship. When the mapping table is not found, use the default default-type specified in nginx.confValue.    Include/etc/nginx/mime.types;    #设置文件使用的默认的MIME-type Default_type text/html;    #默认编码 CharSet UTF-8; #该模块可以读取预先压缩的gz文件, this reduces the CPU resource consumption per request for gzip compression.    When the module is enabled, Nginx first checks if there is a file at the end of GZ that requests a static file, and if so, returns the contents of the GZ file directly.      Gzip_static off;    #开启 gzip compression.    gzip on;    # Disable the gzip feature when the client is IE6.    Gzip_disable "Msie6"; #Nginx做为反向代理的时候启用.    Optional value: Off|expired|no-cache|no-sotre|private|no_last_modified|no_etag|auth|any gzip_proxied any; #设置允许压缩的页面最小字节数, the number of page bytes is obtained from Content-length in header.    It is recommended to set the number of bytes greater than 1k, which may be more or less larger than 1k.    Gzip_min_length 1024; #设置数据的压缩等级.    This level can be any number between 1-9, 9 is the slowest but the maximum compression ratio.    Gzip_comp_level 5; #设置系统获取几个单位的缓存用于存储gzip的压缩结果数据流. For example, 4 4k represents 4 times times the original data size in 4k, in 4k, for memory.    If not set, the default value is to request memory space of the same size as the original data to store gzip compression results.    Gzip_buffers 4 16k; #设置需要压缩的数据格式.    Nginx only compresses the text/html by default. Gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml Application/xml+rss    Text/javascript;  #为打开文件指定缓存, the default is not enabled, Max Specifies the number of caches, the recommended number of open files, and inactive refers to how long the file has not been requested to delete the cache.  Open_file_cache max=65535 inactive=30s;    #多长时间检查一次缓存的有效信息 open_file_cache_valid 30s; #open_file_cache指令中的inactive参数时间内文件的最少使用次数, if this number is exceeded, the file descriptor is always opened in the cache.    In the case of last-modified, it is because when Nginx caches a static file, if it is still accessed within 30s, its cache will persist until you do not access it within 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 module

server {#监听端口, Nginx determines which server segment configuration to use, based on the requested HOST. If there is no matching server_name, the first one in the configuration file is used by default.    Plus default_server, you can specify a default rule when there is no match.    #listen 80;    Listen default_server;    #域名可以有多个, separated by a space server_name www.test.com test.com;    Root/user/share/nginx/html/test;    #404页面配置 Error_page 404/404.html;    #配置 SSL and turn it on when needed.    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 Support, the function is to divide the parameters into $fastcgi _script_name and $fastcgi _path_info according to the given regular expression.        #例如: When request INDEX.PHP/ID/1 does not add this line configuration, Fastcgi_script_name is/index.php/id/1,fastcgi_path_info is empty. #加上之后, Fastcgi_script_name is Index.php,fastcgi_path_info is/ID/1 fastcgi_split_path_info^ (. +\.php) (. *) $;        #此值即是 the value of $_server[' Script_filename ' in PHP 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服务器监听端口与地址.        Must be the same as the PHP-FPM settings.        #fastcgi_pass 127.0.0.1:9000;        Fastcgi_pass Unix:/var/run/php5-fpm.sock;    Include Fastcgi_params; }}
2, the common way

1. Let the wood immediately after the transmission can not be executed: for the upload directory, in the Nginx configuration file to add the configuration, so that the directory cannot parse PHP
2. Make the Trojan do not see the non-site Directory files: Cancel php-fpm Run account Read access to other directories
3. After the Trojan executes the command cannot execute: Cancels PHP-FPM account to SH's execution permission
4. Permissions cannot be too high after the command is executed: PHP-FPM account do not use root or join the root group

3, the specific configuration

1. Prohibit access and execution of PHP files

Location ~  /(Attachments|upload)/.*\. ( PHP|PHP5)? $ {     

2. Prohibit access to IP

Forbidden wording deny 10.0.0.0/24;//allowed to 10.0.0.0/24;  

3, according to the user's real IP to do connection restrictions

# # Here get the original user's IP address map $http _x_forwarded_for  $clientRealIp {"" $remote _addr;~^ (? P<firstaddr>[0-9\.] +),?. *$ $firstAddr;} # # for the original user IP address restrictions limit_conn_zone $clientRealIp zone=totalconnlimitzone:20m; limit_conn  Totalconnlimitzone  50;limit_conn_log_level notice;## for the original user IP address restrictions limit_req_zone $clientRealIp zone=connlimitzone:20m  rate=10r/s; #limit_req zone=connlimitzone burst=10 nodelay;limit_req_log_level notice;## The specific server configuration server {listen   80;location ~ \ . php$ {                # # # up to 5 queues, because processing 10 requests per second + 5 queues, you send a maximum of 15 requests a second, and then return directly 503 errors to you limit_req Zone=connlimitzone burst=5 Nodel Ay;fastcgi_pass   127.0.0.1:9000;fastcgi_index  index.php;includefastcgi_params;}}

4, after the multi-tier CDN to obtain the original user's IP address, nginx configuration

Map $http _x_forwarded_for  $clientRealIp {        # # did not pass the proxy, directly with REMOTE_ADDR "" $remote _addr;          # # Use regular match, get user's original IP from X_forwarded_for        # # For example   x-forwarded-for:202.123.123.11, 208.22.22.234, 192.168.2.100,...        # # Here the first 202.123.123.11 is the user's real IP, after the other is the CDN server ~^ (? P<firstaddr>[0-9\.] +),?. *$ $firstAddr;} # # through the map command, we created a variable for nginx $clientRealIp, this is the original user's real IP address, # # No matter whether the user is direct access, or through a series of CDN access, we can get the correct original IP address

5. Hide version Information

Server_tokens   off;proxy_hide_header        x-powered-by;//or edit the source code when compiling

6. Disable non-essential methods

if ($request _method!~ ^ (get| head| (POST) $) {    return    444;}

7. Disable extension

Location ~*. (Txt|doc|sql|gz|svn|git) $ {   deny all;}

8. Reasonable configuration of the response head

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(abbreviated as HSTS) can tell the browser, within the specified max-age, always access via HTTPS

X-Frame-OptionsTo specify whether this page allows the IFRAME to be nested, deny is not allowed to have any nested occurrences

9. Reject some user-agents

if ($http _user_agent ~* lwp::simple| Bbbike|wget) {    return 403;}

10, prevent the picture hotlinking

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. Control Buffer Overflow Attack

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;

Explanatory notes

1, client_body_buffer_size 1k-(default 8k or 16k) This directive can specify the buffer size of the connection request entity. If the connection request exceeds the value specified by the buffer, the whole or part of the requested entity will attempt to write to a temporary file. The
2, client_header_buffer_size 1k-directive specifies the buffer size of the client request header. In most cases a request header will not be larger than 1k, but if there is a larger cookie from the WAP client it may be greater than 1k,nginx will be allocated to it a larger buffer, which can be set in Large_client_header_buffers. The
3, client_max_body_size 1k-directive specifies the maximum requested entity size that is allowed for client connections, which appears in the Content-length field of the request header. If the request is greater than the specified value, the client will receive a "Request Entity Too Large" (413) error. Remember, the browser does not know how to display this error.
4, large_client_header_buffers-specifies the number and size of buffers used by some of the larger request headers of the client. The request field cannot be larger than a buffer size, and if the client sends a larger header, Nginx returns "request URI too Large" (414)

1. The client_body_timeout 10;-instruction specifies the time-out of the read request entity. The timeout here is that a request entity does not enter the read step, and if the connection exceeds this time and the client does not respond, Nginx returns a "request Time Out" (408) error.
2. The client_header_timeout 10;-instruction specifies the time-out for reading the header of the client request header. The timeout here is that a request header does not enter the read step, and if the connection exceeds this time and the client does not respond, Nginx will return a "Request Time Out" (408) error.
3, keepalive_timeout 5 5; – The first value of the parameter specifies the time-out period for the client to connect to the server, and the server closes the connection over that time. The second value of the parameter (optional) specifies the time value of the keep-alive:timeout=time in the answer header, which allows some browsers to know when to close the connection so that the server does not have to shut down repeatedly, and if this parameter is not specified, Nginx does not send keep-alive information in the answer header. (This does not refer to how the two values of a connected "keep-alive") parameter can be different.
4, Send_timeout 10; The instruction specifies the time-out after the response is sent to the client, and timeout refers to a two-time handshake without entering the full established state, and if the client does not respond at this time, Nginx closes the connection.

12, control the concurrent connection

Limit_zone slimits $binary _remote_addr 5m;limit_conn slimits 5;

13. sysctl.conf Configuration

# Avoid A Smurf attacknet.ipv4.icmp_echo_ignore_broadcasts = 1 # Turn on protection for bad ICMP error messagesnet.ipv4.ic  mp_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_marti ans = 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 N o 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# INCR Ease 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 65 # increase TCP max buffer size setable using setsockopt () Net.ipv4.tcp_rmem = 4096 87380 8388608net.ipv4.tcp_wmem = 409 6 87380 8388608 # increase Linux auto tuning TCP buffer limits# min, default, and max number of bytes to use# set Max to a t least 4MB, or higher if you use very high BDP paths# Tcp Windows etcnet.core.rmem_max = 8388608net.core.wmem_max = 83886 08net.core.netdev_max_backlog = 5000net.ipv4.tcp_window_scaling = 1

14. Limit the number of connections per IP at the firewall level

/sbin/iptables-a input-p TCP--dport 80-i eth0-m State--state new-m recent--set/sbin/iptables-a input-p TCP--DPO RT 80-i Eth0-m State--state new-m recent--update--seconds--hitcount 15-j  DROP

15, limit the Nginx connection outgoing

/sbin/iptables-a output-o eth0-m owner--uid-owner vivek-p TCP--dport 80-m State--state new,established-j  ACCE Pt

 

。。。

Reference links

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

 

 

Security configuration of Nginx under Linux server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.