A relatively basic yet useful helper that can be used to protect your application from CSRF attacks/exploits. Note that this helper merely generates the required data, and provides several methods. You still need to manually add the token to each form.
The reason for this is because this is quite simple. Ramaze is meant as a framework that works with any given helper, ORM, template engine and so on. If we were to automatically load this helper and include (a perhaps more advanced) CSRF system that would mean that every form helper, official or third-party, would have to support that specific system. However, there’s no need to panic as it’s very easy to setup a basic anti CSRF system.
## Usage
In order to enable CSRF protection we need to do two things. Load the helper and create a before_all block in a controller. Take a look at the following code:
class BaseController < Ramaze::Controller before_all do puts "Hello, before_all!" end end
This would output “Hello, before_all!” to the console upon each request. Not very useful but it does show what the before_all block can do. On to actual CSRF related code!
class BaseController < Ramaze::Controller before_all do csrf_protection :save do # .... end end end
This example introduces an extra block that validates the current request. Whenever a user requests a controller that either extends BaseController or has it’s own before_all block Ramaze will check if the current request data contains a CSRF token. Of course an if/end isn’t very useful if it doesn’t do anything, let’s add some code.
class BaseController < Ramaze::Controller before_all do csrf_protection :save do puts "Hello, unsafe data!" end end end
The code above checks if the current method is “save” (or any other of the provided methods) and checks if an CSRF token is supplied if the method matches. Protected methods require a token in ALL HTTP requests (GET, POST, etc). While this may seem weird since GET is generally used for safe actions it actually makes sense. Ramaze stores both the POST and GET parameters in the request.params hash. While this makes it easy to work with POST/GET data this also makes it easier to spoof POST requests using a GET request, thus this helper protects ALL request methods.
If you’re a lazy person you can copy-paste the example below and adapt it to your needs.
class BaseController < Ramaze::Controller before_all do csrf_protection :save do respond("The supplied CSRF token is invalid.", 401) end end end
Method that can be used to protect the specified methods against CSRF exploits. Each protected method will require the token to be stored in a field called “csrf_token“. This method will then validate that token against the current token in the session.
@param [Strings/Symbol] *methods Methods that will be
protected/unprotected.
@param [Block] Block that will be executed if the token is invalid. @example
# Protect "create" and "save" against CSRF exploits before_all do csrf_protection :create, :save do respond("GET TO DA CHOPPA!", 401) end end
# File lib/ramaze/helper/csrf.rb, line 96 96: def csrf_protection(*methods, &block) 97: # Only protect the specified methods 98: if methods.include?(action.name) or methods.include?(action.name.to_sym) 99: # THINK: For now the field name is hard-coded to "csrf_token". While 100: # this is perfectly fine in most cases it might be a good idea 101: # to allow developers to change the name of this field (for whatever 102: # the reason). 103: yield unless validate_csrf_token(request.params['csrf_token']) 104: end 105: end
Generate a new token and create the session array that will be used to validate the client. The following items are stored in the session:
token: An unique hash that will be stored in each form
agent: The visitor’s user agent
ip: The IP address of the visitor
time: Timestamp that indicates at what time the data was generated.
Note that this method will be automatically called if no CSRF token exists.
@param [Hash] Additional arguments that can be set such as the TTL.
# File lib/ramaze/helper/csrf.rb, line 120 120: def generate_csrf_token(args = {}) 121: ttl = args[:ttl] || (15 * 60) 122: random = SecureRandom.random_bytes(512) 123: time = Time.now.to_f 124: token = Digest::SHA512.hexdigest(random + time.to_s) 125: 126: # Time to store all the data we want to check later. 127: session[:_csrf] = { 128: :time => time.to_i, 129: :token => token, 130: :ip => request.ip, 131: :agent => request.env['HTTP_USER_AGENT'], 132: :host => request.host, 133: :ttl => ttl 134: } 135: 136: return 137: end
Retrieves the current value of the CSRF token.
@return [String] The current CSRF token. @example
form(@data, :method => :post) do |f| f.input_hidden :csrf_token, get_csrf_token() end
# File lib/ramaze/helper/csrf.rb, line 148 148: def get_csrf_token 149: if !session[:_csrf] || !self.validate_csrf_token(session[:_csrf][:token]) 150: self.generate_csrf_token 151: end 152: 153: return session[:_csrf][:token] 154: end
Validates the request based on the current session date stored in _csrf. The following items are verified:
Do the user agent, ip and token match those supplied by the visitor?
Has the token been expired? (after 15 minutes).
If any of these checks fail this method will return FALSE. It’s your job to take action based on the results of this method.
@param [String] input_token The CSRF token to validate. @return [TrueClass|FalseClass] @example
before_all do if validate_csrf_token(request.params['csrf_token']) != true respond("Invalid CSRF token", 401) end end
# File lib/ramaze/helper/csrf.rb, line 175 175: def validate_csrf_token(input_token) 176: # Check if the CSRF data has been generated and generate it if this 177: # hasn't been done already (usually on the first request). 178: if !session[:_csrf] or session[:_csrf].empty? 179: self.generate_csrf_token 180: end 181: 182: _csrf = session[:_csrf] 183: 184: valid = session[:_csrf][:token] == input_token && 185: (Time.now.to_f - _csrf[:time]) <= _csrf[:ttl] && 186: _csrf[:host] == request.host && 187: _csrf[:ip] == request.ip && 188: _csrf[:agent] == request.env['HTTP_USER_AGENT'] 189: 190: if valid 191: generate_csrf_token 192: return true 193: else 194: return false 195: end 196: end
Disabled; run with --debug to generate this.
Generated with the Darkfish Rdoc Generator 1.1.6.