123456789_123456789_123456789_123456789_123456789_

Module: ActionController::RequestForgeryProtection

Relationships & Source Files
Namespace Children
Modules:
Extension / Inclusion / Inheritance Descendants
Included In:
Base, ::ActionView::TestCase::TestController, Rails::ApplicationController, Rails::InfoController, Rails::MailersController, Rails::WelcomeController
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
Instance Chain:
Defined in: actionpack/lib/action_controller/metal/request_forgery_protection.rb

Overview

Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks by including a token in the rendered HTML for your application. This token is stored as a random string in the session, to which an attacker does not have access. When a request reaches your application, Rails verifies the received token with the token in the session. All requests are checked except GET requests as these should be idempotent. Keep in mind that all session-oriented requests should be CSRF protected, including JavaScript and HTML requests.

Since HTML and JavaScript requests are typically made from the browser, we need to ensure to verify request authenticity for the web browser. We can use session-oriented authentication for these types of requests, by using the protect_from_forgery method in our controllers.

GET requests are not protected since they don’t have side effects like writing to the database and don’t leak sensitive information. JavaScript requests are an exception: a third-party site can use a <script> tag to reference a JavaScript URL on your site. When your JavaScript response loads on their site, it executes. With carefully crafted JavaScript on their end, sensitive data in your JavaScript response may be extracted. To prevent this, only XmlHttpRequest (known as XHR or Ajax) requests are allowed to make GET requests for JavaScript responses.

It’s important to remember that XML or JSON requests are also affected and if you’re building an API you should change forgery protection method in ApplicationController (by default: :exception):

class ApplicationController < ActionController::Base
  protect_from_forgery unless: -> { request.format.json? }
end

CSRF protection is turned on with the protect_from_forgery method. By default protect_from_forgery protects your session with :null_session method, which provides an empty session during request.

We may want to disable CSRF protection for APIs since they are typically designed to be state-less. That is, the request API client will handle the session for you instead of ::Rails.

The token parameter is named authenticity_token by default. The name and value of this token must be added to every layout that renders forms by including csrf_meta_tags in the HTML head.

Learn more about CSRF attacks and securing your application in the Ruby on {Rails Security Guide}.

Constant Summary

::ActiveSupport::Callbacks - Included

CALLBACK_FILTER_TYPES

::AbstractController::Helpers - Attributes & Methods

Class Method Summary

::ActiveSupport::DescendantsTracker - self

clear, descendants, direct_descendants,
store_inherited

This is the only method that is not thread safe, but is only ever called during the eager loading phase.

::ActiveSupport::Concern - Extended

Instance Attribute Summary

::AbstractController::Callbacks - Included

Instance Method Summary

::AbstractController::Callbacks - Included

#process_action

Override AbstractController::Base#process_action to run the process_action callbacks around the normal behavior.

::ActiveSupport::Callbacks - Included

#run_callbacks

Runs the callbacks for the given event.

DSL Calls

included

[ GitHub ]


65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 65

included do
  # Sets the token parameter name for RequestForgery. Calling protect_from_forgery
  # sets it to <tt>:authenticity_token</tt> by default.
  config_accessor :request_forgery_protection_token
  self.request_forgery_protection_token ||= :authenticity_token

  # Holds the class which implements the request forgery protection.
  config_accessor :forgery_protection_strategy
  self.forgery_protection_strategy = nil

  # Controls whether request forgery protection is turned on or not. Turned off by default only in test mode.
  config_accessor :allow_forgery_protection
  self.allow_forgery_protection = true if allow_forgery_protection.nil?

  # Controls whether a CSRF failure logs a warning. On by default.
  config_accessor :log_warning_on_csrf_failure
  self.log_warning_on_csrf_failure = true

  # Controls whether the Origin header is checked in addition to the CSRF token.
  config_accessor :forgery_protection_origin_check
  self.forgery_protection_origin_check = false

  # Controls whether form-action/method specific CSRF tokens are used.
  config_accessor :per_form_csrf_tokens
  self.per_form_csrf_tokens = false

  # Controls whether forgery protection is enabled by default.
  config_accessor :default_protect_from_forgery
  self.default_protect_from_forgery = false

  # Controls whether URL-safe CSRF tokens are generated.
  config_accessor :urlsafe_csrf_tokens, instance_writer: false
  self.urlsafe_csrf_tokens = false

  helper_method :form_authenticity_token
  helper_method :protect_against_forgery?
end

Class Attribute Details

