code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def initialize(thread_count) @max_active_threads = [thread_count, 0].max @threads = Set.new @threads_mon = Monitor.new @queue = Queue.new @join_cond = @threads_mon.new_cond @history_start_time = nil @history = [] @history_mon = Monitor.new @total_threads_in_play = 0 end
Creates a ThreadPool object. The +thread_count+ parameter is the size of the pool.
initialize
ruby
ruby/rake
lib/rake/thread_pool.rb
https://github.com/ruby/rake/blob/master/lib/rake/thread_pool.rb
MIT
def future(*args, &block) promise = Promise.new(args, &block) promise.recorder = lambda { |*stats| stat(*stats) } @queue.enq promise stat :queued, item_id: promise.object_id start_thread promise end
Creates a future executed by the +ThreadPool+. The args are passed to the block when executing (similarly to Thread#new) The return value is an object representing a future which has been created and added to the queue in the pool. Sending #value to the object will sleep the current thread until the future is finished and will return the result (or raise an exception thrown from the future)
future
ruby
ruby/rake
lib/rake/thread_pool.rb
https://github.com/ruby/rake/blob/master/lib/rake/thread_pool.rb
MIT
def join @threads_mon.synchronize do begin stat :joining @join_cond.wait unless @threads.empty? stat :joined rescue Exception => e stat :joined $stderr.puts e $stderr.print "Queue contains #{@queue.size} items. " + "Thread pool contains #{@threads.count} threads\n" $stderr.print "Current Thread #{Thread.current} status = " + "#{Thread.current.status}\n" $stderr.puts e.backtrace.join("\n") @threads.each do |t| $stderr.print "Thread #{t} status = #{t.status}\n" $stderr.puts t.backtrace.join("\n") end raise e end end end
Waits until the queue of futures is empty and all threads have exited.
join
ruby
ruby/rake
lib/rake/thread_pool.rb
https://github.com/ruby/rake/blob/master/lib/rake/thread_pool.rb
MIT
def gather_history #:nodoc: @history_start_time = Time.now if @history_start_time.nil? end
Enable the gathering of history events.
gather_history
ruby
ruby/rake
lib/rake/thread_pool.rb
https://github.com/ruby/rake/blob/master/lib/rake/thread_pool.rb
MIT
def history # :nodoc: @history_mon.synchronize { @history.dup }. sort_by { |i| i[:time] }. each { |i| i[:time] -= @history_start_time } end
Return a array of history events for the thread pool. History gathering must be enabled to be able to see the events (see #gather_history). Best to call this when the job is complete (i.e. after ThreadPool#join is called).
history
ruby
ruby/rake
lib/rake/thread_pool.rb
https://github.com/ruby/rake/blob/master/lib/rake/thread_pool.rb
MIT
def statistics # :nodoc: { total_threads_in_play: @total_threads_in_play, max_active_threads: @max_active_threads, } end
Return a hash of always collected statistics for the thread pool.
statistics
ruby
ruby/rake
lib/rake/thread_pool.rb
https://github.com/ruby/rake/blob/master/lib/rake/thread_pool.rb
MIT
def process_queue_item #:nodoc: return false if @queue.empty? # Even though we just asked if the queue was empty, it # still could have had an item which by this statement # is now gone. For this reason we pass true to Queue#deq # because we will sleep indefinitely if it is empty. promise = @queue.deq(true) stat :dequeued, item_id: promise.object_id promise.work return true rescue ThreadError # this means the queue is empty false end
processes one item on the queue. Returns true if there was an item to process, false if there was no item
process_queue_item
ruby
ruby/rake
lib/rake/thread_pool.rb
https://github.com/ruby/rake/blob/master/lib/rake/thread_pool.rb
MIT
def trace_on(out, *strings) sep = $\ || "\n" if strings.empty? output = sep else output = strings.map { |s| next if s.nil? s.end_with?(sep) ? s : s + sep }.join end out.print(output) end
Write trace output to output stream +out+. The write is done as a single IO call (to print) to lessen the chance that the trace output is interrupted by other tasks also producing output.
trace_on
ruby
ruby/rake
lib/rake/trace_output.rb
https://github.com/ruby/rake/blob/master/lib/rake/trace_output.rb
MIT
def windows? RbConfig::CONFIG["host_os"] =~ %r!(msdos|mswin|djgpp|mingw|[Ww]indows)! end
True if running on a windows system.
windows?
ruby
ruby/rake
lib/rake/win32.rb
https://github.com/ruby/rake/blob/master/lib/rake/win32.rb
MIT
def win32_system_dir #:nodoc: win32_shared_path = ENV["HOME"] if win32_shared_path.nil? && ENV["HOMEDRIVE"] && ENV["HOMEPATH"] win32_shared_path = ENV["HOMEDRIVE"] + ENV["HOMEPATH"] end win32_shared_path ||= ENV["APPDATA"] win32_shared_path ||= ENV["USERPROFILE"] raise Win32HomeError, "Unable to determine home path environment variable." if win32_shared_path.nil? or win32_shared_path.empty? normalize(File.join(win32_shared_path, "Rake")) end
The standard directory containing system wide rake files on Win 32 systems. Try the following environment variables (in order): * HOME * HOMEDRIVE + HOMEPATH * APPDATA * USERPROFILE If the above are not defined, the return nil.
win32_system_dir
ruby
ruby/rake
lib/rake/win32.rb
https://github.com/ruby/rake/blob/master/lib/rake/win32.rb
MIT
def normalize(path) path.gsub(/\\/, "/") end
Normalize a win32 path so that the slashes are all forward slashes.
normalize
ruby
ruby/rake
lib/rake/win32.rb
https://github.com/ruby/rake/blob/master/lib/rake/win32.rb
MIT
def rake_extension(method) # :nodoc: if method_defined?(method) $stderr.puts "WARNING: Possible conflict with Rake extension: " + "#{self}##{method} already exists" else yield end end
Check for an existing method in the current class before extending. If the method already exists, then a warning is printed and the extension is not added. Otherwise the block is yielded and any definitions in the block will take effect. Usage: class String rake_extension("xyz") do def xyz ... end end end
rake_extension
ruby
ruby/rake
lib/rake/ext/core.rb
https://github.com/ruby/rake/blob/master/lib/rake/ext/core.rb
MIT
def ext(newext="") return self.dup if [".", ".."].include? self if newext != "" newext = "." + newext unless newext =~ /^\./ end self.chomp(File.extname(self)) << newext end
Replace the file extension with +newext+. If there is no extension on the string, append the new extension to the end. If the new extension is not given, or is the empty string, remove any existing extension. +ext+ is a user added method for the String class. This String extension comes from Rake
ext
ruby
ruby/rake
lib/rake/ext/string.rb
https://github.com/ruby/rake/blob/master/lib/rake/ext/string.rb
MIT
def pathmap_explode head, tail = File.split(self) return [self] if head == self return [tail] if head == "." || tail == "/" return [head, tail] if head == "/" return head.pathmap_explode + [tail] end
Explode a path into individual components. Used by +pathmap+. This String extension comes from Rake
pathmap_explode
ruby
ruby/rake
lib/rake/ext/string.rb
https://github.com/ruby/rake/blob/master/lib/rake/ext/string.rb
MIT
def pathmap_partial(n) dirs = File.dirname(self).pathmap_explode partial_dirs = if n > 0 dirs[0...n] elsif n < 0 dirs.reverse[0...-n].reverse else "." end File.join(partial_dirs) end
Extract a partial path from the path. Include +n+ directories from the front end (left hand side) if +n+ is positive. Include |+n+| directories from the back end (right hand side) if +n+ is negative. This String extension comes from Rake
pathmap_partial
ruby
ruby/rake
lib/rake/ext/string.rb
https://github.com/ruby/rake/blob/master/lib/rake/ext/string.rb
MIT
def pathmap_replace(patterns, &block) result = self patterns.split(";").each do |pair| pattern, replacement = pair.split(",") pattern = Regexp.new(pattern) if replacement == "*" && block_given? result = result.sub(pattern, &block) elsif replacement result = result.sub(pattern, replacement) else result = result.sub(pattern, "") end end result end
Perform the pathmap replacement operations on the given path. The patterns take the form 'pat1,rep1;pat2,rep2...'. This String extension comes from Rake
pathmap_replace
ruby
ruby/rake
lib/rake/ext/string.rb
https://github.com/ruby/rake/blob/master/lib/rake/ext/string.rb
MIT
def pathmap(spec=nil, &block) return self if spec.nil? result = "".dup spec.scan(/%\{[^}]*\}-?\d*[sdpfnxX%]|%-?\d+d|%.|[^%]+/) do |frag| case frag when "%f" result << File.basename(self) when "%n" result << File.basename(self).ext when "%d" result << File.dirname(self) when "%x" result << File.extname(self) when "%X" result << self.ext when "%p" result << self when "%s" result << (File::ALT_SEPARATOR || File::SEPARATOR) when "%-" # do nothing when "%%" result << "%" when /%(-?\d+)d/ result << pathmap_partial($1.to_i) when /^%\{([^}]*)\}(\d*[dpfnxX])/ patterns, operator = $1, $2 result << pathmap("%" + operator).pathmap_replace(patterns, &block) when /^%/ fail ArgumentError, "Unknown pathmap specifier #{frag} in '#{spec}'" else result << frag end end result end
Map the path according to the given specification. The specification controls the details of the mapping. The following special patterns are recognized: <tt>%p</tt> :: The complete path. <tt>%f</tt> :: The base file name of the path, with its file extension, but without any directories. <tt>%n</tt> :: The file name of the path without its file extension. <tt>%d</tt> :: The directory list of the path. <tt>%x</tt> :: The file extension of the path. An empty string if there is no extension. <tt>%X</tt> :: Everything *but* the file extension. <tt>%s</tt> :: The alternate file separator if defined, otherwise use # the standard file separator. <tt>%%</tt> :: A percent sign. The <tt>%d</tt> specifier can also have a numeric prefix (e.g. '%2d'). If the number is positive, only return (up to) +n+ directories in the path, starting from the left hand side. If +n+ is negative, return (up to) +n+ directories from the right hand side of the path. Examples: 'a/b/c/d/file.txt'.pathmap("%2d") => 'a/b' 'a/b/c/d/file.txt'.pathmap("%-2d") => 'c/d' Also the <tt>%d</tt>, <tt>%p</tt>, <tt>%f</tt>, <tt>%n</tt>, <tt>%x</tt>, and <tt>%X</tt> operators can take a pattern/replacement argument to perform simple string substitutions on a particular part of the path. The pattern and replacement are separated by a comma and are enclosed by curly braces. The replacement spec comes after the % character but before the operator letter. (e.g. "%{old,new}d"). Multiple replacement specs should be separated by semi-colons (e.g. "%{old,new;src,bin}d"). Regular expressions may be used for the pattern, and back refs may be used in the replacement text. Curly braces, commas and semi-colons are excluded from both the pattern and replacement text (let's keep parsing reasonable). For example: "src/org/onestepback/proj/A.java".pathmap("%{^src,class}X.class") returns: "class/org/onestepback/proj/A.class" If the replacement text is '*', then a block may be provided to perform some arbitrary calculation for the replacement. For example: "/path/to/file.TXT".pathmap("%X%{.*,*}x") { |ext| ext.downcase } Returns: "/path/to/file.txt" This String extension comes from Rake
pathmap
ruby
ruby/rake
lib/rake/ext/string.rb
https://github.com/ruby/rake/blob/master/lib/rake/ext/string.rb
MIT
def load(fn) # :nodoc: lines = File.read fn lines.gsub!(/\\ /, SPACE_MARK) lines.gsub!(/#[^\n]*\n/m, "") lines.gsub!(/\\\n/, " ") lines.each_line do |line| process_line(line) end end
Load the makefile dependencies in +fn+.
load
ruby
ruby/rake
lib/rake/loaders/makefile.rb
https://github.com/ruby/rake/blob/master/lib/rake/loaders/makefile.rb
MIT
def process_line(line) # :nodoc: file_tasks, args = line.split(":", 2) return if args.nil? dependents = args.split.map { |d| respace(d) } file_tasks.scan(/\S+/) do |file_task| file_task = respace(file_task) file file_task => dependents end end
Process one logical line of makefile data.
process_line
ruby
ruby/rake
lib/rake/loaders/makefile.rb
https://github.com/ruby/rake/blob/master/lib/rake/loaders/makefile.rb
MIT
def assert_something_matches(pattern, lines) lines.each do |ln| if pattern =~ ln assert_match pattern, ln return end end flunk "expected #{pattern.inspect} to match something in:\n" + "#{lines.join("\n ")}" end
Assert that the pattern matches at least one line in +lines+.
assert_something_matches
ruby
ruby/rake
test/test_rake_backtrace.rb
https://github.com/ruby/rake/blob/master/test/test_rake_backtrace.rb
MIT
def ztest_file_deletes_on_failure task :obj file NEWFILE => [:obj] do |t| FileUtils.touch NEWFILE fail "Ooops" end assert Task[NEWFILE] begin Task[NEWFILE].invoke rescue Exception end assert(! File.exist?(NEWFILE), "NEWFILE should be deleted") end
I have currently disabled this test. I'm not convinced that deleting the file target on failure is always the proper thing to do. I'm willing to hear input on this topic.
ztest_file_deletes_on_failure
ruby
ruby/rake
test/test_rake_file_task.rb
https://github.com/ruby/rake/blob/master/test/test_rake_file_task.rb
MIT
def capture_subprocess_io begin require "tempfile" captured_stdout = Tempfile.new("out") captured_stderr = Tempfile.new("err") orig_stdout = $stdout.dup orig_stderr = $stderr.dup $stdout.reopen captured_stdout $stderr.reopen captured_stderr yield $stdout.rewind $stderr.rewind [captured_stdout.read, captured_stderr.read] ensure $stdout.reopen orig_stdout $stderr.reopen orig_stderr orig_stdout.close orig_stderr.close captured_stdout.close! captured_stderr.close! end end
Originally copied from minitest/assertions.rb
capture_subprocess_io
ruby
ruby/rake
test/test_rake_file_utils.rb
https://github.com/ruby/rake/blob/master/test/test_rake_file_utils.rb
MIT
def test_dry_run_bug rakefile_dryrun rake FileUtils.rm_f "temp_one" rake "--dry-run" refute_match(/No such file/, @out) end
Test for the trace/dry_run bug found by Brian Chandler
test_dry_run_bug
ruby
ruby/rake
test/test_rake_functional.rb
https://github.com/ruby/rake/blob/master/test/test_rake_functional.rb
MIT
def test_trace_bug rakefile_dryrun rake FileUtils.rm_f "temp_one" rake "--trace" refute_match(/No such file/, @out) end
Test for the trace/dry_run bug found by Brian Chandler
test_trace_bug
ruby
ruby/rake
test/test_rake_functional.rb
https://github.com/ruby/rake/blob/master/test/test_rake_functional.rb
MIT
def test_single_dependent_with_nil_args create_file(SRCFILE) rule nil => ".cpp" do |t| p t.name end rule(/\.o$/ => ".c") do |t| @runs << t.name end Task[OBJFILE].invoke assert_equal [OBJFILE], @runs end
for https://github.com/ruby/rake/pull/182
test_single_dependent_with_nil_args
ruby
ruby/rake
test/test_rake_rules.rb
https://github.com/ruby/rake/blob/master/test/test_rake_rules.rb
MIT
def test_exceptions pool = ThreadPool.new(10) deep_exception_block = lambda do |count| raise CustomError if count < 1 pool.future(count - 1, &deep_exception_block).value end assert_raises(CustomError) do pool.future(2, &deep_exception_block).value end ensure pool.join end
test that throwing an exception way down in the blocks propagates to the top
test_exceptions
ruby
ruby/rake
test/test_rake_thread_pool.rb
https://github.com/ruby/rake/blob/master/test/test_rake_thread_pool.rb
MIT
def ruby(*option_list) run_ruby(@ruby_options + option_list) end
Run a shell Ruby command with command line options (using the default test options). Output is captured in @out and @err
ruby
ruby
ruby/rake
test/support/ruby_runner.rb
https://github.com/ruby/rake/blob/master/test/support/ruby_runner.rb
MIT
def rake(*rake_options) run_ruby @ruby_options + [@rake_exec] + rake_options end
Run a command line rake with the give rake options. Default command line ruby options are included. Output is captured in @out and @err
rake
ruby
ruby/rake
test/support/ruby_runner.rb
https://github.com/ruby/rake/blob/master/test/support/ruby_runner.rb
MIT
def initialize(app, options={}) default_options = { :redirect_to => nil, :redirect_code => nil, :strict => false, :mixed => false, :hsts => nil, :http_port => nil, :https_port => nil, :force_secure_cookies => true, :redirect_html => nil, :before_redirect => nil } CONSTRAINTS_BY_TYPE.values.each do |constraints| constraints.each { |constraint| default_options[constraint] = nil } end @app, @options = app, default_options.merge(options) end
Warning: If you set the option force_secure_cookies to false, make sure that your cookies are encoded and that you understand the consequences (see documentation)
initialize
ruby
tobmatth/rack-ssl-enforcer
lib/rack/ssl-enforcer.rb
https://github.com/tobmatth/rack-ssl-enforcer/blob/master/lib/rack/ssl-enforcer.rb
MIT
def flag_cookies_as_secure!(headers) if cookies = headers['Set-Cookie'] # Support Rails 2.3 / Rack 1.1 arrays as headers unless cookies.is_a?(Array) cookies = cookies.split("\n") end headers['Set-Cookie'] = cookies.map do |cookie| cookie !~ /(^|;\s)secure($|;)/ ? "#{cookie}; secure" : cookie end.join("\n") end end
see http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_theft_and_session_hijacking
flag_cookies_as_secure!
ruby
tobmatth/rack-ssl-enforcer
lib/rack/ssl-enforcer.rb
https://github.com/tobmatth/rack-ssl-enforcer/blob/master/lib/rack/ssl-enforcer.rb
MIT
def set_hsts_headers!(headers) opts = { :expires => 31536000, :subdomains => true, :preload => false } opts.merge!(@options[:hsts]) if @options[:hsts].is_a? Hash value = "max-age=#{opts[:expires]}" value += "; includeSubDomains" if opts[:subdomains] value += "; preload" if opts[:preload] headers.merge!({ 'Strict-Transport-Security' => value }) end
see http://en.wikipedia.org/wiki/Strict_Transport_Security
set_hsts_headers!
ruby
tobmatth/rack-ssl-enforcer
lib/rack/ssl-enforcer.rb
https://github.com/tobmatth/rack-ssl-enforcer/blob/master/lib/rack/ssl-enforcer.rb
MIT
def prepare_params(params) return params if Rails.version[0].to_i <= 4 { params: params } end
Needed to run tests against Rails 4 AND 5
prepare_params
ruby
nicolasblanco/rails_param
spec/rails_integration_spec.rb
https://github.com/nicolasblanco/rails_param/blob/master/spec/rails_integration_spec.rb
MIT
def initialize(url: nil, file: nil, proxy: nil, ssl: false, method: 'GET', placeholder: 'xxURLxx', post_data: nil, rules: nil, no_urlencode: false, ip_encoding: nil, match: '\A(.*)\z', strip: nil, decode_html: false, unescape: false, guess_mime: false, sniff_mime: false, guess_status: false, cors: false, timeout_ok: false, detect_headers: false, fail_no_content: false, forward_method: false, forward_headers: false, forward_body: false, forward_cookies: false, body_to_uri: false, auth_to_uri: false, cookies_to_uri: false, cache_buster: false, cookie: nil, user: nil, timeout: 10, user_agent: nil, insecure: false) @SUPPORTED_METHODS = %w[GET HEAD DELETE POST PUT OPTIONS].freeze @SUPPORTED_IP_ENCODINGS = %w[int ipv6 oct hex dotted_hex].freeze @logger = ::Logger.new(STDOUT).tap do |log| log.progname = 'ssrf-proxy' log.level = ::Logger::WARN log.datetime_format = '%Y-%m-%d %H:%M:%S ' end # SSRF configuration options @proxy = nil @placeholder = placeholder.to_s || 'xxURLxx' @method = 'GET' @headers ||= {} @post_data = post_data.to_s || '' @rules = rules.to_s.split(/,/) || [] @no_urlencode = no_urlencode || false # client request modification @ip_encoding = nil @forward_method = forward_method || false @forward_headers = forward_headers || false @forward_body = forward_body || false @forward_cookies = forward_cookies || false @body_to_uri = body_to_uri || false @auth_to_uri = auth_to_uri || false @cookies_to_uri = cookies_to_uri || false @cache_buster = cache_buster || false # SSRF connection options @user = '' @pass = '' @timeout = timeout.to_i || 10 @insecure = insecure || false # HTTP response modification options @match_regex = match.to_s || '\A(.*)\z' @strip = strip.to_s.downcase.split(/,/) || [] @decode_html = decode_html || false @unescape = unescape || false @guess_status = guess_status || false @guess_mime = guess_mime || false @sniff_mime = sniff_mime || false @detect_headers = detect_headers || false @fail_no_content = fail_no_content || false @timeout_ok = timeout_ok || false @cors = cors || false # ensure either a URL or file path was provided if url.to_s.eql?('') && file.to_s.eql?('') raise ArgumentError, "Option 'url' or 'file' must be provided." end # parse HTTP request file unless file.to_s.eql?('') unless url.to_s.eql?('') raise ArgumentError, "Options 'url' and 'file' are mutually exclusive." end if file.is_a?(String) if File.exist?(file) && File.readable?(file) http = File.read(file).to_s else raise SSRFProxy::HTTP::Error::InvalidSsrfRequest.new, "Invalid SSRF request specified : Could not read file #{file.inspect}" end elsif file.is_a?(StringIO) http = file.read end req = parse_http_request(http) url = req['uri'] @method = req['method'] @headers = {} req['headers'].each do |k, v| @headers[k.downcase] = v.flatten.first end @headers.delete('host') @post_data = req['body'] end # parse target URL begin @url = URI.parse(url.to_s) rescue URI::InvalidURIError raise SSRFProxy::HTTP::Error::InvalidSsrfRequest.new, 'Invalid SSRF request specified : Could not parse URL.' end if @url.scheme.nil? || @url.host.nil? || @url.port.nil? raise SSRFProxy::HTTP::Error::InvalidSsrfRequest.new, 'Invalid SSRF request specified : Invalid URL.' end unless @url.scheme.eql?('http') || @url.scheme.eql?('https') raise SSRFProxy::HTTP::Error::InvalidSsrfRequest.new, 'Invalid SSRF request specified : URL scheme must be http(s).' end if proxy begin @proxy = URI.parse(proxy.to_s) rescue URI::InvalidURIError raise SSRFProxy::HTTP::Error::InvalidUpstreamProxy.new, 'Invalid upstream proxy specified.' end if @proxy.host.nil? || @proxy.port.nil? raise SSRFProxy::HTTP::Error::InvalidUpstreamProxy.new, 'Invalid upstream proxy specified.' end if @proxy.scheme !~ /\A(socks|https?)\z/ raise SSRFProxy::HTTP::Error::InvalidUpstreamProxy.new, 'Unsupported upstream proxy specified. ' \ 'Scheme must be http(s) or socks.' end end if ssl @url.scheme = 'https' end if method case method.to_s.downcase when 'get' @method = 'GET' when 'head' @method = 'HEAD' when 'delete' @method = 'DELETE' when 'post' @method = 'POST' when 'put' @method = 'PUT' when 'options' @method = 'OPTIONS' else raise SSRFProxy::HTTP::Error::InvalidSsrfRequestMethod.new, 'Invalid SSRF request method specified. ' \ "Supported methods: #{@SUPPORTED_METHODS.join(', ')}." end end if ip_encoding unless @SUPPORTED_IP_ENCODINGS.include?(ip_encoding) raise SSRFProxy::HTTP::Error::InvalidIpEncoding.new, 'Invalid IP encoding method specified.' end @ip_encoding = ip_encoding.to_s end if cookie @headers['cookie'] = cookie.to_s end if user if user.to_s =~ /^(.*?):(.*)/ @user = $1 @pass = $2 else @user = user.to_s end end if user_agent @headers['user-agent'] = user_agent end # Ensure a URL placeholder was provided unless @url.request_uri.to_s.include?(@placeholder) || @post_data.to_s.include?(@placeholder) || @headers.to_s.include?(@placeholder) raise SSRFProxy::HTTP::Error::NoUrlPlaceholder.new, 'You must specify a URL placeholder with ' \ "'#{@placeholder}' in the SSRF request" end end
SSRFProxy::HTTP accepts SSRF connection information, and configuration options for request modification and response modification. @param url [String] Target URL vulnerable to SSRF @param file [String] Load HTTP request from a file @param proxy [String] Use a proxy to connect to the server. (Supported proxies: http, https, socks) @param ssl [Boolean] Connect using SSL/TLS @param method [String] HTTP method (GET/HEAD/DELETE/POST/PUT/OPTIONS) (Default: GET) @param post_data [String] HTTP post data @param user [String] HTTP basic authentication credentials @param rules [String] Rules for parsing client request (separated by ',') (Default: none) @param no_urlencode [Boolean] Do not URL encode client request @param ip_encoding [String] Encode client request host IP address. (Modes: int, ipv6, oct, hex, dotted_hex) @param match [String] Regex to match response body content. (Default: \A(.*)\z) @param strip [String] Headers to remove from the response. (separated by ',') (Default: none) @param decode_html [Boolean] Decode HTML entities in response body @param unescape [Boolean] Unescape special characters in response body @param guess_status [Boolean] Replaces response status code and message headers (determined by common strings in the response body, such as 404 Not Found.) @param guess_mime [Boolean] Replaces response content-type header with the appropriate mime type (determined by the file extension of the requested resource.) @param sniff_mime [Boolean] Replaces response content-type header with the appropriate mime type (determined by magic bytes in the response body.) @param timeout_ok [Boolean] Replaces timeout HTTP status code 504 with 200. @param detect_headers [Boolean] Replaces response headers if response headers are identified in the response body. @param fail_no_content [Boolean] Return HTTP status 502 if response body is empty. @param forward_method [Boolean] Forward client request method @param forward_headers [Boolean] Forward all client request headers @param forward_body [Boolean] Forward client request body @param forward_cookies [Boolean] Forward client request cookies @param body_to_uri [Boolean] Add client request body to URI query string @param auth_to_uri [Boolean] Use client request basic authentication credentials in request URI. @param cookies_to_uri [Boolean] Add client request cookies to URI query string @param cache_buster [Boolean] Append a random value to the client request query string @param timeout [Integer] Connection timeout in seconds (Default: 10) @param user_agent [String] HTTP user-agent (Default: none) @param insecure [Boolean] Skip server SSL certificate validation @example Configure SSRF with URL, GET method SSRFProxy::HTTP.new(url: 'http://example.local/?url=xxURLxx') @example Configure SSRF with URL, POST method SSRFProxy::HTTP.new(url: 'http://example.local/', method: 'POST', post_data: 'url=xxURLxx') @example Configure SSRF with raw HTTP request file SSRFProxy::HTTP.new(file: 'ssrf.txt') @example Configure SSRF with raw HTTP request file and force SSL/TLS SSRFProxy::HTTP.new(file: 'ssrf.txt', ssl: true) @example Configure SSRF with raw HTTP request StringIO SSRFProxy::HTTP.new(file: StringIO.new("GET http://example.local/?url=xxURLxx HTTP/1.1\n\n")) @raise [SSRFProxy::HTTP::Error::InvalidSsrfRequest] Invalid SSRF request specified. @raise [SSRFProxy::HTTP::Error::InvalidUpstreamProxy] Invalid upstream proxy specified. @raise [SSRFProxy::HTTP::Error::InvalidSsrfRequestMethod] Invalid SSRF request method specified. Supported methods: GET, HEAD, DELETE, POST, PUT, OPTIONS. @raise [SSRFProxy::HTTP::Error::NoUrlPlaceholder] 'xxURLxx' URL placeholder must be specified in the SSRF request URL or body. @raise [SSRFProxy::HTTP::Error::InvalidIpEncoding] Invalid IP encoding method specified.
initialize
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def parse_http_request(request) # parse method if request.to_s !~ /\A(GET|HEAD|DELETE|POST|PUT|OPTIONS) / logger.warn('HTTP request method is not supported') raise SSRFProxy::HTTP::Error::InvalidClientRequest, 'HTTP request method is not supported.' end # parse client request begin req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(request)) rescue logger.warn('HTTP request is malformed.') raise SSRFProxy::HTTP::Error::InvalidClientRequest, 'HTTP request is malformed.' end # validate host if request.to_s !~ %r{\A(GET|HEAD|DELETE|POST|PUT|OPTIONS) https?://} if request.to_s =~ /^Host: ([^\s]+)\r?\n/ logger.info("Using host header: #{$1}") else logger.warn('HTTP request is malformed : No host specified.') raise SSRFProxy::HTTP::Error::InvalidClientRequest, 'HTTP request is malformed : No host specified.' end end # return request hash uri = req.request_uri method = req.request_method headers = req.header begin body = req.body.to_s rescue WEBrick::HTTPStatus::BadRequest => e logger.warn("HTTP request is malformed : #{e.message}") raise SSRFProxy::HTTP::Error::InvalidClientRequest, "HTTP request is malformed : #{e.message}" rescue WEBrick::HTTPStatus::LengthRequired logger.warn("HTTP request is malformed : Request body without 'Content-Length' header.") raise SSRFProxy::HTTP::Error::InvalidClientRequest, "HTTP request is malformed : Request body without 'Content-Length' header." end { 'uri' => uri, 'method' => method, 'headers' => headers, 'body' => body } end
Parse a raw HTTP request as a string @param [String] request raw HTTP request @raise [SSRFProxy::HTTP::Error::InvalidClientRequest] An invalid client HTTP request was supplied. @return [Hash] HTTP request hash (url, method, headers, body)
parse_http_request
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def send_request(request, use_ssl: false) req = parse_http_request(request) req['uri'].scheme = 'https' if use_ssl send_uri(req['uri'], method: req['method'], headers: req['headers'], body: req['body']) end
Parse a raw HTTP request as a string, then send the requested URL and HTTP headers to #send_uri @param request [String] Raw HTTP request @param use_ssl [Boolean] Connect using SSL/TLS @return [Hash] HTTP response hash (version, code, message, headers, body)
send_request
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def send_uri(uri, method: 'GET', headers: {}, body: '') uri = uri.to_s body = body.to_s headers = {} unless headers.is_a?(Hash) # validate url unless uri.start_with?('http://', 'https://') raise SSRFProxy::HTTP::Error::InvalidClientRequest, 'Invalid request URI' end # set request method if @forward_method if @SUPPORTED_METHODS.include?(method) request_method = method else raise SSRFProxy::HTTP::Error::InvalidClientRequest, "Request method '#{method}' is not supported" end else request_method = @method end # parse request headers client_headers = {} headers.each do |k, v| if v.is_a?(Array) client_headers[k.downcase] = v.flatten.first elsif v.is_a?(String) client_headers[k.downcase] = v.to_s else raise SSRFProxy::HTTP::Error::InvalidClientRequest, "Request header #{k.inspect} value is malformed: #{v}" end end # reject websocket requests if client_headers['upgrade'].to_s.start_with?('WebSocket') logger.warn('WebSocket tunneling is not supported') raise SSRFProxy::HTTP::Error::InvalidClientRequest, 'WebSocket tunneling is not supported' end # copy request body to URL if @body_to_uri && !body.eql?('') logger.debug("Parsing request body: #{body}") separator = uri.include?('?') ? '&' : '?' uri = "#{uri}#{separator}#{body}" logger.info("Added request body to URI: #{body.inspect}") end # copy basic authentication credentials to uri if @auth_to_uri && client_headers['authorization'].to_s.downcase.start_with?('basic ') logger.debug("Parsing basic authentication header: #{client_headers['authorization']}") begin creds = client_headers['authorization'].split(' ')[1] user = Base64.decode64(creds).chomp uri = uri.gsub!(%r{://}, "://#{CGI.escape(user).gsub(/\+/, '%20').gsub('%3A', ':')}@") logger.info("Using basic authentication credentials: #{user}") rescue logger.warn('Could not parse request authorization header: ' \ "#{client_headers['authorization']}") end end # copy cookies to uri cookies = [] if @cookies_to_uri && !client_headers['cookie'].nil? logger.debug("Parsing request cookies: #{client_headers['cookie']}") client_headers['cookie'].split(/;\s*/).each do |c| cookies << c.to_s unless c.nil? end separator = uri.include?('?') ? '&' : '?' uri = "#{uri}#{separator}#{cookies.join('&')}" logger.info("Added cookies to URI: #{cookies.join('&')}") end # add cache buster if @cache_buster separator = uri.include?('?') ? '&' : '?' junk = "#{rand(36**6).to_s(36)}=#{rand(36**6).to_s(36)}" uri = "#{uri}#{separator}#{junk}" end # set request headers request_headers = @headers.dup # forward request cookies new_cookie = [] new_cookie << @headers['cookie'] unless @headers['cookie'].to_s.eql?('') if @forward_cookies && !client_headers['cookie'].nil? client_headers['cookie'].split(/;\s*/).each do |c| new_cookie << c.to_s unless c.nil? end end unless new_cookie.empty? request_headers['cookie'] = new_cookie.uniq.join('; ') logger.info("Using cookie: #{new_cookie.join('; ')}") end # forward request headers and strip proxy headers if @forward_headers && !client_headers.empty? client_headers.each do |k, v| next if k.eql?('proxy-connection') next if k.eql?('proxy-authorization') if v.is_a?(Array) request_headers[k.downcase] = v.flatten.first elsif v.is_a?(String) request_headers[k.downcase] = v.to_s end end end # encode target host ip ip_encoded_uri = @ip_encoding ? encode_ip(uri, @ip_encoding) : uri # run request URI through rules target_uri = run_rules(ip_encoded_uri, @rules).to_s # URL encode target URI unless @no_urlencode target_uri = CGI.escape(target_uri).gsub(/\+/, '%20').to_s end # set path and query string if @url.query.to_s.eql?('') ssrf_url = @url.path.to_s else ssrf_url = "#{@url.path}?#{@url.query}" end # replace xxURLxx placeholder in request URL ssrf_url.gsub!(/#{@placeholder}/, target_uri) # replace xxURLxx placeholder in request body post_data = @post_data.gsub(/#{@placeholder}/, target_uri) # set request body if @forward_body && !body.eql?('') request_body = post_data.eql?('') ? body : "#{post_data}&#{body}" else request_body = post_data end # replace xxURLxx in request header values request_headers.each do |k, v| request_headers[k] = v.gsub(/#{@placeholder}/, target_uri) end # set content type if request_headers['content-type'].nil? && !request_body.eql?('') request_headers['content-type'] = 'application/x-www-form-urlencoded' end # set content length request_headers['content-length'] = request_body.length.to_s # send request response = nil start_time = Time.now begin response = send_http_request(ssrf_url, request_method, request_headers, request_body) if response['content-encoding'].to_s.downcase.eql?('gzip') && response.body begin sio = StringIO.new(response.body) gz = Zlib::GzipReader.new(sio) response.body = gz.read rescue logger.warn('Could not decompress response body') end end result = { 'url' => uri, 'http_version' => response.http_version, 'code' => response.code, 'message' => response.message, 'headers' => '', 'body' => response.body.to_s || '' } rescue SSRFProxy::HTTP::Error::ConnectionTimeout => e unless @timeout_ok raise SSRFProxy::HTTP::Error::ConnectionTimeout, e.message end result = { 'url' => uri, 'http_version' => '1.0', 'code' => 200, 'message' => 'Timeout', 'headers' => '', 'body' => '' } logger.info('Changed HTTP status code 504 to 200') end # set duration end_time = Time.now duration = ((end_time - start_time) * 1000).round(3) result['duration'] = duration # body content encoding result['body'].force_encoding('BINARY') unless result['body'].valid_encoding? begin result['body'] = result['body'].encode( 'UTF-8', 'binary', :invalid => :replace, :undef => :replace, :replace => '' ) rescue end end logger.info("Received #{result['body'].bytes.length} bytes in #{duration} ms") # match response content unless @match_regex.nil? matches = result['body'].scan(/#{@match_regex}/m) if !matches.empty? result['body'] = matches.flatten.first.to_s logger.info("Response body matches pattern '#{@match_regex}'") else result['body'] = '' logger.warn("Response body does not match pattern '#{@match_regex}'") end end # return 502 if matched response body is empty if @fail_no_content if result['body'].to_s.eql?('') result['code'] = 502 result['message'] = 'Bad Gateway' result['status_line'] = "HTTP/#{result['http_version']} #{result['code']} #{result['message']}" return result end end # unescape response body if @unescape # unescape slashes result['body'] = result['body'].tr('\\', '\\') result['body'] = result['body'].gsub('\\/', '/') # unescape whitespace result['body'] = result['body'].gsub('\r', "\r") result['body'] = result['body'].gsub('\n', "\n") result['body'] = result['body'].gsub('\t', "\t") # unescape quotes result['body'] = result['body'].gsub('\"', '"') result['body'] = result['body'].gsub("\\'", "'") end # decode HTML entities if @decode_html result['body'] = HTMLEntities.new.decode(result['body']) end # set title result['title'] = result['body'][0..8192] =~ %r{<title>([^<]*)</title>}im ? $1.to_s : '' # guess HTTP response code and message if @guess_status head = result['body'][0..8192] status = guess_status(head) unless status.empty? result['code'] = status['code'] result['message'] = status['message'] logger.info("Using HTTP response status: #{result['code']} #{result['message']}") end end # replace timeout response with 200 OK if @timeout_ok if result['code'].eql?('504') logger.info('Changed HTTP status code 504 to 200') result['code'] = 200 end end # detect headers in response body if @detect_headers headers = '' head = result['body'][0..8192] # use first 8192 byes detected_headers = head.scan(%r{HTTP/(1\.\d) (\d+) (.*?)\r?\n(.*?)\r?\n\r?\n}m) if detected_headers.empty? logger.info('Found no HTTP response headers in response body.') else # HTTP redirects may contain more than one set of HTTP response headers # Use the last logger.info("Found #{detected_headers.count} sets of HTTP response headers in reponse. Using last.") version = detected_headers.last[0] code = detected_headers.last[1] message = detected_headers.last[2] detected_headers.last[3].split(/\r?\n/).each do |line| if line =~ /^[A-Za-z0-9\-_\.]+: / k = line.split(': ').first v = line.split(': ')[1..-1].flatten.first headers << "#{k}: #{v}\n" else logger.warn('Could not use response headers in response body : Headers are malformed.') headers = '' break end end end unless headers.eql?('') result['http_version'] = version result['code'] = code.to_i result['message'] = message result['headers'] = headers result['body'] = result['body'].split(/\r?\n\r?\n/)[detected_headers.count..-1].flatten.join("\n\n") end end # set status line result['status_line'] = "HTTP/#{result['http_version']} #{result['code']} #{result['message']}" # strip unwanted HTTP response headers unless response.nil? response.each_header do |header_name, header_value| if header_name.downcase.eql?('content-encoding') next if header_value.downcase.eql?('gzip') end if @strip.include?(header_name.downcase) logger.info("Removed response header: #{header_name}") next end result['headers'] << "#{header_name}: #{header_value}\n" end end # add wildcard CORS header if @cors result['headers'] << "Access-Control-Allow-Origin: *\n" end # advise client to close HTTP connection if result['headers'] =~ /^connection:.*$/i result['headers'].gsub!(/^connection:.*$/i, 'Connection: close') else result['headers'] << "Connection: close\n" end # guess mime type and add content-type header content_type = nil if @sniff_mime head = result['body'][0..8192] # use first 8192 byes content_type = sniff_mime(head) if content_type.nil? content_type = guess_mime(File.extname(uri.to_s.split('?').first)) end elsif @guess_mime content_type = guess_mime(File.extname(uri.to_s.split('?').first)) end unless content_type.nil? logger.info("Using content-type: #{content_type}") if result['headers'] =~ /^content\-type:.*$/i result['headers'].gsub!(/^content\-type:.*$/i, "Content-Type: #{content_type}") else result['headers'] << "Content-Type: #{content_type}\n" end end # prompt for password if unauthorised if result['code'] == 401 if result['headers'] !~ /^WWW-Authenticate:.*$/i auth_uri = URI.parse(uri.to_s.split('?').first) realm = "#{auth_uri.host}:#{auth_uri.port}" result['headers'] << "WWW-Authenticate: Basic realm=\"#{realm}\"\n" logger.info("Added WWW-Authenticate header for realm: #{realm}") end end # set location header if redirected if result['code'] == 301 || result['code'] == 302 if result['headers'] !~ /^location:.*$/i location = nil if result['body'] =~ /This document may be found <a href="(.+)">/i location = $1 elsif result['body'] =~ /The document has moved <a href="(.+)">/i location = $1 end unless location.nil? result['headers'] << "Location: #{location}\n" logger.info("Added Location header: #{location}") end end end # set content length content_length = result['body'].length if result['headers'] =~ /^transfer\-encoding:.*$/i result['headers'].gsub!(/^transfer\-encoding:.*$/i, "Content-Length: #{content_length}") elsif result['headers'] =~ /^content\-length:.*$/i result['headers'].gsub!(/^content\-length:.*$/i, "Content-Length: #{content_length}") else result['headers'] << "Content-Length: #{content_length}\n" end # return HTTP response logger.debug("Response:\n" \ "#{result['status_line']}\n" \ "#{result['headers']}\n" \ "#{result['body']}") result end
Fetch a URI via SSRF @param [String] uri URI to fetch @param [String] method HTTP request method @param [Hash] headers HTTP request headers @param [String] body HTTP request body @raise [SSRFProxy::HTTP::Error::InvalidClientRequest] An invalid client HTTP request was supplied. @return [Hash] HTTP response hash (version, code, message, headers, body, etc)
send_uri
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def encode_ip(url, mode) return if url.nil? new_host = nil host = URI.parse(url.to_s.split('?').first).host.to_s begin ip = IPAddress::IPv4.new(host) rescue logger.warn("Could not parse requested host as IPv4 address: #{host}") return url end case mode when 'int' new_host = url.to_s.gsub(host, ip.to_u32.to_s) when 'ipv6' new_host = url.to_s.gsub(host, "[#{ip.to_ipv6}]") when 'oct' new_host = url.to_s.gsub(host, "0#{ip.to_u32.to_s(8)}") when 'hex' new_host = url.to_s.gsub(host, "0x#{ip.to_u32.to_s(16)}") when 'dotted_hex' res = ip.octets.map { |i| "0x#{i.to_s(16).rjust(2, '0')}" }.join('.') new_host = url.to_s.gsub(host, res.to_s) unless res.nil? else logger.warn("Invalid IP encoding: #{mode}") end new_host end
Encode IP address of a given URL @param [String] url target URL @param [String] mode encoding (int, ipv6, oct, hex, dotted_hex) @return [String] encoded IP address
encode_ip
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def run_rules(url, rules) str = url.to_s return str if rules.nil? rules.each do |rule| case rule when 'noproto' str = str.gsub(%r{^https?://}, '') when 'nossl', 'http' str = str.gsub(%r{^https://}, 'http://') when 'ssl', 'https' str = str.gsub(%r{^http://}, 'https://') when 'base32' str = Base32.encode(str).to_s when 'base64' str = Base64.encode64(str).delete("\n") when 'md4' str = OpenSSL::Digest::MD4.hexdigest(str) when 'md5' md5 = Digest::MD5.new md5.update str str = md5.hexdigest when 'sha1' str = Digest::SHA1.hexdigest(str) when 'reverse' str = str.reverse when 'upcase' str = str.upcase when 'downcase' str = str.downcase when 'rot13' str = str.tr('A-Za-z', 'N-ZA-Mn-za-m') when 'urlencode' str = CGI.escape(str).gsub(/\+/, '%20') when 'urldecode' str = CGI.unescape(str) when 'append-hash' str = "#{str}##{rand(36**6).to_s(36)}" when 'append-method-get' separator = str.include?('?') ? '&' : '?' str = "#{str}#{separator}method=get&_method=get" else logger.warn("Unknown rule: #{rule}") end end str end
Run a specified URL through SSRF rules @param [String] url request URL @param [String] rules comma separated list of rules @return [String] modified request URL
run_rules
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def send_http_request(url, method, headers, body) # use upstream proxy if @proxy.nil? http = Net::HTTP::Proxy(nil).new( @url.host, @url.port ) elsif @proxy.scheme.eql?('http') || @proxy.scheme.eql?('https') http = Net::HTTP::Proxy( @proxy.host, @proxy.port ).new( @url.host, @url.port ) elsif @proxy.scheme.eql?('socks') http = Net::HTTP.SOCKSProxy( @proxy.host, @proxy.port ).new( @url.host, @url.port ) else raise SSRFProxy::HTTP::Error::InvalidUpstreamProxy.new, 'Unsupported upstream proxy specified. Scheme must be http(s) or socks.' end # set SSL if @url.scheme.eql?('https') http.use_ssl = true http.verify_mode = @insecure ? OpenSSL::SSL::VERIFY_NONE : OpenSSL::SSL::VERIFY_PEER end # set socket options http.open_timeout = @timeout http.read_timeout = @timeout # set http request method case method when 'GET' request = Net::HTTP::Get.new(url, headers.to_hash) when 'HEAD' request = Net::HTTP::Head.new(url, headers.to_hash) when 'DELETE' request = Net::HTTP::Delete.new(url, headers.to_hash) when 'POST' request = Net::HTTP::Post.new(url, headers.to_hash) when 'PUT' request = Net::HTTP::Put.new(url, headers.to_hash) when 'OPTIONS' request = Net::HTTP::Options.new(url, headers.to_hash) else logger.info("Request method #{method.inspect} not implemented") raise SSRFProxy::HTTP::Error::InvalidClientRequest, "Request method #{method.inspect} not implemented" end # set http request credentials request.basic_auth(@user, @pass) unless @user.eql?('') && @pass.eql?('') # send http request response = {} logger.info('Sending request: ' \ "#{@url.scheme}://#{@url.host}:#{@url.port}#{url}") begin unless body.eql?('') request.body = body logger.info("Using request body: #{request.body.inspect}") end response = http.request(request) rescue Net::HTTPBadResponse, EOFError logger.info('Server returned an invalid HTTP response') raise SSRFProxy::HTTP::Error::InvalidResponse, 'Server returned an invalid HTTP response' rescue Errno::ECONNREFUSED, Errno::ECONNRESET logger.info('Connection failed') raise SSRFProxy::HTTP::Error::ConnectionFailed, 'Connection failed' rescue Timeout::Error, Errno::ETIMEDOUT logger.info("Connection timed out [#{@timeout}]") raise SSRFProxy::HTTP::Error::ConnectionTimeout, "Connection timed out [#{@timeout}]" rescue => e logger.error("Unhandled exception: #{e}") raise e end if response.code.eql?('401') if @user.eql?('') && @pass.eql?('') logger.warn('Authentication required') else logger.warn('Authentication failed') end end response end
Send HTTP request to the SSRF server @param [String] url URI to fetch @param [String] method HTTP request method @param [Hash] headers HTTP request headers @param [String] body HTTP request body @raise [SSRFProxy::HTTP::Error::InvalidSsrfRequestMethod] Invalid SSRF request method specified. Method must be GET/HEAD/DELETE/POST/PUT/OPTIONS. @raise [SSRFProxy::HTTP::Error::ConnectionTimeout] The request to the remote host timed out. @raise [SSRFProxy::HTTP::Error::InvalidUpstreamProxy] Invalid upstream proxy specified. @return [Hash] Hash of the HTTP response (status, code, headers, body)
send_http_request
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def guess_status(response) result = {} # response status code returned by php-simple-proxy and php-json-proxy if response =~ /"status":{"http_code":([\d]+)}/ result['code'] = $1 result['message'] = '' # generic page titles containing HTTP status elsif response =~ />301 Moved</ || response =~ />Document Moved</ || response =~ />Object Moved</ || response =~ />301 Moved Permanently</ result['code'] = 301 result['message'] = 'Document Moved' elsif response =~ />302 Found</ || response =~ />302 Moved Temporarily</ result['code'] = 302 result['message'] = 'Found' elsif response =~ />400 Bad Request</ result['code'] = 400 result['message'] = 'Bad Request' elsif response =~ />401 Unauthorized</ result['code'] = 401 result['message'] = 'Unauthorized' elsif response =~ />403 Forbidden</ result['code'] = 403 result['message'] = 'Forbidden' elsif response =~ />404 Not Found</ result['code'] = 404 result['message'] = 'Not Found' elsif response =~ />The page is not found</ result['code'] = 404 result['message'] = 'Not Found' elsif response =~ />413 Request Entity Too Large</ result['code'] = 413 result['message'] = 'Request Entity Too Large' elsif response =~ />500 Internal Server Error</ result['code'] = 500 result['message'] = 'Internal Server Error' elsif response =~ />503 Service Unavailable</ result['code'] = 503 result['message'] = 'Service Unavailable' # getaddrinfo() errors elsif response =~ /getaddrinfo: / if response =~ /getaddrinfo: nodename nor servname provided/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /getaddrinfo: Name or service not known/ result['code'] = 502 result['message'] = 'Bad Gateway' end # getnameinfo() errors elsif response =~ /getnameinfo failed: / result['code'] = 502 result['message'] = 'Bad Gateway' # PHP 'failed to open stream' errors elsif response =~ /failed to open stream: / # HTTP request failed! HTTP/[version] [code] [message] if response =~ %r{failed to open stream: HTTP request failed! HTTP\/(0\.9|1\.0|1\.1) ([\d]+) } result['code'] = $2.to_s result['message'] = '' if response =~ %r{failed to open stream: HTTP request failed! HTTP/(0\.9|1\.0|1\.1) [\d]+ ([a-zA-Z ]+)} result['message'] = $2.to_s end # No route to host elsif response =~ /failed to open stream: No route to host in/ result['code'] = 502 result['message'] = 'Bad Gateway' # Connection refused elsif response =~ /failed to open stream: Connection refused in/ result['code'] = 502 result['message'] = 'Bad Gateway' # Connection timed out elsif response =~ /failed to open stream: Connection timed out/ result['code'] = 504 result['message'] = 'Timeout' # Success - This likely indicates an SSL/TLS connection failure elsif response =~ /failed to open stream: Success in/ result['code'] = 502 result['message'] = 'Bad Gateway' end # Java 'java.net' exceptions elsif response =~ /java\.net\.[^\s]*Exception: / if response =~ /java\.net\.ConnectException: No route to host/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /java\.net\.ConnectException: Connection refused/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /java\.net\.ConnectException: Connection timed out/ result['code'] = 504 result['message'] = 'Timeout' elsif response =~ /java\.net\.UnknownHostException: Invalid hostname/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /java\.net\.SocketException: Network is unreachable/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /java\.net\.SocketException: Connection reset/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /java\.net\.SocketTimeoutException: Connection timed out/ result['code'] = 504 result['message'] = 'Timeout' end # C errno elsif response =~ /\[Errno -?[\d]{1,5}\]/ if response =~ /\[Errno -2\] Name or service not known/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 101\] Network is unreachable/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 104\] Connection reset by peer/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 110\] Connection timed out/ result['code'] = 504 result['message'] = 'Timeout' elsif response =~ /\[Errno 111\] Connection refused/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 113\] No route to host/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 11004\] getaddrinfo failed/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 10053\] An established connection was aborted/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 10054\] An existing connection was forcibly closed/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 10055\] An operation on a socket could not be performed/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 10060\] A connection attempt failed/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /\[Errno 10061\] No connection could be made/ result['code'] = 502 result['message'] = 'Bad Gateway' end # Python urllib errors elsif response =~ /HTTPError: HTTP Error \d+/ if response =~ /HTTPError: HTTP Error 400: Bad Request/ result['code'] = 400 result['message'] = 'Bad Request' elsif response =~ /HTTPError: HTTP Error 401: Unauthorized/ result['code'] = 401 result['message'] = 'Unauthorized' elsif response =~ /HTTPError: HTTP Error 402: Payment Required/ result['code'] = 402 result['message'] = 'Payment Required' elsif response =~ /HTTPError: HTTP Error 403: Forbidden/ result['code'] = 403 result['message'] = 'Forbidden' elsif response =~ /HTTPError: HTTP Error 404: Not Found/ result['code'] = 404 result['message'] = 'Not Found' elsif response =~ /HTTPError: HTTP Error 405: Method Not Allowed/ result['code'] = 405 result['message'] = 'Method Not Allowed' elsif response =~ /HTTPError: HTTP Error 410: Gone/ result['code'] = 410 result['message'] = 'Gone' elsif response =~ /HTTPError: HTTP Error 500: Internal Server Error/ result['code'] = 500 result['message'] = 'Internal Server Error' elsif response =~ /HTTPError: HTTP Error 502: Bad Gateway/ result['code'] = 502 result['message'] = 'Bad Gateway' elsif response =~ /HTTPError: HTTP Error 503: Service Unavailable/ result['code'] = 503 result['message'] = 'Service Unavailable' elsif response =~ /HTTPError: HTTP Error 504: Gateway Time-?out/ result['code'] = 504 result['message'] = 'Timeout' end # Ruby exceptions elsif response =~ /Errno::[A-Z]+/ # Connection refused if response =~ /Errno::ECONNREFUSED/ result['code'] = 502 result['message'] = 'Bad Gateway' # No route to host elsif response =~ /Errno::EHOSTUNREACH/ result['code'] = 502 result['message'] = 'Bad Gateway' # Connection timed out elsif response =~ /Errno::ETIMEDOUT/ result['code'] = 504 result['message'] = 'Timeout' end # ASP.NET System.Net.WebClient errors elsif response =~ /System\.Net\.WebClient/ # The remote server returned an error: ([code]) [message]. if response =~ /WebException: The remote server returned an error: \(([\d+])\) / result['code'] = $1.to_s result['message'] = '' if response =~ /WebException: The remote server returned an error: \(([\d+])\) ([a-zA-Z ]+)\./ result['message'] = $2.to_s end # Could not resolve hostname elsif response =~ /WebException: The remote name could not be resolved/ result['code'] = 502 result['message'] = 'Bad Gateway' # Remote server denied connection (port closed) elsif response =~ /WebException: Unable to connect to the remote server/ result['code'] = 502 result['message'] = 'Bad Gateway' # This likely indicates a plain-text connection to a HTTPS or non-HTTP service elsif response =~ /WebException: The underlying connection was closed: An unexpected error occurred on a receive/ result['code'] = 502 result['message'] = 'Bad Gateway' # This likely indicates a HTTPS connection to a plain-text HTTP or non-HTTP service elsif response =~ /WebException: The underlying connection was closed: An unexpected error occurred on a send/ result['code'] = 502 result['message'] = 'Bad Gateway' # The operation has timed out elsif response =~ /WebException: The operation has timed out/ result['code'] = 504 result['message'] = 'Timeout' end # Generic error messages elsif response =~ /(Connection refused|No route to host|Connection timed out) - connect\(\d\)/ # Connection refused if response =~ /Connection refused - connect\(\d\)/ result['code'] = 502 result['message'] = 'Bad Gateway' # No route to host elsif response =~ /No route to host - connect\(\d\)/ result['code'] = 502 result['message'] = 'Bad Gateway' # Connection timed out elsif response =~ /Connection timed out - connect\(\d\)/ result['code'] = 504 result['message'] = 'Timeout' end end result end
Guess HTTP response status code and message based on common strings in the response body such as a default title or exception error message @param [String] response HTTP response @return [Hash] includes HTTP response code and message
guess_status
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def guess_mime(ext) content_types = WEBrick::HTTPUtils::DefaultMimeTypes common_content_types = { 'ico' => 'image/x-icon' } content_types.merge!(common_content_types) content_types.each do |k, v| return v.to_s if ext.eql?(".#{k}") end nil end
Guess content type based on file extension @param [String] ext File extension including dots @example Return mime type for extension '.png' guess_mime('favicon.png') @return [String] content-type value
guess_mime
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def sniff_mime(content) m = MimeMagic.by_magic(content) return if m.nil? # Overwrite incorrect mime types case m.type.to_s when 'application/xhtml+xml' return 'text/html' when 'text/x-csrc' return 'text/css' end m.type rescue nil end
Guess content type based on magic bytes @param [String] content File contents @return [String] content-type value
sniff_mime
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/http.rb
MIT
def initialize(ssrf, interface = '127.0.0.1', port = 8081) @banner = 'SSRF Proxy' @server = nil @logger = ::Logger.new(STDOUT).tap do |log| log.progname = 'ssrf-proxy-server' log.level = ::Logger::WARN log.datetime_format = '%Y-%m-%d %H:%M:%S ' end # set ssrf unless ssrf.class == SSRFProxy::HTTP raise SSRFProxy::Server::Error::InvalidSsrf.new, 'Invalid SSRF provided' end @ssrf = ssrf # check if the remote proxy server is responsive unless @ssrf.proxy.nil? if @ssrf.proxy.host == interface && @ssrf.proxy.port == port raise SSRFProxy::Server::Error::ProxyRecursion.new, "Proxy recursion error: #{@ssrf.proxy}" end if port_open?(@ssrf.proxy.host, @ssrf.proxy.port) print_good('Connected to remote proxy ' \ "#{@ssrf.proxy.host}:#{@ssrf.proxy.port} successfully") else raise SSRFProxy::Server::Error::RemoteProxyUnresponsive.new, 'Could not connect to remote proxy ' \ "#{@ssrf.proxy.host}:#{@ssrf.proxy.port}" end end # if no upstream proxy is set, check if the remote server is responsive if @ssrf.proxy.nil? if port_open?(@ssrf.url.host, @ssrf.url.port) print_good('Connected to remote host ' \ "#{@ssrf.url.host}:#{@ssrf.url.port} successfully") else raise SSRFProxy::Server::Error::RemoteHostUnresponsive.new, 'Could not connect to remote host ' \ "#{@ssrf.url.host}:#{@ssrf.url.port}" end end # start server logger.info "Starting HTTP proxy on #{interface}:#{port}" begin print_status "Listening on #{interface}:#{port}" @server = TCPServer.new(interface, port.to_i) rescue Errno::EADDRINUSE raise SSRFProxy::Server::Error::AddressInUse.new, "Could not bind to #{interface}:#{port}" \ ' - address already in use' end end
Start the local server and listen for connections @param [SSRFProxy::HTTP] ssrf A configured SSRFProxy::HTTP object @param [String] interface Listen interface (Default: 127.0.0.1) @param [Integer] port Listen port (Default: 8081) @raise [SSRFProxy::Server::Error::InvalidSsrf] Invalid SSRFProxy::SSRF object provided. @raise [SSRFProxy::Server::Error::ProxyRecursion] Proxy recursion error. SSRF Proxy cannot use itself as an upstream proxy. @raise [SSRFProxy::Server::Error::RemoteProxyUnresponsive] Could not connect to remote proxy. @raise [SSRFProxy::Server::Error::AddressInUse] Could not bind to the port on the specified interface as address already in use. @example Start SSRF Proxy server with the default options ssrf_proxy = SSRFProxy::Server.new( SSRFProxy::HTTP.new('http://example.local/?url=xxURLxx'), '127.0.0.1', 8081) ssrf_proxy.serve
initialize
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/server.rb
MIT
def port_open?(ip, port, seconds = 10) Timeout.timeout(seconds) do TCPSocket.new(ip, port).close true end rescue Errno::ECONNREFUSED, Errno::EHOSTUNREACH, SocketError, Timeout::Error false end
Checks if a port is open or not on a remote host From: https://gist.github.com/ashrithr/5305786 @param [String] ip connect to IP @param [Integer] port connect to port @param [Integer] seconds connection timeout
port_open?
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/server.rb
MIT
def print_status(msg = '') puts '[*] '.blue + msg end
Print status message @param [String] msg message to print
print_status
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/server.rb
MIT
def print_good(msg = '') puts '[+] '.green + msg end
Print progress messages @param [String] msg message to print
print_good
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/server.rb
MIT
def print_error(msg = '') puts '[-] '.red + msg end
Print error message @param [String] msg message to print
print_error
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/server.rb
MIT
def handle_connection(socket) start_time = Time.now _, port, host = socket.peeraddr logger.debug("Client #{host}:#{port} connected") request = socket.read logger.debug("Received client request (#{request.length} bytes):\n" \ "#{request}") response = nil if request.to_s =~ /\ACONNECT ([_a-zA-Z0-9\.\-]+:[\d]+) .*$/ host = $1.to_s logger.info("Negotiating connection to #{host}") response = send_request("GET http://#{host}/ HTTP/1.0\n\n") if response['code'].to_i == 502 || response['code'].to_i == 504 logger.info("Connection to #{host} failed") socket.write("#{response['status_line']}\n" \ "#{response['headers']}\n" \ "#{response['body']}") raise Errno::ECONNRESET end logger.info("Connected to #{host} successfully") socket.write("HTTP/1.0 200 Connection established\r\n\r\n") request = socket.read logger.debug("Received client request (#{request.length} bytes):\n" \ "#{request}") # CHANGE_CIPHER_SPEC 20 0x14 # ALERT 21 0x15 # HANDSHAKE 22 0x16 # APPLICATION_DATA 23 0x17 if request.to_s.start_with?("\x14", "\x15", "\x16", "\x17") logger.warn("Received SSL/TLS client request. SSL/TLS tunneling is not supported. Aborted.") raise Errno::ECONNRESET end end response = send_request(request.to_s) socket.write("#{response['status_line']}\n" \ "#{response['headers']}\n" \ "#{response['body']}") raise Errno::ECONNRESET rescue EOFError, Errno::ECONNRESET, Errno::EPIPE socket.close logger.debug("Client #{host}:#{port} disconnected") end_time = Time.now duration = ((end_time - start_time) * 1000).round(3) if response.nil? logger.info("Served 0 bytes in #{duration} ms") else logger.info("Served #{response['body'].length} bytes in #{duration} ms") end end
Handle client socket connection @param [Celluloid::IO::TCPSocket] socket client socket
handle_connection
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/server.rb
MIT
def send_request(request) response_error = { 'uri' => '', 'duration' => '0', 'http_version' => '1.0', 'headers' => "Server: #{@banner}\n", 'body' => '' } # parse client request begin if request.to_s !~ %r{\A(CONNECT|GET|HEAD|DELETE|POST|PUT|OPTIONS) https?://} if request.to_s !~ /^Host: ([^\s]+)\r?\n/ logger.warn('No host specified') raise SSRFProxy::HTTP::Error::InvalidClientRequest, 'No host specified' end end req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP) req.parse(StringIO.new(request)) rescue => e logger.info('Received malformed client HTTP request.') error_msg = 'Error -- Invalid request: ' \ "Received malformed client HTTP request: #{e.message}" print_error(error_msg) response_error['code'] = '502' response_error['message'] = 'Bad Gateway' response_error['status_line'] = "HTTP/#{response_error['http_version']}" response_error['status_line'] << " #{response_error['code']}" response_error['status_line'] << " #{response_error['message']}" return response_error end uri = req.request_uri # send request response = nil logger.info("Requesting URL: #{uri}") status_msg = "Request -> #{req.request_method}" status_msg << " -> PROXY[#{@ssrf.proxy.host}:#{@ssrf.proxy.port}]" unless @ssrf.proxy.nil? status_msg << " -> SSRF[#{@ssrf.url.host}:#{@ssrf.url.port}] -> URI[#{uri}]" print_status(status_msg) begin response = @ssrf.send_request(request.to_s) rescue SSRFProxy::HTTP::Error::InvalidClientRequest => e logger.info(e.message) error_msg = "Error -- Invalid request: #{e.message}" print_error(error_msg) response_error['code'] = '502' response_error['message'] = 'Bad Gateway' response_error['status_line'] = "HTTP/#{response_error['http_version']}" response_error['status_line'] << " #{response_error['code']}" response_error['status_line'] << " #{response_error['message']}" return response_error rescue SSRFProxy::HTTP::Error::InvalidResponse => e logger.info(e.message) error_msg = 'Response <- 503' error_msg << " <- PROXY[#{@ssrf.proxy.host}:#{@ssrf.proxy.port}]" unless @ssrf.proxy.nil? error_msg << " <- SSRF[#{@ssrf.url.host}:#{@ssrf.url.port}] <- URI[#{uri}]" error_msg << " -- Error: #{e.message}" print_error(error_msg) response_error['code'] = '503' response_error['message'] = 'Service Unavailable' response_error['status_line'] = "HTTP/#{response_error['http_version']}" response_error['status_line'] << " #{response_error['code']}" response_error['status_line'] << " #{response_error['message']}" return response_error rescue SSRFProxy::HTTP::Error::ConnectionFailed => e logger.info(e.message) error_msg = 'Response <- 503' error_msg << " <- PROXY[#{@ssrf.proxy.host}:#{@ssrf.proxy.port}]" unless @ssrf.proxy.nil? error_msg << " <- SSRF[#{@ssrf.url.host}:#{@ssrf.url.port}] <- URI[#{uri}]" error_msg << " -- Error: #{e.message}" print_error(error_msg) response_error['code'] = '503' response_error['message'] = 'Service Unavailable' response_error['status_line'] = "HTTP/#{response_error['http_version']}" response_error['status_line'] << " #{response_error['code']}" response_error['status_line'] << " #{response_error['message']}" return response_error rescue SSRFProxy::HTTP::Error::ConnectionTimeout => e logger.info(e.message) error_msg = 'Response <- 504' error_msg << " <- PROXY[#{@ssrf.proxy.host}:#{@ssrf.proxy.port}]" unless @ssrf.proxy.nil? error_msg << " <- SSRF[#{@ssrf.url.host}:#{@ssrf.url.port}] <- URI[#{uri}]" error_msg << " -- Error: #{e.message}" print_error(error_msg) response_error['code'] = '504' response_error['message'] = 'Timeout' response_error['status_line'] = "HTTP/#{response_error['http_version']}" response_error['status_line'] << " #{response_error['code']}" response_error['status_line'] << " #{response_error['message']}" return response_error rescue => e logger.warn(e.message) error_msg = "Error -- Unexpected error: #{e.backtrace.join("\n")}" print_error(error_msg) response_error['code'] = '502' response_error['message'] = 'Bad Gateway' response_error['status_line'] = "HTTP/#{response_error['http_version']}" response_error['status_line'] << " #{response_error['code']} " response_error['status_line'] << " #{response_error['message']}" return response_error end # return response status_msg = "Response <- #{response['code']}" status_msg << " <- PROXY[#{@ssrf.proxy.host}:#{@ssrf.proxy.port}]" unless @ssrf.proxy.nil? status_msg << " <- SSRF[#{@ssrf.url.host}:#{@ssrf.url.port}] <- URI[#{uri}]" status_msg << " -- Title[#{response['title']}]" unless response['title'].eql?('') status_msg << " -- [#{response['body'].size} bytes]" print_good(status_msg) response end
Send client HTTP request @param [String] request client HTTP request @return [Hash] HTTP response
send_request
ruby
bcoles/ssrf_proxy
lib/ssrf_proxy/server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/lib/ssrf_proxy/server.rb
MIT
def local_port_open?(port) sock = Socket.new(Socket::Constants::AF_INET, Socket::Constants::SOCK_STREAM, 0) sock.bind(Socket.pack_sockaddr_in(port, '127.0.0.1')) sock.close false rescue Errno::EADDRINUSE true end
@note check if a local TCP port is listening
local_port_open?
ruby
bcoles/ssrf_proxy
test/integration_test_helper.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration_test_helper.rb
MIT
def valid_ssrf?(ssrf) assert_equal(SSRFProxy::HTTP, ssrf.class) assert(ssrf.url) assert(ssrf.url.scheme) assert(ssrf.url.host) assert(ssrf.url.port) true end
@note check a SSRFProxy::HTTP object is valid
valid_ssrf?
ruby
bcoles/ssrf_proxy
test/test_helper.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/test_helper.rb
MIT
def valid_http_response?(res) assert(res) assert(res =~ %r{\AHTTP/\d\.\d [\d]+ }) true end
@note check a HTTP response is valid
valid_http_response?
ruby
bcoles/ssrf_proxy
test/test_helper.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/test_helper.rb
MIT
def valid_ssrf_response?(res) assert(res) assert(res['url']) assert(res['duration']) assert_match(/\AHTTP\/\d\.\d [\d]+ /, res['status_line']) assert(res['http_version']) assert(res['code']) assert(res['message']) assert(res['headers']) true end
@note check a HTTP response is valid
valid_ssrf_response?
ruby
bcoles/ssrf_proxy
test/test_helper.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/test_helper.rb
MIT
def run! # # @note start http server # interface = '127.0.0.1' port = '8088' puts 'Starting HTTP server...' Thread.new do begin HTTPServer.new( 'interface' => interface, 'port' => port, 'ssl' => false, 'verbose' => false, 'debug' => false ) rescue => e puts "Error: Could not start test HTTP server: #{e}" exit 1 end end puts "HTTP server listening on #{interface}:#{port} (Press ENTER to exit)..." gets end
@note: start HTTP server if run from command line
run!
ruby
bcoles/ssrf_proxy
test/common/http_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/common/http_server.rb
MIT
def get_url_http(uri) logger.info "Fetching URL: #{uri}" uri = URI.parse(uri) http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == 'https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE # VERIFY_PEER end # set socket options http.open_timeout = @timeout http.read_timeout = @timeout # send http request response = '' begin res = http.request Net::HTTP::Get.new(uri.request_uri) if res.nil? response = 'Could not fetch URL' else headers = [] res.each_header do |header_name, header_value| headers << "#{header_name}: #{header_value}" end logger.info "Received response: HTTP/#{res.http_version} #{res.code} #{res.message}\n#{headers.join("\n")}\n\n#{res.body}" response = res.body end rescue Timeout::Error, Errno::ETIMEDOUT response = 'Timeout fetching URL' rescue => e response = "Unhandled exception: #{e.message}: #{e}" end response end
@note fetch a URL with Ruby Net::HTTP
get_url_http
ruby
bcoles/ssrf_proxy
test/common/http_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/common/http_server.rb
MIT
def get_url_openuri(uri) logger.info "Fetching URL: #{uri}" uri = URI.parse(uri) response = '' open(uri) do |f| f.each_line do |line| response << line end end response rescue => e return "Unhandled exception: #{e.message}: #{e}" end
@note fetch a URL with Ruby OpenURI
get_url_openuri
ruby
bcoles/ssrf_proxy
test/common/http_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/common/http_server.rb
MIT
def curl_proxy(uri, method = 'GET', headers = {}, data = {}) logger.info "Fetching URL: #{uri}" post_data = [] data.each do |k, v| post_data << "#{k}=#{v}" unless k.eql?('url') end body = post_data.join('&').to_s args = [curl_path, '-sk', '--connect-timeout', @timeout.to_s, uri.to_s, '-X', method, '-d', body] headers.each do |header| args << '-H' if header.to_s.downcase.start_with?('content-length:') args << "Content-Length: #{body.length}" else args << header.strip end end IO.popen(args, 'r+').read.to_s rescue => e return "Unhandled exception: #{e.message}: #{e}" end
@note post data to a URL with cURL
curl_proxy
ruby
bcoles/ssrf_proxy
test/common/http_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/common/http_server.rb
MIT
def typhoeus_proxy(uri, headers = {}, data = {}) Typhoeus.post(uri, headers: headers, body: data).body rescue => e return "Unhandled exception: #{e.message}: #{e}" end
@note post data to a URL with Typhoeus
typhoeus_proxy
ruby
bcoles/ssrf_proxy
test/common/http_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/common/http_server.rb
MIT
def setup @server_opts = SERVER_DEFAULT_OPTS.dup @ssrf_opts = SSRF_DEFAULT_OPTS.dup # start Hamms server Thread.new do hamms = IO.popen(['/usr/bin/python', '-m', 'hamms'], 'r+') @pid = hamms.pid if @pid.nil? puts 'Error: Could not start Python Hamms module. Skipping Hamms fuzz tests...' exit end end puts 'Waiting for Hamms server to start...' sleep 1 end
@note (re)set default SSRF and SSRF Proxy options and start Hamms server
setup
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_no_data @ssrf_opts[:url] = 'http://127.0.0.1:5501/?url=xxURLxx' @ssrf_opts[:timeout] = 2 # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(504, res.code.to_i) end
Fuzz test port 5501 - port accepts traffic but never sends back data
test_no_data
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_empty_string_upon_connection @ssrf_opts[:url] = 'http://127.0.0.1:5502/?url=xxURLxx' # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(503, res.code.to_i) end
Fuzz test port 5502 - port sends back an empty string immediately upon connection
test_empty_string_upon_connection
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_empty_string_after_client_data @ssrf_opts[:url] = 'http://127.0.0.1:5503/?url=xxURLxx' # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(503, res.code.to_i) end
Fuzz test port 5503 - port sends back an empty string after the client sends data
test_empty_string_after_client_data
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_malformed_response_upon_connection @ssrf_opts[:url] = 'http://127.0.0.1:5504/?url=xxURLxx' # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(503, res.code.to_i) end
Fuzz test port 5504 - port sends back a malformed response ("foo bar") immediately upon connection
test_malformed_response_upon_connection
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_malformed_response_after_client_data @ssrf_opts[:url] = 'http://127.0.0.1:5505/?url=xxURLxx' # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(503, res.code.to_i) end
Fuzz test port 5505 - port sends back a malformed response ("foo bar") after the client sends data
test_malformed_response_after_client_data
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_one_byte_every_5_seconds @ssrf_opts[:url] = 'http://127.0.0.1:5506/?url=xxURLxx' @ssrf_opts[:timeout] = 2 # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(504, res.code.to_i) end
Fuzz test port 5506 - sends back one byte every 5 seconds
test_one_byte_every_5_seconds
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_one_byte_every_30_seconds @ssrf_opts[:url] = 'http://127.0.0.1:5507/?url=xxURLxx' @ssrf_opts[:timeout] = 2 # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(504, res.code.to_i) end
Fuzz test port 5507 - sends back one byte every 30 seconds
test_one_byte_every_30_seconds
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_sleep @ssrf_opts[:url] = 'http://127.0.0.1:5508/?url=xxURLxx&sleep=5' @ssrf_opts[:timeout] = 2 # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(504, res.code.to_i) end
Fuzz test port 5508 - sleeps for the specified time
test_sleep
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_content_length_too_short @ssrf_opts[:url] = 'http://127.0.0.1:5510/?url=xxURLxx' @ssrf_opts[:timeout] = 2 # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(200, res.code.to_i) end
Fuzz test port 5510 - port sends 1MB response with header 'Content-Length: 3'
test_content_length_too_short
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_close_part_way_through @ssrf_opts[:url] = 'http://127.0.0.1:5516/?url=xxURLxx' @ssrf_opts[:timeout] = 2 # Start SSRF Proxy server with dummy SSRF start_server(@ssrf_opts, @server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(200, res.code.to_i) end
Fuzz port 5516 - server closes the connection partway through
test_close_part_way_through
ruby
bcoles/ssrf_proxy
test/fuzz/hamms.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/fuzz/hamms.rb
MIT
def test_upstream_proxy opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8088/net_http?url=xxURLxx' opts[:proxy] = 'http://127.0.0.1:8008/' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) res = ssrf.send_uri('http://127.0.0.1:8088/') assert valid_ssrf_response?(res) assert_includes(res['body'], '<title>public</title>') end
@note test upstream HTTP proxy server
test_upstream_proxy
ruby
bcoles/ssrf_proxy
test/integration/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/test_http.rb
MIT
def setup @url = 'http://127.0.0.1:8088/curl?url=xxURLxx' end
@note (re)set default SSRF and SSRF Proxy options
setup
ruby
bcoles/ssrf_proxy
test/integration/test_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/test_server.rb
MIT
def test_server_address_in_use server_opts = SERVER_DEFAULT_OPTS.dup ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = @url ssrf = SSRFProxy::HTTP.new(ssrf_opts) assert_raises SSRFProxy::Server::Error::AddressInUse do SSRFProxy::Server.new(ssrf, server_opts['interface'], 8088) end end
@note test server address in use
test_server_address_in_use
ruby
bcoles/ssrf_proxy
test/integration/test_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/test_server.rb
MIT
def test_server_upstream_proxy_unresponsive server_opts = SERVER_DEFAULT_OPTS.dup ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = @url ssrf_opts[:proxy] = "http://#{server_opts['interface']}:99999" ssrf = SSRFProxy::HTTP.new(ssrf_opts) ssrf.logger.level = ::Logger::WARN assert_raises SSRFProxy::Server::Error::RemoteProxyUnresponsive do SSRFProxy::Server.new(ssrf, server_opts['interface'], server_opts['port']) end end
@note test server upstream proxy unresponsive
test_server_upstream_proxy_unresponsive
ruby
bcoles/ssrf_proxy
test/integration/test_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/test_server.rb
MIT
def test_server_host_unresponsive server_opts = SERVER_DEFAULT_OPTS.dup ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:99999/curl?url=xxURLxx' ssrf = SSRFProxy::HTTP.new(ssrf_opts) ssrf.logger.level = ::Logger::WARN assert_raises SSRFProxy::Server::Error::RemoteHostUnresponsive do SSRFProxy::Server.new(ssrf, server_opts['interface'], server_opts['port']) end end
@note test server remote host unresponsive
test_server_host_unresponsive
ruby
bcoles/ssrf_proxy
test/integration/test_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/test_server.rb
MIT
def test_upstream_proxy server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = @url ssrf_opts[:proxy] = 'http://127.0.0.1:8008/' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:strip] = 'server,date' ssrf_opts[:guess_mime] = true ssrf_opts[:guess_status] = true ssrf_opts[:forward_cookies] = true ssrf_opts[:body_to_uri] = true ssrf_opts[:auth_to_uri] = true ssrf_opts[:cookies_to_uri] = true ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_includes(res.body, '<title>public</title>') end
@note test upstream HTTP proxy server
test_upstream_proxy
ruby
bcoles/ssrf_proxy
test/integration/test_server.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/test_server.rb
MIT
def test_send_request_php_readfile # http get opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php?url=xxURLxx' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) res = ssrf.send_request("GET / HTTP/1.1\nHost: 127.0.0.1:8088\n\n") assert valid_ssrf_response?(res) assert_equal('public', res['title']) res = ssrf.send_request("GET /admin HTTP/1.1\nHost: 127.0.0.1:8088\n\n") assert valid_ssrf_response?(res) assert_equal('administration', res['title']) # http head opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php?url=xxURLxx' opts[:method] = 'HEAD' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) res = ssrf.send_request("GET / HTTP/1.1\nHost: 127.0.0.1:8088\n\n") assert valid_ssrf_response?(res) # post opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php' opts[:method] = 'POST' opts[:post_data] = 'url=xxURLxx' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) res = ssrf.send_request("GET / HTTP/1.1\nHost: 127.0.0.1:8088\n\n") assert valid_ssrf_response?(res) assert_equal('public', res['title']) # match opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php?url=xxURLxx' opts[:match] = '<body>\n(.+)</body>' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) res = ssrf.send_request("GET / HTTP/1.1\nHost: 127.0.0.1:8088\n\n") assert valid_ssrf_response?(res) assert(res['body'].start_with?('<html>')) refute_includes(res['body'], 'Response:') refute_includes(res['body'], '<textarea>') # guess mime opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php?url=xxURLxx' opts[:guess_mime] = true ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) res = ssrf.send_request("GET /#{('a'..'z').to_a.sample(8).join}.ico HTTP/1.1\nHost: 127.0.0.1:8088\n\n") assert valid_ssrf_response?(res) assert(res['headers'] =~ /^Content-Type: image\/x\-icon$/i) # guess status opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php?url=xxURLxx' opts[:guess_status] = true ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) # body to URI opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php?url=xxURLxx' opts[:body_to_uri] = true ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) junk1 = ('a'..'z').to_a.sample(8).join.to_s junk2 = ('a'..'z').to_a.sample(8).join.to_s data = "data1=#{junk1}&data2=#{junk2}" req = "POST /submit HTTP/1.1\n" req << "Host: 127.0.0.1:8088\n" req << "Content-Length: #{data.length}\n" req << "\n" req << data.to_s res = ssrf.send_request(req) assert valid_ssrf_response?(res) assert_includes(res['body'], "data1: #{junk1}") assert_includes(res['body'], "data2: #{junk2}") req = "POST /submit?query HTTP/1.1\n" req << "Host: 127.0.0.1:8088\n" req << "Content-Length: #{data.length}\n" req << "\n" req << data.to_s res = ssrf.send_request(req) assert valid_ssrf_response?(res) assert_includes(res['body'], "data1: #{junk1}") assert_includes(res['body'], "data2: #{junk2}") # cookies to URI opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php?url=xxURLxx' opts[:cookies_to_uri] = true ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) cookie_name = ('a'..'z').to_a.sample(8).join.to_s cookie_value = ('a'..'z').to_a.sample(8).join.to_s req = "GET /submit HTTP/1.1\n" req << "Host: 127.0.0.1:8088\n" req << "Cookie: #{cookie_name}=#{cookie_value}\n" req << "\n" res = ssrf.send_request(req) assert valid_ssrf_response?(res) assert_includes(res['body'], "#{cookie_name}: #{cookie_value}") req = "GET /submit?query HTTP/1.1\n" req << "Host: 127.0.0.1:8088\n" req << "Cookie: #{cookie_name}=#{cookie_value}\n" req << "\n" res = ssrf.send_request(req) assert valid_ssrf_response?(res) assert_includes(res['body'], "#{cookie_name}: #{cookie_value}") # auth to URI opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php?url=xxURLxx' opts[:auth_to_uri] = true ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) req = "GET /auth HTTP/1.1\n" req << "Host: 127.0.0.1:8088\n" req << "Authorization: Basic #{Base64.encode64('admin user:test password!@#$%^&*()_+-={}|\:";\'<>?,./').delete("\n")}\n" req << "\n" res = ssrf.send_request(req) assert valid_ssrf_response?(res) assert_equal('authentication successful', res['title']) # ip encoding %w[int oct hex dotted_hex].each do |encoding| opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1:8087/readfile.php?url=xxURLxx' opts[:ip_encoding] = encoding ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) res = ssrf.send_request("GET / HTTP/1.1\nHost: 127.0.0.1:8088\n\n") assert valid_ssrf_response?(res) assert_equal('public', res['title']) end end
@note test send_request with PHP readfile SSRF
test_send_request_php_readfile
ruby
bcoles/ssrf_proxy
test/integration/http/test_php_readfile_ssrf.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/http/test_php_readfile_ssrf.rb
MIT
def test_forwarding_curl_client # Configure path to curl skip 'Could not find curl executable. Skipping curl tests...' unless curl_path server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl_proxy' ssrf_opts[:method] = 'GET' ssrf_opts[:post_data] = 'url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:strip] = 'server,date' ssrf_opts[:guess_mime] = true ssrf_opts[:guess_status] = true ssrf_opts[:forward_method] = true ssrf_opts[:forward_headers] = true ssrf_opts[:forward_body] = true ssrf_opts[:forward_cookies] = true ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) # junk request data junk1 = ('a'..'z').to_a.sample(8).join.to_s junk2 = ('a'..'z').to_a.sample(8).join.to_s junk3 = ('a'..'z').to_a.sample(8).join.to_s junk4 = ('a'..'z').to_a.sample(8).join.to_s # check if method and post data are forwarded cmd = [curl_path, '-isk', '-X', 'POST', '-d', "data1=#{junk1}&data2=#{junk2}", '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/submit'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert_equal(junk1, res.scan(%r{<p>data1: (#{junk1})</p>}).flatten.first) assert_equal(junk2, res.scan(%r{<p>data2: (#{junk2})</p>}).flatten.first) # check if method and headers (including cookies) are forwarded cmd = [curl_path, '-isk', '-X', 'POST', '-d', '', '-H', "header1: #{junk1}", '-H', "header2: #{junk2}", '--cookie', "junk3=#{junk3}; junk4=#{junk4}", '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/headers'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{<p>Header1: #{junk1}</p>}) assert(res =~ %r{<p>Header2: #{junk2}</p>}) assert(res =~ /junk3=#{junk3}/) assert(res =~ /junk4=#{junk4}/) # test forwarding method and headers with compression headers cmd = [curl_path, '-isk', '-X', 'POST', '-d', '', '--compressed', '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert_includes(res, '<title>public</title>') end
@note test forwarding headers, method, body and cookies with cURL requests
test_forwarding_curl_client
ruby
bcoles/ssrf_proxy
test/integration/server/test_curl_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_curl_client.rb
MIT
def test_server_https_curl_client server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl?url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:rules] = 'ssl' ssrf_opts[:insecure] = true ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) # get request method cmd = [curl_path, '-isk', '-X', 'GET', '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8089/'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert_includes(res, '<title>public</title>') end
@note test server with https request using 'ssl' rule
test_server_https_curl_client
ruby
bcoles/ssrf_proxy
test/integration/server/test_curl_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_curl_client.rb
MIT
def test_server_curl_client skip 'Could not find curl executable. Skipping curl tests...' unless curl_path server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl?url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:strip] = 'server,date' ssrf_opts[:guess_mime] = true ssrf_opts[:guess_status] = true ssrf_opts[:forward_cookies] = true ssrf_opts[:body_to_uri] = true ssrf_opts[:auth_to_uri] = true ssrf_opts[:cookies_to_uri] = true ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) # invalid request cmd = [curl_path, '-isk', '-X', 'GET', '--proxy', '127.0.0.1:8081', "http://127.0.0.1:8088/#{'A' * 5000}"] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{\AHTTP/1\.0 502 Bad Gateway}) # get request method cmd = [curl_path, '-isk', '-X', 'GET', '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert_includes(res, '<title>public</title>') # strip headers assert(res !~ /^Server: /) assert(res !~ /^Date: /) # post request method cmd = [curl_path, '-isk', '-X', 'POST', '-d', '', '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert_includes(res, '<title>public</title>') # invalid request method cmd = [curl_path, '-isk', '-X', ('a'..'z').to_a.sample(8).join.to_s, '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{\AHTTP/1\.0 502 Bad Gateway}) # body to URI junk1 = ('a'..'z').to_a.sample(8).join.to_s junk2 = ('a'..'z').to_a.sample(8).join.to_s data = "data1=#{junk1}&data2=#{junk2}" cmd = [curl_path, '-isk', '-X', 'POST', '-d', data.to_s, '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/submit'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert_equal(junk1, res.scan(%r{<p>data1: (#{junk1})</p>}).flatten.first) assert_equal(junk2, res.scan(%r{<p>data2: (#{junk2})</p>}).flatten.first) cmd = [curl_path, '-isk', '-X', 'POST', '-d', data.to_s, '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/submit?query'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert_equal(junk1, res.scan(%r{<p>data1: (#{junk1})</p>}).flatten.first) assert_equal(junk2, res.scan(%r{<p>data2: (#{junk2})</p>}).flatten.first) # auth to URI cmd = [curl_path, '-isk', '--proxy', '127.0.0.1:8081', '-u', 'admin user:test password!@#$%^&*()_+-={}|\:";\'<>?,./', 'http://127.0.0.1:8088/auth'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{<title>authentication successful</title>}) cmd = [curl_path, '-isk', '--proxy', '127.0.0.1:8081', '-u', (1..255).to_a.shuffle.pack('C*'), 'http://127.0.0.1:8088/auth'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{<title>401 Unauthorized</title>}) # cookies to URI cookie_name = ('a'..'z').to_a.sample(8).join.to_s cookie_value = ('a'..'z').to_a.sample(8).join.to_s cmd = [curl_path, '-isk', '--cookie', "#{cookie_name}=#{cookie_value}", '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/submit'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{<p>#{cookie_name}: #{cookie_value}</p>}) cmd = [curl_path, '-isk', '--cookie', "#{cookie_name}=#{cookie_value}", '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/submit?query'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{<p>#{cookie_name}: #{cookie_value}</p>}) # ask password cmd = [curl_path, '-isk', '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/auth'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ /^WWW-Authenticate: Basic realm="127\.0\.0\.1:8088"$/i) # detect redirect cmd = [curl_path, '-isk', '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/redirect'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{^Location: /admin$}i) # guess mime cmd = [curl_path, '-isk', '--proxy', '127.0.0.1:8081', "http://127.0.0.1:8088/#{('a'..'z').to_a.sample(8).join}.ico"] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{^Content-Type: image\/x\-icon$}i) # guess status cmd = [curl_path, '-isk', '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/auth'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{\AHTTP/\d\.\d 401 Unauthorized}) # WebSocket request cmd = [curl_path, '-isk', '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/auth', '-H', 'Upgrade: WebSocket'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{\AHTTP/1\.0 502 Bad Gateway}) # CONNECT tunnel cmd = [curl_path, '-isk', '-X', 'GET', '--proxytunnel', '--proxy', '127.0.0.1:8081', 'http://127.0.0.1:8088/'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert_includes(res, '<title>public</title>') # CONNECT tunnel host unreachable cmd = [curl_path, '-isk', '-X', 'GET', '--proxytunnel', '--proxy', '127.0.0.1:8081', 'http://10.99.88.77/'] res = IO.popen(cmd, 'r+').read.to_s assert valid_http_response?(res) assert(res =~ %r{\AHTTP/1\.0 504 Timeout}) end
@note test server with curl requests
test_server_curl_client
ruby
bcoles/ssrf_proxy
test/integration/server/test_curl_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_curl_client.rb
MIT
def test_server_proxychains_curl skip 'Could not find curl executable. Skipping proxychains tests...' unless curl_path skip 'Could not find proxychains executable. Skipping proxychains tests...' unless proxychains_path server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl?url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:strip] = 'server,date' ssrf_opts[:guess_mime] = true ssrf_opts[:guess_status] = true ssrf_opts[:forward_cookies] = true ssrf_opts[:body_to_uri] = true ssrf_opts[:auth_to_uri] = true ssrf_opts[:cookies_to_uri] = true ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) # change to ./test/common to load proxychains.conf Dir.chdir("#{$root_dir}/test/common/") do # invalid request cmd = [proxychains_path, curl_path, '-isk', '-X', 'GET', "http://127.0.0.1:8088/#{'A' * 5000}"] res = IO.popen(cmd, 'r+').read.to_s assert(res =~ %r{^HTTP/1\.0 502 Bad Gateway}) # get request method cmd = [proxychains_path, curl_path, '-isk', '-X', 'GET', 'http://127.0.0.1:8088/'] res = IO.popen(cmd, 'r+').read.to_s assert_includes(res, '<title>public</title>') # strip headers assert(res !~ /^Server: /) assert(res !~ /^Date: /) # post request method cmd = [proxychains_path, curl_path, '-isk', '-X', 'POST', '-d', '', 'http://127.0.0.1:8088/'] res = IO.popen(cmd, 'r+').read.to_s assert_includes(res, '<title>public</title>') end end
@note test server with curl requests via proxychains
test_server_proxychains_curl
ruby
bcoles/ssrf_proxy
test/integration/server/test_curl_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_curl_client.rb
MIT
def test_forwarding_net_http_client server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl_proxy' ssrf_opts[:method] = 'GET' ssrf_opts[:post_data] = 'url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:strip] = 'server,date' ssrf_opts[:guess_mime] = true ssrf_opts[:guess_status] = true ssrf_opts[:forward_method] = true ssrf_opts[:forward_headers] = true ssrf_opts[:forward_body] = true ssrf_opts[:forward_cookies] = true ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 # junk request data junk1 = ('a'..'z').to_a.sample(8).join.to_s junk2 = ('a'..'z').to_a.sample(8).join.to_s junk3 = ('a'..'z').to_a.sample(8).join.to_s junk4 = ('a'..'z').to_a.sample(8).join.to_s # check if method and post data are forwarded req = Net::HTTP::Post.new('/submit') req.set_form_data('data1' => junk1, 'data2' => junk2) res = http.request req assert(res) assert_includes(res.body, "<p>data1: #{junk1}</p>") assert_includes(res.body, "<p>data2: #{junk2}</p>") # check if method and headers (including cookies) are forwarded headers = { 'header1' => junk1, 'header2' => junk2, 'cookie' => "junk3=#{junk3}; junk4=#{junk4}" } req = Net::HTTP::Post.new('/headers', headers.to_hash) req.set_form_data({}) res = http.request req assert(res) assert_includes(res.body, "<p>Header1: #{junk1}</p>") assert_includes(res.body, "<p>Header2: #{junk2}</p>") assert_includes(res.body, "junk3=#{junk3}") assert_includes(res.body, "junk4=#{junk4}") # test forwarding method and headers with compression headers headers = { 'accept-encoding' => 'deflate, gzip' } req = Net::HTTP::Post.new('/', headers.to_hash) req.set_form_data({}) res = http.request req assert(res) assert_includes(res.body, '<title>public</title>') end
@note test forwarding headers, method, body and cookies with Net::HTTP requests
test_forwarding_net_http_client
ruby
bcoles/ssrf_proxy
test/integration/server/test_net_http_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_net_http_client.rb
MIT
def test_server_https_net_http_client server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl?url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:rules] = 'ssl' ssrf_opts[:insecure] = true ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8089') http.open_timeout = 10 http.read_timeout = 10 # get request method res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_includes(res.body, '<title>public</title>') end
@note test server with https request using 'ssl' rule
test_server_https_net_http_client
ruby
bcoles/ssrf_proxy
test/integration/server/test_net_http_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_net_http_client.rb
MIT
def test_server_net_http_client server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl?url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:strip] = 'server,date' ssrf_opts[:guess_mime] = true ssrf_opts[:guess_status] = true ssrf_opts[:forward_cookies] = true ssrf_opts[:body_to_uri] = true ssrf_opts[:auth_to_uri] = true ssrf_opts[:cookies_to_uri] = true ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 # get request method res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_includes(res.body, '<title>public</title>') # strip headers assert(res['Server'].nil?) assert(res['Date'].nil?) # post request method headers = {} req = Net::HTTP::Post.new('/', headers.to_hash) req.set_form_data({}) res = http.request req assert(res) assert_includes(res.body, '<title>public</title>') # body to URI junk1 = ('a'..'z').to_a.sample(8).join.to_s junk2 = ('a'..'z').to_a.sample(8).join.to_s url = '/submit' headers = {} req = Net::HTTP::Post.new(url, headers.to_hash) req.set_form_data('data1' => junk1, 'data2' => junk2) res = http.request req assert(res) assert_equal(junk1, res.body.scan(%r{<p>data1: (#{junk1})</p>}).flatten.first) assert_equal(junk2, res.body.scan(%r{<p>data2: (#{junk2})</p>}).flatten.first) url = '/submit?query' headers = {} req = Net::HTTP::Post.new(url, headers.to_hash) req.set_form_data('data1' => junk1, 'data2' => junk2) res = http.request req assert(res) assert_equal(junk1, res.body.scan(%r{<p>data1: (#{junk1})</p>}).flatten.first) assert_equal(junk2, res.body.scan(%r{<p>data2: (#{junk2})</p>}).flatten.first) # auth to URI url = '/auth' headers = {} req = Net::HTTP::Get.new(url, headers.to_hash) req.basic_auth('admin user', 'test password!@#$%^&*()_+-={}|\:";\'<>?,./') res = http.request req assert(res) assert(res.body =~ %r{<title>authentication successful</title>}) # cookies to URI cookie_name = ('a'..'z').to_a.sample(8).join.to_s cookie_value = ('a'..'z').to_a.sample(8).join.to_s url = '/submit' headers = {} headers['Cookie'] = "#{cookie_name}=#{cookie_value}" res = http.request Net::HTTP::Get.new(url, headers.to_hash) assert(res) assert(res.body =~ %r{<p>#{cookie_name}: #{cookie_value}</p>}) url = '/submit?query' headers = {} headers['Cookie'] = "#{cookie_name}=#{cookie_value}" res = http.request Net::HTTP::Get.new(url, headers.to_hash) assert(res) assert(res.body =~ %r{<p>#{cookie_name}: #{cookie_value}</p>}) # ask password url = '/auth' res = http.request Net::HTTP::Get.new(url, {}) assert(res) assert_equal('Basic realm="127.0.0.1:8088"', res['WWW-Authenticate']) # detect redirect url = '/redirect' res = http.request Net::HTTP::Get.new(url, {}) assert(res) assert_equal('/admin', res['Location']) # guess mime url = "/#{('a'..'z').to_a.sample(8).join}.ico" res = http.request Net::HTTP::Get.new(url, {}) assert(res) assert_equal('image/x-icon', res['Content-Type']) # guess status url = '/auth' res = http.request Net::HTTP::Get.new(url, {}) assert(res) assert_equal(401, res.code.to_i) # CONNECT tunnel http = Net::HTTP::Proxy('127.0.0.1', '8081').new('127.0.0.1', '8088') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert(res.body =~ %r{<title>public</title>}) # CONNECT tunnel host unreachable http = Net::HTTP::Proxy('127.0.0.1', '8081').new('10.99.88.77', '80') http.open_timeout = 10 http.read_timeout = 10 res = http.request Net::HTTP::Get.new('/', {}) assert(res) assert_equal(504, res.code.to_i) end
@note test server with Net::HTTP requests
test_server_net_http_client
ruby
bcoles/ssrf_proxy
test/integration/server/test_net_http_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_net_http_client.rb
MIT
def test_server_proxychains_nmap skip 'Could not find nmap executable. Skipping proxychains tests...' unless nmap_path skip 'Could not find proxychains executable. Skipping proxychains tests...' unless proxychains_path server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl?url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:guess_mime] = true ssrf_opts[:guess_status] = true ssrf_opts[:forward_cookies] = true ssrf_opts[:body_to_uri] = true ssrf_opts[:auth_to_uri] = true ssrf_opts[:cookies_to_uri] = true ssrf_opts[:fail_no_content] = true ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) # change to ./test/common to load proxychains.conf Dir.chdir("#{$root_dir}/test/common/") do cmd = [proxychains_path, nmap_path, '127.0.0.1', '-p', '1,8088'] res = IO.popen(cmd, 'r+').read.to_s puts '-' * 80 puts res puts '-' * 80 assert(res =~ %r{8088/tcp\s*open}) assert(res =~ %r{1/tcp\s*closed}) end end
@note test server with nmap requests via proxychains
test_server_proxychains_nmap
ruby
bcoles/ssrf_proxy
test/integration/server/test_nmap_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_nmap_client.rb
MIT
def test_server_tcpsocket_client server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl?url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:timeout] = 2 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) # valid HTTP/1.0 request client = TCPSocket.new(server_opts['interface'], server_opts['port']) client.write("GET http://127.0.0.1:8088/ HTTP/1.0\n\n") res = client.readpartial(1024) client.close assert valid_http_response?(res) assert_includes(res, '<title>public</title>') # valid HTTP/1.1 request client = TCPSocket.new(server_opts['interface'], server_opts['port']) client.write("GET / HTTP/1.1\nHost: 127.0.0.1:8088\n\n") res = client.readpartial(1024) client.close assert valid_http_response?(res) assert_includes(res, '<title>public</title>') # invalid HTTP/1.0 request client = TCPSocket.new(server_opts['interface'], server_opts['port']) client.write("GET / HTTP/1.0\n\n") res = client.readpartial(1024) client.close assert valid_http_response?(res) assert(res =~ %r{\AHTTP/1\.0 502 Bad Gateway}) # invalid HTTP/1.1 request client = TCPSocket.new(server_opts['interface'], server_opts['port']) client.write("GET / HTTP/1.1\n\n") res = client.readpartial(1024) client.close assert valid_http_response?(res) assert(res =~ %r{\AHTTP/1\.0 502 Bad Gateway}) # CONNECT tunnel client = TCPSocket.new(server_opts['interface'], server_opts['port']) client.write("CONNECT 127.0.0.1:8088 HTTP/1.0\n\n") res = client.readpartial(1024) assert valid_http_response?(res) assert(res =~ %r{\AHTTP/1\.0 200 Connection established\r\n\r\n\z}) client.write("GET / HTTP/1.1\nHost: 127.0.0.1:8088\n\n") res = client.readpartial(1024) assert valid_http_response?(res) client.close assert_includes(res, '<title>public</title>') # CONNECT tunnel host unreachable client = TCPSocket.new(server_opts['interface'], server_opts['port']) client.write("CONNECT 10.99.88.77:80 HTTP/1.0\n\n") res = client.readpartial(1024) assert valid_http_response?(res) client.close assert(res =~ %r{\AHTTP/1\.0 504 Timeout}) end
@note test server with raw TCP socket
test_server_tcpsocket_client
ruby
bcoles/ssrf_proxy
test/integration/server/test_tcpsocket_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_tcpsocket_client.rb
MIT
def test_forwarding_tcpsocket_client server_opts = SERVER_DEFAULT_OPTS.dup # Configure SSRF options ssrf_opts = SSRF_DEFAULT_OPTS.dup ssrf_opts[:url] = 'http://127.0.0.1:8088/curl_proxy' ssrf_opts[:method] = 'GET' ssrf_opts[:post_data] = 'url=xxURLxx' ssrf_opts[:match] = '<textarea>(.*)</textarea>\z' ssrf_opts[:strip] = 'server,date' ssrf_opts[:guess_mime] = true ssrf_opts[:guess_status] = true ssrf_opts[:forward_method] = true ssrf_opts[:forward_headers] = true ssrf_opts[:forward_body] = true ssrf_opts[:forward_cookies] = true ssrf_opts[:timeout] = 5 # Start SSRF Proxy server and open connection start_server(ssrf_opts, server_opts) # long request body client = TCPSocket.new(server_opts['interface'], server_opts['port']) junk = 'A' * 10_000 body = "data=#{junk}" client.write("POST /submit HTTP/1.1\nHost: 127.0.0.1:8088\nContent-Length: #{body.length}\n\n#{body}") res = client.read client.close assert valid_http_response?(res) assert_includes(res, "<p>data: #{junk}</p>") # test forwarding method and headers with compression headers client = TCPSocket.new(server_opts['interface'], server_opts['port']) client.write("POST / HTTP/1.1\nHost: 127.0.0.1:8088\nContent-Length: 0\nAccept-Encoding: deflate, gzip\n\n") res = client.read client.close assert(res) assert_includes(res, '<title>public</title>') end
@note test forwarding headers, method, body and cookies with TCP socket
test_forwarding_tcpsocket_client
ruby
bcoles/ssrf_proxy
test/integration/server/test_tcpsocket_client.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/integration/server/test_tcpsocket_client.rb
MIT
def test_arg_required assert_raises ArgumentError do opts = SSRF_DEFAULT_OPTS.dup SSRFProxy::HTTP.new(opts) end end
@note test required arguments 'url' or 'file' are provided
test_arg_required
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_arg_mutual_exclusivity assert_raises ArgumentError do opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/xxURLxx' opts[:file] = ('a'..'z').to_a.sample(8).join.to_s SSRFProxy::HTTP.new(opts) end end
@note test 'url' and 'file' option mutual exclusivity
test_arg_mutual_exclusivity
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_file_stringio opts = SSRF_DEFAULT_OPTS.dup http = <<-EOS GET /curl?url=xxURLxx&xxJUNKxx HTTP/1.1 Host: 127.0.0.1:8088 Cookie: xxJUNKxx=xxJUNKxx; xxJUNKxx=xxJUNKxx User-Agent: xxJUNKxx xxJUNKxx: xxJUNKxx EOS junk = ('a'..'z').to_a.sample(8).join.to_s http.gsub!('xxJUNKxx', junk) opts[:file] = StringIO.new(http) ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) assert_equal('http', ssrf.url.scheme) assert_equal('127.0.0.1', ssrf.url.host) assert_equal(8088, ssrf.url.port) assert_equal(junk, ssrf.headers['user-agent']) assert_equal("#{junk}=#{junk}; #{junk}=#{junk}", ssrf.headers['cookie']) assert_equal(junk, ssrf.headers[junk.downcase]) end
@note test creating SSRFProxy::HTTP object with file StringIO
test_file_stringio
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_file_path opts = SSRF_DEFAULT_OPTS.dup opts[:file] = "#{$root_dir}/test/common/http.request" ssrf = SSRFProxy::HTTP.new(opts) junk = 'xxJUNKxx' assert valid_ssrf?(ssrf) assert_equal('http://127.0.0.1:8088/curl?url=xxURLxx&xxJUNKxx', ssrf.url.to_s) assert_equal('http', ssrf.url.scheme) assert_equal('127.0.0.1', ssrf.url.host) assert_equal(8088, ssrf.url.port) assert_equal(junk, ssrf.headers['user-agent']) assert_equal("#{junk}=#{junk}; #{junk}=#{junk}", ssrf.headers['cookie']) assert_equal(junk, ssrf.headers[junk.downcase]) end
@note test creating SSRFProxy::HTTP object with file path string
test_file_path
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_file_does_not_exist opts = SSRF_DEFAULT_OPTS.dup opts[:file] = 'doesnotexist' assert_raises SSRFProxy::HTTP::Error::InvalidSsrfRequest do SSRFProxy::HTTP.new(opts) end end
@note test creating SSRFProxy::HTTP object with file with invalid HTTP request
test_file_does_not_exist
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_url_method_get opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/xxURLxx' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/xxURLxx' opts[:post_data] = 'xxURLxx' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) end
@note test creating SSRFProxy::HTTP objects with GET method
test_url_method_get
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_url_method_head opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/xxURLxx' opts[:method] = 'HEAD' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/' opts[:method] = 'HEAD' opts[:post_data] = 'xxURLxx' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) end
@note test creating SSRFProxy::HTTP objects with HEAD method
test_url_method_head
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_url_method_delete opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/xxURLxx' opts[:method] = 'DELETE' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/' opts[:method] = 'DELETE' opts[:post_data] = 'xxURLxx' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) end
@note test creating SSRFProxy::HTTP objects with DELETE method
test_url_method_delete
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_url_method_post opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/xxURLxx' opts[:method] = 'POST' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) opts[:url] = 'http://127.0.0.1/' opts[:method] = 'POST' opts[:post_data] = 'xxURLxx' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) end
@note test creating SSRFProxy::HTTP objects with POST method
test_url_method_post
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_url_method_put opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/xxURLxx' opts[:method] = 'PUT' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/' opts[:method] = 'PUT' opts[:post_data] = 'xxURLxx' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) end
@note test creating SSRFProxy::HTTP objects with PUT method
test_url_method_put
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_url_method_options opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/xxURLxx' opts[:method] = 'OPTIONS' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) opts = SSRF_DEFAULT_OPTS.dup opts[:url] = 'http://127.0.0.1/' opts[:method] = 'OPTIONS' opts[:post_data] = 'xxURLxx' ssrf = SSRFProxy::HTTP.new(opts) assert valid_ssrf?(ssrf) end
@note test creating SSRFProxy::HTTP objects with OPTIONS method
test_url_method_options
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_url_invalid_url urls = [ 'http://', 'ftp://', 'smb://', '://z', '://z:80', [], [[[]]], {}, { {} => {} }, "\x00", false, true, 'xxURLxx://127.0.0.1/file.ext?query1=a&query2=b', 'ftp://127.0.0.1', 'ftp://xxURLxx@127.0.0.1/file.ext?query1=a&query2=b', 'ftp://xxURLxx/file.ext?query1=a&query2=b', 'ftp://http:xxURLxx@localhost' ] urls.each do |url| ssrf = nil begin opts = SSRF_DEFAULT_OPTS.dup opts[:url] = URI.parse(url) assert_raises SSRFProxy::HTTP::Error::InvalidSsrfRequest do ssrf = SSRFProxy::HTTP.new(opts) end rescue URI::InvalidURIError end assert_nil(ssrf) end end
@note test creating SSRFProxy::HTTP objects with invalid URL
test_url_invalid_url
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_url_invalid_method url = 'http://127.0.0.1/xxURLxx' assert_raises SSRFProxy::HTTP::Error::InvalidSsrfRequestMethod do SSRFProxy::HTTP.new(url: url, method: ('a'..'z').to_a.sample(8).join.to_s) end end
@note test creating SSRFProxy::HTTP objects with invalid reqest method
test_url_invalid_method
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT
def test_url_xxurlxx_placeholder_get urls = [ 'http://127.0.0.1', 'http://xxURLxx@127.0.0.1/file.ext?query1=a&query2=b', 'http://xxURLxx/file.ext?query1=a&query2=b', 'http://http:xxURLxx@localhost' ] urls.each do |url| opts = SSRF_DEFAULT_OPTS.dup opts[:url] = URI.parse(url) assert_raises SSRFProxy::HTTP::Error::NoUrlPlaceholder do SSRFProxy::HTTP.new(opts) end end end
@note test xxURLxx placeholder with GET method
test_url_xxurlxx_placeholder_get
ruby
bcoles/ssrf_proxy
test/unit/test_http.rb
https://github.com/bcoles/ssrf_proxy/blob/master/test/unit/test_http.rb
MIT