current position:Home>Nginx security optimization

Nginx security optimization

2022-04-29 15:26:29Cloud computing security

Preface

As mixed in IT A member of the industry , I believe everyone has been in contact with Nginx Web service , Whether it's development 、 Operation and maintenance 、 test 、 Or algorithms are inseparable Nginx, And everyone is concerned about Nginx Our deployment is also handy . But sometimes we are only limited to the deployment application level , No consideration is given to its operation in Internet Security issues on , Next, we will summarize some common security policies that are also necessary to configure in the production environment .

1、 Use SSL/TLS certificate

Conventional HTTP It is an end-to-end hypertext transmission protocol in plaintext form , There are great security problems in data transmission , Such as : hacking 、 Tampering 、 Security issues such as impersonation . So we need to adopt SSL/TLS Certificate to achieve data encryption ,SSL/TLS A certificate is an encrypted digital certificate , Used to access the client (Web browser ) Encrypt the traffic between and the server . By doing so , The encryption is secure , And it can prevent attackers from using man in the middle attack to eavesdrop and steal confidential information , for example user name 、 Password and credit card information, etc .

How to be in Nginx Configuration on the server ?

server {
    
    listen              443 ssl;
    ssl_certificate     /etc/nginx/ssl/bundle.pem;
    ssl_certificate_key /etc/nginx/ssl/mytechnix.com.key;
}

#  Of course , In our practical application , Different cloud factories will provide corresponding reference configurations 

2、 Use secure key exchange mechanism

DH The purpose of the parameter is to allow the exchange of a secret , Use the secret copy of the message in the encrypted session . temporary DH Provide forward security , This means that the session key is deleted when the session terminates . therefore , An attacker cannot retrieve messages exchanged between more than two parties in the previous session .

Use OpenSSL Generate at least 2048 The only one DH Group :

openssl dhparam -out /etc/ssl/dhparam.pem 2048

How to be in Nginx Configuration on the server ?

ssl_dhparam  /etc/ssl/dhparam.pem; 

3、 Disable the old SSL/TLS agreement

Weak SSL/TLS agreement (SSLv2.0、SSL v3.0、TLSv1.0 and TLSv1.1) May be vulnerable to attack and lead to problems such as BEAST( in the light of SSL/TLS Browser exploits )、POODLE( Fill in the degraded old version Oracle ) Such attacks . Therefore, it is recommended to use updated and secure SSL/TLS agreement .

How to be in Nginx Configuration on the server ?

server {
    
    listen              443 ssl;
    ssl_certificate     /etc/nginx/ssl/bundle.pem;
    ssl_certificate_key /etc/nginx/ssl/mytechnix.com.key;
    ssl_protocols TLSv1.2 TLSv1.3;
}

4、 Ban SSL/TLS Weak cipher Suite

Weak and old password suite configuration may easily make your website vulnerable , For example, the attacker may intercept or modify the data in transmission . therefore , You can be more different Nginx Version and SSL/TLS Version to choose a better Password Suite , You can use this website to evaluate the best solution —> Portal . Input nginx and SSL/TLS After version , It will automatically generate the best configuration file for you , For example, I entered Nginx Version is 1.18.0、SSL/TLS Version is 1.1.1, The following results will be generated :

# generated 2022-04-27, Mozilla Guideline v5.6, nginx 1.18.0, OpenSSL 1.1.1k, intermediate configuration
# https://ssl-config.mozilla.org/#server=nginx&version=1.18.0&config=intermediate&openssl=1.1.1k&guideline=5.6
server {
    
    listen 80 default_server;
    listen [::]:80 default_server;

    location / {
    
        return 301 https://$host$request_uri;
    }
}

server {
    
    listen 443 ssl http2;
    listen [::]:443 ssl http2;

    ssl_certificate /path/to/signed_cert_plus_intermediates;
    ssl_certificate_key /path/to/private_key;
    ssl_session_timeout 1d;
    ssl_session_cache shared:MozSSL:10m;  # about 40000 sessions
    ssl_session_tickets off;

    # curl https://ssl-config.mozilla.org/ffdhe2048.txt > /path/to/dhparam
    ssl_dhparam /path/to/dhparam;

    # intermediate configuration
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers off;  #  If necessary, change to on that will do 

    # HSTS (ngx_http_headers_module is required) (63072000 seconds)
    add_header Strict-Transport-Security "max-age=63072000" always;

    # OCSP stapling
    ssl_stapling on;
    ssl_stapling_verify on;

    # verify chain of trust of OCSP response using Root CA and Intermediate certs
    ssl_trusted_certificate /path/to/root_CA_cert_plus_intermediates;

    # replace with the IP address of your resolver
    resolver 127.0.0.1;
}

