CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
rapid7

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: rapid7/metasploit-framework
Path: blob/master/modules/encoders/x86/shikata_ga_nai.rb
Views: 11780
1
##
2
# This module requires Metasploit: https://metasploit.com/download
3
# Current source: https://github.com/rapid7/metasploit-framework
4
##
5
6
require 'rex/poly'
7
8
class MetasploitModule < Msf::Encoder::XorAdditiveFeedback
9
10
# The shikata encoder has an excellent ranking because it is polymorphic.
11
# Party time, excellent!
12
Rank = ExcellentRanking
13
14
def initialize
15
super(
16
'Name' => 'Polymorphic XOR Additive Feedback Encoder',
17
'Description' => %q{
18
This encoder implements a polymorphic XOR additive feedback encoder.
19
The decoder stub is generated based on dynamic instruction
20
substitution and dynamic block ordering. Registers are also
21
selected dynamically.
22
},
23
'Author' => 'spoonm',
24
'Arch' => ARCH_X86,
25
'License' => MSF_LICENSE,
26
'Decoder' =>
27
{
28
'KeySize' => 4,
29
'BlockSize' => 4
30
})
31
end
32
33
#
34
# Generates the shikata decoder stub.
35
#
36
def decoder_stub(state)
37
38
# If the decoder stub has not already been generated for this state, do
39
# it now. The decoder stub method may be called more than once.
40
if (state.decoder_stub == nil)
41
42
# Sanity check that saved_registers doesn't overlap with modified_registers
43
if (modified_registers & saved_registers).length > 0
44
raise BadGenerateError
45
end
46
47
# Shikata will only cut off the last 1-4 bytes of it's own end
48
# depending on the alignment of the original buffer
49
cutoff = 4 - (state.buf.length & 3)
50
block = generate_shikata_block(state, state.buf.length + cutoff, cutoff) || (raise BadGenerateError)
51
52
# Set the state specific key offset to wherever the XORK ended up.
53
state.decoder_key_offset = block.index('XORK')
54
55
# Take the last 1-4 bytes of shikata and prepend them to the buffer
56
# that is going to be encoded to make it align on a 4-byte boundary.
57
state.buf = block.slice!(block.length - cutoff, cutoff) + state.buf
58
59
# Cache this decoder stub. The reason we cache the decoder stub is
60
# because we need to ensure that the same stub is returned every time
61
# for a given encoder state.
62
state.decoder_stub = block
63
end
64
65
state.decoder_stub
66
end
67
68
# Indicate that this module can preserve some registers
69
def can_preserve_registers?
70
true
71
end
72
73
# A list of registers always touched by this encoder
74
def modified_registers
75
# ESP is assumed and is handled through preserves_stack?
76
[
77
# The counter register is hardcoded
78
Rex::Arch::X86::ECX,
79
# These are modified by div and mul operations
80
Rex::Arch::X86::EAX, Rex::Arch::X86::EDX
81
]
82
end
83
84
# Always blacklist these registers in our block generation
85
def block_generator_register_blacklist
86
[Rex::Arch::X86::ESP, Rex::Arch::X86::ECX] | saved_registers
87
end
88
89
protected
90
91
#
92
# Returns the set of FPU instructions that can be used for the FPU block of
93
# the decoder stub.
94
#
95
def fpu_instructions
96
fpus = []
97
98
0xe8.upto(0xee) { |x| fpus << "\xd9" + x.chr }
99
0xc0.upto(0xcf) { |x| fpus << "\xd9" + x.chr }
100
0xc0.upto(0xdf) { |x| fpus << "\xda" + x.chr }
101
0xc0.upto(0xdf) { |x| fpus << "\xdb" + x.chr }
102
0xc0.upto(0xc7) { |x| fpus << "\xdd" + x.chr }
103
104
fpus << "\xd9\xd0"
105
fpus << "\xd9\xe1"
106
fpus << "\xd9\xf6"
107
fpus << "\xd9\xf7"
108
fpus << "\xd9\xe5"
109
110
# This FPU instruction seems to fail consistently on Linux
111
#fpus << "\xdb\xe1"
112
113
fpus
114
end
115
116
#
117
# Returns a polymorphic decoder stub that is capable of decoding a buffer
118
# of the supplied length and encodes the last cutoff bytes of itself.
119
#
120
def generate_shikata_block(state, length, cutoff)
121
# Declare logical registers
122
count_reg = Rex::Poly::LogicalRegister::X86.new('count', 'ecx')
123
addr_reg = Rex::Poly::LogicalRegister::X86.new('addr')
124
key_reg = nil
125
126
if state.context_encoding
127
key_reg = Rex::Poly::LogicalRegister::X86.new('key', 'eax')
128
else
129
key_reg = Rex::Poly::LogicalRegister::X86.new('key')
130
end
131
132
# Declare individual blocks
133
endb = Rex::Poly::SymbolicBlock::End.new
134
135
# Clear the counter register
136
clear_register = Rex::Poly::LogicalBlock.new('clear_register',
137
"\x31\xc9", # xor ecx,ecx
138
"\x29\xc9", # sub ecx,ecx
139
"\x33\xc9", # xor ecx,ecx
140
"\x2b\xc9") # sub ecx,ecx
141
142
# Initialize the counter after zeroing it
143
init_counter = Rex::Poly::LogicalBlock.new('init_counter')
144
145
# Divide the length by four but ensure that it aligns on a block size
146
# boundary (4 byte).
147
length += 4 + (4 - (length & 3)) & 3
148
length /= 4
149
150
if (length <= 255)
151
init_counter.add_perm("\xb1" + [ length ].pack('C'))
152
elsif (length <= 65536)
153
init_counter.add_perm("\x66\xb9" + [ length ].pack('v'))
154
else
155
init_counter.add_perm("\xb9" + [ length ].pack('V'))
156
end
157
158
# Key initialization block
159
init_key = nil
160
161
# If using context encoding, we use a mov reg, [addr]
162
if state.context_encoding
163
init_key = Rex::Poly::LogicalBlock.new('init_key',
164
Proc.new { |b| (0xa1 + b.regnum_of(key_reg)).chr + 'XORK'})
165
# Otherwise, we do a direct mov reg, val
166
else
167
init_key = Rex::Poly::LogicalBlock.new('init_key',
168
Proc.new { |b| (0xb8 + b.regnum_of(key_reg)).chr + 'XORK'})
169
end
170
171
xor = Proc.new { |b| "\x31" + (0x40 + b.regnum_of(addr_reg) + (8 * b.regnum_of(key_reg))).chr }
172
add = Proc.new { |b| "\x03" + (0x40 + b.regnum_of(addr_reg) + (8 * b.regnum_of(key_reg))).chr }
173
174
sub4 = Proc.new { |b| sub_immediate(b.regnum_of(addr_reg), -4) }
175
add4 = Proc.new { |b| add_immediate(b.regnum_of(addr_reg), 4) }
176
177
if (datastore["BufferRegister"])
178
179
buff_reg = Rex::Poly::LogicalRegister::X86.new('buff', datastore["BufferRegister"])
180
offset = (datastore["BufferOffset"] ? datastore["BufferOffset"].to_i : 0)
181
if ((offset < -255 or offset > 255) and state.badchars.include? "\x00")
182
raise EncodingError.new("Can't generate NULL-free decoder with a BufferOffset bigger than one byte")
183
end
184
mov = Proc.new { |b|
185
# mov <buff_reg>, <addr_reg>
186
"\x89" + (0xc0 + b.regnum_of(addr_reg) + (8 * b.regnum_of(buff_reg))).chr
187
}
188
add_offset = Proc.new { |b| add_immediate(b.regnum_of(addr_reg), offset) }
189
sub_offset = Proc.new { |b| sub_immediate(b.regnum_of(addr_reg), -offset) }
190
191
getpc = Rex::Poly::LogicalBlock.new('getpc')
192
getpc.add_perm(Proc.new{ |b| mov.call(b) + add_offset.call(b) })
193
getpc.add_perm(Proc.new{ |b| mov.call(b) + sub_offset.call(b) })
194
195
# With an offset of less than four, inc is smaller than or the same size as add
196
if (offset > 0 and offset < 4)
197
getpc.add_perm(Proc.new{ |b| mov.call(b) + inc(b.regnum_of(addr_reg))*offset })
198
elsif (offset < 0 and offset > -4)
199
getpc.add_perm(Proc.new{ |b| mov.call(b) + dec(b.regnum_of(addr_reg))*(-offset) })
200
end
201
202
# NOTE: Adding a perm with possibly different sizes is normally
203
# wrong since it will change the SymbolicBlock::End offset during
204
# various stages of generation. In this case, though, offset is
205
# constant throughout the whole process, so it isn't a problem.
206
getpc.add_perm(Proc.new{ |b|
207
if (offset < -255 or offset > 255)
208
# lea addr_reg, [buff_reg + DWORD offset]
209
# NOTE: This will generate NULL bytes!
210
"\x8d" + (0x80 + b.regnum_of(buff_reg) + (8 * b.regnum_of(addr_reg))).chr + [offset].pack('V')
211
elsif (offset > -255 and offset != 0 and offset < 255)
212
# lea addr_reg, [buff_reg + byte offset]
213
"\x8d" + (0x40 + b.regnum_of(buff_reg) + (8 * b.regnum_of(addr_reg))).chr + [offset].pack('c')
214
else
215
# lea addr_reg, [buff_reg]
216
"\x8d" + (b.regnum_of(buff_reg) + (8 * b.regnum_of(addr_reg))).chr
217
end
218
})
219
220
# BufferReg+BufferOffset points right at the beginning of our
221
# buffer, so in contrast to the fnstenv technique, we don't have to
222
# sub off any other offsets.
223
xor1 = Proc.new { |b| xor.call(b) + [ (b.offset_of(endb) - cutoff) ].pack('c') }
224
xor2 = Proc.new { |b| xor.call(b) + [ (b.offset_of(endb) - 4 - cutoff) ].pack('c') }
225
add1 = Proc.new { |b| add.call(b) + [ (b.offset_of(endb) - cutoff) ].pack('c') }
226
add2 = Proc.new { |b| add.call(b) + [ (b.offset_of(endb) - 4 - cutoff) ].pack('c') }
227
228
else
229
# FPU blocks
230
fpu = Rex::Poly::LogicalBlock.new('fpu',
231
*fpu_instructions)
232
233
fnstenv = Rex::Poly::LogicalBlock.new('fnstenv',
234
"\xd9\x74\x24\xf4")
235
fnstenv.depends_on(fpu)
236
237
# Get EIP off the stack
238
getpc = Rex::Poly::LogicalBlock.new('getpc',
239
Proc.new { |b| (0x58 + b.regnum_of(addr_reg)).chr })
240
getpc.depends_on(fnstenv)
241
242
# Subtract the offset of the fpu instruction since that's where eip points after fnstenv
243
xor1 = Proc.new { |b| xor.call(b) + [ (b.offset_of(endb) - b.offset_of(fpu) - cutoff) ].pack('c') }
244
xor2 = Proc.new { |b| xor.call(b) + [ (b.offset_of(endb) - b.offset_of(fpu) - 4 - cutoff) ].pack('c') }
245
add1 = Proc.new { |b| add.call(b) + [ (b.offset_of(endb) - b.offset_of(fpu) - cutoff) ].pack('c') }
246
add2 = Proc.new { |b| add.call(b) + [ (b.offset_of(endb) - b.offset_of(fpu) - 4 - cutoff) ].pack('c') }
247
end
248
249
# Decoder loop block
250
loop_block = Rex::Poly::LogicalBlock.new('loop_block')
251
252
loop_block.add_perm(
253
Proc.new { |b| xor1.call(b) + add1.call(b) + sub4.call(b) },
254
Proc.new { |b| xor1.call(b) + sub4.call(b) + add2.call(b) },
255
Proc.new { |b| sub4.call(b) + xor2.call(b) + add2.call(b) },
256
Proc.new { |b| xor1.call(b) + add1.call(b) + add4.call(b) },
257
Proc.new { |b| xor1.call(b) + add4.call(b) + add2.call(b) },
258
Proc.new { |b| add4.call(b) + xor2.call(b) + add2.call(b) })
259
260
# Loop instruction block
261
loop_inst = Rex::Poly::LogicalBlock.new('loop_inst',
262
"\xe2\xf5")
263
# In the current implementation the loop block is a constant size,
264
# so really no need for a fancy calculation. Nevertheless, here's
265
# one way to do it:
266
#Proc.new { |b|
267
# # loop <loop_block label>
268
# # -2 to account for the size of this instruction
269
# "\xe2" + [ -2 - b.size_of(loop_block) ].pack('c')
270
#})
271
272
# Define block dependencies
273
clear_register.depends_on(getpc)
274
init_counter.depends_on(clear_register)
275
loop_block.depends_on(init_counter, init_key)
276
loop_inst.depends_on(loop_block)
277
278
begin
279
# Generate a permutation saving the ECX, ESP, and user defined registers
280
loop_inst.generate(block_generator_register_blacklist, nil, state.badchars)
281
rescue RuntimeError, EncodingError => e
282
# The Rex::Poly block generator can raise RuntimeError variants
283
raise EncodingError, e.to_s
284
end
285
end
286
287
# Convert the SaveRegisters to an array of x86 register constants
288
def saved_registers
289
Rex::Arch::X86.register_names_to_ids(datastore['SaveRegisters'])
290
end
291
292
def sub_immediate(regnum, imm)
293
return "" if imm.nil? or imm == 0
294
if imm > 255 or imm < -255
295
"\x81" + (0xe8 + regnum).chr + [imm].pack('V')
296
else
297
"\x83" + (0xe8 + regnum).chr + [imm].pack('c')
298
end
299
end
300
def add_immediate(regnum, imm)
301
return "" if imm.nil? or imm == 0
302
if imm > 255 or imm < -255
303
"\x81" + (0xc0 + regnum).chr + [imm].pack('V')
304
else
305
"\x83" + (0xc0 + regnum).chr + [imm].pack('c')
306
end
307
end
308
def inc(regnum)
309
[0x40 + regnum].pack('C')
310
end
311
def dec(regnum)
312
[0x48 + regnum].pack('C')
313
end
314
end
315
316