CodeQL 文档

不安全的批量赋值

ID: rb/insecure-mass-assignment
Kind: path-problem
Security severity: 9.8
Severity: error
Precision: high
Tags:
   - security
   - external/cwe/cwe-915
Query suites:
   - ruby-code-scanning.qls
   - ruby-security-extended.qls
   - ruby-security-and-quality.qls

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

允许批量赋值(使用哈希设置对象的多个属性)的操作,例如 ActiveRecord::Base.new,应该注意不要允许用户设置任意参数。否则,可能会设置意外的属性,例如 User 对象的 is_admin 字段。

建议

在使用来自用户提供的参数的批量赋值操作时,使用 ActionController::Parameters#permit 来限制用户可以提供的参数,而不是 ActionController::Parameters#permit!,后者允许使用任意参数进行批量赋值。

示例

在以下示例中,使用了 permit!,允许用户提供任意参数。

class UserController < ActionController::Base
    def create
        # BAD: arbitrary params are permitted to be used for this assignment
        User.new(user_params).save!
    end

    def user_params
        params.require(:user).permit!
    end
end

在以下示例中,只允许特定的参数,因此批量赋值是安全的。

class UserController < ActionController::Base
    def create
        # GOOD: the permitted parameters are explicitly specified
        User.new(user_params).save!
    end

    def user_params
        params.require(:user).permit(:name, :email)
    end
end

参考资料

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