Permalink
Browse files

xhr requests cannot be used for the json attack, fixes #39

  • Loading branch information...
rkh committed Mar 1, 2013
1 parent c823079 commit 2560bb93b0896aed823431a316550c93fc6e0eac
Showing with 17 additions and 6 deletions.
  1. +13 −6 lib/rack/protection/json_csrf.rb
  2. +4 −0 spec/json_csrf_spec.rb
@@ -14,14 +14,21 @@ class JsonCsrf < Base
default_reaction :deny
def call(env)
+ request = Request.new(env)
status, headers, body = app.call(env)
- if headers['Content-Type'].to_s.split(';', 2).first =~ /^\s*application\/json\s*$/
- if origin(env).nil? and referrer(env) != Request.new(env).host
- result = react(env)
- warn env, "attack prevented by #{self.class}"
- end
+
+ if has_vector? request, headers
+ warn env, "attack prevented by #{self.class}"
+ react(env)
+ else
+ [status, headers, body]
end
- result or [status, headers, body]
+ end
+
+ def has_vector?(request, headers)
+ return false if request.xhr?
+ return false unless headers['Content-Type'].to_s.split(';', 2).first =~ /^\s*application\/json\s*$/
+ origin(request.env).nil? and referrer(request.env) != request.host
end
end
end
View
@@ -27,6 +27,10 @@
it "accepts get requests with json responses with no referrer" do
get('/', {}).should be_ok
end
+
+ it "accepts XHR requests" do
+ get('/', {}, 'HTTP_REFERER' => 'http://evil.com', 'HTTP_X_REQUESTED_WITH' => 'XMLHttpRequest').should be_ok
+ end
end
describe 'not json response' do

0 comments on commit 2560bb9

Please sign in to comment.