maxjustus / sinatra-authentication

A sinatra extension wrapped in a gem that implements authentication/permissions with users stored in the database. Now with optional support for facebook connect
The Unlicense
476 stars 94 forks source link

XSRF / CSRF #41

Open timmillwood opened 11 years ago

timmillwood commented 11 years ago

There seems to be little or no protection for XSRF / CSRF.

timmillwood commented 11 years ago

Simple solution:

before do
  if request.post?
   if session[:csrf] != params[:csrf]
     halt 503
   end
  end

  time = Time.now.to_s
  @key = Digest::SHA1.hexdigest(time)
  session[:csrf] = @key
end

Then on all form views add:

<input type="hidden" name="csrf" value="<%= @key %>" />
cmhobbs commented 11 years ago

I should have some spare time next weekend. I'll take a look at this if @maxjustus doesn't nail it first.

timmillwood commented 11 years ago

My "simple solution" can be added to any Sinatra app. I think if we're looking to alter the original, a better solution may be available.

timmillwood commented 11 years ago

A better solution is to use rack/csrf

require 'rack/csrf'

use Rack::Csrf, :raise => true

Then in the views <%= Rack::Csrf.csrf_tag(env) %>