Log in

View Full Version : modifying code in memory


Vigual
November 5th, 2009, 18:32
I'm trying to modify code that has already been loaded into memory. I was hoping to open a crackme so that it is loaded into memeory. Then run a program to patch the crackme in memory. First, I can't seem to open the crackme then open it using the patching program. I don't know if I have the wrong attributes for the CreateFile and MapViewoFile apis. Also, can I just write directly to the memory, or do I need to use a specific api to write to memory like with writing to a file?

below is the code I wrote

This is the DlgProc function
Code:

invoke CreateFile, addr TargetName,\
GENERIC_READ+GENERIC_WRITE,\
FILE_SHARE_READ+FILE_SHARE_WRITE,\
NULL,\
OPEN_EXISTING,\
FILE_ATTRIBUTE_NORMAL,\
NULL
.if eax!=INVALID_HANDLE_VALUE
mov hTarget, eax
call Search
.endif


This is the Function that searches and tries to write to the memory to patch the crackme

Code:

Search proc
Local ReturnValue WORD
mov ReturnValue, 0
invoke GetFileSize, hTarget, NULL
mov FileSize,eax
invoke CreateFileMapping, hTarget, NULL, PAGE_READWRITE, 0,0,NULL
mov hTargetMap, eax
invoke MapViewOfFile, hTargetMap, FILE_MAP_WRITE,0,0,0
mov pTargetMap,eax
mov edi, pTargetMap
mov esi, offset Sequence
mov ecx, FileSize
mov al, byte ptr [Sequence]
dec edi
@@:
inc edi
dec ecx
cmp byte ptr[edi],al
jne @b
cmp ecx, 0
jz @notfound
push ecx
push edi
push esi
mov ecx, 4
dec esi
dec edi
@a:
inc esi
inc edi
mov bl, byte ptr[esi]
cmp bl,byte ptr[edi]
je @a
cmp ecx, 0
jz @found
pop esi
pop edi
pop ecx
jmp @b

@found:
dec edi
dec esi
mov byte ptr[edi], 4Ch
pop esi
pop edi
pop ecx
mov eax, FileSize
sub eax, ecx
mov ReturnValue, eax
jmp @return

@notfound:
mov ReturnValue,0
jmp @return

@return:
invoke UnmapViewOfFile,pTargetMap
invoke CloseHandle,hTargetMap
mov eax, ReturnValue
Ret
Search EndP

end start

Extremist
November 5th, 2009, 20:36
VirtualProtect()

disavowed
November 7th, 2009, 00:31
No, if you want to patch the memory of the program as it's running, you need to use WriteProcessMemory(...) to write to the process's memory. File mappings are for patching the file on disk.

Aimless
November 7th, 2009, 10:49
Hi.

Memory Loaders + Source code = One good result for the topic.

Have Phun