Nginxsecurityconfigurationtutorial

LearningNginxsecurityconfiguration, SSL/TLSconfiguration, security加固 and 防止common攻击, improvingserver security性

securityconfigurationoverview

for whatNginxsecurityconfiguration很 important ?

Nginxserving asWebserver and 反向proxy, 直接暴露 in 公网in, 面临着各种security威胁. 合理 securityconfiguration可以 has 效防止恶意攻击, 保护server and application security, 确保data 机密性 and integrity.

common security威胁

Nginxsecurityconfiguration 目标

SSL/TLSconfiguration

what is SSL/TLS?

SSL (Secure Sockets Layer) and TLS (Transport Layer Security) is 用于 in network通信inprovidingencryption and 身份verification protocol. 它们可以确保客户端 and server之间 通信data被encryption, 防止in间人攻击 and data窃听.

1. 获取SSLcertificate

要configurationHTTPS, 首先需要获取SSLcertificate. has 以 under 几种方式:

usingLet's Encrypt获取免费certificate

# installationCertbot
# Ubuntu/Debian
sudo apt update
sudo apt install certbot python3-certbot-nginx

# CentOS/RHEL
sudo yum install epel-release
sudo yum install certbot python3-certbot-nginx

# usingCertbot获取certificate并自动configurationNginx
sudo certbot --nginx -d example.com -d www.example.com

# verificationcertificate自动续期
sudo systemctl status certbot.timer

2. 手动configurationSSL/TLS

server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    server_name example.com www.example.com;
    
    # SSLcertificateconfiguration
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
    
    # SSLparameteroptimization
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;
    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_session_cache shared:SSL:10m;
    ssl_session_timeout 10m;
    ssl_session_tickets off;
    
    # HSTSconfiguration
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
    
    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;
    
    # 根Table of Contents and indexfile
    root /var/www/example.com;
    index index.html;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

3. SSL/TLSconfigurationparameter说明

4. testSSL/TLSconfiguration

可以using以 under tooltestSSL/TLSconfiguration security性:

Nginxsecurity加固

for what需要security加固?

默认 Nginxconfiguration可能存 in security隐患, 需要for适当 加固, 以improvingserver security性. security加固including禁用不必要 functions, 限制访问permission, 设置合理 超时时间etc..

1. basicsecurity加固

# 隐藏Nginxversioninformation
http {
    server_tokens off;
    
    # 限制request体 big  small 
    client_max_body_size 10m;
    
    # 限制connections and request速率
    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
    limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s;
    
    # configurationserver
    server {
        listen 80;
        server_name example.com;
        
        # 限制每个IP connections
        limit_conn conn_limit_per_ip 10;
        
        # 限制request速率
        limit_req zone=req_limit_per_ip burst=20 nodelay;
        
        # 根Table of Contents and indexfile
        root /var/www/example.com;
        index index.html;
        
        location / {
            try_files $uri $uri/ =404;
        }
    }
}

2. HTTPsecurity头configuration

