阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Nginx服务器中的安全配置

112次阅读
没有评论

共计 10450 个字符,预计需要花费 27 分钟才能阅读完成。

一、关闭 SELinux

安全增强型 Linux(SELinux)的是一个 Linux 内核的功能,它提供支持访问控制的安全政策保护机制。

但是,SELinux 带来的附加安全性和使用复杂性上不成比例,性价比不高

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

/usr/sbin/sestatus -v  #查看状态

二、通过分区挂载允许最少特权

服务器上 nginx 目录单独分区。例如,新建一个分区 /dev/sda5(第一逻辑分区),并且挂载在 /nginx。确保 /nginx 是以 noexec, nodev and nosetuid 的权限挂载

以下是我的 /etc/fstab 的挂载 /nginx 的信息:LABEL=/nginx /nginx ext3 defaults,nosuid,noexec,nodev 1 2

注意:你需要使用 fdisk 和 mkfs.ext3 命令创建一个新分区。

三、配置 /etc/sysctl.conf 强化 Linux 安全

你可以通过编辑 /etc/sysctl.conf 来控制和配置 Linux 内核、网络设置

# 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

# Don’t 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

四、删除所有不需要的 Nginx 模块

你需要直接通过编译 Nginx 源代码使模块数量最少化。通过限制只允许 web 服务器访问模块把风险降到最低。你可以只配置安装 nginx 你所需要的模块。例如,禁用 SSL 和 autoindex 模块你可以执行以下命令:

./configure –without-http_autoindex_module –without-http_ssi_module

make && make install

更改 nginx 版本名称、编辑文件 /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;

// 更改为

static char ngx_http_server_string[] =“Server: Ninja Web Server”CRLF;

static char ngx_http_server_full_string[] =“Server: Ninja Web Server”CRLF;

关闭 nginx 版本号的显示

server_tokens off

五、基于 Iptables 防火墙的限制

下面的防火墙脚本阻止任何除了允许:

  • 来自 HTTP(TCP 端口 80)的请求
  • 来自 ICMP ping 的请求
  • ntp(端口 123)的请求输出
  • smtp(TCP 端口 25)的请求输出

六、控制缓冲区溢出攻击

编辑和设置所有客户端缓冲区的大小限制如下:

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(默认 8k 或 16k)这个指令可以指定连接请求实体的缓冲区大小。如果连接请求超过缓存区指定的值,那么这些请求实体的整体或部分将尝试写入一个临时文件。
  • client_header_buffer_size 1k- 指令指定客户端请求头部的缓冲区大小。绝大多数情况下一个请求头不会大于 1k,不过如果有来自于 wap 客户端的较大的 cookie 它可能会大于 1k,Nginx 将分配给它一个更大的缓冲区,这个值可以在 large_client_header_buffers 里面设置。
  • client_max_body_size 1k- 指令指定允许客户端连接的最大请求实体大小,它出现在请求头部的 Content-Length 字段。如果请求大于指定的值,客户端将收到一个”Request Entity Too Large”(413)错误。记住,浏览器并不知道怎样显示这个错误。
  • large_client_header_buffers- 指定客户端一些比较大的请求头使用的缓冲区数量和大小。请求字段不能大于一个缓冲区大小,如果客户端发送一个比较大的头,nginx 将返回”Request URI too large”(414)
  • 同样,请求的头部最长字段不能大于一个缓冲区,否则服务器将返回”Bad request”(400)。缓冲区只在需求时分开。默认一个缓冲区大小为操作系统中分页文件大小,通常是 4k 或 8k,如果一个连接请求最终将状态转换为 keep- alive,它所占用的缓冲区将被释放。

你还需要控制超时来提高服务器性能并与客户端断开连接。按照如下编辑:

client_body_timeout  10;

client_header_timeout 10;

keepalive_timeout    5 5;

send_timeout          10;

