PDA

View Full Version : Editing stings in an executable file once its executed(memory).


cookiemaster
March 1st, 2015, 13:35
The title is a bit unclear but I dont really know how to explain the problem in one line:

I have a program that connects to a server and I want to change what server it connects to with a separate program written in C.

I have located the the strings that need to be edited in a hex editor. The problem is that this program has many version that are often used so I would like to create a program that searches for the strings and replaces them.

I'm wondering if anyone knows a tutorial or if anyone could point me in the right direction(maybe there is some online documentation)

Thanks!

Edit: If its not possible(or easy), can I search the file before its executed, edit, then execute from within my program?

Also, I want to do it in C because I want to use it sort of as a learning experience and because I need it to run on Windows, Linux and MacOS.

CrackZ
March 1st, 2015, 18:26
This sounds pretty simple to me unless I'm missing something.

Either you create a *search/replace patcher* for the server string you are looking for and run it against each version you encounter, or you *create a loader* (CreateProcess) and patch the program live in memory, seems to me the easiest approach would be the first one if the string isn't encrypted in anyway, note I've *'d the search strings you might use to go either route.

Regards,

CrackZ.

cookiemaster
March 1st, 2015, 18:32
The string is not encrypted(as far as I can tell) because I can find it simply by searching for it in a hex editor.

It is as simple as you think, however I'm looking for some guidance(like a tutorial or example code I can start from) for creating the loader(or a patcher but I want to edit the file in memory instead of the actual executable file)

Aimless
March 1st, 2015, 23:09
Mr. C!

You're alive and well and cracking!

Thank God!



Have Phun

cookiemaster
March 2nd, 2015, 18:37
Are there any functions that search memory in C?

Also, I cant find any loader tutorials with google for some reason. What I've found searching RCE and other forums broght back very complicated tutorials that are just to complicated for what I'm trying to accomplish.

BanMe_2
March 3rd, 2015, 13:25
memchr();is a good place to start, but this is the general layout of what you want to accomplish.
hope that helps.

ULONG Entry = 0x(your entry point)
ULONG OfFsEt = your offset from entry

for OfFsEt = 1 to x OfFsEt++;
if strcmp(*(Entry+OfFsEt),comparee) = 0 then
//you found it.
Entry+OfFsEt = "Whateveryouwanttoputhere"
end
next

of course you will have to make it safer then that...

Kind regards.

cookiemaster
March 3rd, 2015, 13:31
This is an excellent place to start.

But how would I target a specific executable?

BanMe_2
March 3rd, 2015, 13:53
Dll injection and the loader approach.
modding the file on disc is probably the best route. no need for preparations for when you want to run it.

http://stackoverflow.com/questions/22057846/hex-file-reading-in-c-programming
http://stackoverflow.com/questions/21682441/write-hex-in-c-byte

And to Tie it all in read this as well

http://null-byte.wonderhowto.com/how-to/binary-patching-brute-force-reverse-engineering-with-ida-and-hopper-and-hex-editor-0157194/

enjoy.

cookiemaster
March 3rd, 2015, 13:56
This will be a great help for me. Thanks alot!

I'll post here if I encounter any problems.

blabberer
March 4th, 2015, 04:34
the code below searches the address space of self to locate the SearchString
instead of VirtualQuery use VirtualQueryEx provide a process handle (duly obtained by OpenProcess()) for windows.

Code:

#include <stdio.h>
#include <windows.h>
#define MAXPROCADDRSPACE 0x7ffe0fff //use GetSystemInfo
int main (int argc,char *argv[]) {
if(argc != 2 ){printf("usage %s %s\n",argv[0],"\"srchstr\""; return 0;}
int membase = 0;
do {
MEMORY_BASIC_INFORMATION mem;
memset(&mem,0,sizeof(MEMORY_BASIC_INFORMATION));
VirtualQuery((void *)membase,&mem,sizeof(MEMORY_BASIC_INFORMATION));
if(mem.State == MEM_COMMIT) {
char *dest = (char *)mem.BaseAddress;
do {
int remainingsize = (mem.RegionSize-(dest-(char *)mem.BaseAddress));
dest = (char *)memchr(dest,argv[1][0],remainingsize );
if (dest == 0) { break; } else {
if((memcmp(dest,argv[1],strlen(argv[1]))) == 0 ) {
printf("%p\t",dest);
for (int j=0 ;j <16; j++) {
printf("%c",dest[j]);
}
printf("\n";
}
dest++;
}
}while((dest<((char *)mem.BaseAddress+mem.RegionSize)) && (dest != 0));
}
membase += mem.RegionSize;
}while(membase < MAXPROCADDRSPACE);
}


output for search sting allocate in Address Space of ones own process
Code:


scanmem.exe "allocate "
00035480 allocate
00152F15 allocate " G ♦
7C93C482 allocate dynamic
7C94077E allocate current
7C9407D6 allocate PEB_LDR
7C940840 allocate "%wZ"'s
7C9408C3 allocate NTDLL's
7C940A42 allocate heap fo
7C94140E allocate its ful
7C94226C allocate string
7C942BE4 allocate new dat
7C9468CC allocate %u byte
7C96BFAD allocate virtual
7C96D0DE allocate page de
7C96F597 allocate block a

BanMe_2
March 4th, 2015, 09:48
Now that is just pure genius. Great work blabber.

Aimless
March 4th, 2015, 13:25
Unghh.... sorry brother. The "Mr. C" Comment was meant for Crackz. Not you.

Peace

Have Phun

blabberer
March 4th, 2015, 15:15
the code posted few threads above duly modified to Search Address space of remote process
using VirtualQueryEx and ReadProcessMemory

Code:

#include <stdio.h>
#include <windows.h>
#define MAXPROCADDRSPACE 0x7ffe0fff //use GetSystemInfo
int main (int argc,char *argv[]) {
if(argc != 3 ){printf("usage %s %s\n",argv[0],"\"srchstr\" pidindeicmal"; return 0;}
char *endptr;
unsigned long pid = strtoul(argv[2],&endptr,10);
HANDLE prochandle = OpenProcess(PROCESS_ALL_ACCESS,false,pid);
if(prochandle != NULL) {
int membase = 0;
do {
MEMORY_BASIC_INFORMATION mem;
memset(&mem,0,sizeof(MEMORY_BASIC_INFORMATION));
VirtualQueryEx(prochandle,(void *)membase,&mem,sizeof(MEMORY_BASIC_INFORMATION));
if(mem.State == MEM_COMMIT) {
char *adest = (char *)mem.BaseAddress;
char *bdest = (char *)calloc(mem.RegionSize+10,sizeof(char)); if(bdest == 0) {
printf("calloc failed %d\n",__LINE__);break;}
char * dest = bdest;
if (( ReadProcessMemory(prochandle,adest,dest,mem.RegionSize,NULL)) == 0) {
printf("ReadProcessMemory failed %d %p\n",__LINE__,adest);}
do {
int remainingsize = (mem.RegionSize-(((dest-bdest)+adest) -(char *)mem.BaseAddress));
dest = (char *)memchr(dest,argv[1][0],remainingsize );
if (dest == 0) { break; } else {
if((memcmp(dest,argv[1],strlen(argv[1]))) == 0 ) {
printf("%p\t",((dest-bdest)+adest));
for (int j=0 ;j <16; j++) {
printf("%c",dest[j]);
}
printf("\n";
}
dest++;
}
}while((dest<((char *)mem.BaseAddress+mem.RegionSize)) && (dest != 0));
free(bdest);
}
membase += mem.RegionSize;
}while(membase < MAXPROCADDRSPACE);
}
}



scan the file calc.exe for the string calc.pdb and print the file offset using strings from sysinternals
and convert the file offset to RVA execute calc.exe and use the code above to scan the address space for the same string

Code:

:\>strings -o c:\WINDOWS\system32\calc.exe | grep -i calc.pdb
2588:calc.pdb

:\>set /a 2588 - 0x400 + 0x1000000
16778780
:\>printf "%x\n" 16778780
100061c

:\>calc

:\>tlist | grep calc
2888 calc.exe Calculator

:\>scanremmem.exe calc.pdb 2888
ReadProcessMemory failed 21 0007C000
0100161C calc.pdb

BanMe_2
March 14th, 2015, 23:36
Javascript implementation. ROUGH Draft.

Code:

function PatchBinaryString(file,searchString,replacementString)
{
var reader = new FileReader();
reader.onloadend = function(e)
{
rawData = reader.result;
//Work on it in base64 format...

rawData = rawData.replace(searchString,replacementString);
//need to convert it back to binary..
rawData = rawData.toString(2);
if (window.webkitURL != null)
{
//inject a link on the page that allows us to get our modified file...
var downloadLink = document.createElement("a";
downloadLink.download = "Testing123.exe";
downloadLink.innerHTML = "Download File <label>Your File</label><br>";
downloadLink.href = window.webkitURL.createObjectURL(rawData);
document.body.appendChild(downloadLink);
}
else
{
//inject a link on the page that allows us to get our modified file...
var downloadLink = document.createElement("a";
downloadLink.download = "Testing123.exe";
downloadLink.innerHTML = "Download File <label>Your File</label><br>";
downloadLink.href = window.URL.createObjectURL(rawData);
document.body.appendChild(downloadLink);
}
}
reader.readAsBinaryString(file);
}


Again this is very initial implementation.. and is designed around the latest browser features.
Still much respect for the old school implementation.

I refined it a little bit.. this idea and code might work.

update 2:

I am putting together a JsFiddle to refine and test this. I am thinking that working in Base64 format on the file might be the best route to avoid encoding issues. Will provide a link if I achieve a favorable result.

blabberer
March 16th, 2015, 03:31
wow javascript must have come a loooooong way in last some years it seems javascript can now execute or map an exe ? like windows loader ??
and we can search the address space of the process !!!!!!!!!!!! that sounds great i should try to put my head into this pot again it seems

thansk for the head,s up

BanMe_2
March 16th, 2015, 08:08
Short answer to the flurry of questions is no as of yet it cannot access the address space of another process. It can access the static file(similar to a loader) and modify that in it's own memory and produce the file as output.

I hope I clarified this for you, certainly made me look into it a bit closer.

[update after investigation.]

Apparently with V8 javascript there is a way. But it involves writing wrappers for the functions that need to be called.

https://0xef.wordpress.com/2013/10/22/calling-functions-in-dlls-from-javascript/

Further investigation is needed to fully understand the features and technique described.

MDN really puts my statement to shame, and explains ctypes which I didn't even know existed..Now I am glad I kept digging,

https://developer.mozilla.org/en-US/docs/Mozilla/js-ctypes/Using_js-ctypes?redirectlocale=en-US&redirectslug=js-ctypes%2FUsing_js-ctypes

Thank you for the excellent prompt.

BanMe_2
March 17th, 2015, 11:08
https://jsfiddle.net/ILikeToCodeStuffSometimes/qAGHT/330/

Many more updates to go, But it should be workable now.updated
* trying to dynamically determine file extension types( that isn't working, but is in the work in progress section)
* added blob usage for file name
some other stuff..

blabberer
March 18th, 2015, 18:06
thanks for the clarification here is my attempt to srch and replace a text file FileWriter is non standard so as of now writing back is ??
but mod data downloadable using uri (HACK)
Code:

<html>
<head>
<script>
function foo(e) {
var srchstr = new RegExp(document.getElementById("srchstr".value,'gi');
var replstr = document.getElementById("replstr".value;
var infile = document.getElementById('input').files[0];
var reader = new FileReader();
reader.addEventListener("loadend", function() {
var str = reader.result;
document.getElementById("intext".innerHTML = str;
var newstr = str.replace(srchstr,replstr);
document.getElementById("outtext".innerHTML = newstr;
window.location.href = "data:application/x-download;charset=utf-8," + encodeURIComponent(newstr);
});
reader.readAsText(document.getElementById("input".files[0]);
};
</script>
</head>
<body >
<h4>Select a Text File</h4>
<input type="file" id="input" onchange="foo(this.files)" ></input>
<h4> Enter Search String </h4>
<input type="text" id="srchstr"> </input>
<h4> Enter Replace String </h4>
<input type="text" id="replstr"> </input>
<pre><h4> PreMod PostMod </h4></pre>
<textarea id = "intext" rows ="9" cols = "8" > </textarea>
<textarea id = "outtext" rows ="9" cols = "8" > </textarea>
</body>
</html>


sed rules the world
:sed -i s/"js"/"vb"/g jsf.txt
awk rawks
awk "{ gsub( /js/, \"vb\"; print }" jsf.txt

BanMe_2
March 20th, 2015, 13:17
If ever there was a school and blabberer was the teacher, I would not doubt the volumes of knowledge that could be interlinked and built upon, and there are many here with such knowledge.

you might be interested in this as well.
https://whatwg.org/demos/workers/

specifically the multicore, multiviewer, maybe the stock ticker if your into that money thing...