Skip to content

防止SQL注入

防止SQL注入攻击,保护数据库安全。

基本防护

禁止特定请求

nginx
location ~* \.(php|jsp|asp)$ {
    if ($args ~* "union.*select.*(") {
        return 403;
    }
}

禁止SQL关键字

nginx
location ~* \.(php|jsp|asp)$ {
    if ($args ~* "(select|insert|update|delete|drop|union|exec|script|javascript)") {
        return 403;
    }
}

完整配置

SQL注入防护

nginx
server {
    listen 80;
    server_name www.example.com;

    root /var/www/html;

    # 禁止SQL注入
    location ~* \.(php|jsp|asp)$ {
        if ($args ~* "(select|insert|update|delete|drop|union|exec|script|javascript)") {
            return 403;
        }

        try_files $uri $uri/ /index.php?$query_string;
    }
}

高级防护

使用Nginx Lua模块

nginx
location ~* \.(php|jsp|asp)$ {
    access_by_lua_block {
        if ngx.var.args and ngx.re.match(ngx.var.args, "(select|insert|update|delete|drop|union|exec|script|javascript)", "ij") then
            ngx.exit(403)
        end
    }

    try_files $uri $uri/ /index.php?$query_string;
}

使用ModSecurity

nginx
location ~* \.(php|jsp|asp)$ {
    ModSecurityEnabled On;
    ModSecurityConfig /etc/nginx/modsecurity.conf;

    try_files $uri $uri/ /index.php?$query_string;
}

常见SQL注入模式

UNION注入

nginx
if ($args ~* "union.*select.*(") {
    return 403;
}

盲注

nginx
if ($args ~* "(and|or) .*=") {
    return 403;
}

时间注入

nginx
if ($args ~* "waitfor.*delay") {
    return 403;
}

完整示例

生产环境配置

nginx
server {
    listen 80;
    server_name www.example.com;

    root /var/www/html;

    # SQL注入防护
    location ~* \.(php|jsp|asp)$ {
        if ($args ~* "(select|insert|update|delete|drop|union|exec|script|javascript|waitfor|delay)") {
            return 403;
        }

        if ($args ~* "(and|or) .*=") {
            return 403;
        }

        if ($args ~* "union.*select.*(") {
            return 403;
        }

        try_files $uri $uri/ /index.php?$query_string;
    }

    # 禁止访问敏感文件
    location ~* \.(sql|bak|old|backup)$ {
        deny all;
    }
}

常见问题

正常请求被拦截

原因: 正则表达式过于严格

解决: 调整正则表达式

nginx
if ($args ~* "union.*select.*\(") {
    return 403;
}

SQL注入未拦截

原因: 正则表达式不完整

解决: 添加更多SQL关键字

nginx
if ($args ~* "(select|insert|update|delete|drop|union|exec|script|javascript)") {
    return 403;
}

总结

防止SQL注入的关键点:

  • 禁止SQL关键字:select、insert、update、delete等
  • 禁止特殊字符:union、exec、script等
  • 禁止特定模式:UNION注入、盲注等
  • 使用Lua模块:更灵活的防护
  • 使用ModSecurity:专业的WAF解决方案

合理配置SQL注入防护,保护数据库安全。