CodeQL 文档

使用外部控制的格式字符串

ID: rb/tainted-format-string
Kind: path-problem
Security severity: 7.3
Severity: warning
Precision: high
Tags:
   - security
   - external/cwe/cwe-134
Query suites:
   - ruby-code-scanning.qls
   - ruby-security-extended.qls
   - ruby-security-and-quality.qls

单击查看 CodeQL 存储库中的查询

类似 Kernel.printf 的方法接受一个格式字符串,该字符串用于通过提供内联格式说明符来格式化其余参数。如果格式字符串包含来自不受信任源的未经清理的输入,则该字符串可能包含导致输出混乱或引发异常的意外格式说明符。

建议

要么在将输入包含在格式字符串中之前对其进行清理,要么在格式字符串中使用 %s 说明符,并将不受信任的数据作为相应的参数传递。

示例

以下程序片段记录了有关未经授权访问尝试的信息。日志消息包含用户名,用户的 IP 地址作为附加参数传递给 Kernel.printf 以附加到消息中

class UsersController < ActionController::Base
  def index
    printf("Unauthorised access attempt by #{params[:user]}: %s", request.ip)
  end
end

但是,如果恶意用户将其用户名提供为 %s 这样的格式说明符,Kernel.printf 将引发异常,因为没有足够的参数来满足格式。这会导致拒绝服务或通过堆栈跟踪向攻击者泄露内部信息。

相反,应使用 %s 说明符包含用户名

class UsersController < ActionController::Base
  def index
    printf("Unauthorised access attempt by %s: %s", params[:user], request.ip)
  end
end

或者,应该独占使用字符串插值

class UsersController < ActionController::Base
  def index
    puts "Unauthorised access attempt by #{params[:user]}: #{request.ip}"
  end
end

参考

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