server {
    listen 443 ssl http2;
    server_name example.com;
    
    # SSLconfiguration
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
    # HTTPsecurity头
    add_header X-Content-Type-Options nosniff;
    add_header X-Frame-Options SAMEORIGIN;
    add_header X-XSS-Protection "1; mode=block";
    add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self';";
    add_header Referrer-Policy "strict-origin-when-cross-origin";
    add_header Permissions-Policy "geolocation=(), microphone=(), camera=()";
    
    # 根Table of Contents and indexfile
    root /var/www/example.com;
    index index.html;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

3. file and Table of Contentspermission控制

# 禁止访问隐藏file
location ~ /\. {
    deny all;
}

# 禁止访问specificfileclass型
location ~ \.(conf|log|sql|bak|swp)$ {
    deny all;
}

# 禁止访问敏感Table of Contents
location ~* ^/(admin|wp-admin|dashboard|config)/ {
    deny all;
}

# 限制PHPfile访问, 防止PHPfile被直接访问
location ~* \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

# 限制Table of Contents浏览
location / {
    autoindex off;
    try_files $uri $uri/ =404;
}

4. runNginx user and permission

# modifyNginxconfigurationfile, using非rootuserrun
# /etc/nginx/nginx.conf
user nginx;  # usingnginxuserrun
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

# 设置file and Table of Contentspermission
sudo chown -R nginx:nginx /var/www/example.com
sudo chmod -R 755 /var/www/example.com
sudo chmod -R 644 /var/www/example.com/*

# 限制Nginxconfigurationfilepermission
sudo chmod 644 /etc/nginx/nginx.conf
sudo chmod 644 /etc/nginx/conf.d/*
sudo chmod 600 /etc/letsencrypt/live/example.com/privkey.pem

访问控制configuration

1. 基于IP 访问控制

# 允许specificIP访问
location /admin/ {
    allow 192.168.1.100;
    allow 10.0.0.0/24;
    deny all;
}

# 禁止specificIP访问
location / {
    deny 192.168.1.200;
    deny 172.16.0.0/16;
    allow all;
}

# 限制management界面访问
location ~* ^/admin/ {
    allow 192.168.1.0/24;
    deny all;
    
    # otherconfiguration
    proxy_pass http://localhost:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

2. HTTPbasicauthentication

# installationhtpasswdtool
# Ubuntu/Debian
sudo apt install apache2-utils

# CentOS/RHEL
sudo yum install httpd-tools

# creationpasswordfile
sudo htpasswd -c /etc/nginx/.htpasswd admin

# configurationHTTPbasicauthentication
location /admin/ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
    
    # otherconfiguration
    proxy_pass http://localhost:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

#  for specificfile设置authentication
location ~* ^/config\.php$ {
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

3. 结合IP and passwordauthentication

location /admin/ {
    # 先限制IP
    allow 192.168.1.0/24;
    deny all;
    
    # 再要求passwordauthentication
    auth_basic "Restricted Area";
    auth_basic_user_file /etc/nginx/.htpasswd;
    
    # otherconfiguration
    proxy_pass http://localhost:8080;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

防止common攻击

common Web攻击class型

Webapplication面临着各种security威胁, Nginx可以through适当 configuration来防止这些攻击.

1. 防止DDoS攻击

# 限制connections and request速率
http {
    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
    limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s;
    limit_req_zone $server_name zone=req_limit_per_server:10m rate=100r/s;
    
    server {
        listen 80;
        server_name example.com;
        
        # 限制每个IP connections
        limit_conn conn_limit_per_ip 10;
        
        # 限制每个IP request速率
        limit_req zone=req_limit_per_ip burst=20 nodelay;
        
        # 限制每个server request速率
        limit_req zone=req_limit_per_server burst=200 nodelay;
        
        # otherconfiguration
        root /var/www/example.com;
        index index.html;
        
        location / {
            try_files $uri $uri/ =404;
        }
    }
}

# configuration连接超时
http {
    keepalive_timeout 65;
    client_body_timeout 10s;
    client_header_timeout 10s;
    send_timeout 10s;
    
    # otherconfiguration
}

2. 防止SQL注入 and XSS攻击

# configuration in 容security策略
server {
    listen 80;
    server_name example.com;
    
    #  in 容security策略, 防止XSS攻击
    add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self';";
    
    # othersecurity头
    add_header X-XSS-Protection "1; mode=block";
    add_header X-Content-Type-Options nosniff;
    
    # otherconfiguration
    root /var/www/example.com;
    index index.html;
    
    location / {
        try_files $uri $uri/ =404;
    }
}

# 限制requestmethod
if ($request_method !~ ^(GET|POST|HEAD)$ ) {
    return 405;
}

# filter恶意requestparameter
if ($args ~* "(\<|\>|'|\"|%3C|%3E|%27|%22)" ) {
    return 403;
}

# 防止Table of Contents遍历
if ($request_uri ~* "\.\./" ) {
    return 403;
}

3. 防止点击劫持

# 设置X-Frame-Options头, 防止点击劫持
add_header X-Frame-Options SAMEORIGIN;

#  or 者完全禁止framework
add_header X-Frame-Options DENY;

#  or 者允许specific域名 framework
add_header X-Frame-Options "ALLOW-FROM https://trusted-domain.com";

4. 防止CSRF攻击

# configuration in 容security策略, 防止CSRF攻击
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; form-action 'self';";

# verificationReferer头
if ($request_method = POST) {
    if ($http_referer !~ ^https?://(www\.)?example\.com) {
        return 403;
    }
}

# othersecurityconfiguration
add_header Referrer-Policy "strict-origin-when-cross-origin";

实践case: configurationsecurity Nginxserver

fake设我们需要configuration一个security Nginxserver, 要求:

http {
    # logconfiguration
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    
    access_log /var/log/nginx/access.log main;
    error_log /var/log/nginx/error.log warn;
    
    # 连接 and 超时configuration
    keepalive_timeout 65;
    client_body_timeout 10s;
    client_header_timeout 10s;
    send_timeout 10s;
    client_max_body_size 10m;
    
    # 限制configuration
    limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
    limit_req_zone $binary_remote_addr zone=req_limit_per_ip:10m rate=10r/s;
    limit_req_zone $server_name zone=req_limit_per_server:10m rate=100r/s;
    
    # 隐藏versioninformation
    server_tokens off;
    
    # Gzip压缩
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
    gzip_comp_level 6;
    
    # serverconfiguration
    server {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://$host$request_uri;
    }
    
    server {
        listen 443 ssl http2;
        server_name example.com www.example.com;
        
        # SSLconfiguration
        ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
        ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
        
        # SSLparameteroptimization
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_prefer_server_ciphers on;
        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_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
        ssl_session_tickets off;
        ssl_stapling on;
        ssl_stapling_verify on;
        resolver 8.8.8.8 8.8.4.4 valid=300s;
        resolver_timeout 5s;
        
        # HTTPsecurity头
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        add_header X-Content-Type-Options nosniff;
        add_header X-Frame-Options SAMEORIGIN;
        add_header X-XSS-Protection "1; mode=block";
        add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self';";
        add_header Referrer-Policy "strict-origin-when-cross-origin";
        add_header Permissions-Policy "geolocation=(), microphone=(), camera=()";
        
        # 限制configuration
        limit_conn conn_limit_per_ip 10;
        limit_req zone=req_limit_per_ip burst=20 nodelay;
        limit_req zone=req_limit_per_server burst=200 nodelay;
        
        # 根Table of Contents and indexfile
        root /var/www/example.com;
        index index.html;
        
        # 禁止访问隐藏file
        location ~ /\. {
            deny all;
        }
        
        # 禁止访问specificfileclass型
        location ~ \.(conf|log|sql|bak|swp)$ {
            deny all;
        }
        
        # 限制management界面访问
        location ~* ^/admin/ {
            allow 192.168.1.0/24;
            deny all;
            
            # HTTPbasicauthentication
            auth_basic "Restricted Area";
            auth_basic_user_file /etc/nginx/.htpasswd;
            
            # otherconfiguration
            proxy_pass http://localhost:8080;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
        }
        
        # 主requestprocessing
        location / {
            try_files $uri $uri/ =404;
        }
    }
}

这个configurationproviding了全面 security保护, including:

互动练习

1. 以 under 哪些 is Nginxsecurityconfiguration important 措施? ( many 选)

A. 启用HTTPS
B. 隐藏Nginxversioninformation
C. 设置HTTPsecurity头
D. 限制connections and request速率
E. configuration访问控制

2. 以 under 哪个指令用于configurationSSLcertificatefilepath?

A. ssl_certificate
B. ssl_certificate_key
C. ssl_protocols
D. ssl_ciphers

3. 实践练习: configurationsecurity Nginxserver

请configuration一个security Nginxserver, 要求:

  • 启用HTTPS, usingLet's Encryptcertificate
  • configurationSSL/TLSparameteroptimization
  • 设置HTTPsecurity头 (HSTS, X-XSS-Protection, X-Frame-Optionsetc.)
  • 限制connections and request速率
  • 禁止访问隐藏file and 敏感fileclass型
  • for management界面configurationIP限制 and HTTPbasicauthentication

summarized and 展望

through本tutorial, 您已经Learning了Nginxsecurityconfiguration important 性, SSL/TLSconfiguration, security加固措施, 访问控制 and 防止common攻击 method. securityconfiguration is Nginxservermanagement important 组成部分, 它可以:

in after 续 tutorialin, 我们将深入LearningNginx performanceoptimization, logmanagement and advanced主题, helping您全面MasterNginx usingtechniques.