forked from rapid7/metasploit-framework
-
Notifications
You must be signed in to change notification settings - Fork 1
/
msfvenom
executable file
·358 lines (297 loc) · 9.58 KB
/
msfvenom
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#!/usr/bin/env ruby
# -*- coding: binary -*-
msfbase = __FILE__
while File.symlink?(msfbase)
msfbase = File.expand_path(File.readlink(msfbase), File.dirname(msfbase))
end
$:.unshift(File.expand_path(File.join(File.dirname(msfbase), 'lib')))
require 'msfenv'
$:.unshift(ENV['MSF_LOCAL_LIB']) if ENV['MSF_LOCAL_LIB']
require 'rex'
require 'msf/ui'
require 'msf/base'
require 'msf/core/payload_generator'
class MsfVenomError < StandardError; end
class HelpError < StandardError; end
class UsageError < MsfVenomError; end
class NoTemplateError < MsfVenomError; end
class IncompatibleError < MsfVenomError; end
require 'optparse'
# Creates a new framework object.
#
# @note Ignores any previously cached value.
# @param (see ::Msf::Simple::Framework.create)
# @return [Msf::Framework]
def init_framework(create_opts={})
create_opts[:module_types] ||= [
::Msf::MODULE_PAYLOAD, ::Msf::MODULE_ENCODER, ::Msf::MODULE_NOP
]
@framework = ::Msf::Simple::Framework.create(create_opts.merge('DisableDatabase' => true))
end
# Cached framework object
#
# @return [Msf::Framework]
def framework
return @framework if @framework
init_framework
@framework
end
def parse_args(args)
opts = {}
datastore = {}
opt = OptionParser.new
banner = "MsfVenom - a Metasploit standalone payload generator.\n"
banner << "Also a replacement for msfpayload and msfencode.\n"
banner << "Usage: #{$0} [options] <var=val>"
opt.banner = banner
opt.separator('')
opt.separator('Options:')
opt.on('-p', '--payload <payload>', String,
'Payload to use. Specify a \'-\' or stdin to use custom payloads') do |p|
if p == '-'
opts[:payload] = 'stdin'
else
opts[:payload] = p
end
end
opt.on('--payload-options', "List the payload's standard options") do
opts[:list_options] = true
end
opt.on('-l', '--list [type]', Array, 'List a module type. Options are: payloads, encoders, nops, all') do |l|
if l.nil? or l.empty?
l = ["all"]
end
opts[:list] = l
end
opt.on('-n', '--nopsled <length>', Integer, 'Prepend a nopsled of [length] size on to the payload') do |n|
opts[:nops] = n.to_i
end
opt.on('-f', '--format <format>', String, "Output format (use --help-formats for a list)") do |f|
opts[:format] = f
end
opt.on('--help-formats', String, "List available formats") do
init_framework(:module_types => [])
msg = "Executable formats\n" +
"\t" + ::Msf::Util::EXE.to_executable_fmt_formats.join(", ") + "\n" +
"Transform formats\n" +
"\t" + ::Msf::Simple::Buffer.transform_formats.join(", ")
raise HelpError, msg
end
opt.on('-e', '--encoder <encoder>', String, 'The encoder to use') do |e|
opts[:encoder] = e
end
opt.on('-a', '--arch <arch>', String, 'The architecture to use') do |a|
opts[:arch] = a
end
opt.on('--platform <platform>', String, 'The platform of the payload') do |l|
opts[:platform] = l
end
opt.on('--help-platforms', String, 'List available platforms') do
init_framework(:module_types => [])
supported_platforms = []
Msf::Module::Platform.subclasses.each {|c| supported_platforms << "#{c.realname.downcase}"}
msg = "Platforms\n" +
"\t" + supported_platforms.sort * ", "
raise HelpError, msg
end
opt.on('-s', '--space <length>', Integer, 'The maximum size of the resulting payload') do |s|
opts[:space] = s
end
opt.on('--encoder-space <length>', Integer, 'The maximum size of the encoded payload (defaults to the -s value)') do |s|
opts[:encoder_space] = s
end
opt.on('-b', '--bad-chars <list>', String, 'The list of characters to avoid example: \'\x00\xff\'') do |b|
opts[:badchars] = Rex::Text.hex_to_raw(b)
end
opt.on('-i', '--iterations <count>', Integer, 'The number of times to encode the payload') do |i|
opts[:iterations] = i
end
opt.on('-c', '--add-code <path>', String, 'Specify an additional win32 shellcode file to include') do |x|
opts[:add_code] = x
end
opt.on('-x', '--template <path>', String, 'Specify a custom executable file to use as a template') do |x|
opts[:template] = x
end
opt.on('-k', '--keep', 'Preserve the template behavior and inject the payload as a new thread') do
opts[:keep] = true
end
opt.on('-o', '--out <path>', 'Save the payload') do |x|
opts[:out] = x
end
opt.on('-v', '--var-name <name>', String, 'Specify a custom variable name to use for certain output formats') do |x|
opts[:var_name] = x
end
opt.on('--smallest', 'Generate the smallest possible payload') do
opts[:smallest] = true
end
opt.on_tail('-h', '--help', 'Show this message') do
raise HelpError, "#{opt}"
end
begin
opt.parse!(args)
rescue OptionParser::InvalidOption => e
raise UsageError, "Invalid option\n#{opt}"
rescue OptionParser::MissingArgument => e
raise UsageError, "Missing required argument for option\n#{opt}"
end
if opts.empty?
raise UsageError, "No options\n#{opt}"
end
if args
args.each do |x|
k,v = x.split('=', 2)
datastore[k.upcase] = v.to_s
end
if opts[:payload].to_s =~ /[\_\/]reverse/ and datastore['LHOST'].nil?
datastore['LHOST'] = Rex::Socket.source_address
end
end
if opts[:payload].nil? # if no payload option is selected assume we are reading it from stdin
opts[:payload] = "stdin"
end
if opts[:payload] == 'stdin' and not opts[:list]
$stderr.puts "Attempting to read payload from STDIN..."
begin
::Timeout.timeout(30) do
opts[:stdin] = payload_stdin
end
rescue Timeout::Error
opts[:stdin] = ''
end
end
opts[:datastore] = datastore
opts
end
# Read a raw payload from stdin (or whatever IO object we're currently
# using as stdin, see {#initialize})
#
# @return [String]
def payload_stdin
@in = $stdin
@in.binmode
payload = @in.read
payload
end
def dump_payloads
init_framework(:module_types => [ ::Msf::MODULE_PAYLOAD ])
tbl = Rex::Text::Table.new(
'Indent' => 4,
'Header' => "Framework Payloads (#{framework.stats.num_payloads} total)",
'Columns' =>
[
"Name",
"Description"
])
framework.payloads.each_module { |name, mod|
tbl << [ name, mod.new.description.split.join(' ') ]
}
"\n" + tbl.to_s + "\n"
end
def dump_encoders(arch = nil)
init_framework(:module_types => [ ::Msf::MODULE_ENCODER ])
tbl = Rex::Text::Table.new(
'Indent' => 4,
'Header' => "Framework Encoders" + ((arch) ? " (architectures: #{arch})" : ""),
'Columns' =>
[
"Name",
"Rank",
"Description"
])
cnt = 0
framework.encoders.each_module(
'Arch' => arch ? arch.split(',') : nil) { |name, mod|
tbl << [ name, mod.rank_to_s, mod.new.name ]
cnt += 1
}
(cnt > 0) ? "\n" + tbl.to_s + "\n" : "\nNo compatible encoders found.\n\n"
end
def dump_nops
init_framework(:module_types => [ ::Msf::MODULE_NOP ])
tbl = Rex::Text::Table.new(
'Indent' => 4,
'Header' => "Framework NOPs (#{framework.stats.num_nops} total)",
'Columns' =>
[
"Name",
"Description"
])
framework.nops.each_module { |name, mod|
tbl << [ name, mod.new.description.split.join(' ') ]
}
"\n" + tbl.to_s + "\n"
end
begin
generator_opts = parse_args(ARGV)
rescue HelpError => e
$stderr.puts e.message
exit(1)
rescue MsfVenomError, Msf::OptionValidateError => e
$stderr.puts "Error: #{e.message}"
exit(1)
end
if generator_opts[:list]
generator_opts[:list].each do |mod|
case mod.downcase
when "payloads", "payload", "p"
$stdout.puts dump_payloads
when "encoders", "encoder", "e"
$stdout.puts dump_encoders(generator_opts[:arch])
when "nops", "nop", "n"
$stdout.puts dump_nops
when "all"
# Init here so #dump_payloads doesn't create a framework with
# only payloads, etc.
init_framework
$stdout.puts dump_payloads
$stdout.puts dump_encoders
$stdout.puts dump_nops
else
$stderr.puts "Invalid module type. These are valid: payloads, encoders, nops, all"
end
end
exit(0)
end
if generator_opts[:list_options]
payload_mod = framework.payloads.create(generator_opts[:payload])
if payload_mod.nil?
$stderr.puts "Invalid payload: #{generator_opts[:payload]}"
exit
end
$stderr.puts "Options for #{payload_mod.fullname}:\n\n"
$stdout.puts ::Msf::Serializer::ReadableText.dump_module(payload_mod, ' ')
$stderr.puts "Advanced options for #{payload_mod.fullname}:\n\n"
$stdout.puts ::Msf::Serializer::ReadableText.dump_advanced_options(payload_mod, ' ')
$stderr.puts "Evasion options for #{payload_mod.fullname}:\n\n"
$stdout.puts ::Msf::Serializer::ReadableText.dump_evasion_options(payload_mod, ' ')
exit(0)
end
generator_opts[:framework] = framework
generator_opts[:cli] = true
begin
venom_generator = Msf::PayloadGenerator.new(generator_opts)
payload = venom_generator.generate_payload
rescue ::Exception => e
elog("#{e.class} : #{e.message}\n#{e.backtrace * "\n"}")
$stderr.puts "Error: #{e.message}"
end
# No payload generated, no point to go on
exit(2) unless payload
if generator_opts[:out]
begin
::File.open(generator_opts[:out], 'wb') do |f|
f.write(payload)
end
$stderr.puts "Saved as: #{generator_opts[:out]}"
rescue ::Exception => e
# If I can't save it, then I can't save it. I don't think it matters what error.
elog("#{e.class} : #{e.message}\n#{e.backtrace * "\n"}")
$stderr.puts "Error: #{e.message}"
end
else
output_stream = $stdout
output_stream.binmode
output_stream.write payload
# trailing newline for pretty output
$stderr.puts unless payload =~ /\n$/
end