MySQL SQL注入
概述
SQL注入是一种代码注入技术,其中恶意SQL语句被插入到应用程序查询中。了解SQL注入以及如何预防它对于数据库安全至关重要。
SQL注入类型
经典SQLi:基本查询操作 盲SQLi:没有可见的查询结果 基于时间:基于响应时间 基于联合:组合查询结果 基于错误:从错误中提取数据
SQL注入示例
基本注入
sql
-- Vulnerable query (application code)
-- Malicious input
-- Resulting query
-- Returns all users (bypasses authentication)登录绕过
sql
-- Vulnerable login query
-- Malicious input (any password works)
-- Resulting query (comment bypasses password check)基于联合的注入
sql
-- Vulnerable query
-- Malicious input
-- Resulting query
-- Exposes user credentials基于错误的注入
sql
-- Vulnerable query
-- Malicious input
-- Extracts username:password from error message识别SQL注入
测试漏洞
sql
-- Test with single quote
-- Test with logical operators
-- Test with comments
-- Test with mathematical operators自动化测试
sql
-- Common injection payloads
-- Boolean-based testing预防SQL注入
预备语句
MySQL预备语句
sql
-- Vulnerable query
-- Still vulnerable if @user_id contains malicious input
-- Secure query (parameterized)
-- User input treated as data, not codePHP / PHP
php
Python / Python
python
# Vulnerable
# Secure with prepared statementJava / Java
java
Node.js / Node.js
javascript
输入验证
php
转义
php
最小权限
sql
-- Create limited user for application
-- Grant only necessary privileges
-- Avoid GRANT ALL PRIVILEGES
-- Application can't drop tables, modify schema, etc.高级SQL注入
盲SQL注入
sql
-- No visible results
-- Boolean-based blind
-- Time-based blind二阶注入
sql
-- Stored input used in another query
-- Step 1: Insert malicious name
-- Step 2: Name used in vulnerable query
-- Executes: SELECT * FROM orders WHERE user_id = (SELECT id FROM users WHERE name = 'admin'--)SQL注入预防工具
Web应用防火墙
ModSecurity:Apache模块 SQLMap:自动化测试 OWASP ZAP:安全扫描器
代码分析
sql
-- Static analysis tools
-- PHP: RIPS, Pixy
-- Python: Bandit
-- Java: FindBugs, SpotBugs
-- Review common patterns
-- String concatenation with user input
-- Dynamic SQL construction
-- Lack of input validation
-- Missing prepared statements最佳实践
安全编码实践
sql
-- 1. Always use prepared statements
-- 2. Never concatenate user input
-- 3. Validate input type and format
-- 4. Use whitelist when possible
-- 5. Escape output (XSS prevention)
-- 6. Limit error messages
-- 7. Use least privilege accounts
-- 8. Regular security audits数据库安全
sql
-- Disable dangerous functions (if not needed)
-- SET GLOBAL sql_mode = 'TRADITIONAL';
-- Restrict file access
-- Disable symbolic links
-- Monitor query logs测试和审计
定期安全测试
sql
-- Test with automated tools
-- SQLMap: sqlmap -u "http://example.com/page?id=1"
-- Manual testing checklist
-- - Single quote test
-- - Boolean logic test
-- - Time-based test
-- - Error-based test
-- - Union-based test日志记录和监控
sql
-- Enable query logging
-- Monitor suspicious patterns小结
SQL注入预防涉及:
预备语句:参数化查询 输入验证:类型和格式检查 最小权限:受限的数据库账户 Web安全:WAF和监控 定期测试:自动和手动检查 安全审计:代码和基础设施审查
始终使用预备语句并验证所有用户输入以防止SQL注入攻击。
上一个:处理重复数据
下一个:导出数据