主机名不完整的正则表达式¶
ID: rb/incomplete-hostname-regexp
Kind: problem
Security severity: 7.8
Severity: warning
Precision: high
Tags:
- correctness
- security
- external/cwe/cwe-020
Query suites:
- ruby-code-scanning.qls
- ruby-security-extended.qls
- ruby-security-and-quality.qls
清理不受信任的 URL 是防止诸如请求伪造和恶意重定向等攻击的重要技术。通常,这是通过检查 URL 的主机是否在允许的主机集中来完成的。
如果正则表达式实现这样的检查,则很容易意外地通过不适当地转义 .
元字符来使检查过于宽松。即使检查未在安全关键上下文中使用,不完整的检查在意外成功时也可能导致不良行为。
建议¶
在构建用于安全检查的正则表达式时,请适当地转义所有元字符,并特别注意 .
元字符。
示例¶
以下示例代码检查 URL 重定向是否将到达 example.com
域或其子域之一。
class AppController < ApplicationController
def index
url = params[:url]
host = URI(url).host
# BAD: the host of `url` may be controlled by an attacker
regex = /^((www|beta).)?example.com/
if host.match(regex)
redirect_to url
end
end
end
但是,由于未转义的 .
允许在 example.com
之前出现任何字符,因此该检查很容易绕过,实际上允许重定向到攻击者控制的域,例如 wwwXexample.com
。
通过适当地转义 .
来解决此漏洞:regex = /^((www|beta)\.)?example\.com/
。