Sha256: 01c02ad1f5461f2cf12cb70a67f2d6bda61dff2adb6f60458c72e20c4359fa29

Contents?: true

Size: 1.25 KB

Versions: 16

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

require 'rack/protection'

module Rack
  module Protection
    ##
    # 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>.
    class PathTraversal < Base
      def call(env)
        path_was         = env['PATH_INFO']
        env['PATH_INFO'] = cleanup path_was if path_was && !path_was.empty?
        app.call env
      ensure
        env['PATH_INFO'] = path_was
      end

      def cleanup(path)
        encoding = path.encoding
        dot   = '.'.encode(encoding)
        slash = '/'.encode(encoding)
        backslash = '\\'.encode(encoding)

        parts     = []
        unescaped = path.gsub(/%2e/i, dot).gsub(/%2f/i, slash).gsub(/%5c/i, backslash)
        unescaped = unescaped.gsub(backslash, slash)

        unescaped.split(slash).each do |part|
          next if part.empty? || (part == dot)

          part == '..' ? parts.pop : parts << part
        end

        cleaned = slash + parts.join(slash)
        cleaned << slash if parts.any? && unescaped =~ (%r{/\.{0,2}$})
        cleaned
      end
    end
  end
end

Version data entries

16 entries across 16 versions & 2 rubygems

Version Path
rack-protection-4.1.1 lib/rack/protection/path_traversal.rb
rack-protection-4.1.0 lib/rack/protection/path_traversal.rb
rack-protection-4.0.0 lib/rack/protection/path_traversal.rb
rack-protection-3.2.0 lib/rack/protection/path_traversal.rb
rack-protection-3.1.0 lib/rack/protection/path_traversal.rb
rubypitaya-3.12.5 ./lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/rack-protection-3.0.5/lib/rack/protection/path_traversal.rb
rack-protection-3.0.6 lib/rack/protection/path_traversal.rb
rubypitaya-3.12.4 ./lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/rack-protection-3.0.5/lib/rack/protection/path_traversal.rb
rubypitaya-3.12.3 ./lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/rack-protection-3.0.5/lib/rack/protection/path_traversal.rb
rubypitaya-3.12.2 ./lib/rubypitaya/app-template/vendor/bundle/ruby/3.1.0/gems/rack-protection-3.0.5/lib/rack/protection/path_traversal.rb
rack-protection-3.0.5 lib/rack/protection/path_traversal.rb
rack-protection-3.0.4 lib/rack/protection/path_traversal.rb
rack-protection-3.0.3 lib/rack/protection/path_traversal.rb
rack-protection-3.0.2 lib/rack/protection/path_traversal.rb
rack-protection-3.0.1 lib/rack/protection/path_traversal.rb
rack-protection-3.0.0 lib/rack/protection/path_traversal.rb