TrashFormer is a 64 bit junk code engine made to provide code that does not affect the behaviour of the program but lets malware reprogram itself on each infection.
- TrashFormer is a full cycle divided into three phases, responsible for placing the appropriate instructions, including filtering.
- As mentioned above,
xchgand many other instructions are excluded. In fact, onlymov,or,xor,cmp, andleaare supported. - The engine is designed to insert a few instructions between executions. The idea is to avoid drawing much attention while still creating maximum distraction.
- It is written 100% in assembly, specifically for MASM (Microsoft Assembler).
- It's called from C++ for ease of integration and display.
- In the code, I deliberately avoid using the stack, keeping it clean (except for
pushandpop). Everything is handled via variables and registers:rax,rdx,rdx,r8, andr9.
You can find an explanation of the internals of both this engine and ETG, created by z0mbie and the engine that inspired TrashFormer, on my blog post Junk Code Engines for Polymorphic Malware
Here’s a proof of concept demonstrating how the engine works. The result is a fully executable buffer.
...
unsigned int result = TrashFormer(pTrashBuffer, 300, (((reg_any) << 24) | ((any_cmd) << 16) | ((reg_any_any) << 8) | (0xFF)));
...Here's the buffer:
0x49, 0x33, 0xDB, 0x48, 0x0B, 0xC2, 0x4C, 0x0B,
0xC2, 0x48, 0x8B, 0xC1, 0x4D, 0x0B, 0xC0, 0x48,
0x3B, 0xC1, 0x49, 0x8B, 0xC8, 0x48, 0x3B, 0xC2,
0x48, 0x3B, 0xC1, 0x48, 0x33, 0xC1, 0x49, 0x8B,
0xC0, 0x4C, 0x33, 0xCA, 0x49, 0x0B, 0xCA, 0x4D,
0x8B, 0xDB, 0x4D, 0x0B, 0xDB, 0x4D, 0x33, 0xC3,
0x48, 0x33, 0xC2, 0x48, 0x33, 0xC2, 0x4D, 0x33,
0xDB, 0x48, 0x0B, 0xC0, 0x4C, 0x3B, 0xCA, 0x48,
0x33, 0xC3, 0x4D, 0x33, 0xC2, 0x4D, 0x0B, 0xDB,
0x48, 0x8B, 0xCA, 0x48, 0x0B, 0xD0, 0x48, 0x8B,
0xC1, 0x4D, 0x0B, 0xC0, 0x48, 0x8B, 0xDB, 0x4D,
0x33, 0xC3, 0x4C, 0x3B, 0xC1, 0x49, 0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
0xC9, 0x48, 0x0B, 0xCA, 0xC3, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
Here's the generated code:
4C 3B D2 cmp r10,rdx
49 33 C1 xor rax,r9
4C 8B D0 mov r10,rax
48 8D 02 lea rax,[rdx]
49 8B D0 mov rdx,r8
4D 8B C2 mov r8,r10
4C 3B DB cmp r11,rbx
Then we can execute the buffer to test if we get any error
...
(*(void(*)())(void*)pTrashBuffer) ();
...