# Author: LMH <lmh@info-pull.com>
# Description: The exploit controller of msfweb v.3. Handles views, listing
# and other actions related to exploit modules. Code and processing goes here.
# Instance variables, final values, etc, go into views.

class ExploitsController < ApplicationController
layout 'windows'

def list
end

def view
	@tmod = get_view_for_module("exploit", params[:refname])
	
	unless @tmod
	 render_text "Unknown module specified."
	end
end

def config
	# Retrieve object to module with the given refname
	@tmod     = get_view_for_module("exploit", params[:refname])
	unless @tmod
		render_text "Unknown module specified."
	end
	
	# Get target, using index given in 'target' parameter
	@target   = @tmod.targets[params[:target].to_i]
	unless @target
		render_text "Unknown target specified."
	end
	
	@tmod.datastore['TARGET'] = params[:target].to_i
	
	@cur_step = nil
	if params[:step]
		@cur_step = params[:step]
	end
	
	
	if (params[:payload])
	
		if (params[:payload] =~ /^\d+$/ )
			@payload_ref = @tmod.compatible_payloads[params[:payload].to_i]
		else
			@tmod.compatible_payloads.each_with_index do |ref, i|

				if(ref[0] == params[:payload])
					@payload_ref = ref
				end
			end
		end
	end


	if @cur_step == "exploit"
		
		# Always show the option page after an exploit is launched
		@cur_step = "config"
		
		unless @payload_ref
			render_text "Unknown payload specified or not supported."
		end
		
		@payload_name, @payload_class  = @payload_ref
		@payload_inst = @payload_class.new 

		# Create a new console driver instance
		@cid = $msfweb.create_console()
		@con = $msfweb.consoles[@cid]

		# Use the selected module
		@con.execute("use exploit/#{@tmod.refname}")

		# Configure the target and payload	
		@exploit = @con.active_module
		@exploit.datastore['PAYLOAD'] = @payload_name
		@exploit.datastore['TARGET']  = params[:target].to_i

		# Configure the selected options
		params.each_key do |k|
			eopt = k.to_s.match(/^eopt_/) ? true : false
			popt = k.to_s.match(/^popt_/) ? true : false
			name = k.to_s.gsub(/^.opt_/, '')

			if (eopt or popt)
				if (params[k] and params[k].to_s.length > 0)
					@exploit.datastore[name] = params[k].to_s
				end
			end
		end

		# Validate the exploit and payload options
		@payload_inst.share_datastore(@exploit.datastore)
		
		begin
			@exploit.options.validate(@exploit.datastore)
			@payload_inst.options.validate(@payload_inst.datastore)
			@con.write("exploit\n")
			@exploit_console = @cid
		rescue ::Exception => e
			$msfweb.destroy_console(@cid)
			@exploit_error = e.to_s
		end	
	end
	
	
	if @cur_step == "config"
		
		unless @payload_ref
			render_text "Unknown payload specified or not supported."
		end
		
		@payload_name, @payload_class = @payload_ref
		@payload_inst = @payload_class.new 
		
	else
		@payloads = @tmod.compatible_payloads
	end
	
end


end
