Prevent SQL Injection (SQLi) attacks
SQLi injects malicious SQL 通过用户输入. Learn parameterized queries, 输入 validation, 和原则的 最少 privilege.
- 1
SQLi occurs 当用户输入是 concatenated 为 SQL queries. Example: "SELECT * 从 users WHERE name = '" + 输入 + "'" — 输入 ' 或 1=1 -- returns 所有 users. Prevention: (1) Parameterized queries / prepared statements (主防御) — 查询和 数据是 sent separately, 数据库从不 interprets 数据 as SQL. (2) 输入 validation (备). (3) 最少 privilege — 数据库用户能够仅 什么它 needs. (4) ORM 具有 parameterized queries.
- 2 SQL 格式化器 →
格式化 SQL queries to identify injection-prone patterns. Look for string concatenation ('...' + input + '...'), dynamic SQL (EXEC), and unparameterized queries. Format the query with placeholders (?, :name) to show the parameterized form.
- 3 正则表达式替换器 →
验证 and sanitize input before using it in queries. Whitelist allowed characters (alphanumeric for identifiers, specific patterns for dates/emails). Reject input that contains SQL metacharacters (', ", ;, --, /*, */). Note: validation is secondary — always use parameterized queries as the primary defense.
常见问题
- 是 parameterized queries 100% 安全?
- 为数据 values, 是 — 数据库 treats parameters as 数据, 从不 as SQL. However, parameterized queries cannot 是 used 为 identifiers (表 names, 列 names) — 那些必须是 validated 针对 whitelist. 动态 SQL (EXECUTE/EXEC) 具有 concatenated identifiers 是仍然 vulnerable. Use ORM 查询 builders 或 whitelist validation 为 identifiers.
- 什么是 blind SQL injection?
- 当应用不 返回 SQL 错误或 查询结果 directly. attacker infers 信息通过 observing 行为: 布尔值-based (page differs 如果条件是 真/假), 时间-based (SLEEP() delays 响应如果条件是 真), out-of-band (DNS/HTTP exfiltration). Parameterized queries prevent 所有 forms 的 SQLi, including blind.