Detailed nginx the security configuration in the server _nginx

Source: Internet
Author: User
Tags openssl openssl rsa openssl x509 php error sql safe iptables least privilege nginx ssl

This article details the security configuration of the Nginx server, as follows:

First, close SELinux

Security-Enhanced Linux (SELinux) is a Linux kernel feature that provides security policy protection for access control.

However, the added security and usage complexity of selinux is disproportionate and cost-effective

Sed-i/selinux=enforcing/selinux=disabled//etc/selinux/config
/usr/sbin/sestatus-v #查看状态

Second, through the partition mount allows least privilege

A separate partition of the Nginx directory on the server. For example, create a new partition/DEV/SDA5 (first logical partition) and mount it in/nginx. Ensure that/nginx is mounted with the permissions of Noexec, Nodev and Nosetuid

The following is my/etc/fstab/nginx information: Label=/nginx/nginx ext3 defaults,nosuid,noexec,nodev 1 2

Note: You need to create a new partition using the Fdisk and MKFS.EXT3 commands.

Third, configure/etc/sysctl.conf to enhance Linux security

You can edit the/etc/sysctl.conf to control and configure the Linux kernel, network settings

# Avoid a smurf attack net.ipv4.icmp_echo_ignore_broadcasts = 1 # Turn on protection for bad ICMP error messages Net.ipv4 . icmp_ignore_bogus_error_responses = 1 # Turn on syncookies for SYN flood attack protection net.ipv4.tcp_syncookies = 1 # Turn on and log spoofed, source routed, and redirect packets Net.ipv4.conf.all.log_martians = 1 Net.ipv4.conf.default.log_ Martians = 1 # No source routed packets Here Net.ipv4.conf.all.accept_source_route = 0 Net.ipv4.conf.default.accept_source _route = 0 # Turn on reverse path filtering net.ipv4.conf.all.rp_filter = 1 Net.ipv4.conf.default.rp_filter = 1 # make Sur e no one can alter the routing tables net.ipv4.conf.all.accept_redirects = 0 net.ipv4.conf.default.accept_redirects = 0 NE t.ipv4.conf.all.secure_redirects = 0 net.ipv4.conf.default.secure_redirects = 0 # Don ' t act as a router Net.ipv4.ip_forwar  d = 0 net.ipv4.conf.all.send_redirects = 0 net.ipv4.conf.default.send_redirects = 0 # Turn on Execshild Kernel.exec-shield = 1 Kernel.randomize_va_space = 1 # tuen IPv6 net.ipv6.conf.default.router_solicitations = 0 net.ipv6.conf.default.accept_ra_rtr_pref = 0 NET.IPV
6.conf.default.accept_ra_pinfo = 0 Net.ipv6.conf.default.accept_ra_defrtr = 0 net.ipv6.conf.default.autoconf = 0 Net.ipv6.conf.default.dad_transmits = 0 net.ipv6.conf.default.max_addresses = 1 # optimization for Port usefor LBs # Incre ASE System file descriptor Limit Fs.file-max = 65535 # Allow for more PIDs (to reduce rollover problems); May-Break Some programs 32768 Kernel.pid_max = 65536 # Increase system IP Port limits Net.ipv4.ip_local_port_range = 2000  65000 # Increase TCP max buffer size setable using setsockopt () Net.ipv4.tcp_rmem = 4096 87380 8388608 = 4096 87380 8388608 # increase Linux auto tuning TCP buffer limits # min, default, and max number of bytes to use # Set MA X to at least 4MB, or higher if your use very high BDP paths # TCP Windows etc Net.core.rmem_max = 8388608 Net.core.wmem_ma x = 8388608 Net.core.netdev_max_backlog = 5000 NEt.ipv4.tcp_window_scaling = 1
 

Iv. Delete all unwanted nginx modules

You need to minimize the number of modules by compiling Nginx source code directly. Limit the risk to only the Web server access module by restricting it. You can only configure the Nginx to install the modules you need. For example, to disable SSL and AutoIndex modules you can execute the following command:

./configure–without-http_autoindex_module–without-http_ssi_module make
&& make install

Change Nginx version name, edit file/http/ngx_http_header_filter_module.c:

Vim src/http/ngx_http_header_filter_module.c
 
static char ngx_http_server_string[] = "Server:nginx" CRLF;
static char ngx_http_server_full_string[] = "server:" Nginx_ver CRLF;
 
Change to
 
static char ngx_http_server_string[] = "Server:ninja Web server" CRLF;
static char ngx_http_server_full_string[] = "Server:ninja Web server" CRLF;

Turn off the display of the Nginx version number

Server_tokens off

V. Limitations based on the iptables firewall

The following firewall script blocks any except allow:

    • Requests from HTTP (TCP port 80)
    • Requests from the ICMP ping
    • Request output for NTP (Port 123)
    • Request output for SMTP (TCP port 25)

Vi. Controlling buffer overflow attacks

Edit and set the size limit for all client buffers as follows:

Client_body_buffer_size 1K;
Client_header_buffer_size 1k;
Client_max_body_size 1k;
Large_client_header_buffers 2 1k;
    • Client_body_buffer_size 1k (default 8k or 16k) This instruction 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 request entity will attempt to write to a temporary file.
    • The client_header_buffer_size 1k-directive specifies the buffer size of the client request header. In most cases, a request header will not be greater than 1k, but if there is a larger cookie from the WAP client it may be greater than 1k,nginx will assign it a larger buffer, which can be set in Large_client_header_buffers.
    • The client_max_body_size 1k-directive specifies the maximum request entity size to allow client connections, which appears in the Content-length field of the request header. If the request is greater than the specified value, the client receives a "request Entity Too Large" (413) error. Remember, browsers don't know how to display this error.
    • 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 will return "request URI too Large" (414)
    • Similarly, the maximum requested header field cannot be greater than a buffer, or the server will return "Bad Request" (400). Buffers are separated only when required. The default buffer size is the paging file size in the operating system, usually 4k or 8k, and the buffer it occupies will be freed if a connection request eventually converts the state to keep-alive.

You also need to control the timeout to improve server performance and disconnect from the client. Edit as follows:

Client_body_timeout  ;
Client_header_timeout;
Keepalive_timeout   5 5;
Send_timeout     10;
    • The client_body_timeout 10;-instruction specifies the time-out period for the read request entity. Timeout here means 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.
    • The client_header_timeout 10;-directive specifies the time-out period for reading client request header headers. The timeout here means that a request header 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.
    • Keepalive_timeout 5 5; – The first value of the parameter specifies the timeout for the client-server long connection, over which the server closes the connection. 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 repeat the shutdown, and if this parameter is not specified, Nginx will not Send keep-alive information in the answer header. (This does not mean that the two values for a connection "keep-alive" argument can be different.)
    • Send_timeout 10; directive specifies the timeout after sending to the client answer, timeout refers to the failure to enter the full established state, completes only two handshake, if the client does not have any response over this time, Nginx closes the connection.

Seven, control concurrent connection

You can use the Nginxhttplimitzone module to limit concurrent connections in the specific case of a specified session or an IP address. Edit nginx.conf:

### directive describes the zone, in which the session states are the stored. Store in i.e. ###
### 1m can handle 32000 sessions with-bytes/session, set to 5m x 32000 session ###
Limit_zone slimits $bina RY_REMOTE_ADDR 5m;
 
### control maximum number of simultaneous connections for one session i.e. ### ### restricts the
amount of connection s from a single IP address ###
 
limit_conn slimits 5;

The above indicates that a client that restricts each remote IP address cannot have more than 5 connections open at the same time.

Eight, only allow our domain name access

If the robot is just randomly scanning all domain names for the server, then reject the request. You must allow configuration of virtual domains or reverse proxy requests. You don't have to use an IP address to reject it.

if ($host!~ ^ (test.in|www.test.in|images.test.in) $) {return
  444;
}

Ix. restrictions on available request methods

Get and post are the most common methods on the Internet. The Web server method is defined in RFC 2616. If the Web server does not require all available methods to be enabled, they should be disabled. The following instruction filters only the Get,head and post methods:

# # Only allow these request methods # #
if ($request _method!~ ^ (get| head| POST) $ {return
  444;
}
# # do not accept deletes, SEARCH and other methods # #

More on the HTTP method introduction

    • The Get method is used to request, such as file http://www.moqifei.com/index.php.
    • The head method is the same unless the server's GET request is not returned to the body of the message.
    • Post methods can involve a lot of things, such as storing or updating data, ordering products, or sending e-mail by submitting a form. This is usually a script that uses server-side processing, such as Php,perl and Python. If you are uploading files and processing data on the server, you must use this method.

Ten, how to refuse some user-agents?

You can easily block user-agents, such as scanners, bots, and spammers who misuse your server.

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

A robot that blocks Soso and Youdao:

# # Block Some robots #
if ($http _user_agent ~* sosospider| Yodaobot) {return
  403;
}

Xi. Prevention of picture hotlinking

A picture or HTML hotlinking means someone is directly using the image address of your site to display it on his site. In the end, you'll need to pay for the extra broadband costs. This is usually in forums and blogs. I strongly recommend that you blockade and prevent hotlinking behavior.

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

For example, redirect and display the specified picture

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
}

12, Directory Restrictions

You can set access permissions on the specified directory. All Web site directories should be one by one configured to allow only the required directory access.

Restricting access by IP address

You can restrict access to directory/admin/by IP address:

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  ;
}

Protect the directory by password, first create the password file and increase the "user" user

mkdir/usr/local/nginx/conf/.htpasswd/
htpasswd-c/usr/local/nginx/conf/.htpasswd/passwd User

Edit nginx.conf to add a directory to be protected

### Password protect/personal-images/and/delta/directories ###
Location ~/(personal-images/.*|delta/.*) {
  auth_basic "restricted";
  Auth_basic_user_file  /usr/local/nginx/conf/.htpasswd/passwd;
}

