Multiloader checksum check FFS - Bada Software and Hacking General

hi guys I'm doing some research on samsung's firmware files...
is there any good disassembler in here?
We need to know how is the checksum at the end of FFS // APP files calculated!
That's very important...
is there anyone who can help?

im sorry im not but maybe a frined of mine...
why is so important?
its hard to do?
if you give a link with a tutorial may be in some days i will be able to help...
i have programmed in c in the past...
cheers

I am a C programmer (university student) but we need disassemblers here, no programmers atm

Guys I don't know if you understand that the solution to this problem is CRUCIAL for the realization of custom firmwares!!
Trust me! Find some windows (desktop) disassembler as soon as possible!!
thanks

Type : Unofficial Version
Number : 41
Builder : HP05
Host : SCMHP05
Date : 2010/05/28
Time : 21:49:29
Size : 81790332 bytes
CheckSum : 0x259b3fc5
View
Click to expand...
Click to collapse
Hmmm. Whole file is smaller... 50.856.960...
apps_compressed.bin
Decrypted with PSAS... but I can't decompress...
Anyway.
CRC32 (32 bit) could be used...
The Question could be, where the content starts and ends correct to fit size to make crc32...
Best Regards

wait u're talking about the apps_compressed...
while I'm talking about the ffs/app files...which have a 16byte checksum in the footer!

Sorry. I'm thinking loud. As I thought they used for all files same CRC or Hash...
I compared for instance Rsrc2_S8500(Mid).rc2 and Rsrc2_S8500(Low).rc2.
As 1 Byte at Start leads to 16 Byte change at end of file... So maybe MD5 too used by Multiloader.
Again. I'm thinking loud.
Best Regards

No progress. But few Screenshots for better understanding...
If we manipulate *.FFS we can't flash. (ALL other files protected too...)
Test 1.
I changed 1 useless Byte...
Somewhere blabla.jad in blabla.jam
Multiloader 5.64 accept to choose my file. But Error message if I press Download.
Test 2.
I add 1 Byte at the end of file. To check if some crap or if whole file is checked...
Result:
Multiloader 5.64 not allow to choose this file.
Both files tested also via Multiloader 5.62. And this Versions not allow both files to choose.
See Screenshots for Error messages.
Ideas...
Maybe disable CRC Check in Multiloader...
Or find other way to flash and check if Wave self checks Manipulation of files. Or only Multiloader is the bottleneck.
Maybe it is more complex... as I found via Internal menu the Info I've posted above... in Wave self. If Wave have selfcheck...
Best Regards

hi,
I'm not sure if you're hear about fmtBADA plugin for TriX - I wrote it few days ago (it is very simple but quite usefull). It parse any bada firmware file (*ffs, amss, ShpApp etc), so we can easly manipulate with it. After all program recalculate checksum, update all needed values so we can put file back to phone using multiuploader

b.kubica said:
hi,
I'm not sure if you're hear about fmtBADA plugin for TriX - I wrote it few days ago (it is very simple but quite usefull). It parse any bada firmware file (*ffs, amss, ShpApp etc), so we can easly manipulate with it. After all program recalculate checksum, update all needed values so we can put file back to phone using multiuploader
Click to expand...
Click to collapse
what u talking about?
let us know more...
I made lots of research on ffs and app files...

I put some files at NokiX site (check my homepage), so you can play with firmware files quite easily. GUI is qt based so you need to download Qt libraries for the first time. Two packages you will find in bada subdir - program and scripts.
Start program, at General tab select input and output file (e.g. FFS PFS ShpApp,amss). Go to the Scripts tab and load scripts you want to fire up.
For the first time I reccomend you to try fs_shell script - it is simly command line script to edit filesystem images (ffs,pfs,shpapp). You can list, dump delete rename files, adding is not supported yet (but can be easy implemented - scripts are written in pure C).
Before asking just play with it
br,
Bartek

ok then I don't need it already made more
thanks to a russian friend, I probably solved the checksum problem
good news will come the next days

Nice. I have extracted *.FFS and ShpApp.app files.
I'm blind to find the Button where Rename or Delete is stored to output file.
How to save my changes to file?
Best Regards
Edit:
Maybe my fault...
I have bada_scripts_20110104.zip.
Will look into bada_20110106.zip

kubica no reason to make a new script, I'll post something in the next days if it's ok to you, take care about the amss
if you want to do it for personal reason, no problem of course

nevermind, script was already done
you're working on some kind of file system tool, right? We're lucky guys FS images have very simply structure (as you know), only one md5 checksum on it, kewl
One of TriX most advantage is work on stages ( e.g. amss is parsed to elf, elf is parsed to memory segments, than we can edit them and TriX roll back to amss again).
adfree, yes I uploaded today latest version (can be found in repository also). As I said it is only text version (command line), more like programmer preview, and it was not designed as end user tool.
faenil, you asked about dissasembler - have you tried IDA? ( quite expensive though ). I tried in trix hack amss (resize memory segments, add own routines), all works fine, now it's time to investigate functions (some of them can be located with locate script).
Another question - ok, it's sad bootloader is crypted with RSA, but I guess is stored in flash decoded. What if we try to access nand directly using Flash_Read/Write? I can't find flash access routines in amss but i did't look
deeply...

