Class: SSRFProxy::HTTP

Inherits:
Object
  • Object
show all
Defined in:
lib/ssrf_proxy/http.rb

Overview

SSRFProxy::HTTP object takes information required to connect to a HTTP server vulnerable to SSRF and issue arbitrary HTTP requests via the SSRF.

Once configured, the #send_uri method can be used to tunnel HTTP requests through the server.

Several request modification options can be used to format the HTTP request appropriately for the SSRF vector and the destination web server accessed via the SSRF.

Several response modification options can be used to infer information about the response from the destination server and format the response such that the vulnerable intermediary server is mostly transparent to the client initiating the HTTP request.

Refer to the wiki for more information about configuring the SSRF, requestion modification, and response modification: github.com/bcoles/ssrf_proxy/wiki/Configuration

Defined Under Namespace

Modules: Error

Instance Method Summary collapse

Constructor Details

#initialize(url = '', opts = {}) ⇒ HTTP

SSRFProxy::HTTP accepts SSRF connection information, and configuration options for request modificaiton and response modification.

Examples:

SSRF with default options

SSRFProxy::HTTP.new('http://example.local/index.php?url=xxURLxx')

Parameters:

  • url (String) (defaults to: '')

    SSRF URL with ‘xxURLxx’ placeholder

  • opts (Hash) (defaults to: {})

    SSRF and HTTP connection options:

Options Hash (opts):

  • proxy (String)
  • method (String)
  • post_data (String)
  • rules (String)
  • ip_encoding (String)
  • match (Regex)
  • strip (String)
  • decode_html (Boolean)
  • guess_status (Boolean)
  • guess_mime (Boolean)
  • ask_password (Boolean)
  • forward_cookies (Boolean)
  • body_to_uri (Boolean)
  • auth_to_uri (Boolean)
  • cookies_to_uri (Boolean)
  • cookie (String)
  • timeout (Integer)
  • user_agent (String)
  • insecure (Boolean)

Raises:

  • (SSRFProxy::HTTP::Error::InvalidSsrfRequest)

    Invalid SSRF request specified.



82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/ssrf_proxy/http.rb', line 82

def initialize(url = '', opts = {})
  @detect_waf = true
  @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
  begin
    @ssrf_url = URI.parse(url.to_s)
  rescue URI::InvalidURIError
    raise SSRFProxy::HTTP::Error::InvalidSsrfRequest.new,
          'Invalid SSRF request specified.'
  end
  if @ssrf_url.scheme.nil? || @ssrf_url.host.nil? || @ssrf_url.port.nil?
    raise SSRFProxy::HTTP::Error::InvalidSsrfRequest.new,
          'Invalid SSRF request specified.'
  end
  if @ssrf_url.scheme !~ /\Ahttps?\z/
    raise SSRFProxy::HTTP::Error::InvalidSsrfRequest.new,
          'Invalid SSRF request specified. Scheme must be http(s).'
  end
  parse_options(opts)
end

Instance Method Details

#hostString

Host accessor

Returns:

  • (String)

    SSRF host



267
268
269
# File 'lib/ssrf_proxy/http.rb', line 267

def host
  @ssrf_url.host
end

#loggerLogger

Logger accessor

Returns:

  • (Logger)

    class logger object



249
250
251
# File 'lib/ssrf_proxy/http.rb', line 249

def logger
  @logger
end

#portString

Port accessor

Returns:

  • (String)

    SSRF host port



276
277
278
# File 'lib/ssrf_proxy/http.rb', line 276

def port
  @ssrf_url.port
end

#proxyURI

Upstream proxy accessor

Returns:

  • (URI)

    upstream HTTP proxy



285
286
287
# File 'lib/ssrf_proxy/http.rb', line 285

def proxy
  @upstream_proxy
end

#send_request(request) ⇒ Hash

Parse a HTTP request as a string, then send the requested URL and HTTP headers to send_uri

