Path: blob/master/lib/rex/proto/http/client.rb
21536 views
# -*- coding: binary -*-12require 'rex/socket'34require 'rex/text'5require 'digest'67module Rex8module Proto9module Http10###11#12# Acts as a client to an HTTP server, sending requests and receiving responses.13#14# See the RFC: http://www.w3.org/Protocols/rfc2616/rfc2616.html15#16###17class Client1819#20# Creates a new client instance21#22# @param [Rex::Proto::Http::HttpSubscriber] subscriber A subscriber to Http requests/responses23def initialize(host, port = 80, context = {}, ssl = nil, ssl_version = nil, proxies = nil, username = '', password = '', kerberos_authenticator: nil, comm: nil, subscriber: nil, sslkeylogfile: nil)24self.hostname = host25self.port = port.to_i26self.context = context27self.ssl = ssl28self.ssl_version = ssl_version29self.proxies = proxies30self.username = username31self.password = password32self.kerberos_authenticator = kerberos_authenticator33self.comm = comm34self.subscriber = subscriber || HttpSubscriber.new35self.sslkeylogfile = sslkeylogfile3637# Take ClientRequest's defaults, but override with our own38self.config = Http::ClientRequest::DefaultConfig.merge({39'read_max_data' => (1024 * 1024 * 1),40'vhost' => hostname,41'ssl_server_name_indication' => hostname42})43config['agent'] ||= Rex::UserAgent.session_agent4445# XXX: This info should all be controlled by ClientRequest46self.config_types = {47'uri_encode_mode' => ['hex-normal', 'hex-all', 'hex-random', 'hex-noslashes', 'u-normal', 'u-random', 'u-all'],48'uri_encode_count' => 'integer',49'uri_full_url' => 'bool',50'pad_method_uri_count' => 'integer',51'pad_uri_version_count' => 'integer',52'pad_method_uri_type' => ['space', 'tab', 'apache'],53'pad_uri_version_type' => ['space', 'tab', 'apache'],54'method_random_valid' => 'bool',55'method_random_invalid' => 'bool',56'method_random_case' => 'bool',57'version_random_valid' => 'bool',58'version_random_invalid' => 'bool',59'uri_dir_self_reference' => 'bool',60'uri_dir_fake_relative' => 'bool',61'uri_use_backslashes' => 'bool',62'pad_fake_headers' => 'bool',63'pad_fake_headers_count' => 'integer',64'pad_get_params' => 'bool',65'pad_get_params_count' => 'integer',66'pad_post_params' => 'bool',67'pad_post_params_count' => 'integer',68'shuffle_get_params' => 'bool',69'shuffle_post_params' => 'bool',70'uri_fake_end' => 'bool',71'uri_fake_params_start' => 'bool',72'header_folding' => 'bool',73'chunked_size' => 'integer',74'partial' => 'bool'75}76end7778#79# Set configuration options80#81def set_config(opts = {})82opts.each_pair do |var, val|83# Default type is string84typ = config_types[var] || 'string'8586# These are enum types87if typ.is_a?(Array) && !typ.include?(val)88raise "The specified value for #{var} is not one of the valid choices"89end9091# The caller should have converted these to proper ruby types, but92# take care of the case where they didn't before setting the93# config.9495if (typ == 'bool')96val = val == true || val.to_s =~ /^(t|y|1)/i97end9899if (typ == 'integer')100val = val.to_i101end102103config[var] = val104end105end106107#108# Create an arbitrary HTTP request109#110# @param opts [Hash]111# @option opts 'agent' [String] User-Agent header value112# @option opts 'connection' [String] Connection header value113# @option opts 'cookie' [String] Cookie header value114# @option opts 'data' [String] HTTP data (only useful with some methods, see rfc2616)115# @option opts 'encode' [Bool] URI encode the supplied URI, default: false116# @option opts 'headers' [Hash] HTTP headers, e.g. <code>{ "X-MyHeader" => "value" }</code>117# @option opts 'method' [String] HTTP method to use in the request, not limited to standard methods defined by rfc2616, default: GET118# @option opts 'proto' [String] protocol, default: HTTP119# @option opts 'query' [String] raw query string120# @option opts 'raw_headers' [String] Raw HTTP headers121# @option opts 'uri' [String] the URI to request122# @option opts 'version' [String] version of the protocol, default: 1.1123# @option opts 'vhost' [String] Host header value124#125# @return [ClientRequest]126def request_raw(opts = {})127opts = config.merge(opts)128129opts['cgi'] = false130opts['port'] = port131opts['ssl'] = ssl132133ClientRequest.new(opts)134end135136#137# Create a CGI compatible request138#139# @param (see #request_raw)140# @option opts (see #request_raw)141# @option opts 'ctype' [String] Content-Type header value, default for POST requests: +application/x-www-form-urlencoded+142# @option opts 'encode_params' [Bool] URI encode the GET or POST variables (names and values), default: true143# @option opts 'vars_get' [Hash] GET variables as a hash to be translated into a query string144# @option opts 'vars_post' [Hash] POST variables as a hash to be translated into POST data145# @option opts 'vars_form_data' [Hash] POST form_data variables as a hash to be translated into multi-part POST form data146#147# @return [ClientRequest]148def request_cgi(opts = {})149opts = config.merge(opts)150151opts['cgi'] = true152opts['port'] = port153opts['ssl'] = ssl154155ClientRequest.new(opts)156end157158#159# Connects to the remote server if possible.160#161# @param t [Integer] Timeout162# @see Rex::Socket::Tcp.create163# @return [Rex::Socket::Tcp]164def connect(t = -1)165# If we already have a connection and we aren't pipelining, close it.166if conn167if !pipelining?168close169else170return conn171end172end173174timeout = (t.nil? or t == -1) ? 0 : t175176self.conn = Rex::Socket::Tcp.create(177'PeerHost' => hostname,178'PeerHostname' => config['ssl_server_name_indication'] || config['vhost'],179'PeerPort' => port.to_i,180'LocalHost' => local_host,181'LocalPort' => local_port,182'Context' => context,183'SSL' => ssl,184'SSLVersion' => ssl_version,185'SSLKeyLogFile' => sslkeylogfile,186'Proxies' => proxies,187'Timeout' => timeout,188'Comm' => comm189)190end191192#193# Closes the connection to the remote server.194#195def close196if conn && !conn.closed?197conn.shutdown198conn.close199end200201self.conn = nil202self.ntlm_client = nil203end204205#206# Sends a request and gets a response back207#208# If the request is a 401, and we have creds, it will attempt to complete209# authentication and return the final response210#211# @return (see #_send_recv)212def send_recv(req, t = -1, persist = false)213res = _send_recv(req, t, persist)214if res and res.code == 401 and res.headers['WWW-Authenticate']215res = send_auth(res, req.opts, t, persist)216end217res218end219220#221# Transmit an HTTP request and receive the response222#223# If persist is set, then the request will attempt to reuse an existing224# connection.225#226# Call this directly instead of {#send_recv} if you don't want automatic227# authentication handling.228#229# @return (see #read_response)230def _send_recv(req, t = -1, persist = false)231@pipeline = persist232subscriber.on_request(req)233if req.respond_to?(:opts) && req.opts['ntlm_transform_request'] && ntlm_client234req = req.opts['ntlm_transform_request'].call(ntlm_client, req)235elsif req.respond_to?(:opts) && req.opts['krb_transform_request'] && krb_encryptor236req = req.opts['krb_transform_request'].call(krb_encryptor, req)237end238239send_request(req, t)240241res = read_response(t, original_request: req)242if req.respond_to?(:opts) && req.opts['ntlm_transform_response'] && ntlm_client243req.opts['ntlm_transform_response'].call(ntlm_client, res)244elsif req.respond_to?(:opts) && req.opts['krb_transform_response'] && krb_encryptor245req = req.opts['krb_transform_response'].call(krb_encryptor, res)246end247res.request = req.to_s if res248res.peerinfo = peerinfo if res249subscriber.on_response(res)250res251end252253#254# Send an HTTP request to the server255#256# @param req [Request,ClientRequest,#to_s] The request to send257# @param t (see #connect)258#259# @return [void]260def send_request(req, t = -1)261connect(t)262conn.put(req.to_s)263end264265# Resends an HTTP Request with the proper authentication headers266# set. If we do not support the authentication type the server requires267# we return the original response object268#269# @param res [Response] the HTTP Response object270# @param opts [Hash] the options used to generate the original HTTP request271# @param t [Integer] the timeout for the request in seconds272# @param persist [Boolean] whether or not to persist the TCP connection (pipelining)273#274# @return [Response] the last valid HTTP response object we received275def send_auth(res, opts, t, persist)276if opts['username'].nil? or opts['username'] == ''277if username and !(username == '')278opts['username'] = username279opts['password'] = password280else281opts['username'] = nil282opts['password'] = nil283end284end285286if opts[:kerberos_authenticator].nil?287opts[:kerberos_authenticator] = kerberos_authenticator288end289290return res if (opts['username'].nil? or opts['username'] == '') and opts[:kerberos_authenticator].nil?291292supported_auths = res.headers['WWW-Authenticate']293294# if several providers are available, the client may want one in particular295preferred_auth = opts['preferred_auth']296297if supported_auths.include?('Basic') && (preferred_auth.nil? || preferred_auth == 'Basic')298opts['headers'] ||= {}299opts['headers']['Authorization'] = basic_auth_header(opts['username'], opts['password'])300req = request_cgi(opts)301res = _send_recv(req, t, persist)302return res303elsif supported_auths.include?('Digest') && (preferred_auth.nil? || preferred_auth == 'Digest')304temp_response = digest_auth(opts)305if temp_response.is_a? Rex::Proto::Http::Response306res = temp_response307end308return res309elsif supported_auths.include?('NTLM') && (preferred_auth.nil? || preferred_auth == 'NTLM')310opts['provider'] = 'NTLM'311temp_response = negotiate_auth(opts)312if temp_response.is_a? Rex::Proto::Http::Response313res = temp_response314end315return res316elsif supported_auths.include?('Kerberos') && (preferred_auth.nil? || preferred_auth == 'Kerberos') && kerberos_authenticator317opts['provider'] = 'Kerberos'318temp_response = kerberos_auth(opts, mechanism: Rex::Proto::Gss::Mechanism::KERBEROS)319if temp_response.is_a? Rex::Proto::Http::Response320res = temp_response321end322return res323elsif supported_auths.include?('Negotiate') && (preferred_auth.nil? || preferred_auth == 'Negotiate')324opts['provider'] = 'Negotiate'325temp_response = negotiate_auth(opts)326if temp_response.is_a? Rex::Proto::Http::Response327res = temp_response328end329return res330elsif supported_auths.include?('Negotiate') && (preferred_auth.nil? || preferred_auth == 'Kerberos') && kerberos_authenticator331opts['provider'] = 'Negotiate'332temp_response = kerberos_auth(opts, mechanism: Rex::Proto::Gss::Mechanism::SPNEGO)333if temp_response.is_a? Rex::Proto::Http::Response334res = temp_response335end336return res337end338return res339end340341# Converts username and password into the HTTP Basic authorization342# string.343#344# @return [String] A value suitable for use as an Authorization header345def basic_auth_header(username, password)346auth_str = username.to_s + ':' + password.to_s347'Basic ' + Rex::Text.encode_base64(auth_str)348end349# Send a series of requests to complete Digest Authentication350#351# @param opts [Hash] the options used to build an HTTP request352# @return [Response] the last valid HTTP response we received353def digest_auth(opts = {})354to = opts['timeout'] || 20355356digest_user = opts['username'] || ''357digest_password = opts['password'] || ''358359method = opts['method']360path = opts['uri']361iis = true362if (opts['DigestAuthIIS'] == false or config['DigestAuthIIS'] == false)363iis = false364end365366begin367resp = opts['response']368369if !resp370# Get authentication-challenge from server, and read out parameters required371r = request_cgi(opts.merge({372'uri' => path,373'method' => method374}))375resp = _send_recv(r, to)376unless resp.is_a? Rex::Proto::Http::Response377return nil378end379380if resp.code != 401381return resp382end383return resp unless resp.headers['WWW-Authenticate']384end385386# Don't anchor this regex to the beginning of string because header387# folding makes it appear later when the server presents multiple388# WWW-Authentication options (such as is the case with IIS configured389# for Digest or NTLM).390resp['www-authenticate'] =~ /Digest (.*)/391392parameters = {}393::Regexp.last_match(1).split(/,[[:space:]]*/).each do |p|394k, v = p.split('=', 2)395parameters[k] = v.gsub('"', '')396end397398auth_digest = Rex::Proto::Http::AuthDigest.new399auth = auth_digest.digest(digest_user, digest_password, method, path, parameters, iis)400401headers = { 'Authorization' => auth.join(', ') }402headers.merge!(opts['headers']) if opts['headers']403404# Send main request with authentication405r = request_cgi(opts.merge({406'uri' => path,407'method' => method,408'headers' => headers409}))410resp = _send_recv(r, to, true)411unless resp.is_a? Rex::Proto::Http::Response412return nil413end414415return resp416rescue ::Errno::EPIPE, ::Timeout::Error417end418end419420def kerberos_auth(opts = {}, mechanism: Rex::Proto::Gss::Mechanism::KERBEROS)421to = opts['timeout'] || 20422auth_result = kerberos_authenticator.authenticate(mechanism: mechanism)423gss_data = auth_result[:security_blob]424gss_data_b64 = Rex::Text.encode_base64(gss_data)425426# Separate options for the auth requests427auth_opts = opts.clone428auth_opts['headers'] = opts['headers'].clone429case mechanism430when Rex::Proto::Gss::Mechanism::KERBEROS431auth_opts['headers']['Authorization'] = "Kerberos #{gss_data_b64}"432when Rex::Proto::Gss::Mechanism::SPNEGO433auth_opts['headers']['Authorization'] = "Negotiate #{gss_data_b64}"434end435436if auth_opts['no_body_for_auth']437auth_opts.delete('data')438auth_opts.delete('krb_transform_request')439auth_opts.delete('krb_transform_response')440end441442begin443# Send the auth request444r = request_cgi(auth_opts)445resp = _send_recv(r, to)446unless resp.is_a? Rex::Proto::Http::Response447return nil448end449450# Get the challenge and craft the response451response = resp.headers['WWW-Authenticate'].scan(/Kerberos ([A-Z0-9\x2b\x2f=]+)/ni).flatten[0]452return resp unless response453454decoded = Rex::Text.decode_base64(response)455mutual_auth_result = kerberos_authenticator.parse_gss_init_response(decoded, auth_result[:session_key])456self.krb_encryptor = kerberos_authenticator.get_message_encryptor(mutual_auth_result[:ap_rep_subkey],457auth_result[:client_sequence_number],458mutual_auth_result[:server_sequence_number])459460if opts['no_body_for_auth']461# If the body wasn't sent in the authentication, now do the actual request462r = request_cgi(opts)463resp = _send_recv(r, to, true)464end465return resp466rescue ::Errno::EPIPE, ::Timeout::Error467return nil468end469end470471#472# Builds a series of requests to complete Negotiate Auth. Works essentially473# the same way as Digest auth. Same pipelining concerns exist.474#475# @option opts (see #send_request_cgi)476# @option opts provider ["Negotiate","NTLM"] What Negotiate provider to use477#478# @return [Response] the last valid HTTP response we received479def negotiate_auth(opts = {})480to = opts['timeout'] || 20481opts['username'] ||= ''482opts['password'] ||= ''483484if opts['provider'] and opts['provider'].include? 'Negotiate'485provider = 'Negotiate '486else487provider = 'NTLM '488end489490opts['method'] ||= 'GET'491opts['headers'] ||= {}492493workstation_name = Rex::Text.rand_text_alpha(rand(6..13))494domain_name = config['domain']495496ntlm_client = ::Net::NTLM::Client.new(497opts['username'],498opts['password'],499workstation: workstation_name,500domain: domain_name501)502type1 = ntlm_client.init_context503504begin505# Separate options for the auth requests506auth_opts = opts.clone507auth_opts['headers'] = opts['headers'].clone508auth_opts['headers']['Authorization'] = provider + type1.encode64509510if auth_opts['no_body_for_auth']511auth_opts.delete('data')512auth_opts.delete('ntlm_transform_request')513auth_opts.delete('ntlm_transform_response')514end515516# First request to get the challenge517r = request_cgi(auth_opts)518resp = _send_recv(r, to)519unless resp.is_a? Rex::Proto::Http::Response520return nil521end522523return resp unless resp.code == 401 && resp.headers['WWW-Authenticate']524525# Get the challenge and craft the response526ntlm_challenge = resp.headers['WWW-Authenticate'].scan(/#{provider}([A-Z0-9\x2b\x2f=]+)/ni).flatten[0]527return resp unless ntlm_challenge528529ntlm_message_3 = ntlm_client.init_context(ntlm_challenge, channel_binding)530531self.ntlm_client = ntlm_client532# Send the response533auth_opts['headers']['Authorization'] = "#{provider}#{ntlm_message_3.encode64}"534r = request_cgi(auth_opts)535resp = _send_recv(r, to, true)536537unless resp.is_a? Rex::Proto::Http::Response538return nil539end540541if opts['no_body_for_auth']542# If the body wasn't sent in the authentication, now do the actual request543r = request_cgi(opts)544resp = _send_recv(r, to, true)545end546return resp547rescue ::Errno::EPIPE, ::Timeout::Error548return nil549end550end551552def channel_binding553if !conn.respond_to?(:peer_cert) or conn.peer_cert.nil?554nil555else556Net::NTLM::ChannelBinding.create(OpenSSL::X509::Certificate.new(conn.peer_cert))557end558end559560# Read a response from the server561#562# Wait at most t seconds for the full response to be read in.563# If t is specified as a negative value, it indicates an indefinite wait cycle.564# If t is specified as nil or 0, it indicates no response parsing is required.565#566# @return [Response]567def read_response(t = -1, opts = {})568# Return a nil response if timeout is nil or 0569return if t.nil? || t == 0570571resp = Response.new572resp.max_data = config['read_max_data']573574original_request = opts.fetch(:original_request) { nil }575parse_opts = {}576unless original_request.nil?577parse_opts = { orig_method: original_request.opts['method'] }578end579580Timeout.timeout((t < 0) ? nil : t) do581rv = nil582while (583!conn.closed? and584rv != Packet::ParseCode::Completed and585rv != Packet::ParseCode::Error586)587588begin589buff = conn.get_once(resp.max_data, 1)590rv = resp.parse(buff || '', parse_opts)591592# Handle unexpected disconnects593rescue ::Errno::EPIPE, ::EOFError, ::IOError594case resp.state595when Packet::ParseState::ProcessingHeader596resp = nil597when Packet::ParseState::ProcessingBody598# truncated request, good enough599resp.error = :truncated600end601break602end603604# This is a dirty hack for broken HTTP servers605next unless rv == Packet::ParseCode::Completed606607rbody = resp.body608rbufq = resp.bufq609610rblob = rbody.to_s + rbufq.to_s611tries = 0612begin613# XXX: This doesn't deal with chunked encoding614while tries < 1000 and resp.headers['Content-Type'] and resp.headers['Content-Type'].start_with?('text/html') and rblob !~ %r{</html>}i615buff = conn.get_once(-1, 0.05)616break if !buff617618rblob += buff619tries += 1620end621rescue ::Errno::EPIPE, ::EOFError, ::IOError622end623624resp.bufq = ''625resp.body = rblob626end627end628629return resp if !resp630631# As a last minute hack, we check to see if we're dealing with a 100 Continue here.632# Most of the time this is handled by the parser via check_100()633if resp.proto == '1.1' and resp.code == 100 and !(opts[:skip_100])634# Read the real response from the body if we found one635# If so, our real response became the body, so we re-parse it.636if resp.body.to_s =~ /^HTTP/637body = resp.body638resp = Response.new639resp.max_data = config['read_max_data']640resp.parse(body, parse_opts)641# We found a 100 Continue but didn't read the real reply yet642# Otherwise reread the reply, but don't try this hack again643else644resp = read_response(t, skip_100: true)645end646end647648resp649rescue Timeout::Error650# Allow partial response due to timeout651resp if config['partial']652end653654#655# Cleans up any outstanding connections and other resources.656#657def stop658close659end660661#662# Returns whether or not the conn is valid.663#664def conn?665conn != nil666end667668#669# Whether or not connections should be pipelined.670#671def pipelining?672pipeline673end674675#676# Target host addr and port for this connection677#678def peerinfo679if conn680pi = conn.peerinfo || nil681if pi682return {683'addr' => pi.split(':')[0],684'port' => pi.split(':')[1].to_i685}686end687end688nil689end690691#692# An optional comm to use for creating the underlying socket.693#694attr_accessor :comm695#696# The client request configuration697#698attr_accessor :config699#700# The client request configuration classes701#702attr_accessor :config_types703#704# Whether or not pipelining is in use.705#706attr_accessor :pipeline707#708# The local host of the client.709#710attr_accessor :local_host711#712# The local port of the client.713#714attr_accessor :local_port715#716# The underlying connection.717#718attr_accessor :conn719#720# The calling context to pass to the socket721#722attr_accessor :context723#724# The proxy list725#726attr_accessor :proxies727728# Auth729attr_accessor :username, :password, :kerberos_authenticator730731# When parsing the request, thunk off the first response from the server, since junk732attr_accessor :junk_pipeline733734# @return [Rex::Proto::Http::HttpSubscriber] The HTTP subscriber735attr_accessor :subscriber736737protected738739# https740attr_accessor :ssl, :ssl_version # :nodoc:741742attr_accessor :hostname, :port # :nodoc:743744#745# The SSL key log file for the connected socket.746#747# @return [String]748attr_accessor :sslkeylogfile749750#751# The established NTLM connection info752#753attr_accessor :ntlm_client754755#756# The established kerberos connection info757#758attr_accessor :krb_encryptor759end760end761end762end763764765