SQL注入是Web应用最常见的安全威胁之一,作为IT工程师,了解如何在Nginx层面防范这类攻击至关重要。以下是Nginx防范SQL注入的主要策略:
在Nginx配置中拦截常见SQL注入特征:
server {
# 拦截常见SQL注入关键词
if ($args ~* "union.*select.*\(") {
return 403;
}
if ($args ~* "concat.*\(") {
return 403;
}
if ($args ~* "sleep\(.*\)") {
return 403;
}
# 拦截注释符和引号
if ($args ~* "([';]+|(--)+)") {
return 403;
}
}
location / {
# 只允许GET和POST方法
if ($request_method !~ ^(GET|POST)$ ) {
return 405;
}
}
# 安装后配置
load_module modules/ngx_http_modsecurity_module.so;
http {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;
}
set $block_sql_injections 0;
if ($query_string ~ "union.*select.*\(") {
set $block_sql_injections 1;
}
if ($block_sql_injections = 1) {
return 403;
}
location / {
# 限制查询字符串长度
if ($args ~ "^(.{1000,})$") {
return 413;
}
}
location /api/ {
# 只允许数字ID参数
if ($arg_id ~ "[^0-9]") {
return 400;
}
}
log_format security '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'SQLi: $sql_injection';
map $args $sql_injection {
default "0";
~* "union.*select" "1";
~* "([';]+|(--)+)" "1";
}
access_log /var/log/nginx/security.log security;
nginx
server {
error_page 500 502 503 504 /50x.html;
location = /50x.html {
internal;
}
}
nginx
location ^~ /uploads/ {
client_max_body_size 10m;
client_body_buffer_size 128k;
# 禁止执行上传目录中的PHP等脚本
location ~ \.php$ {
deny all;
}
}
通过以上配置,可以显著提高Nginx服务器对SQL注入攻击的防御能力。