._helper_methods (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 11

class_attribute :_helper_methods, default: Array.new

._helper_methods?Boolean (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 11

class_attribute :_helper_methods, default: Array.new

._helpers (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 10

class_attribute :_helpers, default: Module.new

._helpers?Boolean (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 10

class_attribute :_helpers, default: Module.new

Instance Attribute Details

#_helper_methods (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 11

class_attribute :_helper_methods, default: Array.new

#_helper_methods?Boolean (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 11

class_attribute :_helper_methods, default: Array.new

#_helpers (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 10

class_attribute :_helpers, default: Module.new

#_helpers?Boolean (rw)

[ GitHub ]

  
# File 'actionpack/lib/abstract_controller/helpers.rb', line 10

class_attribute :_helpers, default: Module.new

#any_authenticity_token_valid?Boolean (readonly, private)

Checks if any of the authenticity tokens from the request are valid.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 299

def any_authenticity_token_valid? # :doc:
  request_authenticity_tokens.any? do |token|
    valid_authenticity_token?(session, token)
  end
end

#marked_for_same_origin_verification?Boolean (readonly, private)

If the #verify_authenticity_token before_action ran, verify that JavaScript responses are only served to same-origin GET requests.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 277

def marked_for_same_origin_verification? # :doc:
  @marked_for_same_origin_verification ||= false
end

#non_xhr_javascript_response?Boolean (readonly, private)

Check for cross-origin JavaScript responses.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 282

def non_xhr_javascript_response? # :doc:
  content_type =~ %r(\Atext/javascript) && !request.xhr?
end

#protect_against_forgery?Boolean (readonly, private)

Checks if the controller allows forgery protection.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 439

def protect_against_forgery? # :doc:
  allow_forgery_protection
end

#valid_request_origin?Boolean (readonly, private)

Checks if the request originated from the same origin by looking at the Origin header.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 454

def valid_request_origin? # :doc:
  if forgery_protection_origin_check
    # We accept blank origin headers because some user agents don't send it.
    raise InvalidAuthenticityToken, NULL_ORIGIN_MESSAGE if request.origin == "null"
    request.origin.nil? || request.origin == request.base_url
  else
    true
  end
end

#verified_request?Boolean (readonly, private)

Returns true or false if a request is verified. Checks:

  • Is it a GET or HEAD request? GETs should be safe and idempotent

  • Does the form_authenticity_token match the given token value from the params?

  • Does the X-CSRF-Token header match the form_authenticity_token?

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 293

def verified_request? # :doc:
  !protect_against_forgery? || request.get? || request.head? ||
    (valid_request_origin? && any_authenticity_token_valid?)
end

Instance Method Details

#compare_with_global_token(token, session) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 385

def compare_with_global_token(token, session) # :doc:
  ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, global_csrf_token(session))
end

#compare_with_real_token(token, session) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 381

def compare_with_real_token(token, session) # :doc:
  ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, real_csrf_token(session))
end

#csrf_token_hmac(session, identifier) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 419

def csrf_token_hmac(session, identifier) # :doc:
  OpenSSL::HMAC.digest(
    OpenSSL::Digest::SHA256.new,
    real_csrf_token(session),
    identifier
  )
end

#form_authenticity_param (private)

The form’s authenticity parameter. Override to provide your own.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 434

def form_authenticity_param # :doc:
  params[request_forgery_protection_token]
end

#global_csrf_token(session) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 415

def global_csrf_token(session) # :doc:
  csrf_token_hmac(session, GLOBAL_CSRF_TOKEN_IDENTIFIER)
end

#handle_unverified_request (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 246

def handle_unverified_request # :doc:
  forgery_protection_strategy.new(self).handle_unverified_request
end

#mark_for_same_origin_verification! (private)

GET requests are checked for cross-origin JavaScript after rendering.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 271

def mark_for_same_origin_verification! # :doc:
  @marked_for_same_origin_verification = request.get?
end

#mask_token(raw_token) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 374

def mask_token(raw_token) # :doc:
  one_time_pad = SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)
  encrypted_csrf_token = xor_byte_strings(one_time_pad, raw_token)
  masked_token = one_time_pad + encrypted_csrf_token
  encode_csrf_token(masked_token)
end

#masked_authenticity_token(session, form_options: {}) (private)

Creates a masked version of the authenticity token that varies on each request. The masking is used to mitigate SSL attacks like BREACH.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 318

def masked_authenticity_token(session, form_options: {}) # :doc:
  action, method = form_options.values_at(:action, :method)

  raw_token = if per_form_csrf_tokens && action && method
    action_path = normalize_action_path(action)
    per_form_csrf_token(session, action_path, method)
  else
    global_csrf_token(session)
  end

  mask_token(raw_token)
end

#normalize_action_path(action_path) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 464

def normalize_action_path(action_path) # :doc:
  uri = URI.parse(action_path)
  uri.path.chomp("/")
end

#per_form_csrf_token(session, action_path, method) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 408

def per_form_csrf_token(session, action_path, method) # :doc:
  csrf_token_hmac(session, [action_path, method.downcase].join("#"))
end

#real_csrf_token(session) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 403

def real_csrf_token(session) # :doc:
  session[:_csrf_token] ||= generate_csrf_token
  decode_csrf_token(session[:_csrf_token])
end

#request_authenticity_tokens (private)

Possible authenticity tokens sent in the request.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 306

def request_authenticity_tokens # :doc:
  [form_authenticity_param, request.x_csrf_token]
end

#unmask_token(masked_token) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 366

def unmask_token(masked_token) # :doc:
  # Split the token into the one-time pad and the encrypted
  # value and decrypt it.
  one_time_pad = masked_token[0...AUTHENTICITY_TOKEN_LENGTH]
  encrypted_csrf_token = masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]
  xor_byte_strings(one_time_pad, encrypted_csrf_token)
