SQL injection · SQL 注入
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
When input becomes a command
- Many apps build a database query by gluing the user's input into a string. That is dangerous.
- If an attacker types SQL as their input, it can become part of the query. This is SQL injection — the most famous web attack.
中文
当输入变成了命令
- 许多应用通过把用户输入拼接进一个字符串来构造数据库查询。这很危险。
- 如果攻击者把 SQL 当作输入来输入,它就可能成为查询的一部分。这就是 SQL 注入 —— 最著名的 Web 攻击。
English
See the attack
- Imagine a login that checks
... WHERE name = '<whatever you typed>'. - An attacker types
' OR '1'='1as the name. The query becomes:
'1'='1'is always true, so the database returns every user. The login is bypassed. Run it and see.
中文
看看这次攻击
- 设想一个登录功能,它检查
... WHERE name = '<你输入的内容>'。 - 攻击者把
' OR '1'='1当作用户名输入。查询于是变成:
SELECT * FROM users WHERE name = '' OR '1'='1';
'1'='1'永远为真,所以数据库返回每一个用户。登录被绕过了。运行一下看看。
English
The fix: parameterised queries
- Never glue user input into SQL. Use parameterised queries (also called prepared statements).
- The database treats the input strictly as a value, never as code — so
' OR '1'='1is just a (failed) name to look up. - Also apply least privilege: the web app's database account should only do what it needs.
中文
修复之道:参数化查询
- 绝不要把用户输入拼接进 SQL。要用参数化查询(也叫预编译语句)。
- 数据库会严格地把输入当作一个值,而绝不当作代码 —— 于是
' OR '1'='1只是一个(查不到的)名字。 - 同时应用最小权限:Web 应用所用的数据库账户,只应能做它需要做的事。
English
Your turn
- Below, write a precise, safe query that returns only bob by his
id. That is the spirit of a parameterised lookup.
Covers: A-Level data security; web application security.
中文
轮到你了
- 下面,写一个精确而安全的查询,通过
id只返回 bob。这正是参数化查询的精神所在。
涵盖:A-Level 数据安全;Web 应用安全。
English
Common mistakes
- Never build a query by joining raw user input into the text.
- Use parameterised queries so input can never change the query.
中文
常见错误
- 绝不要把用户的原始输入拼进查询文本里。
- 使用参数化查询,让输入永远无法改变查询。
First, run the attack and see the damage. The app glued the attacker's input into the query, so the condition became name = '' OR '1'='1'. Complete the query exactly like that and see every user leak out. · 先运行这次攻击,看看破坏有多大。应用把攻击者的输入拼进了查询,于是条件变成了 name = '' OR '1'='1'。把查询补成这个样子,看所有用户如何被泄露。
Click Run to see the output here. · 点击“运行”查看此处输出。
A safe lookup uses a precise condition. Change the query to return only bob's row, by adding WHERE id = 2. · 安全的查询使用精确的条件。修改查询,只返回 bob 的那一行 —— 加上 WHERE id = 2。
Click Run to see the output here. · 点击“运行”查看此处输出。