Path: blob/master/lib/rex/proto/http/response.rb
19758 views
# -*- coding: binary -*-1require 'cgi'2require 'uri'34require 'nokogiri'5require 'rkelly'67module Rex8module Proto9module Http1011###12#13# HTTP response class.14#15###16class Response < Packet1718##19#20# Builtin response class wrappers.21#22##2324#25# HTTP 200/OK response class wrapper.26#27class OK < Response28def initialize(message = 'OK', proto = DefaultProtocol)29super(200, message, proto)30end31end3233#34# HTTP 404/File not found response class wrapper.35#36class E404 < Response37def initialize(message = 'File not found', proto = DefaultProtocol)38super(404, message, proto)39end40end4142#43# Constructage of the HTTP response with the supplied code, message, and44# protocol.45#46def initialize(code = 200, message = 'OK', proto = DefaultProtocol)47super()4849self.code = code.to_i50self.message = message51self.proto = proto5253# Default responses to auto content length on54self.auto_cl = true5556# default chunk sizes (if chunked is used)57self.chunk_min_size = 158self.chunk_max_size = 105960# 100 continue counter61self.count_100 = 062end6364#65# Gets cookies from the Set-Cookie header in a format to be used66# in the 'cookie' send_request field67#68def get_cookies69cookies = ""70if (self.headers.include?('Set-Cookie'))71set_cookies = self.headers['Set-Cookie']72key_vals = set_cookies.scan(/\s?([^, ;]+?)=([^, ;]*?)[;,]/)73key_vals.each do |k, v|74# Dont downcase actual cookie name as may be case sensitive75name = k.downcase76next if name == 'path'77next if name == 'expires'78next if name == 'domain'79next if name == 'max-age'80cookies << "#{k}=#{v}; "81end82end8384return cookies.strip85end8687#88# Gets cookies from the Set-Cookie header in a parsed format89#90def get_cookies_parsed91if (self.headers.include?('Set-Cookie'))92ret = CGI::Cookie::parse(self.headers['Set-Cookie'])93else94ret = {}95end96ret97end9899100# Returns a parsed HTML document.101# Instead of using regexes to parse the HTML body, you should use this and use the Nokogiri API.102#103# @see http://www.nokogiri.org/104# @return [Nokogiri::HTML::Document]105def get_html_document106Nokogiri::HTML(self.body)107end108109# Returns a parsed XML document.110# Instead of using regexes to parse the XML body, you should use this and use the Nokogiri API.111#112# @see http://www.nokogiri.org/113# @return [Nokogiri::XML::Document]114def get_xml_document115Nokogiri::XML(self.body)116end117118def gzip_decode!119self.body = gzip_decode120end121122def gzip_decode123gz = Zlib::GzipReader.new(StringIO.new(self.body.to_s))124125gz.read126end127128# Returns a parsed json document.129# Instead of using regexes to parse the JSON body, you should use this.130#131# @return [Hash]132def get_json_document133json = {}134135begin136json = JSON.parse(self.body)137rescue JSON::ParserError => e138elog(e)139end140141json142end143144# Returns meta tags.145# You will probably want to use this the web app's version info (or other stuff) can be found146# in the metadata.147#148# @return [Array<Nokogiri::XML::Element>]149def get_html_meta_elements150n = get_html_document151n.search('//meta')152end153154# Returns parsed JavaScript blocks.155# The parsed version is a RKelly object that allows you to be able do advanced parsing.156#157# @see https://github.com/tenderlove/rkelly158# @return [Array<RKelly::Nodes::SourceElementsNode>]159def get_html_scripts160n = get_html_document161rkelly = RKelly::Parser.new162n.search('//script').map { |s| rkelly.parse(s.text) }163end164165166# Returns a collection of found hidden inputs167#168# @return [Array<Hash>] An array, each element represents a form that contains a hash of found hidden inputs169# * 'name' [String] The hidden input's original name. The value is the hidden input's original value.170# @example171# res = send_request_cgi('uri'=>'/')172# inputs = res.get_hidden_inputs173# session_id = inputs[0]['sessionid'] # The first form's 'sessionid' hidden input174def get_hidden_inputs175forms = []176noko = get_html_document177noko.search("form").each_entry do |form|178found_inputs = {}179form.search("input").each_entry do |input|180input_type = input.attributes['type'] ? input.attributes['type'].value : ''181next if input_type !~ /hidden/i182183input_name = input.attributes['name'] ? input.attributes['name'].value : ''184input_value = input.attributes['value'] ? input.attributes['value'].value : ''185found_inputs[input_name] = input_value unless input_name.empty?186end187forms << found_inputs unless found_inputs.empty?188end189190forms191end192193#194# Updates the various parts of the HTTP response command string.195#196def update_cmd_parts(str)197if (md = str.match(/HTTP\/(.+?)\s+(\d+)\s?(.+?)\r?\n?$/))198self.message = md[3].gsub("\r", '')199self.code = md[2].to_i200self.proto = md[1]201else202raise RuntimeError, "Invalid response command string", caller203end204205check_100()206end207208#209# Allow 100 Continues to be ignored by the caller210#211def check_100212# If this was a 100 continue with no data, reset213if self.code == 100 and (self.body_bytes_left == -1 or self.body_bytes_left == 0) and self.count_100 < 5214self.reset_except_queue215self.count_100 += 1216end217end218219# Answers if the response is a redirection one.220#221# @return [Boolean] true if the response is a redirection, false otherwise.222def redirect?223[301, 302, 303, 307, 308].include?(code)224end225226# Provides the uri of the redirection location.227#228# @return [URI] the uri of the redirection location.229# @return [nil] if the response hasn't a Location header or it isn't a valid uri.230def redirection231URI(headers['Location'])232rescue ArgumentError, ::URI::InvalidURIError233nil234end235236#237# Returns the response based command string.238#239def cmd_string240"HTTP\/#{proto} #{code}#{(message and message.length > 0) ? ' ' + message : ''}\r\n"241end242243#244# Used to store a copy of the original request245#246attr_accessor :request247248#249# Host address:port associated with this request/response250#251attr_accessor :peerinfo252253attr_accessor :code254attr_accessor :message255attr_accessor :proto256attr_accessor :count_100257end258259end260end261end262263264