Home IT Linux Windows Database Network Programming Server Mobile  
           
  Home \ Server \ Nginx server security configuration     - learning Linux ls command examples (Linux)

- Linux signal and orphans, and zombie process (Programming)

- Docker build their own private warehouses (Linux)

- How SSHfs mount a remote file system on Linux (Linux)

- Erase do with HTML5 Canvas and diffusion effect (Programming)

- The method of Linux into the rescue mode (Linux)

- To compile and install Clang 3.5.0 in Linux CentOS (Linux)

- Four levels of intrusion on Linux server and counter-measures (Linux)

- Linux redirection and piping (Linux)

- How to install and configure in Ubuntu 14.10 'Weather Information Indicator' (Linux)

- Java objects are taking up much space (Programming)

- OpenGL Programming Guide (8th edition of the original book) - compute shader (Programming)

- cp: omitting directory error solutions under Linux (Linux)

- Build RubyMine + Ruby On Rails + MySQL development environment under Windows (Server)

- CentOS 6.6 source compiler GCC upgrade to 4.8.2 (Linux)

- Ubuntu 12.04 configure NVIDIA CUDA 5.5 Record (Linux)

- Security Knowledge: redirection command application security (Linux)

- Linux, Google Test (GTest) test environment to build step (Linux)

- Linux serial debugging tools xgcom install (Linux)

- Monitoring Linux System 7 command-line tool (Linux)

 
         
  Nginx server security configuration
     
  Add Date : 2018-11-21      
         
       
         
  First, turn off SELinux

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

However, SELinux brings additional security and the disproportionate use of complex, cost is not high

sed -i / SELINUX = enforcing / SELINUX = disabled / / etc / selinux / config

/ Usr / sbin / sestatus -v # View state

Second, through the partition mounted least privilege allowed

Nginx server directory on a separate partition. For example, create a new partition / dev / sda5 (first logical partition) and mount / nginx. Ensure / nginx is noexec, nodev and nosetuid permission to mount

Here is my / etc / fstab mount / nginx information: LABEL = / nginx / nginx ext3 defaults, nosuid, noexec, nodev 1 2

Note: You need to create a new partition using fdisk and mkfs.ext3 command.

Third, to strengthen the Linux security configuration /etc/sysctl.conf

You can control and configure the Linux kernel by editing /etc/sysctl.conf, 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 sure no one can alter the routing tables

net.ipv4.conf.all.accept_redirects = 0

net.ipv4.conf.default.accept_redirects = 0

net.ipv4.conf.all.secure_redirects = 0

net.ipv4.conf.default.secure_redirects = 0

# Do not act as a router

net.ipv4.ip_forward = 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.ipv6.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

# Increase 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

net.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 etc

net.core.rmem_max = 8388608

net.core.wmem_max = 8388608

net.core.netdev_max_backlog = 5000

net.ipv4.tcp_window_scaling = 1

Fourth, remove all unnecessary Nginx module

You need to make the number of modules directly by compiling the source code Nginx minimized. By limiting access to only allow web server module to minimize risk. You can only install nginx configuration modules you need. For example, disabling SSL and autoindex module you can execute the following command:

./configure -without-http_autoindex_module -without-http_ssi_module

make && make install

Change nginx version name, edit the 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;


Close nginx version number display

server_tokens off

Fifth, based on Iptables firewall restrictions

The following firewall script block any addition to allowing:

HTTP (TCP port 80) requests from
From ICMP ping requests
ntp (port 123) of the request output
smtp (TCP port 25) request output

Six control buffer overflow attacks

Edit and set all clients buffer size limits 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 size of the buffer connection request entity. If the value exceeds the specified buffer connection request, then the whole or part of the requesting entity will attempt to write to a temporary file.
client_header_buffer_size 1k- directive specifies the client request buffer size of the head. In most cases a request header is not greater than 1k, but if there is a large cookie wap from clients it may be greater than 1k, Nginx will be assigned to it a larger buffer, this value can be set inside the large_client_header_buffers .
client_max_body_size 1k- directive specifies the maximum allowable size of the client requesting entity connected, it appears in the Content-Length header field of the request. 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 show this error.
large_client_header_buffers- specify the client number and size of some of the larger buffer request header use. Request a field can not be greater than the buffer size, if the client sends a relatively large head, nginx returns "Request URI too large" (414)
Similarly, the head of the longest field of the request can not be larger than a buffer, or the server returns a "Bad request" (400). Buffer only separated when demand. A default buffer size for the operating system paging file size is usually 4k or 8k, if a connection request is eventually converted to state keep- alive, it occupies the buffer will be released.
You also need to improve the performance of the server control timeout and disconnect the client. Edit as follows:

