CodeQL 文档

锚定不当的正则表达式

ID: rb/regex/badly-anchored-regexp
Kind: path-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

点击查看 CodeQL 仓库中的查询

Ruby 中的正则表达式可以使用锚点来匹配字符串的开头和结尾。但是,如果使用了 ^$ 锚点,正则表达式可能会匹配多行字符串中的一行。这使得恶意攻击者可以绕过您的正则表达式检查并注入恶意输入。

建议

使用 \A\z 锚点,因为这些锚点始终匹配字符串的开头和结尾,即使字符串包含换行符。

示例

以下(不良)示例代码使用正则表达式检查字符串是否只包含数字。

def bad(input) 
    raise "Bad input" unless input =~ /^[0-9]+$/

    # ....
end

正则表达式 /^[0-9]+$/ 将匹配多行字符串中的一行,这可能不是预期行为。以下(良好)示例代码使用正则表达式 \A[0-9]+\z 匹配整个输入字符串。

def good(input)
    raise "Bad input" unless input =~ /\A[0-9]+\z/

    # ....
end

参考

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