CodeQL 文档

正则表达式注入

ID: rb/regexp-injection
Kind: path-problem
Security severity: 7.5
Severity: error
Precision: high
Tags:
   - security
   - external/cwe/cwe-1333
   - external/cwe/cwe-730
   - external/cwe/cwe-400
Query suites:
   - ruby-code-scanning.qls
   - ruby-security-extended.qls
   - ruby-security-and-quality.qls

点击查看 CodeQL 代码库中的查询

使用未经清理的用户输入构建正则表达式是危险的,因为恶意用户可能能够修改表达式的含义。特别是,这样的用户可能能够提供一个在最坏情况下需要指数级时间的正则表达式片段,并利用它来执行拒绝服务攻击。

建议

在将用户输入嵌入到正则表达式之前,使用清理函数(如Regexp.escape)来转义具有特殊含义的元字符。

示例

以下示例从 HTTP 请求参数构建正则表达式,但没有先对其进行清理

class UsersController < ActionController::Base
  def first_example
    # BAD: Unsanitized user input is used to construct a regular expression
    regex = /#{ params[:key] }/
  end

  def second_example
    # BAD: Unsanitized user input is used to construct a regular expression
    regex = Regexp.new(params[:key])
  end
end

相反,应先清理请求参数。这可以确保用户无法插入在正则表达式中具有特殊含义的字符。

class UsersController < ActionController::Base
  def example
    # GOOD: User input is sanitized before constructing the regular expression
    regex = Regexp.new(Regex.escape(params[:key]))
  end
end

参考资料

  • ©GitHub, Inc.
  • 条款
  • 隐私