•client_body_timeout 10;- 指令指定读取请求实体的超时时间。这里的超时是指一个请求实体没有进入读取步骤,如果连接超过这个时间而客户端没有任何响应,Nginx 将返回一个”Request time out”(408)错误。
•client_header_timeout 10;- 指令指定读取客户端请求头标题的超时时间。这里的超时是指一个请求头没有进入读取步骤,如果连接超过这个时间而客户端没有任何响应,Nginx 将返回一个”Request time out”(408)错误。
•keepalive_timeout 5 5; – 参数的第一个值指定了客户端与服务器长连接的超时时间,超过这个时间,服务器将关闭连接。参数的第二个值(可选)指定了应答头中 Keep-Alive: timeout=time 的 time 值,这个值可以使一些浏览器知道什么时候关闭连接,以便服务器不用重复关闭,如果不指定这个参数,nginx 不会在应 答头中发送 Keep-Alive 信息。(但这并不是指怎样将一个连接“Keep-Alive”)参数的这两个值可以不相同。
•send_timeout 10; 指令指定了发送给客户端应答后的超时时间,Timeout 是指没有进入完整 established 状态,只完成了两次握手,如果超过这个时间客户端没有任何响应,nginx 将关闭连接。

七、控制并发连接

你可以使用 NginxHttpLimitZone 模块来限制指定的会话或者一个 IP 地址的特殊情况下的并发连接。编辑 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;

上面表示限制每个远程 IP 地址的客户端同时打开连接不能超过 5 个。

八、只允许我们的域名的访问

如果机器人只是随机扫描服务器的所有域名,那拒绝这个请求。你必须允许配置的虚拟域或反向代理请求。你不必使用 IP 地址来拒绝。

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

    return 444;

}

九、限制可用的请求方法

GET 和 POST 是互联网上最常用的方法。Web 服务器的方法被定义在 RFC 2616。如果 Web 服务器不要求启用所有可用的方法,它们应该被禁用。下面的指令将过滤只允许 GET,HEAD 和 POST 方法:

## Only allow these request methods ##

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

    return 444;

}

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

更多关于 HTTP 方法的介绍

•GET 方法是用来请求,如文件 http://www.linuxidc.com/index.php。

•HEAD 方法是一样的,除非该服务器的 GET 请求无法返回消息体。

•POST 方法可能涉及到很多东西,如储存或更新数据,或订购产品,或通过提交表单发送电子邮件。这通常是使用服务器端处理,如 PHP,Perl 和 Python 等脚本。如果你要上传的文件和在服务器处理数据,你必须使用这个方法。

十、如何拒绝一些 User-Agents?

你可以很容易地阻止 User-Agents, 如扫描器,机器人以及滥用你服务器的垃圾邮件发送者。

## Block download agents ##

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

    return 403;

}

阻止 Soso 和有道的机器人:

## Block some robots ##

if ($http_user_agent ~* Sosospider|YodaoBot) {

    return 403;

}

十一、防止图片盗链

图片或 HTML 盗链的意思是有人直接用你网站的图片地址来显示在他的网站上。最终的结果,你需要支付额外的宽带费用。这通常是在论坛和博客。我强烈建议您封锁,并阻止盗链行为。

# Stop deep linking or hot linking

location /images/ {

    valid_referers none blocked www.example.com example.com;

    if ($invalid_referer) {

        return  403;

    }

}

例如:重定向并显示指定图片

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

}

十二、目录限制

你可以对指定的目录设置访问权限。所有的网站目录应该一一的配置,只允许必须的目录访问权限。
通过 IP 地址限制访问
你可以通过 IP 地址来限制访问目录 /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;

}

通过密码保护目录, 首先创建密码文件并增加“user”用户

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

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

编辑 nginx.conf, 加入需要保护的目录

### Password Protect /personal-images/ and /delta/ directories ###

location ~ /(personal-images/.*|delta/.*) {

    auth_basic“Restricted”;

    auth_basic_user_file  /usr/local/nginx/conf/.htpasswd/passwd;

}

一旦密码文件已经生成,你也可以用以下的命令来增加允许访问的用户

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