client_body_timeout 10;

client_header_timeout 10;

keepalive_timeout 5 5;

send_timeout 10;

• client_body_timeout 10; - directive specifies the timeout request entity read. Here timeout refers to a requesting entity did not enter the reading step, if the connection after this time the client does not have any response, Nginx will return a "Request time out" (408) error.
• client_header_timeout 10; - directive specifies the client request header headline read timeout. Here timeout refers to a request header did not enter the reading step, if the connection after this time the client does not have any response, Nginx will return a "Request time out" (408) error.
• keepalive_timeout 5 5; - the first parameter specifies the timeout length of the client and server connections, over this time, the server closes the connection. The second value of the parameter (optional) specifies the response header Keep-Alive: timeout = time value of the time, this value can make some browsers know when to close the connection to the server without having to repeatedly shut down, if you do not specify this parameter , nginx does not send Keep-Alive header information in the response. (This does not refer to how to connect a "Keep-Alive") values ​​of these two parameters can be different.
• send_timeout 10; directive specifies the timeout is sent to the client after the response, Timeout refers not enter the state established a complete, finished only two handshakes, if more than this time the client send nothing, nginx will close the connection.

Seven control concurrent connections

You can use NginxHttpLimitZone module to restrict a specific session or a special case of concurrent connections IP addresses under. Edit nginx.conf:

### Directive describes the zone, in which the session states are stored i.e. store in slimits. ###

### 1m can handle 32000 sessions with 32 bytes / session, set to 5m x 32000 session ###

limit_zone slimits $ binary_remote_addr 5m;

 

### Control maximum number of simultaneous connections for one session i.e. ###

### Restricts the amount of connections from a single ip address ###

 

limit_conn slimits 5;


The above represents the remote IP address to limit each client connection can not be open at the same time more than five.

Eight, only allow access to our domain

If the robot is just random scan all domain name servers, that reject the request. You must allow the configuration of the virtual domain or reverse proxy request. You do not use IP addresses to refuse.

if ($ host ~ ^ (test.in |! www.test.in | images.test.in) $) {

    return 444;

}


Nine, to limit the usable request method

GET and POST are the Internet's most commonly used method. The method of the Web server is defined in RFC 2616. If the Web server is not required to run all available methods, they should be disabled. The following command will filter only allows GET, HEAD and POST methods:

## Only allow these request methods ##

if ($ request_method ~ ^ (GET |! HEAD | POST) $) {

    return 444;

}

## Do not accept DELETE, SEARCH and other methods ##


More about HTTP method introduced

• GET method is used to request such documents http://www.linuxidc.com/index.php.


• HEAD method is the same, unless the GET request to the server can not return the message body.


• POST method may involve a lot of things, such as a store or update data, or ordering products, or send e-mail by submitting the form. This is often the use of server-side processing, such as PHP, Perl and Python scripts. If the file you want to upload and server processing data, you must use this method.


Ten, how to refuse a number of User-Agents?

You can easily stop User-Agents, such as scanners, robotics and abuse of your server spammers.

## Block download agents ##

if ($ http_user_agent ~ * LWP :: Simple | BBBike | wget) {

    return 403;

}

Soso and proper way to prevent robots:

## Block some robots ##

if ($ http_user_agent ~ * Sosospider | YodaoBot) {

    return 403;

}


XI prevent image hotlinking

Images or HTML directly Daolian mean someone with your website address to display pictures on his website. The end result, you need to pay the extra cost of broadband. This is usually in forums and blog. I strongly recommend that you block 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 displays the specified image

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

}

XII directory restrictions

You can set up access to the specified directory. All web directory every one of them should be configured to allow only directory access required.
Restrict access by IP address
You can restrict access by IP address directory / admin /:

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;

}

Via password protected directory, first create a password file to add the "user" user

mkdir /usr/local/nginx/conf/.htpasswd/

htpasswd -c /usr/local/nginx/conf/.htpasswd/passwd user


Edit nginx.conf, added to the directory in need of protection

### 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 access of users to allow

htpasswd -s /usr/local/nginx/conf/.htpasswd/passwd userName

Thirteen, Nginx SSL Configuration

HTTP is a plain text protocol, which is open to passive surveillance. You should use SSL to encrypt your user content.
Create an SSL certificate, execute the following command:

cd / usr / local / nginx / conf

openssl genrsa -des3 -out server.key 1024

openssl req -new -key server.key -out server.csr

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 nginx.conf press the following update:

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;

}


Fourteen, Nginx and PHP Security Recommendations

PHP is a popular scripting language on the server side. Edit /etc/php.ini following documents:

# Disallow dangerous functions

disable_functions = phpinfo, system, mail, exec

## Try to limit resources ##

# Maximum execution time of each script, in seconds

max_execution_time = 30

# Maximum amount of time each script may spend parsing request data

max_input_time = 60

# Maximum amount of memory a script may consume (8MB)

memory_limit = 8M

# Maximum size of POST data that PHP will accept.

post_max_size = 8M

# Whether to allow HTTP file uploads.

file_uploads = Off

# Maximum allowed size for uploaded files.

upload_max_filesize = 2M

# Do not expose PHP error messages to external users

display_errors = Off

# Turn on safe mode

safe_mode = On

# Only 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

expose_php = Off

# Log all errors

log_errors = On

# Do not register globals for input data

register_globals = Off

# Minimize allowable PHP post size

post_max_size = 1K

# Ensure PHP redirects appropriately

cgi.force_redirect = 0

# Disallow uploading unless necessary

# Enable SQL safe mode

sql.safe_mode = On

# Avoid Opening remote files

allow_url_fopen = Off


Fifth, if possible, let Nginx runs in a chroot jail

The nginx placed in a chroot jail to reduce the potential for illegal entry into other directories. You can use the traditional and nginx installed with chroot. If possible, that use FreeBSD jails, Xen, OpenVZ virtualization container concept.

XVI firewall level limits the number of connections per IP

Web server must monitor connections and connection limits per second. PF and Iptales are able to enter your nginx server to stop before the end-user access.
Linux Iptables: limit the number of connections each Nginx
The following example will prevent from a single IP connection of more than 15 port number 80 within 60 seconds.

/ 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

service iptables save


Depending on your specific situation to set the connection limit.

XVII configure the operating system to protect Web servers

Start SELinux like described above. Correctly set permissions / nginx document root directory. Nginx runs with the user nginx. But the root directory (/ nginx or / usr / local / nginx / html) should not be set, or the user belongs to the user nginx nginx writable. Find the error file permissions can use the following command:

find / nginx -user nginx

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


Make sure you more ownership for the root or other user, a typical set of permissions for / usr / local / nginx / html /

ls -l / usr / local / nginx / html /

Sample output:

-rw-r-r- 1 root root 925 Jan 3 00:50 error4xx.html

-rw-r-r- 1 root root 52 Jan 3 10:00 error5xx.html

-rw-r-r- 1 root root 134 Jan 3 00:52 index.html

You must delete the backup files from the vi or another text editor to create:

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 * '


To delete these files -delete option to find command.

Eighth, the outgoing connections limit Nginx

Hackers use tools such as wget download your local file server. Use Iptables from nginx user to block outgoing connections. ipt_owner module tries to match the creator of locally generated packets. The following examples only allows user to connect 80 users to use 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 very safe and you can publish web pages. However, you should also find more information on the security settings according to your site procedures. For example, wordpress or third-party programs.
     
         
       
         
  More:      
 
- Linux Command Tutorial: du command to view disk space (Linux)
- Ubuntu comes with gedit editor to add Markdown preview widget (Linux)
- Linux scheduling summary (Linux)
- Java data structures - the linear form of the single-chain applications (Programming)
- Linux system on how to use rsync to synchronize data (Server)
- Ubuntu 14.04 and derivative versions of the user install Pantheon Photos 0.1 (Linux)
- Slow update statement Performance Analysis (Database)
- Try to use Lets Encrypt (Linux)
- Simple security measures to reinforce the Linux kernel (Linux)
- MySQL query plan key_len know all (Database)
- Linux basic introductory tutorial ---- regex basis (Linux)
- Subsequent binary search tree traversal sequence (Programming)
- MySQL 5.6.26 source install (Database)
- Android Notification (Programming)
- CentOS source installation GitLab Chinese Version (Server)
- Teach you how to ensure password security under the Linux operating system (Linux)
- Linux installation Jetty deployment under RedHat5 8 (Linux)
- Linux server remote user to obtain root privileges prevention (Linux)
- Programmer editor Vim (Linux)
- Implement firewall function on a closed Linux machine (Linux)
     
           
     
  CopyRight 2002-2016 newfreesoft.com, All Rights Reserved.