Parameters:

  • request (String)

    raw HTTP request

Returns:

  • (Hash)

    HTTP response hash (version, code, message, headers, body, etc)

Raises:

  • (SSRFProxy::HTTP::Error::InvalidClientRequest)

    An invalid client HTTP request was supplied.



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/ssrf_proxy/http.rb', line 300

def send_request(request)
  if request.to_s !~ /\A(GET|HEAD|DELETE|POST|PUT) /
    logger.warn("Client request method is not supported")
    raise SSRFProxy::HTTP::Error::InvalidClientRequest,
          'Client request method is not supported'
  end
  if request.to_s !~ %r{\A(GET|HEAD|DELETE|POST|PUT) https?://}
    if request.to_s =~ /^Host: ([^\s]+)\r?\n/
      logger.info("Using host header: #{$1}")
    else
      logger.warn('No host specified')
      raise SSRFProxy::HTTP::Error::InvalidClientRequest,
            'No host specified'
    end
  end
  # parse client request
  begin
    req = WEBrick::HTTPRequest.new(WEBrick::Config::HTTP)
    req.parse(StringIO.new(request))
  rescue
    logger.info('Received malformed client HTTP request.')
    raise SSRFProxy::HTTP::Error::InvalidClientRequest,
          'Received malformed client HTTP request.'
  end
  if req.to_s =~ /^Upgrade: WebSocket/
    logger.warn("WebSocket tunneling is not supported: #{req.host}:#{req.port}")
    raise SSRFProxy::HTTP::Error::InvalidClientRequest,
          "WebSocket tunneling is not supported: #{req.host}:#{req.port}"
  end
  uri = req.request_uri
  if uri.nil?
    raise SSRFProxy::HTTP::Error::InvalidClientRequest,
          'URI is nil'
  end

  # parse request body and move to uri
  if @body_to_uri && !req.body.nil?
    logger.debug("Parsing request body: #{req.body}")
    begin
      if req.query_string.nil?
        uri = "#{uri}?#{req.body}"
      else
        uri = "#{uri}&#{req.body}"
      end
      logger.info("Added request body to URI: #{req.body}")
    rescue
      logger.warn('Could not parse client request body')
    end
  end

  # move basic authentication credentials to uri
  if @auth_to_uri && !req.header.nil?
    req.header['authorization'].each do |header|
      logger.debug("Parsing basic authentication header: #{header}")
      next unless header.split(' ').first =~ /^basic$/i
      begin
        creds = header.split(' ')[1]
        user = Base64.decode64(creds).chomp
        uri = uri.to_s.gsub!(%r{:(//)}, "://#{user}@")
        logger.info("Using basic authentication credentials: #{user}")
      rescue
        logger.warn "Could not parse request authorization header: #{header}"
      end
      break
    end
  end

  # copy cookies to uri
  cookies = []
  if @cookies_to_uri && !req.cookies.nil? && !req.cookies.empty?
    logger.debug("Parsing request cookies: #{req.cookies.join('; ')}")
    cookies = []
    begin
      req.cookies.each do |c|
        cookies << c.to_s.gsub(/;\z/, '').to_s unless c.nil?
      end
      query_string = uri.to_s.split('?')[1..-1]
      if query_string.empty?
        s = '?'
      else
        s = '&'
      end
      uri = "#{uri}#{s}#{cookies.join('&')}"
      logger.info("Added cookies to URI: #{cookies.join('&')}")
    rescue => e
      logger.warn "Could not parse request coookies: #{e}"
    end
  end

  # HTTP request headers
  headers = {}

  # forward client cookies
  new_cookie = []
  new_cookie << @cookie unless @cookie.nil?
  if @forward_cookies
    req.cookies.each do |c|
      new_cookie << c.to_s
    end
  end
  unless new_cookie.empty?
    headers['cookie'] = new_cookie.uniq.join('; ').to_s
    logger.info("Using cookie: #{headers['cookie']}")
  end
  send_uri(uri, headers)
end

#send_uri(uri, headers = {}) ⇒ Hash

Fetch a URI via SSRF

Parameters:

  • uri (String)

    URI to fetch

  • HTTP (Hash)

    request headers

Returns:

  • (Hash)

    HTTP response hash (version, code, message, headers, body, etc)

Raises:

  • (SSRFProxy::HTTP::Error::InvalidClientRequest)

    An invalid client HTTP request was supplied.



418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
# File 'lib/ssrf_proxy/http.rb', line 418

def send_uri(uri, headers = {})
  if uri.nil?
    raise SSRFProxy::HTTP::Error::InvalidClientRequest,
          'Request URI is nil'
  end

  # encode target host ip
  if @ip_encoding
    encoded_uri = encode_ip(uri, @ip_encoding)
  else
    encoded_uri = uri
  end

  # run target url through rules
  target_uri = run_rules(encoded_uri, @rules)

  # replace xxURLxx placeholder in SSRF request URL
  ssrf_url = "#{@ssrf_url.path}?#{@ssrf_url.query}".gsub(/xxURLxx/, target_uri.to_s)

  # replace xxURLxx placeholder in SSRF request body
  if @post_data.nil?
    body = ''
  else
    body = @post_data.gsub(/xxURLxx/, target_uri.to_s)
  end

  # set user agent
  headers['User-Agent'] = @user_agent if headers['User-Agent'].nil?

  # set content type
  if headers['Content-Type'].nil? && @method.eql?('POST')
    headers['Content-Type'] = 'application/x-www-form-urlencoded'
  end

  # send request
  start_time = Time.now
  response = send_http_request(ssrf_url, @method, headers, body)
  end_time = Time.now
  duration = ((end_time - start_time) * 1000).round(3)
  result = {
    'url'          => uri,
    'duration'     => duration,
    'http_version' => response.http_version,
    'code'         => response.code,
    'message'      => response.message,
    'headers'      => '',
    'body'         => response.body.to_s || '' }
  logger.info("Received #{result['body'].length} bytes in #{duration} ms")

  # 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
  result['status_line'] = "HTTP/#{result['http_version']} #{result['code']} #{result['message']}"

  # strip unwanted HTTP response headers
  response.each_header do |header_name, header_value|
    if @strip.include?(header_name.downcase)
      logger.info("Removed response header: #{header_name}")
      next
    end
    result['headers'] << "#{header_name}: #{header_value}\n"
  end

  # detect WAF and SSRF protection libraries
  if @detect_waf
    head = result['body'][0..8192]
    # SafeCurl (safe_curl) InvalidURLException
    if head =~ /fin1te\\SafeCurl\\Exception\\InvalidURLException/
      logger.info('SafeCurl protection mechanism appears to be in use')
    end
  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
  if @guess_mime
    content_type = guess_mime(File.extname(uri.to_s.split('?').first))
    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
  end

  # match response content
  unless @match_regex.nil?
    matches = result['body'].scan(/#{@match_regex}/m)
    if matches.length > 0
      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

  # decode HTML entities
  if @decode_html
    result['body'] = HTMLEntities.new.decode(
      result['body'].encode(
        'UTF-8',
        :invalid => :replace,
        :undef   => :replace,
        :replace => '?'))
  end

  # prompt for password
  if @ask_password
    if result['code'].to_i == 401
      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 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

  # set title
  if result['body'][0..1024] =~ %r{<title>([^<]*)<\/title>}im
    result['title'] = $1.to_s
  else
    result['title'] = ''
  end

  # return HTTP response
  logger.debug("Response:\n#{result['status_line']}\n#{result['headers']}\n#{result['body']}")
  result
end

#urlString

URL accessor

Returns:

  • (String)

    SSRF URL



258
259
260
# File 'lib/ssrf_proxy/http.rb', line 258

def url
  @ssrf_url
end