5、 Disable unnecessary HTTP Method

frequently-used HTTP The method is GET and POST, If other methods are allowed, such as TRACE、DELETE、PUT and OPTIONS There are risks , Because this could allow an attacker to launch Cross site tracking attacks And steal... From your website cookie Information , Therefore, it is recommended to disable unwanted and unused HTTP Method .

How to be in Nginx Configuration on the server ?

#  Configuration mode 1: here , The server will only allow  GET、HEAD  and  POST  Method .
location / {
    
    limit_except GET HEAD POST {
     deny all; }
}

#  Configuration mode 2: The effect is the same 1
#  The server only allows  GET、HEAD  and  POST  Method , And issued  444 No Response  The status code filters out any other  HTTP  Method .
if ($request_method !~ ^(GET|HEAD|POST)$ )
{
    
    return 444;
}

6、 Prevent buffer overflow attacks

A buffer is a small storage location in system memory , When data begins to transfer from one memory location to another , It can hold data temporarily . When the data size exceeds the capacity of the buffer size , A buffer overflow will occur . therefore , An attacker can use this vulnerability to inject malicious code that can harm the system .

How to be in Nginx Configuration on the server ?

client_body_buffer_size 1K;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;

7、 prevent CSP、XSS attack

CSP( Content security policy ) It's an extra layer of security , Helps mitigate some attacks , Such as XSS Cross-site scripting attacks . By adding CSP header , You can tell the browser that it can only download content from domains you explicitly allow , Include Javascript and CSS file .

How to be in Nginx Configuration on the server ?

add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

in the light of XSS Cross-site scripting attacks , The following parameters can be configured :

add_header X-XSS-Protection "1; mode=block";

8、 prevent Click-jacking hijacked

Click-jacking( Click hijack ) It's a kind of Web Application vulnerability , The attacker uses this vulnerability to force the user to click without the user's consent , Cause redirection to an unknown website .HTTP In the response header X-Frame -Option Can be used to indicate Web Whether the browser should be in the frame or iframe Load page in . therefore , stay nginx.conf Of documents HTTP Append... To the header X-Frame-Options, This will instruct the browser to load resources only from the same source .

How to be in Nginx Configuration on the server ?

add_header X-Frame-Options "SAMEORIGIN";

9、 Disable content sniffing

Content sniffing , Also known as MIME(Multipurpose Internet Mail Extensions) Sniffing , namely Multipurpose web mail extension Sniffing , Is a technique for checking the contents of a byte stream to determine the file format of the data in it . This can also lead to security vulnerabilities , Because attackers can take advantage of MIME Sniff to send XSS Cross site scripting attacks .

for example , If your website allows users to upload media content such as pictures , An attacker may upload a file that contains JavaScript Malicious image file of code . When the browser sniffs for content , May be tricked into executing the malicious file . To prevent content sniffing attacks , Can be X-Content-Type-Options The response header is set to nosniff, This tells the browser to avoid guessing the response type and only rely on Content-Type head .

How to be in Nginx Configuration on the server ?

add_header X-Content-Type-Options nosniff;

10、 Photo anti theft chain

“ Photo anti theft chain ” As the name suggests, it is to prevent others from stealing your picture links , This may cause your bandwidth usage to increase , Especially in the current server bandwidth use strategy, it is basically pay as you go , Therefore, this may indirectly cause economic losses to your company .

for example , Suppose you web There is a named in the root directory of the server images The catalog of , It stores all the images you use on the site . To prevent others from using your image , You need to Nginx web Make the following configuration on the server .

How to be in Nginx Configuration on the server ?

location /images/ {
    
  valid_referers none blocked www.hello.com hello.com;
   if ($invalid_referer) {
    
     return   403;
   }
}

11、 Enable HSTS function

