Skip to content

Commit

Permalink
Fix open redirect vulnerability
Browse files Browse the repository at this point in the history
An open redirect can be possible when users are able to set the value of
session[:return_to]. If the value used for return_to contains multiple
leading slashes (/////example.com) the user ends up being redirected the
external domain that comes after the slashes (http://example.com).

To fix this issue, extra sanitization was added when processing the
return_to url, removing multiple leading slashes to avoid the open
redirect.
  • Loading branch information
MottiniMauro committed Aug 31, 2021
1 parent d1fade8 commit d2324db
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
8 changes: 7 additions & 1 deletion lib/clearance/authorization.rb
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,16 @@ def redirect_back_or(default)
def return_to
if return_to_url
uri = URI.parse(return_to_url)
"#{uri.path}?#{uri.query}".chomp("?") + "##{uri.fragment}".chomp("#")
path = path_without_leading_slashes(uri)
"#{path}?#{uri.query}".chomp("?") + "##{uri.fragment}".chomp("#")
end
end

# @api private
def path_without_leading_slashes(uri)
uri.path.sub(/\A\/+/, '/')
end

# @api private
def return_to_url
session[:return_to]
Expand Down
13 changes: 13 additions & 0 deletions spec/controllers/sessions_controller_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,19 @@
end

context "with good credentials and a session return url" do
it "redirects to the return URL removing leading slashes" do
user = create(:user)
url = "/url_in_the_session?foo=bar#baz"
return_url = "//////#{url}"
request.session[:return_to] = return_url

post :create, params: {
session: { email: user.email, password: user.password },
}

should redirect_to(url)
end

it "redirects to the return URL maintaining query and fragment" do
user = create(:user)
return_url = "/url_in_the_session?foo=bar#baz"
Expand Down

0 comments on commit d2324db

Please sign in to comment.