b.kubica said:
nevermind, script was already done
you're working on some kind of file system tool, right? We're lucky guys FS images have very simply structure (as you know), only one md5 checksum on it, kewl
One of TriX most advantage is work on stages ( e.g. amss is parsed to elf, elf is parsed to memory segments, than we can edit them and TriX roll back to amss again).
adfree, yes I uploaded today latest version (can be found in repository also). As I said it is only text version (command line), more like programmer preview, and it was not designed as end user tool.
faenil, you asked about dissasembler - have you tried IDA? ( quite expensive though ). I tried in trix hack amss (resize memory segments, add own routines), all works fine, now it's time to investigate functions (some of them can be located with locate script).
Another question - ok, it's sad bootloader is crypted with RSA, but I guess is stored in flash decoded. What if we try to access nand directly using Flash_Read/Write? I can't find flash access routines in amss but i did't look
deeply...
Click to expand...
Click to collapse
I'm not that experienced unfortunately I needed a disassembler (person) not a disassembler (software)
btw I needed it to discover that it was md5 and on which bytes it was computed and I discovered this yesterday evening
So now we know everything about ffs and app
Still have to understand the new values in pfs header...if you already know that raise your hand
Btw, yes I'm working on something like that I won't have time now to do the GUI, so I'll probably leave it as an "experienced users only" for the moment...
I've got lots to study for university, and some programming projects to end (for uni too) so my spare time is almost finished and I still have to release a custom firmware for i8910 and a software for that firmware for Symbian...
damn I'm full of things to do xD
I'll send u a pm though, if you want to chat a lil

all file footer looks the same
typedef struct s_bada_footer // last 1024 bytes
{
unsigned int magic; // always 0xABCDABCD
unsigned int addr; // nand(?) address
unsigned int unk0; // SBZ (=Should Be Zero)
char name[32]; // e.g. S8500
char ext[8]; // e.g. mbn, ffs
unsigned int unk1[5]; // some flags, values, to be checked later
t_cert_info info; // crypto data ( zeroed if file is not crypted )
char md5sum[16]; // MD5 sum of image ( without footer )
char padd[424]; // padding bytes, SBZ
} t_bada_priv;
typedef struct t_cert_info // 512 bytes
{
unsigned int magic; // 0x79461379
char cert0[324]; // ...
unsigned int magic; // 0x79461379
unsigned int length; // crypted length ( without footer )
char cert1[16]; // exist in image also at ( length - 0x10 ) position
char publickey[64]; // ?
char name[64]; // e.g. S8500+XX+JEE
char tool[32]; // TkToolVer famous string
}
headers are different. boot_loader, Apps, Rsrc1, Rsrc2, fota and CSC don't have header.
dbl and Amss have 0x200 bytes header.
ShpApp, Factory FS, Partial FS have 0x60 bytes header
Code:
typedef struct s_bada_object
{
unsigned int offset;
unsigned int length;
char name[24];
} t_bada_object;
typedef struct s_bada_hdr200
{
unsigned int magic; // 0x12345678
unsigned int count; // count of objects below
char padd[24]; // padding bytes
t_bada_object[15]; // not used SBZ
} t_bada_hdr200;
typedef struct s_bada_hdr60
{
wchar_t name[16]; // UCS-2 name
unsigned int unk0[14]; // unknown
char padd[8]; // FF FF FF
} t_bada_hdr200;
from my observations, unk0 fields in FS system header are not *SO* important - I just preserve original values, removed files I want from factory FS, and put file back to phone

all file footer looks the same
Code:
typedef struct s_bada_footer // last 1024 bytes
{
unsigned int magic; // always 0xABCDABCD
unsigned int addr; // nand(?) address
unsigned int unk0; // SBZ (=Should Be Zero)
char name[32]; // e.g. S8500
char ext[8]; // e.g. mbn, ffs
unsigned int unk1[5]; // some flags, values, to be checked later
t_cert_info info; // crypto data ( zeroed if file is not crypted )
char md5sum[16]; // MD5 sum of image ( without footer )
char padd[424]; // padding bytes, SBZ
} t_bada_priv;
typedef struct t_cert_info // 512 bytes
{
unsigned int magic; // 0x79461379
char cert0[324]; // ...
unsigned int magic; // 0x79461379
unsigned int length; // crypted length ( without footer )
char cert1[16]; // exist in image also at ( length - 0x10 ) position
char publickey[64]; // ?
char name[64]; // e.g. S8500+XX+JEE
char tool[32]; // TkToolVer famous string ;)
}
headers are different. boot_loader, Apps, Rsrc1, Rsrc2, fota and CSC don't have header.
dbl and Amss have 0x200 bytes header.
ShpApp, Factory FS, Partial FS have 0x60 bytes header
Code:
typedef struct s_bada_object
{
unsigned int offset;
unsigned int length;
char name[24];
} t_bada_object;
typedef struct s_bada_hdr200
{
unsigned int magic; // 0x12345678
unsigned int count; // count of objects below
char padd[24]; // padding bytes
t_bada_object[15]; // not used SBZ
} t_bada_hdr200;
typedef struct s_bada_hdr60
{
wchar_t name[16]; // UCS-2 name
unsigned int unk0[14]; // unknown
char padd[8]; // FF FF FF
} t_bada_hdr200;
from my observations, unk0 fields in FS system header are not *SO* important - I just preserve original values, removed files I want from factory FS, and put file back to phone

CSC has got its header, it's just that there are more files into 1
after about half the file, we come back to the same plain structure

very simple ( 2KB ) partial file system in attachment, all values from header preserved
Code:
FileSystem Shell
---------------------------
<1.> List Files
<2.> Get File
<3.> Put File
<4.> Delete File
<5.> Rename File
<6.> Dump all files
<0.> Quit
Type Size Flags Name
DIR 0x00000000 0x00000000 /Arggh
FILE 0x00000000 0x00000000 /Arggh/it_works.txt

