-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathencoder.go
More file actions
511 lines (463 loc) · 12.1 KB
/
encoder.go
File metadata and controls
511 lines (463 loc) · 12.1 KB
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
package ssce
import (
"bytes"
cr "crypto/rand"
"encoding/binary"
"errors"
"fmt"
"maps"
"math"
"math/rand"
"slices"
"strings"
"text/template"
"time"
"github.com/For-ACGN/go-keystone"
)
var (
registerX86 = []string{
"eax", "ebx", "ecx", "edx",
"ebp", "esi", "edi",
}
registerX64 = []string{
"rax", "rbx", "rcx", "rdx",
"rbp", "rsi", "rdi",
}
)
// Encoder is a simple shellcode encoder.
type Encoder struct {
rand *rand.Rand
// assembler engine
ase32 *keystone.Engine
ase64 *keystone.Engine
// context arguments
arch int
opts *Options
key []byte
// stub key for xor stubs
stubKey any
// save and restore context
contextSeq []int
// for select random register
regBox []string
}
// Options contains options about encode shellcode.
type Options struct {
// the number of iterate.
NumIterate int `toml:"num_iterate" json:"num_iterate"`
// the size of the garbage instruction at tail.
NumTailInst int `toml:"num_tail_inst" json:"num_tail_inst"`
// only use the mini loader, not use loader
// for erase shellcode and more feature.
MinifyMode bool `toml:"minify_mode" json:"minify_mode"`
// save and restore context after call shellcode.
SaveContext bool `toml:"save_context" json:"save_context"`
// erase loader instruction and shellcode after call it.
EraseInst bool `toml:"erase_inst" json:"erase_inst"`
// disable iterator, not recommend.
NoIterator bool `toml:"no_iterator" json:"no_iterator"`
// disable garbage instruction, not recommend.
NoGarbage bool `toml:"no_garbage" json:"no_garbage"`
// specify a random seed for encoder.
RandSeed int64 `toml:"rand_seed" json:"rand_seed"`
// trim the seed at the tail of output.
TrimSeed bool `toml:"trim_seed" json:"trim_seed"`
// specify the x86 mini decoder template.
MiniDecoderX86 string `toml:"mini_decoder_x86" json:"mini_decoder_x86"`
// specify the x64 mini decoder template.
MiniDecoderX64 string `toml:"mini_decoder_x64" json:"mini_decoder_x64"`
// specify the x86 loader template.
LoaderX86 string `toml:"loader_x86" json:"loader_x86"`
// specify the x64 loader template.
LoaderX64 string `toml:"loader_x64" json:"loader_x64"`
// specify the x86 junk code templates.
JunkCodeX86 []string `toml:"junk_code_x86" json:"junk_code_x86"`
// specify the x64 junk code templates.
JunkCodeX64 []string `toml:"junk_code_x64" json:"junk_code_x64"`
}
// Context contains the output and context data in Encode.
type Context struct {
Output []byte `json:"output"`
Seed int64 `json:"seed"`
NumIterate int `json:"num_iterate"`
MinifyMode bool `json:"minify_mode"`
NoGarbage bool `json:"no_garbage"`
SaveContext bool `json:"save_context"`
EraseInst bool `json:"erase_inst"`
}
// NewEncoder is used to create a simple shellcode encoder.
func NewEncoder() *Encoder {
var seed int64
buf := make([]byte, 8)
_, err := cr.Read(buf)
if err == nil {
seed = int64(binary.LittleEndian.Uint64(buf)) // #nosec G115
} else {
seed = time.Now().UTC().UnixNano()
}
encoder := Encoder{
rand: rand.New(rand.NewSource(seed)), // #nosec
}
return &encoder
}
// Encode is used to encode input shellcode to a unique shellcode.
func (e *Encoder) Encode(shellcode []byte, arch int, opts *Options) (ctx *Context, err error) {
defer func() {
if r := recover(); r != nil {
err = errors.New(fmt.Sprint(r))
}
}()
if len(shellcode) == 0 {
return nil, errors.New("empty shellcode")
}
switch arch {
case 32, 64:
default:
return nil, fmt.Errorf("unsupported architecture: %d", arch)
}
if opts == nil {
opts = new(Options)
}
e.arch = arch
e.opts = opts
// initialize keystone engine
err = e.initAssembler()
if err != nil {
return nil, fmt.Errorf("failed to initialize assembler: %s", err)
}
// set random seed
seed := opts.RandSeed
if seed == 0 {
seed = e.rand.Int63()
}
e.rand.Seed(seed)
// encode the raw shellcode and add loader
output, err := e.addLoader(shellcode)
if err != nil {
return nil, err
}
// insert mini decoder at the prefix
output, err = e.addMiniDecoder(output)
if err != nil {
return nil, err
}
// iterate the encoding of the pre-decoder and part of the shellcode
numIter := opts.NumIterate
if numIter < 1 {
numIter = 2 + e.rand.Intn(4)
}
if opts.NoIterator {
numIter = 0
}
for i := 0; i < numIter; i++ {
output, err = e.addMiniDecoder(output)
if err != nil {
return nil, err
}
}
// padding garbage at the tail
if !opts.NoGarbage {
times := 8 + e.rand.Intn((numIter+1)*4)
size := e.rand.Intn(16 * times)
output = append(output, e.randBytes(size)...)
}
// append garbage data to tail for prevent brute-force
output = append(output, e.randBytes(opts.NumTailInst)...)
// append garbage data to the output shellcode prefix
output = append(e.garbageInst(), output...)
// append the random seed to tail
if !opts.TrimSeed {
buf := binary.BigEndian.AppendUint64(nil, uint64(seed)) // #nosec G115
output = append(output, buf...)
}
// build encode context for test and debug
ctx = &Context{
Output: output,
Seed: seed,
NumIterate: numIter,
MinifyMode: opts.MinifyMode,
NoGarbage: opts.NoGarbage,
SaveContext: opts.SaveContext,
EraseInst: opts.EraseInst,
}
return ctx, nil
}
func (e *Encoder) initAssembler() error {
var (
ase *keystone.Engine
err error
)
switch e.arch {
case 32:
if e.ase32 != nil {
return nil
}
ase, err = keystone.NewEngine(keystone.ARCH_X86, keystone.MODE_32)
if err != nil {
return err
}
e.ase32 = ase
case 64:
if e.ase64 != nil {
return nil
}
ase, err = keystone.NewEngine(keystone.ARCH_X86, keystone.MODE_64)
if err != nil {
return err
}
e.ase64 = ase
default:
panic("unreachable code")
}
return ase.Option(keystone.OPT_SYNTAX, keystone.OPT_SYNTAX_INTEL)
}
func (e *Encoder) assemble(src string) ([]byte, error) {
if strings.Contains(src, "<no value>") {
return nil, errors.New("invalid register in assembly source")
}
if strings.Contains(src, "<nil>") {
return nil, errors.New("invalid usage in assembly source")
}
switch e.arch {
case 32:
return e.ase32.Assemble(src, 0)
case 64:
return e.ase64.Assemble(src, 0)
default:
panic("unreachable code")
}
}
func (e *Encoder) addLoader(shellcode []byte) ([]byte, error) {
if e.opts.MinifyMode {
return shellcode, nil
}
var loader string
switch e.arch {
case 32:
loader = e.getLoaderX86()
case 64:
loader = e.getLoaderX64()
}
asm, sc, err := e.buildLoader(loader, shellcode)
if err != nil {
return nil, err
}
inst, err := e.assemble(asm)
if err != nil {
return nil, err
}
return append(inst, sc...), nil
}
func (e *Encoder) buildLoader(loader string, shellcode []byte) (string, []byte, error) {
// append instructions for "IV" about encoder
shellcode = append(e.garbageInst(), shellcode...)
// append instructions to tail for prevent brute-force
tail := e.randBytes(64 + len(shellcode)/40)
shellcode = append(shellcode, tail...)
// generate crypto key for shellcode decoder
cryptoKey := e.randBytes(32)
var (
stubKey any
eraserLen int
)
switch e.arch {
case 32:
stubKey = e.rand.Uint32()
eraserLen = len(eraserX86) + e.rand.Intn(len(cryptoKey))
shellcode = encrypt32(shellcode, cryptoKey)
case 64:
stubKey = e.rand.Uint64()
eraserLen = len(eraserX64) + e.rand.Intn(len(cryptoKey))
shellcode = encrypt64(shellcode, cryptoKey)
}
e.key = cryptoKey
e.stubKey = stubKey
// parse loader template
tpl, err := template.New("loader").Funcs(template.FuncMap{
"db": toDB,
"hex": toHex,
"igi": e.insertGarbageInst,
}).Parse(loader)
if err != nil {
return "", nil, fmt.Errorf("invalid assembly source template: %s", err)
}
ctx := loaderCtx{
StubKey: stubKey,
DecoderStub: e.decoderStub(),
EraserStub: e.eraserStub(),
CryptoKeyStub: e.cryptoKeyStub(),
CryptoKeyLen: len(cryptoKey),
ShellcodeLen: len(shellcode),
EraserLen: eraserLen,
EraseShellcode: e.opts.EraseInst,
}
if e.opts.SaveContext {
ctx.SaveContext = e.saveContext()
ctx.RestoreContext = e.restoreContext()
}
// build source from template and assemble it
buf := bytes.NewBuffer(make([]byte, 0, 4096))
err = tpl.Execute(buf, &ctx)
if err != nil {
return "", nil, fmt.Errorf("failed to build assembly source: %s", err)
}
return buf.String(), shellcode, nil
}
func (e *Encoder) addMiniDecoder(input []byte) ([]byte, error) {
var miniDecoder string
switch e.arch {
case 32:
miniDecoder = e.getMiniDecoderX86()
case 64:
miniDecoder = e.getMiniDecoderX64()
}
asm, body, err := e.buildMiniDecoder(miniDecoder, input)
if err != nil {
return nil, err
}
inst, err := e.assemble(asm)
if err != nil {
return nil, err
}
return append(inst, body...), nil
}
func (e *Encoder) buildMiniDecoder(decoder string, input []byte) (string, []byte, error) {
// parse mini decoder template
tpl, err := template.New("mini_decoder").Funcs(template.FuncMap{
"db": toDB,
"hex": toHex,
"igi": e.insertGarbageInst,
"igs": e.insertGarbageInstShort,
}).Parse(decoder)
if err != nil {
return "", nil, fmt.Errorf("invalid assembly source template: %s", err)
}
seed := e.rand.Uint32()
key := e.rand.Uint32()
body := e.xsrl(input, seed, key)
numLoopMaskA := e.rand.Int31()
numLoopMaskB := e.rand.Int31()
numLoopStub := int32(len(body)/4) ^ numLoopMaskA ^ numLoopMaskB // #nosec G115
offsetT := e.rand.Int31n(math.MaxInt32/4 - 4096)
offsetA := e.rand.Int31n(math.MaxInt32/4 - 8192)
offsetS := offsetT + offsetA
ctx := miniDecoderCtx{
Seed: seed,
Key: key,
NumLoopStub: numLoopStub,
NumLoopMaskA: numLoopMaskA,
NumLoopMaskB: numLoopMaskB,
OffsetT: offsetT,
OffsetA: offsetA,
OffsetS: offsetS,
Reg: e.buildRandomRegisterMap(),
}
// add padding data at tail of mini decoder
if !e.opts.MinifyMode {
ctx.Padding = true
ctx.PadData = e.randBytes(8 + e.rand.Intn(48))
}
// build source from template and assemble it
buf := bytes.NewBuffer(make([]byte, 0, 512))
err = tpl.Execute(buf, &ctx)
if err != nil {
return "", nil, fmt.Errorf("failed to build assembly source: %s", err)
}
return buf.String(), body, nil
}
func (e *Encoder) getMiniDecoderX86() string {
if e.opts.MiniDecoderX86 != "" {
return e.opts.MiniDecoderX86
}
return defaultMiniDecoderX86
}
func (e *Encoder) getMiniDecoderX64() string {
if e.opts.MiniDecoderX64 != "" {
return e.opts.MiniDecoderX64
}
return defaultMiniDecoderX64
}
func (e *Encoder) getLoaderX86() string {
if e.opts.LoaderX86 != "" {
return e.opts.LoaderX86
}
return defaultLoaderX86
}
func (e *Encoder) getLoaderX64() string {
if e.opts.LoaderX64 != "" {
return e.opts.LoaderX64
}
return defaultLoaderX64
}
func (e *Encoder) randBytes(n int) []byte {
buf := make([]byte, n)
_, _ = e.rand.Read(buf)
return buf
}
func (e *Encoder) buildRandomRegisterMap() map[string]string {
var reg []string
switch e.arch {
case 32:
reg = slices.Clone(registerX86)
case 64:
reg = slices.Clone(registerX64)
}
e.regBox = reg
register := make(map[string]string, 16)
switch e.arch {
case 32:
for _, reg := range registerX86 {
register[reg] = e.selectRegister()
}
case 64:
for _, reg := range registerX64 {
register[reg] = e.selectRegister()
}
e.buildLowBitRegisterMap(register)
}
return register
}
func (e *Encoder) buildLowBitRegisterMap(register map[string]string) {
// build register map about low dword
low := make(map[string]string, len(register))
for reg, act := range register {
low[toRegDWORD(reg)] = toRegDWORD(act)
}
maps.Copy(register, low)
}
// selectRegister is used to make sure each register will be selected once.
func (e *Encoder) selectRegister() string {
idx := e.rand.Intn(len(e.regBox))
reg := e.regBox[idx]
// remove selected register
e.regBox = append(e.regBox[:idx], e.regBox[idx+1:]...)
return reg
}
func (e *Encoder) insertGarbageInst() string {
if e.opts.NoGarbage {
return ""
}
return ";" + toDB(e.garbageInst())
}
func (e *Encoder) insertGarbageInstShort() string {
if e.opts.NoGarbage {
return ""
}
return ";" + toDB(e.garbageInstShort())
}
// Close is used to close shellcode encoder.
func (e *Encoder) Close() error {
if e.ase32 != nil {
err := e.ase32.Close()
if err != nil {
return err
}
}
if e.ase64 != nil {
err := e.ase64.Close()
if err != nil {
return err
}
}
return nil
}