首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >修补Rails 3以修复CSRF保护漏洞

修补Rails 3以修复CSRF保护漏洞
EN

Stack Overflow用户
提问于 2015-03-02 18:12:13
回答 1查看 321关注 0票数 2

我目前正在开发一个大型项目,它使用Rails 3.2,没有机会迁移到Rails 4。我知道,Rails 3在有JS视图时存在CSRF保护漏洞,这是GET请求的。在Rails 4中,它是由这个PR修复的。

https://github.com/rails/rails/pull/13345/files

有人知道如何修补Rails 3来修复此漏洞吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-03-03 17:39:00

您可以对Rails 3.2 ActionController:: RequestForgeryProtection模块应用完全相同的更改。

代码语言:javascript
复制
# config/initializers/cross_origin_script_tag_protection.rb

module ActionController
  class InvalidCrossOriginRequest < ActionControllerError
  end

  module RequestForgeryProtection
    module ClassMethods
      def protect_from_forgery(options = {})
        self.request_forgery_protection_token ||= :authenticity_token
        prepend_before_filter :verify_authenticity_token, options
        append_after_action :verify_same_origin_request
      end
    end

    protected

      def verify_authenticity_token
        @marked_for_same_origin_verification = true

        unless verified_request?
          logger.warn "WARNING: Can't verify CSRF token authenticity" if logger
          handle_unverified_request
        end
      end

      CROSS_ORIGIN_JAVASCRIPT_WARNING = "Security warning: an embedded " \
        "<script> tag on another site requested protected JavaScript. " \
        "If you know what you're doing, go ahead and disable forgery " \
        "protection on this action to permit cross-origin JavaScript embedding."
      private_constant :CROSS_ORIGIN_JAVASCRIPT_WARNING

      # If `verify_authenticity_token` was run (indicating that we have
      # forgery protection enabled for this request) then also verify that
      # we aren't serving an unauthorized cross-origin response.
      def verify_same_origin_request
        if marked_for_same_origin_verification? && non_xhr_javascript_response?
          logger.warn CROSS_ORIGIN_JAVASCRIPT_WARNING if logger
          raise ActionController::InvalidCrossOriginRequest, CROSS_ORIGIN_JAVASCRIPT_WARNING
        end
      end

      # If the `verify_authenticity_token` before_action ran, verify that
      # JavaScript responses are only served to same-origin GET requests.
      def marked_for_same_origin_verification?
        defined? @marked_for_same_origin_verification
      end

      # Check for cross-origin JavaScript responses.
      def non_xhr_javascript_response?
        content_type =~ %r(\Atext/javascript) && !request.xhr?
      end
  end
end

如果对你有用的话请告诉我。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28816617

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档