Related

copied exe-file is not a valid application

Hi,
I have written a litte application (eMbedded Visual C++) for Pocket PC 2002
to copy an exe-file from the root-directory to the startmenu-directory.
It seems to work fine, but when I start the copied application (the exe-file) I get the message
"... is not a valid Pocket PC application"
What is wrong with this applcation?
Or does anyone know how to call Copy from an Pocket PC application directly?
Here is the code:
// Setup.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#define SOURCEFILE_NAME "\\banking.exe"
#define DESTINATIONFILE_NAME "\\Windows\\Start Menu\\banking.exe"
#define DESTINATIONFILE_NAME_GERMAN "\\Windows\\Startmenü\\banking.exe"
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
BOOL german = FALSE;
FILE *file = 0;
FILE *rfile = 0;
rfile = fopen (SOURCEFILE_NAME, "rb");
if (!rfile)
{
MessageBox (0, TEXT("Error"), TEXT("Setup"), MB_TOPMOST);
return 1;
}
file = fopen (DESTINATIONFILE_NAME_GERMAN, "wb");
if (!file)
file = fopen (DESTINATIONFILE_NAME, "wb");
else
german = TRUE;
if (file)
{
char buffer [1000];
size_t num_read = 0;
size_t num_written = 0;
size_t num_read_tot = 0;
size_t num_written_tot = 0;
do
{
num_read = fread (buffer, sizeof (char), 1000, rfile);
if (feof(rfile))
break;
num_read_tot += num_read;
if (num_read > 0)
{
num_written= fwrite (buffer, sizeof (char), num_read, file);
num_written_tot += num_written;
}
else
break;
} while (1);
fclose (file);
}
fclose (rfile);
DWORD attr = 0;
BOOL rc = 0;
attr = GetFileAttributes (TEXT(SOURCEFILE_NAME));
if (german)
rc = SetFileAttributes (TEXT(DESTINATIONFILE_NAME_GERMAN), attr);
else
rc = SetFileAttributes (TEXT(DESTINATIONFILE_NAME), attr);
MessageBox (0, TEXT("Ready"), TEXT("Setup"), MB_TOPMOST);
return 0;
}
// END
Hello,
You are trying to reinvent the wheel by copying yourself the info from the file. Use the CopyFile function.
But your error
"... is not a valid Pocket PC application"
Click to expand...
Click to collapse
has probably appeared for another reason...
You should also look at SHFileOperation
It's not a good idea to copy *.exe files to start menu...
Create a shortcut with CECreateShortcut(...) instead.
If this is part of a application setup (in a cab file) just create the shortcut with the build in features:
...
[DefaultInstall]
...
CEShortcuts = Shortcuts
...
[Shortcuts]
BankingMenuText,0,banking.exe
...
John
John,
thank you for your comment.
Perhaps you ore someone else can tell me how to create a shortcut (for the banking.exe) from a Pocket PC - application ?
(The background is as follows:
I want to deliver my banking-application on SD-Card;
a little setup-application on the SD-Card copies the banking.exe from SD-Card into the program-directory of the Pocket PC.
And last but not least this setup-application shoult insert a shortcut for the copied banking.exe in the Start Menu.
OK,
cabwiz.exe does exactly the job.
One open question:
How can I achieve, that after executing the cab-file is N O T deleted?
Create Shortcut with SHCreateShortcut.
Not deleting cab file : mark it as read-only on the desktop (before copying) 8)

Hook API function WM6

