-
Notifications
You must be signed in to change notification settings - Fork 0
/
dinvoke.nim
266 lines (219 loc) · 9.08 KB
/
dinvoke.nim
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
import winim
import tables
import strformat
import algorithm
import obf
when defined(WIN64):
const
PEB_OFFSET* = 0x30
else:
const
PEB_OFFSET* = 0x60
const
LdrLoadDll_SW2 * = obf("LdrLoadDll")
MZ* = 0x5A4D
const
NTDLL_DLL* = obf("ntdll.dll")
type
LdrLoadDll_t* = proc (PathToFile: PWCHAR, Flags: ULONG, ModuleFileName: PUNICODE_STRING, ModuleHandle: PHANDLE): NTSTATUS {.stdcall.}
type
ND_LDR_DATA_TABLE_ENTRY* {.bycopy.} = object
InMemoryOrderLinks*: LIST_ENTRY
InInitializationOrderLinks*: LIST_ENTRY
DllBase*: PVOID
EntryPoint*: PVOID
SizeOfImage*: ULONG
FullDllName*: UNICODE_STRING
BaseDllName*: UNICODE_STRING
PND_LDR_DATA_TABLE_ENTRY* = ptr ND_LDR_DATA_TABLE_ENTRY
ND_PEB_LDR_DATA* {.bycopy.} = object
Length*: ULONG
Initialized*: UCHAR
SsHandle*: PVOID
InLoadOrderModuleList*: LIST_ENTRY
InMemoryOrderModuleList*: LIST_ENTRY
InInitializationOrderModuleList*: LIST_ENTRY
PND_PEB_LDR_DATA* = ptr ND_PEB_LDR_DATA
ND_PEB* {.bycopy.} = object
Reserved1*: array[2, BYTE]
BeingDebugged*: BYTE
Reserved2*: array[1, BYTE]
Reserved3*: array[2, PVOID]
Ldr*: PND_PEB_LDR_DATA
PND_PEB* = ptr ND_PEB
proc GetPPEB(p: culong): P_PEB {.
header:
"""#include <windows.h>
#include <winnt.h>""",
importc: "__readgsqword"
.}
template RVA*(atype: untyped, base_addr: untyped, rva: untyped): untyped = cast[atype](cast[ULONG_PTR](cast[ULONG_PTR](base_addr) + cast[ULONG_PTR](rva)))
template RVASub*(atype: untyped, base_addr: untyped, rva: untyped): untyped = cast[atype](cast[ULONG_PTR](cast[ULONG_PTR](base_addr) - cast[ULONG_PTR](rva)))
template RVA2VA(casttype, dllbase, rva: untyped): untyped =
cast[casttype](cast[ULONG_PTR](dllbase) + rva)
proc `+`[T](a: ptr T, b: int): ptr T =
cast[ptr T](cast[uint](a) + cast[uint](b * a[].sizeof))
proc `-`[T](a: ptr T, b: int): ptr T =
cast[ptr T](cast[uint](a) - cast[uint](b * a[].sizeof))
proc is_dll*(hLibrary: PVOID): BOOL
proc get_library_address*(LibName: LPWSTR; DoLoad: BOOL): HANDLE
proc get_function_address*(hLibrary: HMODULE; fname: cstring; ordinal: int, specialCase: BOOL): PVOID
proc is_dll*(hLibrary: PVOID): BOOL =
var dosHeader: PIMAGE_DOS_HEADER
var ntHeader: PIMAGE_NT_HEADERS
if (hLibrary == nil):
when not defined(release):
echo "[-] hLibrary == 0, exiting"
return FALSE
dosHeader = cast[PIMAGE_DOS_HEADER](hLibrary)
#echo "Got dos Header"
## check the MZ magic bytes
if dosHeader.e_magic != MZ:
when not defined(release):
echo "[-] No Magic bytes found"
return FALSE
ntHeader = cast[PIMAGE_NT_HEADERS](cast[DWORD_PTR](hLibrary) + dosHeader.e_lfanew)
#echo "Got NT Headers"
## check the NT_HEADER signature
if ntHeader.Signature != IMAGE_NT_SIGNATURE:
when not defined(release):
echo "[-] Nt Header signature wrong, exiting"
return FALSE
var Characteristics: USHORT = ntHeader.FileHeader.Characteristics
if (Characteristics and IMAGE_FILE_DLL) != IMAGE_FILE_DLL:
when not defined(release):
echo "[-] Characteristics shows this is not an DLL, exiting"
return FALSE
#echo "Everything fine, this is indeed a DLL"
return TRUE
##
## Get the base address of a DLL
##
proc get_library_address*(LibName: LPWSTR; DoLoad: BOOL): HANDLE =
when not defined(release):
echo "\r\n[*] Parsing the PEB to search for the target DLL\r\n"
var Peb: PPEB = GetPPEB(PEB_OFFSET)
var Ldr = Peb.Ldr
var FirstEntry: PVOID = addr(Ldr.InMemoryOrderModuleList.Flink)
var Entry: PND_LDR_DATA_TABLE_ENTRY = cast[PND_LDR_DATA_TABLE_ENTRY](Ldr.InMemoryOrderModuleList.Flink)
while true:
# lstrcmpiW is not case sensitive, lstrcmpW is case sensitive
var compare: int = lstrcmpiW(LibName,cast[LPWSTR](Entry.BaseDllName.Buffer))
if(compare == 0):
#echo "DLL names equal"
when not defined(release):
echo "\r\n[+] Found the DLL!\r\n"
return cast[HANDLE](Entry.DllBase)
Entry = cast[PND_LDR_DATA_TABLE_ENTRY](Entry.InMemoryOrderLinks.Flink)
if not (Entry != FirstEntry):
when not defined(release):
echo "DLL not found for the current proc, loading."
break
if (DoLoad == FALSE):
echo "Exit, loading is not appreciated"
return 0
var MyLdrLoadDll: LdrLoadDll_t = cast[LdrLoadDll_t](cast[LPVOID](get_function_address(cast[HMODULE](get_library_address(NTDLL_DLL, FALSE)), LdrLoadDll_SW2, 0, TRUE)))
if MyLdrLoadDll == nil:
echo "[-] Address of LdrLoadDll not found"
return 0
var ModuleFileName: UNICODE_STRING
var hLibrary: HANDLE = 0
RtlInitUnicodeString(&ModuleFileName, LibName)
## load the library
var status: NTSTATUS = MyLdrLoadDll(nil, 0, &ModuleFileName, &hLibrary)
if (status != 0):
echo fmt"[-] Failed to load {Libname}, status: {status}\n"
if (hLibrary == 0):
echo "HLibrary still null"
return 0
else:
echo fmt"Loaded {LibName} successfully!"
echo fmt"[+] Loaded {LibName} at {hLibrary}"
return hLibrary
##
## Find an export in a DLL
##
proc get_function_address*(hLibrary: HMODULE; fname: cstring; ordinal: int, specialCase: BOOL): PVOID =
var dos: PIMAGE_DOS_HEADER
var nt: PIMAGE_NT_HEADERS
#var data: PIMAGE_DATA_DIRECTORY
var data: array[0..15, IMAGE_DATA_DIRECTORY]
var exp: PIMAGE_EXPORT_DIRECTORY
var exp_size: DWORD
var adr: PDWORD
var ord: PDWORD
var functionAddress: PVOID
var toCheckLibrary: PVOID = cast[PVOID](hLibrary)
if (is_dll(toCheckLibrary) == FALSE):
echo "[-] Exiting, not a DLL"
return nil
dos = cast[PIMAGE_DOS_HEADER](hLibrary)
nt = RVA(PIMAGE_NT_HEADERS, cast[PVOID](hLibrary), dos.e_lfanew)
data = nt.OptionalHeader.DataDirectory
if (data[0].Size == 0 or data[0].VirtualAddress == 0):
echo "[-] Data size == 0 or no VirtualAddress"
return nil
exp = RVA(PIMAGE_EXPORT_DIRECTORY, hLibrary, data[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress)
exp_size = data[0].Size
adr = RVA2VA(PDWORD, cast[DWORD_PTR](hLibrary), exp.AddressOfFunctions)
ord = RVA2VA(PDWORD, cast[DWORD_PTR](hLibrary), exp.AddressOfNameOrdinals)
functionAddress = nil
var numofnames = cast[DWORD](exp.NumberOfNames)
var functions = RVA2VA(PDWORD, cast[PVOID](hLibrary), exp.AddressOfFunctions)
var addressOfFunctionsvalue = RVA2VA(PDWORD, cast[PVOID](hLibrary), exp.AddressOfFunctions)[]
var names = RVA2VA(PDWORD, cast[PVOID](hLibrary), exp.AddressOfNames)[]
#echo "\r\n[*] Checking DLL's Export Directory for the target function\r\n"
if fname != "":
## iterate over all the exports
#var i: DWORD = 0
for i in 0 .. numofnames:
# Getting the function name value
var funcname = RVA2VA(cstring, cast[PVOID](hLibrary), names)
var finalfunctionAddress = RVA(PVOID, cast[PVOID](hLibrary), addressOfFunctionsvalue)
# We are comparing against function names, which include "." because for some reason all function names in this loop also contain references to other DLLs, e.g. "api-ms-win-core-libraryloader-l1-1-0.AddDllDirectory" in kernel32.dll
var test = StrRStrIA(cast[LPCSTR](funcname),nil,cast[LPCSTR]("."))
if test != nil:
# As we found a trash (indirect reference, normally this is in the address field and not in the names field) function, we have to increase this value -> Not an official function
numofnames = numofnames + 1
else:
functions = functions + 1
addressOfFunctionsvalue = functions[]
#echo "Relative Address: ", toHex(functions[])
names += cast[DWORD](len(funcname) + 1)
#echo "Function: ", funcname
if fname == funcname:
# So many edge cases, have to investigate
if (funcname == "CreateFileW"):
functions = functions - 1
if (funcname == "SetFileInformationByHandle"):
functions = functions - 1
if (funcname == "CloseHandle"):
functions = functions - 1
if (funcname == "GetModuleFileNameW"):
functions = functions - 1
#echo "\r\n[+] Found API call: ",funcname
#echo "\r\n"
# Strange. For ntdll functions the following is needed, but for kernel32 functions it's not. Don't ask me why. This is a workaround for the moment. Need to troubleshoot.
if (specialCase):
# Why?
#echo "This is a special case, subtract one function"
finalfunctionAddress = RVA(PVOID, cast[PVOID](hLibrary), addressOfFunctionsvalue)
#echo "Relative Address: ", toHex(functions[])
functions = functions - 1
#echo "Relative Address one before: ", toHex(functions[])
functions = functions + 2
#echo "Relative Address one after: ", toHex(functions[])
functionAddress = finalfunctionAddress
break
else:
# Add the ordinal number e.g. 1034 for OpenProcess and - the EXP Base address
#echo fmt"Getting address via ordinal: {ordinal}"
functions = functions + ordinal - 1
functionAddress = RVA(PVOID, hLibrary, functions[])
#echo "Relative Address: ", toHex(functions[])
#echo "Function address via ordinal:"
#echo repr(functionAddress)
if functionAddress == nil:
return nil
else:
return functionAddress