HSTS This feature only allows clients (Web browser ) Use HTTPS communicate , this return and rewrite The concept of method is different . When the browser receives HSTS Header time , It will not be in the specified time with HTTP Form and web Server communication , To ensure the HTTPS Strictly secure transmission problem .

How to be in Nginx Configuration on the server ?

add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

12、 Only allow access through domain name

Online web Application comrades know , After the launch IP Or domain name form, we can access , If you don't want to allow IP Request for address , That only needs to be in Nginx You can configure it as follows .

if ($host !~ ^(mytechnix.com|www.mytechnix.com)$ ) {
    
    return 301 https://mytechnix.com$request_uri;
}

13、 Disable automatic user agents

To protect your server from robots 、 The infringement of scripts and other automatic web page retrieval methods , Please explicitly reject these user agents .

for example , image wget Such an application can retrieve the entire document root structure , Make them useful DoS An attacker may simply visit a protected file on a website .

How to be in Nginx Configuration on the server ?

if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
    
    return 403;
}

14、 Prevent server information disclosure

What does that mean ?Nginx The default configuration of the server server_tokens Instructions on all automatically generated error pages and HTTP The response header will show Nginx Version number , I had this problem in a previous project , At that time, the customer's safety engineer swept out the problem with tools . This may lead to web Server information disclosure , An attacker can gain information about Nginx Version information , In order to narrow the range of attack . therefore , We must prohibit the use of ( browser ) Show Nginx Version number and other relevant information .

How to be in Nginx Configuration on the server ?

server_tokens off;

15、 upgrade Nginx edition

It is suggested that your Nginx Update the server to the latest and stable version , Because there are many performance improvements 、 Security repair and new function realization .


The attachment

Through the above basic configuration , Now integrate a complete configuration

#========== Global profile ============

#  avoid  Nginx  Version information disclosure 
server_tokens off;

#  prevent  Click-jacking  Clickjacking 
add_header X-Frame-Options SAMEORIGIN;

#  Disable content sniffing , prevent  XSS  Cross-site scripting attacks 
add_header X-Content-Type-Options nosniff;

# CSP  Content security policy , Tell the browser that it can only download content from domains you explicitly allow , prevent  XSS  Cross-site scripting attacks 
add_header X-XSS-Protection "1; mode=block";
add_header Content-Security-Policy "default-src 'self' http: https: data: blob: 'unsafe-inline'" always;

#  Enable  HSTS  function , Only clients are allowed (Web  browser ) Use  HTTPS  communicate , To ensure the  HTTPS  Strictly secure transmission problem .
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

#  Prevent buffer overflow attacks , Secret free attackers inject malicious code 
client_body_buffer_size 1K;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;

#========== Virtual host configuration ============

server {
    
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name hello.com;
    return 301 https://$host$request_uri;
}

server {
    
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name hello.com;

    # SSL/TLS  certificate / secret key 
    ssl_certificate     /etc/nginx/ssl/bundle.pem;
    ssl_certificate_key /etc/nginx/ssl/hello.com.key;

    # DH  Key exchange mechanism , The session key is deleted when the session terminates , The attacker cannot retrieve the messages exchanged between the two sides .
    ssl_dhparam /etc/nginx/ssl/dhparam.pem;

    ssl_prefer_server_ciphers on;

    #  Disable the old  SSL/TLS  agreement 
    ssl_protocols TLSv1.2 TLSv1.3;

    #  Ban  SSL/TLS  Weak cipher Suite 
    ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

    #  Disable unnecessary  HTTP  Method 
    if ($request_method !~ ^(GET|HEAD|POST)$ ){
    
        return 444;
    }

    #  Photo anti theft chain 
    location /images/ {
    
        valid_referers none blocked www.hello.com hello.com;
        if ($invalid_referer) {
    
            return   403;
        }
    }
    #  Only access via domain name is allowed  web  The server 
    if ($host !~ ^(hello.com|www.hello.com)$ ) {
    
        return 301 https://hello.com$request_uri;
    }
    #  Disable automatic user agents , prevent  Dos  attack 
    if ($http_user_agent ~* LWP::Simple|BBBike|wget) {
    
        return 403;
    }

}

< Click to jump to the beginning >

copyright notice
author[Cloud computing security],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/119/202204291414408707.html

Random recommended