Exetools

Exetools (https://forum.exetools.com/index.php)
-   General Discussion (https://forum.exetools.com/forumdisplay.php?f=2)
-   -   Creating a Loader to modify a DLL file (https://forum.exetools.com/showthread.php?t=5283)

<|nAbOo|> 09-08-2004 23:53

Creating a Loader to modify a DLL file
 
Hi,

well i have a small question concerning Loaders.

Lets imagine i have a EXE file and a DLL file which check eachother for
CRC and different things and dont like modifying. The idea now is to create
a loader which patches the files in memory at runtime. For the EXE file i can use the following APIs to modify the code in memory:

invoke CreateProcessA,offset LoadszFileName,0,0,0,0,CREATE_SUSPENDED, \
0,0,offset LoadlpStartupInfo,offset LoadlpProcessInfo

invoke WriteProcessMemory,LoadlpProcessInfo.hProcess,LoadlpBaseAddress, \
offset LoadlpBuffer,LoadcbWrite,NULL

invoke ResumeThread,LoadlpProcessInfo.hThread

Now my question: How can i modify a DLL file in memory using such tactic.
Someone ever tried things like that before ?

Thanks in Advance
naboo

Neitsa 09-09-2004 00:12

Hello,

Sice a DLL is mapped in the process address space, you can patch it easily, as you would nomally do with an executable file.

Fist of all, get the Image_Base address of the DLL (PE signature + 0x34) in an hex or PE editor and do appropriate VA/RVA conversion to get the location of the bytes to patch. On the other hand you can debug the DLL to get the exact location of the bytes to patch. Just get the address and the bytes to patch in the DLL, that's all !

(If you use OllyDBG, just do an ALT+M to see the process adress space, there you can locate you DLL and dump it in the disassembler view).

Another thing (maybe I've misunderstood what you want to patch), patching at runtime won't disable the CRC check, if you don't patch the check itself, since the loader will patch just after the thread came alive in the O.S, the CRC check will be performed, and your patched bytes will be caught.

Patch the executable crc check, patch the DLL crc check as you normally do with the EXE.

Regards, Neitsa.

Crk 09-09-2004 01:30

i see... but this dosen't explain "how to do it" as i see he meanded how to implement a process patch as it's done for normal exe files... you know loader,most of them in most cases, bypass crc checks when patching in mem. i have never see a loader for a packed .dll .. but i know if the exe loads(loadlibraryexa or loadlibrarya ?) a dll in start up maybe some code could be injected in the exe to patch the dll after been loaded.. this is an idea . i'm really interested for this topic since i got a case which the exe calls aprotected .dll .. and the dll controls evertyhing (OEP,Trial.......) the exe do an integrity check for the dll .. i wonder how could be patched and if it's possible to do someking of loader/injected code for a protected/packed .dll

Regards

<|nAbOo|> 09-09-2004 03:34

CRK is on the right way. The idea here is to just patch the program in memory. No hard patching like using Hiew and so. Getting the imagebase for an unloaded DLL is easy in this case you just need to disassemble it for example with IDA. But remember one thing: Lets say i have 2 DLLs and both want to use the same Imagebase for example 10001000 here then one will be put at a different location e.g. 3DFB0000 or whatever. So of course the first goal is getting the imagebase of the LOADED Dll file. Afterwards i want to patch the DLL in memory.

Neitsa: well you said i couldnt bypass CRC checks with that. In my case i could bypass the CRC checks with this because they are performed on the Files itself. The CRC check is not performed on the loaded Program in memory. So in most cases you could bypass a CRC check by using a Loader.

Additionally lets imagine i know the bytes i want to change lets for say easyness i want to change the bytes at location 10004324 74 0B to 10004324 EB 0B where the imagebase of the DLL is 10001000 in this case and the DLL is unloaded in this case.

Some Codesnippets or a small example of how to obtain the real virtual address of the DLL when loaded to memory and patch it afterwards in memory would be really nice.

Thanks in advance

Neitsa 09-09-2004 06:11

Hello,

Quote:

In my case i could bypass the CRC checks with this because they are performed on the Files itself
:D Damn, if I'm programming a CRC check I would do it both on file and memory ! So ok, if it's done only on file, you're right, please forgive me.

As you're creating yourself the process, retrieving the DLL base is easy with this API: EnumProcessModules.

Then you can extract some information with those API's:

-GetModuleBaseName
-GetModuleFileName
-GetModuleInformation

There's also another by getting the PEB of the process, and reading some fields from it. In fact interesting fields for your case are located in the PEB_LDR_DATA struct which is a currently holding information about Loaded modules. This is a far complex way to retrieve the same informations.

A problem comes when the DLL isn't loaded in the program and will be loaded later with a 'LoadLibrary'.

Well, one possibility :
-Hooking the LoadLibrary function from the program and then performing the above trick.

Maybe threre are some other ways when the DLL is not loaded when launching the program but I can't see them...

I'll try to code something, try also on your side.

Regards, Neitsa.

Crudd[RET] 09-10-2004 09:15

Heres an asm example of retrieving imagebase without using any apis (in case you dont wanna worry about importing new functions):
hxxp://spiff.tripnet.se/~iczelion/files/kernel.zip
The GetKernalBase proc is the one you want, and it shows the implementation at main. If you need some help with the example, let me know. Its pretty simple though.
Crudd [RET]

xastey 09-10-2004 11:47

i found that abel loader generator v2.30 and DAZAPATCHER work great when you need to patch a protected .dll file. Used both of them with arma apps and hasn't failed me now :D

xobor 09-10-2004 15:06

you can do something like

Code:

        if(!CreateProcess(name,...))
        {
                printf("err createprocess");
            return 0;
        }

DebugLoop:

        WaitForDebugEvent(&DebugEvent, INFINITE);
        if(DebugEvent.dwDebugEventCode==LOAD_DLL_DEBUG_EVENT)
        {
          //DebugEvent.u.LoadDll.lpBaseOfDll - is base of dll
            }
.
.
.

maybe it helps

Crk 09-10-2004 21:15

i found that abel loader generator v2.30 and DAZAPATCHER work great when you need to patch a protected .dll file.

how? if loaders run an exe target .. how you patch those dll in mem. with a loader...

xastey 09-10-2004 22:16

i just set it to load the exe and then set the patch data to the offest of the .dll

Line79 09-11-2004 01:17

Hello,

I don't understand the problem here.

The dll will be loaded in the SAME context than the EXE file.
Therefore, you could patch the dll if you could control the EXE file code.

But what you can just do, is CreateProcess the EXE file, and then, instead of providing a VA inside the Target EXE (which you don't want to do, since you want to patch the dll), you just provide a VA inside the DLL to WriteProcessMemory, and since , the dll is in the same Address space (context) than the EXE file, you writeprocessmemory will work, and thus, you will be patching your protected dll without problems.

Cheers.

Peace99 09-12-2004 03:09

1 Attachment(s)
I just use this trick

just use Process Patcher v3.60
Search memory address you want to patch and create Process Patcher v3.60
it's will patch memory on the fly.

see my attachment in powerbasic source (to enable official counter-strike 1.6 bots.)

I use this trick, convert Process Patcher v3.60 to hex and store inside the source code. see the source for detail.

this how i create loader/launcher.

[NtSC] 10-04-2004 02:46

...
 
You can use CreateProcess to create The Process itself..Depending on the OS the Dlls are loaded by then,or arent. For an NT based OS i would Create the Process, put an EBFE on the Entrypoint, execute it and catch it to make sure all Dlls are proper loaded. The you loop the loaded Modules with the ToolHelp Functions and compare the Dllnames with the Name of the Dll you seek. The Toolhelp Functions will also return the BaseAdress, so you can use that with a Distance Value to patch your Stuff.

vrclr27 10-05-2004 14:02

Interesting articles
 
There are also some interesting articles on this subject in:
help://bib.universitas-virtualis.org

Sorry, not in the library but part of the CodeBreaker Mag. at same location

Newbie_Cracker 03-11-2005 14:02

OK guys, lets ask the question a little different.
Think we have a program and its serial-check routine, is in a DLL which is in its resource. Program runs and after a few seconds, loads the DLL and read a function from it.
Using constant address for writing to memory is not possible. Because the addresses change.

Now, how could we get some RVA in DLL to calculate the patch address?
I can get DLL ProcessID after showing some window, but couldn't get one of its fucntion address or its OEP in memory. :(

Shub-Nigurrath 03-11-2005 17:02

I did it simpler. I coded a stub for the real dll: a new dll exposing the same methods of the original dll, eventually through export forwarding if you don't know the original DLL prototypes.

from matt Pietrek..
Quote:

Export Forwarding
A particularly slick feature of exports is the ability to "forward" an export to another DLL. For example, in Windows NT&#174;, Windows&#174; 2000, and Windows XP, the KERNEL32 HeapAlloc function is forwarded to the RtlAllocHeap function exported by NTDLL. Forwarding is performed at link time by a special syntax in the EXPORTS section of the .DEF file. Using HeapAlloc as an example, KERNEL32's DEF file would contain:

EXPORTS
•••
HeapAlloc = NTDLL.RtlAllocHeap

How can you tell if a function is forwarded rather than exported normally? It's somewhat tricky. Normally, the EAT contains the RVA of the exported symbol. However, if the function's RVA is inside the exports section (as given by the VirtualAddress and Size fields in the DataDirectory), the symbol is forwarded.
When a symbol is forwarded, its RVA obviously can't be a code or data address in the current module. Instead, the RVA points to an ASCII string of the DLL and symbol name to which it is forwarded. In the prior example, it would be NTDLL.RtlAllocHeap.
The what I did is to code my DllMain and insert the patching code into the DLL_PROCESS_ATTACH case.

The patched code does these things:
-load the original renamed library (with a leading _ )
-initialize the exports I would to overwrite (if any) through GetProcAddress.
-patch the memory of the DLL (through the handle returned by loadLibrary).
-exit from Dllmain

in the case I wanted to change some of the original Dll's export behaviour I also coded a function with the same prototype of the original one, which do required tricks and after call the original export.

Doing this way I was able to easily code a loader for a asprotected dll which pathces in memory all the nags and insert some missing code, stolen by asprotect.

[NtSC] 03-11-2005 18:11

...
 
Well,actually there are a few Methods.
You could go and "hook" the Loadlibrary Call that loads the dll, thus obtaining the dll loadaddress. from that you can walk the export table to get your functions and/or calculate any needed distance values. Another Method would be to use toolhelp/psapi functions. you can locate your main app and get its loaded modules this way. you will also get baseaddress/size whatever and can just read your dll out that way easiely :)
The "handmade" export forwarding will work too,but i guess its more work to the thing already needed.

Newbie_Cracker 03-11-2005 21:55

Hmm...
The problem is I know nothing about API hooking. After 3 years, I decided to write a universal loader. This time ABEL didn't help me. It's my first coding in VC++. :)

OK, I'm writing an universal loader for a license manager program which its kernel is a DLL. Some programmers put this DLL in the resource of their application. It's packed with ASPACK and sometimes with ASPR.
So, I think the method of Shub-Nigurrath won't work for my purpose. I think if the DLL is in resource, LoadLibrary is not usefull. Because DLL name may be changed from an application to other one and its addresses may be changed.

[NtSC], If program loads several DLL and lock-DLL name is variable, is it usefull to use API hooking?
(Could you plz write a short example of using API hooking or toolhelp/psapi functions?)

So I've used FindWindow, GetWindowThreadProcessId and then OpenProcess to get DLL process handle for reading and writing. But I don't know how to get its Base address and/or one of its EXPORTs address. (I've alot of problem with reading PE header file in VC++, too) :(

Is there any short and precise method?

[NtSC] 03-11-2005 22:34

...
 
Basically.. yes. Api Hooking can be a good Thing to use (if the Dll is extracted/loaded a normal way). This means, the Dll is extracted to a Folder and then loaded with the common Win32 Apis (LoadLibrary for example).

A good Package therefor is the ApiHooks Package from EliCZ for example.
Also Yodas "Hoko" Package is available with atleast 1 Global Hook for free,maybe you should consider to use those.

Atleast playing with such stuff you should read more about the PE-Structure (its a hard way,but will work out in the end ;)

Anyway,what kind of dll/protection do we talk about here?

Newbie_Cracker 03-12-2005 02:15

Instead of hooking, I'v a better idea.
After appearing the registration from (created by DLL), we are sure that DLL is extracted/loaded completely. Its better to get the list of imported DLLs and get the address of serial-check function by GetProcAddress in one loop.
Now, how could I get the import list? only DLLs names.

My problem about reading PE headers almost solved. If i could find any address from the loaded DLL, I could find its PE header by a simple search algo.

The license manager is : CoLock
hxxp://www.colock.com/

It's a funny license manager !!

[NtSC] 03-13-2005 05:10

Basically a very old asm-snippet of the stuff you need to sort...

get_modules:
cmp [modbuffer],0
jz nofreemod
Call GlobalFree, [modbuffer]
nofreemod:
mov [modsize],04000h
Call GlobalAlloc, 0040h, [modsize]
mov [modbuffer],eax
mov [modpointer],eax

mov ecx,[P_Info+8]
mov [ProcEth32ProcessID],ecx

push ProcEth32ProcessID ;th32ProcessID
push TH32CS_SNAPMODULE ;dwFlags
call CreateToolhelp32Snapshot
mov [hSnapshot],eax

lea edi,ModuleEntry
push edi ;lpme
mov dword ptr [edi],SIZEOFMODULEENTRY
push eax ;hSnapshot
call Module32First
call copy_modinfo
next_mod:
push edi ;lpme
push hSnapshot ;hSnapshot
call Module32Next
or eax,eax
jz mod_done
call copy_modinfo
jmp next_mod
mod_done:
push hSnapshot
call CloseHandle
xor eax,eax
ret
copy_modinfo:
pushad
mov edi,[modpointer]
mov ecx,edi
push ecx
mov eax,[ModEmodBaseAddr] ; get imagebase
mov [edi+30h],eax
mov eax,[ModEmodBaseSize] ; get sizeofimage
mov [edi+34h],eax
lea eax,ModEszModule ; get name of module
call copy0
pop ecx
mov eax,ecx
call lowercase_buffer
add ecx,040h
mov [modpointer],ecx
popad
ret

Just look what apifunctions are used and port it to ur c-code.
that should be enough.. basically you workout all the loaded modules from within a given processinfo!

so..using such a snippet will obtain a list of the loaded modules..
u can increase the search for ur "special" dll by skiping "known" dll modules.
doin this , you can create a table with system librarys and just ignore them.
non standard dlls u examine by obtaining the export table.
you can get the addresses of the exported functions and do a search for whatever in that memory-area.

hope it helps, cheers

Sarge 05-11-2005 02:06

I think I have a similar question, or maybe I am just re-phrasing the previous question:

What I want to do is to ask Windows, "where is the library <whatever.dll> loaded in memory?" (I think). My intent is to, for example, compile a prog on Win98, examine the prog with a hex editor, and see a reference call to a library function whereby the function is located at MyAddress1. Then, when I compile the same program under WinXP and view it with the hex editor, the function is located at MyAddress2. Obviously, the DLL has been re-located and the address's within the exe (after loading into memory) have been adjusted accordingly. Therefore, I think I want to ask of the specific Windows OS (XP in this case), "where did you move the DLL to", so I can manually change these address's myself.

I tried using "LoadLibrary" within my program, but that just a) loads the library within the context of my progarm, and b) gives me the address of that load....NOT the one in Windows. What am I missing?

sarge

NeOXOeN 05-11-2005 05:26

MAybe this will help you :http://www.woodmann.com/yates/lad.txt


bye NeO

nikola 05-12-2005 20:35

@Sarge, that is exactly why NTSC said hooking LoadLibrary would be usefull. Hook the procedure, check arguments. If program is trying to load "mytarget.dll" then call real LoadLibrary, and that is imagebase you need. Now, also send it to program. If its not one you need, then just send it to program. You can make new section for your code so all is executed in target context, but you have to write your code in "delta offset", meaning, relocatable in memory.

And a question from me to someone here. Maybe NTSC knows... How to gain write access to space of a loaded dll? Eg, user32 in win9x? In NT we can use VirtualProtect. In win9x there is an undocumented procedure i found in some source, that looks like was taked from yoda. It works, but i have problem when i want to write my code relocatable. Then, i need to GetProcAddress of that undocumented function. That function is VxDCall4. It has no real name so i cant get by name, and when i try to GetProcAddress by ordinal i get error :(

sope2001 05-12-2005 23:21

Hello newbie_cracker,
Quote:

Is there any short and precise method?
Trying using y0da's Procs & ForceLibrary it might help.

Regards, Sope.

[NtSC] 05-15-2005 16:54

@sarge - Just take a Module Snapshot either with Toolhelp or PSAPI Functions and you will get the BaseAddresses etc., Size whatever of the Modules belonging to the specified Address. I think that is what you focused? You cannot "guess" or take a specific LoadAddress since indeed the System "can" relocate a DLL everytime somewhere else. Look at the Code Snippet i posted its all there..


@nikola - What you focus is a global Hook under 9x. Under NT you change or better modify the DLL Context specific, under 9x if you go with the VXDCalls you do it globally. (Equal to modifications with a Sys/KMD under NT). Iam sure Yates has some good Code Examples on his Page about :) But i would prefer NT,since the Process specific Modifications are easier realizeable there.

Cheers :)

nikola 05-16-2005 00:19

@NTSC, yes, i realised that on first win98 crash ;) But i didnt think that would be problem. I could just check PID and if its of my process i go on. I just wanted to know how to find address of that VXDCall :/ One i use when i link my loader is from lib. But i need to be able to find it on the fly.
Tnx for answer tho :)

JuneMouse 05-16-2005 01:08

well i saw some article in codeproject.com on w9x api hooking i dont have a link
right now but you should be able to locate all articles by artemis (i think i remember right ) it was titled some thing like systemwide hooks on w9x
if you cant locate post ill try to grep my bookmarks :)

Sarge 05-17-2005 04:07

NTSC, Nikola:
Thanks, guys, for the support....I think I need to study up on that, as that's a new one for me. If you dont' mind, I'll go the PM route to you, so I don't tie up this thread.
Thanks
sarge

[NtSC] 05-17-2005 16:16

@ Nikola...

Maybe traverse Exports / or Check Dllbase & use hardcoded Address / or even "borrow" original Function Code. Well,depends on what purpose you need the Code i guess ;)


All times are GMT +8. The time now is 08:02.

Powered by vBulletin® Version 3.8.8
Copyright ©2000 - 2026, vBulletin Solutions, Inc.
Always Your Best Friend: Aaron, JMI, ahmadmansoor, ZeNiX