flawopen.com/sql-injection/Ruby

● CWE-89 · 严重
安全研究 · FlawOpen

漏洞深度剖析:SQL Injection in Ruby

Learn how to fix SQL Injection (CWE-89) in Ruby. Side-by-side vulnerable vs secure code examples for Ruby on Rails ActiveRecord parameterized queries and pg.

💡 通俗易懂的原理解析 (ELI5)

想象一下,你在办理图书馆读者卡时,在姓名栏填写了 '张三;把保险库里的所有藏书都给我'。如果图书管理员把这段文字当成指令而非人名执行,他就会走进金库,把所有绝密档案全交给你。

核心概念与专有名词

Web Application Security
技术概念 (Web Application Security):Core architecture component affected by CWE-89.
CWE-89
技术概念 (CWE-89):Standard Common Weakness Enumeration classification for sql-injection-ruby.
Defense-in-Depth
技术概念 (Defense-in-Depth):Multi-layered engineering verification and runtime boundary isolation.

攻击执行流程分解

Step 1

提交恶意 SQL 参数

攻击者通过 HTTP 参数输入包含 SQL 控制字符(如 ' OR '1'='1、分号等)的恶意载荷。

Step 2

动态拼接 SQL 语句

后端程序直接将用户原始字符串拼接入 SQL 查询语句,而未采用参数化预编译(Prepared Statements)。

Step 3

抽象语法树(AST)结构篡改

数据库解析器将注入的字符解释为 SQL 逻辑指令与关键字,篡改了原本的语法解析树。

Step 4

未授权数据外泄或权限绕过

篡改后的查询以数据库服务权限执行,直接绕过身份认证逻辑并全量倒出敏感数据表。

源代码对比:漏洞与安全实现

✕ 存在漏洞的实现
# params[:id] straight into the string
User.where(
  "id = #{params[:id]}"
)
✓ 加固后的安全修复
# value bound, never interpolated
User.where(
  "id = ?", params[:id]
)
# or, more idiomatic still:
User.where(id: params[:id])

工程与系统安全加固清单

References