十三、Nginx SSL 配置

HTTP 是一个纯文本协议,它是开放的被动监测。你应该使用 SSL 来加密你的用户内容。
创建 SSL 证书, 执行以下命令:

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

编辑 nginx.conf 并按如下来更新:

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;

}

十四、Nginx 与 PHP 安全建议

PHP 是流行的服务器端脚本语言之一。如下编辑 /etc/php.ini 文件:

# 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

十五、如果可能让 Nginx 运行在一个 chroot 监狱

把 nginx 放在一个 chroot 监狱以减小潜在的非法进入其它目录。你可以使用传统的与 nginx 一起安装的 chroot。如果可能,那使用 FreeBSD jails,Xen,OpenVZ 虚拟化的容器概念。

十六、在防火墙级限制每个 IP 的连接数

网络服务器必须监视连接和每秒连接限制。PF 和 Iptales 都能够在进入你的 nginx 服务器之前阻止最终用户的访问。
Linux Iptables: 限制每次 Nginx 连接数
下面的例子会阻止来自一个 IP 的 60 秒钟内超过 15 个连接端口 80 的连接数。

/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

请根据你的具体情况来设置限制的连接数。

十七、配置操作系统保护 Web 服务器

像以上介绍的启动 SELinux. 正确设置 /nginx 文档根目录的权限。Nginx 以用户 nginx 运行。但是根目录(/nginx 或者 /usr /local/nginx/html)不应该设置属于用户 nginx 或对用户 nginx 可写。找出错误权限的文件可以使用如下命令:

find /nginx -user nginx

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

确保你更所有权为 root 或其它用户,一个典型的权限设置 /usr/local/nginx/html/

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

示例输出:

-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

你必须删除由 vi 或其它文本编辑器创建的备份文件:

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

通过 find 命令的 -delete 选项来删除这些文件。

十八、限制 Nginx 连接传出

黑客会使用工具如 wget 下载你服务器本地的文件。使用 Iptables 从 nginx 用户来阻止传出连接。ipt_owner 模块试图匹配本地产生的数据包的创建者。下面的例子中只允许 user 用户在外面使用 80 连接。

/sbin/iptables -A OUTPUT -o eth0 -m owner –uid-owner vivek -p tcp –dport 80 -m state –state NEW,ESTABLISHED  -j ACCEPT

通过以上的配置,你的 nginx 服务器已经非常安全了并可以发布网页。可是,你还应该根据你网站程序查找更多的安全设置资料。例如,wordpress 或者第三方程序。

更多 Nginx 相关教程见以下内容

CentOS 6.2 实战部署 Nginx+MySQL+PHP http://www.linuxidc.com/Linux/2013-09/90020.htm

使用 Nginx 搭建 WEB 服务器 http://www.linuxidc.com/Linux/2013-09/89768.htm

搭建基于 Linux6.3+Nginx1.2+PHP5+MySQL5.5 的 Web 服务器全过程 http://www.linuxidc.com/Linux/2013-09/89692.htm

CentOS 6.3 下 Nginx 性能调优 http://www.linuxidc.com/Linux/2013-09/89656.htm

CentOS 6.3 下配置 Nginx 加载 ngx_pagespeed 模块 http://www.linuxidc.com/Linux/2013-09/89657.htm

CentOS 6.4 安装配置 Nginx+Pcre+php-fpm http://www.linuxidc.com/Linux/2013-08/88984.htm

Nginx 安装配置使用详细笔记 http://www.linuxidc.com/Linux/2014-07/104499.htm

Nginx 日志过滤 使用 ngx_log_if 不记录特定日志 http://www.linuxidc.com/Linux/2014-07/104686.htm

Nginx 的详细介绍:请点这里
Nginx 的下载地址:请点这里

本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-01/127789.htm

正文完
星哥说事-微信公众号
post-qrcode
 0
星锅
版权声明:本站原创文章,由 星锅 于2022-01-21发表,共计10450字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中