2011-05-23 04:07:54 -04:00
|
|
|
require 'rack/protection'
|
|
|
|
|
|
|
|
module Rack
|
|
|
|
module Protection
|
2011-05-24 07:23:57 -04:00
|
|
|
##
|
|
|
|
# Prevented attack:: Directory traversal
|
|
|
|
# Supported browsers:: all
|
|
|
|
# More infos:: http://en.wikipedia.org/wiki/Directory_traversal
|
|
|
|
#
|
|
|
|
# Unescapes '/' and '.', expands +path_info+.
|
|
|
|
# Thus <tt>GET /foo/%2e%2e%2fbar</tt> becomes <tt>GET /bar</tt>.
|
2011-05-23 04:07:54 -04:00
|
|
|
class PathTraversal < Base
|
2011-05-24 11:59:33 -04:00
|
|
|
def call(env)
|
|
|
|
path_was = env["PATH_INFO"]
|
|
|
|
env["PATH_INFO"] = cleanup path_was
|
|
|
|
app.call env
|
|
|
|
ensure
|
|
|
|
env["PATH_INFO"] = path_was
|
|
|
|
end
|
|
|
|
|
|
|
|
def cleanup(path)
|
2011-10-01 19:44:39 -04:00
|
|
|
parts = []
|
|
|
|
unescaped = path.gsub('%2e', '.').gsub('%2f', '/')
|
|
|
|
|
|
|
|
unescaped.split('/').each do |part|
|
|
|
|
next if part.empty? or part == '.'
|
|
|
|
part == '..' ? parts.pop : parts << part
|
|
|
|
end
|
|
|
|
|
|
|
|
cleaned = '/' << parts.join('/')
|
|
|
|
cleaned << '/' if parts.any? and unescaped =~ /\/\.{0,2}$/
|
|
|
|
cleaned
|
2011-05-24 11:59:33 -04:00
|
|
|
end
|
2011-05-23 04:07:54 -04:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|