I'm trying to hook api function "NKDbgPrintfW" from coredll.dll.
I use import table in-memory patch. It works fine for main module (exe file).
It hooks all calls from exe, but does not from dll it uses.
I think root of problem is that exe and loaded dlls use own import table and I patch only exe's one.
I use next function to hook exe api calls:
Code:
DWORD ic_PatchProcImports ( HANDLE hProc, DWORD dFind, DWORD dReplace )
{
DWORD ret = 0;
/* GODMODE ON */
BOOL bOldKMode = SetKMode ( TRUE );
DWORD dOldPerms = SetProcPermissions ( 0xFFFFFFFF );
/* get process ptr prom handle */
HDATA * hProcHD = ( HDATA * ) ( 0x80000000 | ( ( DWORD ) hProc & HANDLE_ADDRESS_MASK ) );
PROCESS * prc = ( PROCESS * ) hProcHD->pvObj;
/* get imports sections */
struct ImpHdr * blockptr, * blockstart;
blockstart = ( struct ImpHdr * ) MapPtrProc ( prc->e32.e32_vbase + prc->e32.e32_unit[IMP].rva, prc );
/* iterate thru imports sections */
for ( blockptr = blockstart; blockptr->imp_lookup; ++blockptr )
{
DWORD dOldProtect, tmp;
/* get vectors ptr */
DWORD * vectors = ( DWORD * ) MapPtrProc ( prc->e32.e32_vbase + blockptr->imp_address, prc );
/* count vectors */
DWORD * vptr = vectors;
while ( * vptr ) ++vptr;
DWORD vcnt = ( vptr - vectors );
/* try to unlock imports section memory */
if ( VirtualProtect ( vectors, vcnt * sizeof ( DWORD ), PAGE_EXECUTE_READWRITE, &dOldProtect ) )
{
/* find&replace */
for ( UINT i = 0; i < vcnt; ++i )
{
if ( vectors[i] == dFind )
{
vectors[i] = dReplace;
++ret;
}
}
/* lock back */
VirtualProtect ( vectors, vcnt * sizeof ( DWORD ), dOldProtect, &tmp );
}
}
/* GODMODE OFF */
SetProcPermissions ( dOldPerms );
SetKMode ( bOldKMode );
/* */
return ret;
}
I tried to find import table in loaded dll module but failed.
Here is the code I used:
Code:
DWORD ic_PatchModuleImports ( HANDLE hProc, Module* mod, DWORD dFind, DWORD dReplace )
{
DWORD ret = 0;
/* GODMODE ON */
BOOL bOldKMode = SetKMode ( TRUE );
DWORD dOldPerms = SetProcPermissions ( 0xFFFFFFFF );
/* get process ptr prom handle */
HDATA * hProcHD = ( HDATA * ) ( 0x80000000 | ( ( DWORD ) hProc & HANDLE_ADDRESS_MASK ) );
PROCESS * prc = ( PROCESS * ) hProcHD->pvObj;
/* get imports sections */
ImpHdr *blockptr, *blockstart;
blockstart = ( ImpHdr * ) MapPtrProc(mod->e32.e32_vbase + mod->e32.e32_unit[IMP].rva, prc);
/* iterate thru imports sections */
for ( blockptr = blockstart; blockptr->imp_lookup; ++blockptr )
{
// NKDbgPrintfW(L"%s", blockptr->imp_dllname);
//DWORD dOldProtect, tmp;
/* get vectors ptr */
DWORD * vectors = ( DWORD * ) MapPtrProc(mod->e32.e32_vbase + blockptr->imp_address, prc);
/* count vectors */
DWORD * vptr = vectors;
while ( * vptr ) ++vptr;
DWORD vcnt = ( vptr - vectors );
/* try to unlock imports section memory */
//if ( VirtualProtect ( vectors, vcnt * sizeof ( DWORD ), PAGE_EXECUTE_READWRITE, &dOldProtect ) )
{
/* find&replace */
for ( UINT i = 0; i < vcnt; ++i )
{
NKDbgPrintfW(L"Serach for: %x; Found: %x", dFind, vectors[i]);
if ( vectors[i] == dFind )
{
vectors[i] = dReplace;
++ret;
}
}
/* lock back */
// VirtualProtect ( vectors, vcnt * sizeof ( DWORD ), dOldProtect, &tmp );
}
}
/* GODMODE OFF */
SetProcPermissions ( dOldPerms );
SetKMode ( bOldKMode );
/* */
return ret;
}
I'm looking for any way to hook this function, but I prefer in-memory import table patch..
Hello!
Perhaps this will help:
http://forum.xda-developers.com/showthread.php?t=372496
I am also working on a program that needs hooks. My problem right now is that I need to create the header with all the structure definitions (PROCESS, THREAD, ect). I found this but it is most likely for an older CE version as it was written in 2003:
http://nah6.com/~itsme/cvs-xdadevtools/itsutils/old/cenk.h
Do you have these definitions for wince 5.x?
I think, you can find it in Windows Mobile Platform SDK .
MS sells that SDK, but if you google it, you'll find a place where you can download it for free
I was working on a similar problem but I decided to make a generic hook that didn't rely only on import table. Thanks to itutils I was able to hook some functions until when I found out that there two methods for making api calls, the standard one and the "speedy" one. I wasn't able to hook any function that was using the second method and after a bit I gave up. How did you overcome this problem?
Any suggestion is welcome, thank you
I still have not solved my problem. I am trying to hook calls to keybd_event in coredll from keypad.dll. I think the root of the problem is that that keypad.dll is in ROM. Therefore the thunk table that is actually inside keypad.dll is not readable or writeable at runtime. I think there is a thunk table created in RAM somewhere else where the function pointers are actually stored. I can find it by analyzing keypad.dll and finding the hex location to where the runtime thunk table is, but I cant find a way to figure it out at runtime so that my hook will work with any dll.
I use the PerformCallback4 DLL hooking and it's working with ROM files. But I'd also be interested if there's a way to inject into a process without needing to load a separate DLL.
Well process injection is not my problem. I am trying to hook calls from a service dll. All I did was add my dll as a service and I am kindly loaded at boot. Its the hooking I cant get to work. How are you accomplishing the hook? I just want to hook all calls from other services to keybd_event.
What _exactly_ do you guys want to do? I may be able to assist.
I know the answers to most questions I see here, but I will simply not give out the code to do this, because it is "dangerous" code. By that I do not mean it is not somewhat reliable, but dangerous to commercial developers as these techniques allow you to crack pretty any commercial app with minimal effort...
(see my notice about having easily bypassed the MS Marketplace "advanced protection" on various news sites for an example of how bad this can be)
Actually I'd be curious to know how to hook an API that can use the kmode speedup, that is one that's using g_pKmodeEntries. I'm not interesting into cracking anything but at this point I'm curious to know how to go ahead.
Thanx for any help.
I heard that the DLL injection hooks won't work for WinCE 6.0 (--> WM 7) but what about the mentioned "kmode speedup"?
bbbird1 said:
Actually I'd be curious to know how to hook an API that can use the kmode speedup, that is one that's using g_pKmodeEntries. I'm not interesting into cracking anything but at this point I'm curious to know how to go ahead.
Thanx for any help.
Click to expand...
Click to collapse
Well there are various ways to patch functions out. The problem is that there are several ways that a kernel function can ultimately be called. Of course there are also various ways to go about patching these functions. To name a few:
(1) Patch the apiset tables and overwrite the function address the trap jumps to. If this is the same table and address are used for the g_pKmodeEntries jump I am not sure - you would have to do some IDA'ing / testing to figure that one out
(2) Patch the import tables of the executable / dll calling this function, if you have a specific target in mind (with some small trickery this can be adapted to also patch 'dynamic imports', i.e. GetProcAddress, even after the call was made)
(3) Patch the export table of coredll (actually if this one matches your wishes, I usually use 4 instead)
(4) Patch the function inside coredll directly by (saving first and then) overwriting the first few instructions with a jump to your code
(5) Patch the actual function inside nk or the other exe server (closely related to 4)
Each method has it's own pros and cons, injection/controlled-leak/code requirements and may or may not work with certain way of calling the function. Some of these patches are much more difficult to do than others...
You'd have to figure out for your function which method might actually work. For example I usually have great results with method 4, however it will not catch some ways of kernel-internal calls, so you have to confirm first with some heavy IDA'ing to see if internal calls exist (completely bypassing coredll, for most functions they actually don't). Unfortunately that I recall I have not tried patching any g_pKmodeEntries intentionally (as in I might have patched such functions, but not knowingly).
RAMMANN said:
I heard that the DLL injection hooks won't work for WinCE 6.0 (--> WM 7) but what about the mentioned "kmode speedup"?
Click to expand...
Click to collapse
Well we'd pretty much have to start from scratch again, figuring a lot of stuff out, but I'm sure we'll find new and exciting ways of hooking kmode speedup might still be there, though, but likely in a different form.
Chainfire said:
What _exactly_ do you guys want to do? I may be able to assist.
I know the answers to most questions I see here, but I will simply not give out the code to do this, because it is "dangerous" code. By that I do not mean it is not somewhat reliable, but dangerous to commercial developers as these techniques allow you to crack pretty any commercial app with minimal effort...
(see my notice about having easily bypassed the MS Marketplace "advanced protection" on various news sites for an example of how bad this can be)
Click to expand...
Click to collapse
Hello chainfire! I am trying to hook keyboard events comming from the keypad driver. There is a service that runs to detect key interrupts and when it does detect them it calls keybd_event to broadcast the event. keybd_event is in coredll. The keypad service is loaded from keypad.dll (in most ROMs). So I want to hook calls from keypad.dll to keybd_event in coredll. The problem is that I want it to work regardless of ROM version and there are different versions of keypad.dll, and some ROMs dont have it at all. Therefore I want to hook all calls to keybd_event from services. I added my dll as a service so injection method is not a problem. Now I need to hook.
Using IDA I found the address of the IAT in keypad, but the IAT that exists in the dll itself is not readable or writeable. It seems that there is a thunk table that gets created in RAM separate from where the dll is loaded. Each process seems to create it's own RAM thunk table for loaded dlls (my guess is just those in ROM). I dont know how to programmatically find these thunk tables.
Do I make sense? This is of course targeting WM6.x (wce5). I just need some way to hook calls to keybd_event from all dlls loaded in the current process. Some of those dlls may be in ROM but they need to be hooked too.
Chainfire said:
Well there are various ways to patch functions out. The problem is that there are several ways that a kernel function can ultimately be called. Of course there are also various ways to go about patching these functions. To name a few:
(1) Patch the apiset tables and overwrite the function address the trap jumps to. If this is the same table and address are used for the g_pKmodeEntries jump I am not sure - you would have to do some IDA'ing / testing to figure that one out
(2) Patch the import tables of the executable / dll calling this function, if you have a specific target in mind (with some small trickery this can be adapted to also patch 'dynamic imports', i.e. GetProcAddress, even after the call was made)
(3) Patch the export table of coredll (actually if this one matches your wishes, I usually use 4 instead)
(4) Patch the function inside coredll directly by (saving first and then) overwriting the first few instructions with a jump to your code
(5) Patch the actual function inside nk or the other exe server (closely related to 4)
Each method has it's own pros and cons, injection/controlled-leak/code requirements and may or may not work with certain way of calling the function. Some of these patches are much more difficult to do than others...
You'd have to figure out for your function which method might actually work. For example I usually have great results with method 4, however it will not catch some ways of kernel-internal calls, so you have to confirm first with some heavy IDA'ing to see if internal calls exist (completely bypassing coredll, for most functions they actually don't). Unfortunately that I recall I have not tried patching any g_pKmodeEntries intentionally (as in I might have patched such functions, but not knowingly).
Well we'd pretty much have to start from scratch again, figuring a lot of stuff out, but I'm sure we'll find new and exciting ways of hooking kmode speedup might still be there, though, but likely in a different form.
Click to expand...
Click to collapse
I like the sound of (3). Why Use (4) instead? How do you find the export table programmatically? If I use this method, as long as my service is loaded first it should work.
Ok I just tried something and it worked. It seems that these RAM thunk tables are always loaded at 0x01bb5000 for every process. The following code worked:
Code:
coremod = GetModuleHandle(L"coredll.dll");
o_keybd_event = (_keybd_event)GetProcAddress(coremod, L"keybd_event");
my_kbe = (DWORD)(my_keybd_event);
addr = (DWORD*)(0x01bb5000);
VirtualProtect(addr, 4, PAGE_READWRITE, NULL);
while(ReadProcessMemory(GetCurrentProcess(), addr, &dat, 4, NULL))
{
if(dat == (DWORD)o_keybd_event)
{
WriteProcessMemory(GetCurrentProcess(), addr, &my_kbe, 4, NULL);
kbe_hkd = TRUE;
}
addr++;
VirtualProtect(addr, 4, PAGE_READWRITE, NULL);
}
The thunk tables seem to be back to back and ReadProcessMemory seems to always fail at the end of them, so the loop does not run too long. Chainfire, does this make sense to you?
JKingDev said:
...
Do I make sense? This is of course targeting WM6.x (wce5). I just need some way to hook calls to keybd_event from all dlls loaded in the current process. Some of those dlls may be in ROM but they need to be hooked too.
Click to expand...
Click to collapse
Using IAT patch to do this is certainly possible but a lengthy process as you'd have to keep track for all dll loads in services.exe and patch each and every dll as it loads. One of the other methods I described may fit better.
JKingDev said:
I like the sound of (3). Why Use (4) instead? How do you find the export table programmatically? If I use this method, as long as my service is loaded first it should work.
Click to expand...
Click to collapse
(3) is actually (IMHO) a very annoying patch to implement. It doesn't easily allow you to patch/unpatch at will. It doesn't cover coredll-internal jumps. The timing/load-order has to be perfect. It requires slightly more memory. And because you have to load it before anything else if you screw something up there's a good chance you'll need a hard-reset to recover (that's a real ***** with testing!). You can get the export table from the e32 structure of the module, though it isn't always easily patched
JKingDev said:
Ok I just tried something and it worked. It seems that these RAM thunk tables are always loaded at 0x01bb5000 for every process. The following code worked:
The thunk tables seem to be back to back and ReadProcessMemory seems to always fail at the end of them, so the loop does not run too long. Chainfire, does this make sense to you?
Click to expand...
Click to collapse
ROM DLLs create a seperate data section in memory for every process it is loaded into, the IAT is also stored there. Note that the addresses / virtual memory are the same across processes, but different physical memory is used for each process (same as data sections for normal DLLs, though those are located at the normal addresses). To figure out where this memory is look at the rwLow and rwHigh members of the PMODULE structure. (actually I'm surprised you found the location without this )
Chainfire said:
ROM DLLs create a seperate data section in memory for every process it is loaded into, the IAT is also stored there. Note that the addresses / virtual memory are the same across processes, but different physical memory is used for each process (same as data sections for normal DLLs, though those are located at the normal addresses). To figure out where this memory is look at the rwLow and rwHigh members of the PMODULE structure. (actually I'm surprised you found the location without this )
Click to expand...
Click to collapse
That is the vital info I needed! Quick question, do I start searching at rwLow and end at rwHigh, or start at rw Low and end at rwLow+rwHigh?
Thanks!
*edit* Answering my own question, start searching at rwLow and end at rwHigh. I was still having problems because my MODULE structure definition is incorrect, but I was able to find where the information I needed was so it doesnt really matter. Thanks so much!!

How do i get folder size rapidly?!

I write a C# app for WindowsMobile.
in order to get a nonrecursive folder size i have this routine:
Code:
static long GetDirectorySize(String path)
{
long size = 0;
String []files = Directory.GetFiles(path);
foreach (String f in files)
{
FileInfo fi = new FileInfo(f);
size += fi.Length;
}
return size;
}
now, my directory (in Storage Card) has about 1000 files that has about 4MB of data alltogether.
the GetDirectorySize takes forever to execute (60 seconds or so) and provide a horribole user expericnce.
executing this in a thread does not help either - i need the response as fast as possibole.
I was wondering if someone could help me figure out how to get folder size (nonrecursive) more rapidly.
in general, i also want to find the older file in the directory and delete it (kid of cache operation). how do i do that without waiting forever to complete?
storing an index file might not be what i'm looking for.
Thanks
I don't know about C#, but in C++ I use GetDiskFreeSpaceEx function, see HERE.
PS,
I think this goes in the Q&A forum?
dgaud007 said:
I use GetDiskFreeSpaceEx function
Click to expand...
Click to collapse
This does not help with Folder size.
My intention is to manage Cache folder and monitor its size and clear out some cached files in case the cache size of the folder is too big.
getting the disk size is not the way to deal with folder size
You can use it for individual folders, as the folder name is the 1st input parameter. I've used at least for \My Documents which is a regular folder and it works. Here is an excerpt from MSDN:
lpDirectoryName [in, optional]
A directory on the disk.
If this parameter is NULL, the function uses the root of the current disk.
If this parameter is a UNC name, it must include a trailing backslash, for example, "\\MyServer\MyShare\".
This parameter does not have to specify the root directory on a disk. The function accepts any directory on a disk.
The calling application must have FILE_LIST_DIRECTORY access rights for this directory.
Click to expand...
Click to collapse
As per MSDN, here is how you implement it in C#:
Code:
[DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)]
internal static extern bool GetDiskFreeSpaceEx(string drive, out long freeBytesForUser, out long totalBytes, out long freeBytes);
I tested GetDiskFreeSpaceEx.
- The coredll has to be used instead kernel32dll (for WindowsMobile).
- the TotalBytes returns the SD card size (on which the folder exists)
- the freeBytesForUser equals FreeBytes and returns the free space in the SD card
this does return the folder size.
appreciate further help.
thanks
I double checked and you're right. Looks like you'll have to recurse while adding the individual sizes. I couldn't find an easier method in a brief search in google. Sorry about the confusion!
PS,
checkout this app...
I'm not that much of a C# expert but isn't the 1000 times calling "new" slowing down? I'd try to write a traditional C++ application using simple FindFirstFile and FindNextFile functions and compare speed towards the C# application. If it's faster then you can just build a C++ DLL and PInvoke her. I'm not sure if results are better but at least it's worth a try.
solution found
I managed to resolve this and get a speedy result by replacing with this code.
all the best.
Code:
private static long GetDirectorySize(String path)
{
long size = 0;
[COLOR="DarkGreen"] /* Slow code
String []files = Directory.GetFiles(path);
foreach (String f in files)
{
FileInfo fi = new FileInfo(f);
size += fi.Length;
} */[/COLOR]
DirectoryInfo di = new DirectoryInfo(path);
FileInfo []fi = di.GetFiles();
for (int i = 0; i < fi.Length; i++)
size += fi.Length;
return size;
}
btw: get my app at http://www.logelog.com/utils

Cant modify module IAT to hook API

This may be better served in the development and hacking forum. Mods please move?
I am trying to hook the keybd_event API in the keypad. I have found the address of the import entry for keybd_event in the keypad.dll's IAT. I have done so by disassembling the keypad.dll and finding the offset from an exported function to that IAT entry. At runtime, I have added my own service (in order to get my dll loaded into services.exe). When loaded, I use GetModuleHandle and GetProcAddress to find that exported function then use the known offset to find the IAT entry. I have verified that I have the right memory location by comparing the pointer to the module's location using remote process viewer.
The problem is that I cannot read from or write to the IAT. My code crashes when I try. IsBadReadPtr and IsBadWritePtr tell me that I cant read or write to this memory location. Even a call to VirtualProtect to set it to PAGE_EXECUTE_READWRITE will not work. The call fails. How can I get access to this memory?
This simple test code exe shows that all the memory in the code section of keypad.dll is writeable. As soon as I hit section 2 which contains the IAT The call starts failing. Once I hit section 3 it succeeds again (the hard coded PID and address come from remote process viewer and my service dll; I debugged to find where the read calls fail).
Code:
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
DWORD PID = 239927214, addr = 2061766572, read = 0, sz = 0;
HANDLE pr;
BOOL ans1;
_SetKMode SetKMode;
SetKMode = (_SetKMode)GetProcAddress(GetModuleHandle(L"coredll.dll"), L"SetKMode");
ans1 = SetKMode(true);
pr = OpenProcess(0, 0, PID);
while(ReadProcessMemory(pr, (LPVOID)addr, &read, 4, &sz))
addr++;
while(!ReadProcessMemory(pr, (LPVOID)addr, &read, 4, &sz))
addr++;
while(ReadProcessMemory(pr, (LPVOID)addr, &read, 4, &sz))
addr++;
//ans4 = WriteProcessMemory(pr, ptr2, &mkep, 4, &p4);
CloseHandle(pr);
return 0;
}
What do I need to do to get access? Calls to VirtualProtect and SetKMode do nothing. Any ideas? Thanks!
Nevermind! It seems I was not modifying the correct location. I was trying to modify the table that simply lists imports. I found where the actual function pointer is stored.

[Q] WP7 - Removing an XElement from an XML file

Hi there,
I'm having a big issue, when trying to remove an XElement from an XML file created in IsolatedStorage.
--------------------------------------------------------------------------------------------
Code to CREATE the XML file
Dim File_to_Create As String = "Tracks.xml"
Dim file As XDocument = <?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlnsd="urn:schemas-microsoft-comfficedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Cartridges.xsd" generated="2010-11-23T14:26:55">
<Carts>
<CART_NAME>First</CART_NAME>
<CART_COLOR>White</CART_COLOR>
</Carts>
<Carts>
<CART_NAME>Second</CART_NAME>
<CART_COLOR>Black</CART_COLOR>
</Carts>
</dataroot>
Dim isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Try
If isoStore.FileExists(File_to_Create) Then
MessageBox.Show(File_to_Create + " TRUE")
Else
MessageBox.Show(File_to_Create + " FALSE")
Dim oStream As New IsolatedStorageFileStream(File_to_Create, FileMode.Create, isoStore)
Dim writer As New StreamWriter(oStream)
writer.WriteLine(file)
writer.Close()
MessageBox.Show("OK")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'open selected file
Dim isoStream As IsolatedStorageFileStream
isoStream = New IsolatedStorageFileStream(File_to_Create, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore)
Dim XML_File As XDocument = XDocument.Load(isoStream)
Dim Cart_Query As System.Collections.IEnumerable = From query In XML_File.Descendants("Carts") Order By _
CStr(query.Element("CART_NAME")) Descending, CStr(query.Element("CART_NAME"))
Select New Class_Cartridge_Data With {.Cart_Name = CStr(query.Element("CART_NAME")), _
.Cart_Color = CStr(query.Element("CART_COLOR"))}
Me.ListBox_Cartridges.ItemsSource = Cart_Query
isoStore.Dispose()
isoStream.Close()
End Try
--------------------------------------------------------------------------------------------
Code to ADD / EDIT XElement
Dim File_to_Create As String = "Tracks.xml"
Dim XML_IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()
' Check that the file exists if not create it
If Not (XML_IsolatedStorage.FileExists(File_to_Create)) Then
Return
End If
Dim XML_StreamReader As New StreamReader(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Read))
Dim XML_Document As XDocument = XDocument.Parse(XML_StreamReader.ReadToEnd())
XML_StreamReader.Close()
' Update the element if it exist or create it if it doesn't
Dim XML_XElement As XElement = XML_Document.Descendants("Carts").Where(Function(c) c.Element("CART_NAME").Value.Equals("First")).FirstOrDefault()
If XML_XElement IsNot Nothing Then
XML_XElement.SetElementValue("CART_NAME", "Third")
Else
' Add new
Dim newProgress As New XElement("Cartridges", New XElement("CART_NAME", "Fourth"), New XElement("CART_COLOR", "Blue"))
Dim rootNode As XElement = XML_Document.Root
rootNode.Add(newProgress)
End If
Using XML_StreamWriter As New StreamWriter(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Write))
XML_StreamWriter.Write(XML_Document.ToString())
XML_StreamWriter.Close()
End Using
--------------------------------------------------------------------------------------------
Now my issue and request for some help!
If I use
XML_XElement.Remove
then the following exception is raised whenever I try to "refresh" the bounded ListBox
System.Xml.XmlException was unhandled
LineNumber=37
LinePosition=12
Message=Data at the root level is invalid. Line 37, position 12.
SourceUri=""
StackTrace:
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString, String[] args)
at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream)
at ListBox_Data_from_XML_LINQ.MainPage.Button_Create_XML_Click(Object sender, RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
InnerException:
--------------------------------------------------------------------------------------------
In short, I can add or edit, but cannot DELETE an XElement...
Any ideas?
Thanks in advance!
Can you post the code you are using for XElement.Remove and use code tags so the formatting is right. Its the # button on the post toolbar.
Ren13B said:
Can you post the code you are using for XElement.Remove and use code tags so the formatting is right. Its the # button on the post toolbar.
Click to expand...
Click to collapse
Well, I did nothing special, just the XML_Element.remove, instead of adding a new xelement.
Then the error raises whenever I try to reopen the XML file.
My point is, how can I delete an specific xelement?
As far as I know, the following code should work
Code:
Dim XML_XElement As XElement = XML_Document.Descendants("Carts").Where(Function(c ) c.Element("CART_NAME").Value.Equals("First")).Firs tOrDefault()
If XML_XElement IsNot Nothing Then
XML_XElement.SetElementValue("CART_NAME", "Third")
Else
' remove the selected record
XML_XElement.Remove
End If
Honestly I don't know if the foregoing code is correct or if the issue is related to how WP7 handles the removal thus corrupting the original file.
Please let me know if you need anything else.
Any help is very appreciated!
PS: Thanks for the other replies, helped a lot!
Here's how I did it in c#. My xml file is very different than yours so the query will be different but the important parts are where you load and close the file streams and then write.
Code:
//Get users private store info
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
//open selected file
isoStream = new IsolatedStorageFileStream(list, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument xml = XDocument.Load(isoStream);
isoStream.Close();
//Find section
XElement sectionElement = xml.Descendants("section").Where(c => c.Attribute("name").Value.Equals(groupn)).FirstOrDefault();
//Find item and remove it
sectionElement.Elements("setting").Where(c => c.Attribute("name").Value.Equals(litem)).FirstOrDefault().Remove();
isoStream.Close(); //Seems unnecessary but it's needed.
//Write xml file
isoStream = new IsolatedStorageFileStream(list, FileMode.Create, FileAccess.Write, isoStore);
xml.Save(isoStream);
isoStream.Close();
Thanks again for your help, greatly appreciated.
However I'm still getting the same error.
Sorry for asking, but are you getting any errors when deleting in WP7 ?
My knowledge on XML is extremely new and I'm sure that I'm making some mistakes somewhere...
But so far, I cannot get past the same exception.
Seems that the XML gots "corrupted" after the delete operation.
On the other hand, if is not too much to ask for, using my current code, how will handle the delete of the selected record?
Thanks!
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Ren13B said:
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Click to expand...
Click to collapse
Problem is my country is not listed so I cannot register...
Here is the C# version of my current code for adding/editing
Code:
public static void ADD_XML_Record()
{
string File_to_Create = "Tracks.xml";
var XML_IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
// Check that the file exists if not create it
if (! (XML_IsolatedStorage.FileExists(File_to_Create)))
{
return;
}
StreamReader XML_StreamReader = new StreamReader(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Read));
XDocument XML_Document = XDocument.Parse(XML_StreamReader.ReadToEnd());
XML_StreamReader.Close();
// Update the element if it exist or create it if it doesn't
XElement XML_XElement = XML_Document.Descendants("Carts").Where((c) => c.Element["CART_NAME"].Value.Equals("dd")).FirstOrDefault();
if (XML_XElement != null)
{
XML_XElement.SetElementValue("CART_NAME", "bbbbb");
}
else
{
// Add new
XElement newProgress = new XElement("Carts", new XElement("CART_NAME", "dd"), new XElement("CART_COLOR", "ff"));
XElement rootNode = XML_Document.Root;
rootNode.Add(newProgress);
}
using (StreamWriter XML_StreamWriter = new StreamWriter(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Write)))
{
XML_StreamWriter.Write(XML_Document.ToString());
XML_StreamWriter.Close();
}
}
I tried your code but I'm having a bad time making it to work.
If not a big deal, please could you tell me how to modify it ?
I mean, if a record is found, instead of editing, to remove it?
Honestly I'm stuck and any help is more than apprecisted!
Ren13B said:
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Click to expand...
Click to collapse
Ren,
Just to say thank you for your last code. I made a little mod and now it works ok!
Thanks a lot for helping me out!

Categories

Resources