Once the password file has been generated, you can also use the following command to increase the number of users who are allowed to access

Htpasswd-s/usr/local/nginx/conf/.htpasswd/passwd UserName

13, Nginx SSL configuration

HTTP is a plain text protocol and it is open to passive monitoring. You should use SSL to encrypt your user's content.
Create an SSL certificate, and execute the following command:

cd/usr/local/nginx/conf
OpenSSL genrsa-des3-out server.key 1024 OpenSSL req-new-key server.key-out server.cs
R
CP Server.key server.key.org
OpenSSL rsa-in server.key.org-out server.key OpenSSL x509-req-days 365-in
Server.csr-signkey Server.key-out SERVER.CRT

Edit the nginx.conf and update as follows:

server {
  server_name example.com;
  Listen 443;
  SSL on;
  SSL_CERTIFICATE/USR/LOCAL/NGINX/CONF/SERVER.CRT;
  Ssl_certificate_key/usr/local/nginx/conf/server.key;
  Access_log/usr/local/nginx/logs/ssl.access.log;
  Error_log/usr/local/nginx/logs/ssl.error.log;
}

14, Nginx and PHP security recommendations
PHP is one of the popular server-side scripting languages. Edit the/etc/php.ini file as follows:

# Disallow Dangerous functions disable_functions = phpinfo, System, mail, EXEC # # Try to limit Resources # # Maximum EXE Cution time of each script, in seconds max_execution_time = # Maximum amount of time each script spend parsing requ EST data max_input_time = Maximum amount of memory a script may consume (8MB) memory_limit = 8M # Maximum size of POS
T data that PHP would accept.
Post_max_size = 8M # Whether to allow HTTP file uploads.
File_uploads = off # Maximum allowed size for uploaded files. Upload_max_filesize = 2M # Don't expose PHP error messages to external users display_errors = out # Turn on Safe Mode SAF E_mode = on # A allow access to executables in isolated directory safe_mode_exec_dir = php-required-executables-path #  Limit external access to PHP environment Safe_mode_allowed_env_vars = php_ # Restrict php Information leakage = Off # Log All Errors log_errors = on # does not register globals to input data register_globals = off # Minimize allowabLe PHP post size post_max_size = 1K # ensure PHP redirects appropriately cgi.force_redirect = 0 # Disallow uploading
 s necessary # Enable SQL Safe Mode sql.safe_mode = on # avoid Opening remote files Allow_url_fopen = off

XV, if possible let Nginx run in a chroot prison

Put Nginx in a chroot prison to reduce the potential for illegal access to other directories. You can use the traditional chroot installed with Nginx. If possible, then use the FreeBSD Jails,xen,openvz virtualization container concept.

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

The network server must monitor the connection and the connection limit per second. Both PF and Iptales are able to block end-user access before entering your Nginx server.
Linux Iptables: Limit the number of connections per Nginx

The following example blocks the number of connections from more than 15 connection ports 80 in 60 seconds from one IP.

/sbin/iptables-a input-p tcp–dport 80-i eth0-m state–state new-m recent–set/sbin/iptables-a input-p TCP–DP
ORT 80-i eth0-m state–state new-m recent–update–seconds 60–hitcount 15-j DROP
service iptables Save

Please set the limit number of connections according to your specific situation.

17, configure the operating system to protect the Web server

Start SELinux like the one described above. Correctly set permissions for the/nginx document root directory. Nginx Run as a user nginx. However, the root directory (/nginx or/usr/local/nginx/html) should not be set to belong to the user nginx or to the user Nginx writable. Files that identify the wrong permissions can use the following command:

Find/nginx-user nginx
find/usr/local/nginx/html-user nginx

Make sure you have more ownership of root or other users, a typical permission setting/usr/local/nginx/html/

Ls-l/usr/local/nginx/html/

Sample output:

-rw-r–r–1 root root 925 3 00:50 error4xx.html
-rw-r–r–1 root root, 3 10:00 error5xx.html-rw-r–r–1
ro OT root 134 3 00:52 index.html

You must delete the backup files created by vi or another text editor:

Find/nginx-name '.? * '-not-name. ht*-or-name ' *~ '-or-name ' *.bak* '-or-name ' *.old* find/usr/local/nginx/html/'-name '
. * '-not-name. ht*-or-name ' *~ '-or-name ' *.bak* '-or-name ' *.old* '

Delete these files by using the-delete option of the Find command.

18, limit nginx connection outgoing

Hackers use tools such as wget to download files that are local to your server. Use Iptables to block outgoing connections from Nginx users. The Ipt_owner module attempts to match the creator of the locally generated packet. In the following example, only user users are allowed to use 80 connections outside.

/sbin/iptables-a output-o eth0-m owner–uid-owner vivek-p tcp–dport 80-m state–state new,established-j ACCEPT

With the above configuration, your Nginx server is already very secure and can publish Web pages. However, you should also search for more security settings according to your website program. For example, WordPress or a third party program.

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.