end

#valid_authenticity_token?(session, encoded_masked_token) ⇒ Boolean (private)

Checks the client’s masked token to see if it matches the session token. Essentially the inverse of #masked_authenticity_token.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 334

def valid_authenticity_token?(session, encoded_masked_token) # :doc:
  if encoded_masked_token.nil? || encoded_masked_token.empty? || !encoded_masked_token.is_a?(String)
    return false
  end

  begin
    masked_token = decode_csrf_token(encoded_masked_token)
  rescue ArgumentError # encoded_masked_token is invalid Base64
    return false
  end

  # See if it's actually a masked token or not. In order to
  # deploy this code, we should be able to handle any unmasked
  # tokens that we've issued without error.

  if masked_token.length == AUTHENTICITY_TOKEN_LENGTH
    # This is actually an unmasked token. This is expected if
    # you have just upgraded to masked tokens, but should stop
    # happening shortly after installing this gem.
    compare_with_real_token masked_token, session

  elsif masked_token.length == AUTHENTICITY_TOKEN_LENGTH * 2
    csrf_token = unmask_token(masked_token)

    compare_with_global_token(csrf_token, session) ||
      compare_with_real_token(csrf_token, session) ||
      valid_per_form_csrf_token?(csrf_token, session)
  else
    false # Token is malformed.
  end
end

#valid_per_form_csrf_token?(token, session) ⇒ Boolean (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 389

def valid_per_form_csrf_token?(token, session) # :doc:
  if per_form_csrf_tokens
    correct_token = per_form_csrf_token(
      session,
      normalize_action_path(request.fullpath),
      request.request_method
    )

    ActiveSupport::SecurityUtils.fixed_length_secure_compare(token, correct_token)
  else
    false
  end
end

#verify_authenticity_token (private)

The actual before_action that is used to verify the CSRF token. Don’t override this directly. Provide your own forgery protection strategy instead. If you override, you’ll disable same-origin <script> verification.

Lean on the protect_from_forgery declaration to mark which actions are due for same-origin request verification. If protect_from_forgery is enabled on an action, this before_action flags its after_action to verify that JavaScript responses are for XHR requests, ensuring they follow the browser’s same-origin policy.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 231

def verify_authenticity_token # :doc:
  mark_for_same_origin_verification!

  if !verified_request?
    if logger && log_warning_on_csrf_failure
      if valid_request_origin?
        logger.warn "Can't verify CSRF token authenticity."
      else
        logger.warn "HTTP Origin header (#{request.origin}) didn't match request.base_url (#{request.base_url})"
      end
    end
    handle_unverified_request
  end
end

#verify_same_origin_request (private)

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.

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 261

def verify_same_origin_request # :doc:
  if marked_for_same_origin_verification? && non_xhr_javascript_response?
    if logger && log_warning_on_csrf_failure
      logger.warn CROSS_ORIGIN_JAVASCRIPT_WARNING
    end
    raise ActionController::InvalidCrossOriginRequest, CROSS_ORIGIN_JAVASCRIPT_WARNING
  end
end

#xor_byte_strings(s1, s2) (private)

[ GitHub ]

  
# File 'actionpack/lib/action_controller/metal/request_forgery_protection.rb', line 427

def xor_byte_strings(s1, s2) # :doc:
  s2_bytes = s2.bytes
  s1.each_byte.with_index { |c1, i| s2_bytes[i] ^= c1 }
  s2_bytes.pack("C*")
end