How To hook time function - c++

EveryOne. I have a project which call some func to get time such as
time_t t = time(NULL);
#ifndef _WIN32
timespec ts;
if( -1 == clock_gettime(CLOCK_MONOTONIC,&ts) )
GenErrnoErr()
return uint64( ( ((uint64)ts.tv_sec*1000 + (uint64)ts.tv_nsec/1000000) - m_uBaseTime ) * ms_dTimeRatio ) ;
#else
LARGE_INTEGER uTime;
QueryPerformanceCounter(&uTime);
return uint64( ( uint64(uTime.QuadPart/CFrequency::Instance().Get().QuadPart) - m_uBaseTime ) * ms_dTimeRatio );
#endif
`
what I wana is to hook all this time func, without change the code exist. when it calls time(NULL) or other func, it returns the time i faked.

The usual way that this sort of thing is done is with the --wrap option to the linker. It works like this:
Write your replacement function, but instead of naming it time(...), name it __wrap_time(...);
In your replacement function, if you need to call the original time() function, actually call __real_time();
When linking the program, add the following option: --wrap=time. This will make the linker link any other module's call to time() to __wrap_time(), and yet still allow the original time() function to be called via __real_time().
Thus:
// Need this to satisfy the compiler
extern time_t __real_time(time_t *seconds);
time_t __wrap_time(time_t *seconds) {
if (seconds==NULL) {
return 0;
} // if
return __real_time(seconds)
} // __wrap_time(seconds)

Detour the function in the process to your hook. You'll need to inject a dll to hook it, and add a jmp to your hook function address within the original functions epilogue. Some more info would help too...

Related

c++ function addresses coming out different in attached profiler library than in the subject code base

I have written an instrument-er in C++ to log entry and exit functions by hooking on enter and exit calls. It is working as supposed to with a legacy code base. However on hooking with a project that I downloaded from git, function addresses that I save in an extern variable in the subject code, they are coming out different in the profiler library. That is messing up the function pointer comparison between hooked and saved functions.
Function address in subject code main file, breakpoint is inside the _penter hook function in the profiler code currently
The same entry is showing a different address with a "_" preceding the function name, in the profiler code
I have no idea how it is changing the addresses and want to know if I am doing something wrong.
The way I am doing it is, I have an extern array of function pointers( and their names) that is initialized with subject code functions' references in the subject main file(where all functions are available). In hook function (_penter) of the library, I get the address of the function just entered. So I compare it with the addresses in the extern array, and if it is a match, I log the entered function.
SNIPPET FROM PROFILE.H (profiler)
extern Signature FuncTable[3000];
SNIPPET FROM PROFILE.CPP (profiler)
void _stdcall EnterFunc0(unsigned * pStack)
{
void * pCaller;
pCaller = (void *)(pStack[0] - 5); // the instruction for calling _penter is 5 bytes long
Signature * funct = FuncTable; //the table that has references to functions and their names
funct = FuncTable;
while (funct->function)
{
//const BYTE * func = (const BYTE *)funct->function;
if ((void *)(pStack[0] - 5) == (void *)(funct->function))
{
int a = 0;
linesBuffer = linesBuffer + "Entering " + funct->signature + ";";
linesBuffer = linesBuffer + "\n";
WriteToFile(false); //function buffers 100kb before writing
break;
}
funct++;
}
}
extern "C" __declspec(naked) void __cdecl _penter()
{
_asm
{
pushad // save all general purpose registers
mov eax, esp // current stack pointer
add eax, 32 // stack pointer before pushad
push eax // push pointer to return address as parameter to EnterFunc0
call EnterFunc0
popad // restore general purpose registers
ret // start executing original function
}
}
SNIPPET FROM main.c (subject code main file)
#include "../Profile/Profile.h"
Signature FuncTable[] = {
{ (int)TetrisView_ProcessPauseMenu, "TetrisView_ProcessPauseMenu" },
{ NULL }
};
I think it is because of Incremental Linking. When it is turned on, you'll get an Incremental Linking Table (ILT). ILT contains a jump table. When a function is called, it is called via this ILT.
In FuncTable, you'll get an address which is in ILT, it won't be the address of the actual function. But in _penter, its return address will be the actual function (this is what is put in pCaller).
Turn off incremental linking, and you'll be fine.

llvm replace a function with another one

I am trying to replace a function call with another one. e.g. here is the code with 3 functions - print1, print2 and main:
#include <stdio.h>
extern "C" {
int print1()
{
printf("Inside print1\n");
return 0xdeadbeef;
}
int print2()
{
printf("Inside print2\n");
return 0xbeefdead;
}
int main(void)
{
return print1();
}
}"
My goal is to replace use of print1 (in main) with print2. I compile the above code into an llvm::Module* (called main in the code below) and then create an execution engine out of it.
std::string errMsg;
llvm::ExecutionEngine *ee =
llvm::EngineBuilder( main ).setErrorStr( &errMsg ).create();
ASSERT_NE( ee, nullptr )<<"Execution engine is nullptr:"<<errMsg;
At this point, I am able to get all the 3 functions (print1, print2 and main) from the execution engine and am able to execute them fine. However, problem occurs when I try to replace function "print1" with "print2", as follows:
llvm::Function *print1f = main->getFunction( "print1" );
llvm::Function *print2f = main->getFunction( "print2" );
llvm::Function *mainf = main->getFunction( "main" );
//carry out the replacement
print2f->takeName( print1f );
ee->freeMachineCodeForFunction( mainf );
ee->freeMachineCodeForFunction( print1f );
print1f->replaceAllUsesWith( print2f );
print1f->deleteBody();
print1f->dropAllReferences();
print1f->eraseFromParent();
//run main
void *mainfPtr = ee->getPointerToFunction( mainf );
mainfPtr = ee->recompileAndRelinkFunction( mainf );
ASSERT_NE( mainfPtr, nullptr );
ret = ((int(*)(void))(mainfPtr))();
*EXPECT_EQ(0xbeefdead, ret);*
However, ret is returned as 0xdeadbeef, as if print1 is being called and not print2. Can someone please let me know if I am following the right steps to replace the function call. If there is other method, please let me know.
thx
Vikas.
==========
If the compiler were to inline print1 in main, the function would never actually be called; Instead, main would have its own private version of print1's code pasted in. Since it doesn't actually have to refer to the shared print1 anymore, swapping in print2 might not affect main's behavior.
If you want to verify that this is the problem (and/or keep it from happening, if it is), try telling the compiler not to inline.

Calling lua function that returns table

I know the basics of interacting with lua and C, and I am currently trying to perform the following line of lua in c++
Func1():Func2().Table1.value1
I am trying to get the value of "value2" and use it in my C program. The following is the code I wrote to attempt to get this value in C.
int GetNumber()
{
int retn = 0;
g_clientlua.lua_getfield(LUA_REGISTRYINDEX, "Player");
g_clientlua.lua_getfield(-1, "Func2");
g_clientlua.lua_getfield(LUA_GLOBALSINDEX, "Func1");
g_clientlua.lua_call(0, 1);
g_clientlua.lua_call(1, 1);
if (g_clientlua.lua_isnil(-1))
return retn;
g_clientlua.lua_getfield(-1, "Table1");
if (g_clientlua.lua_isnil(-1))
return retn;
g_clientlua.lua_getfield(-1, "value1");
if (g_clientlua.lua_isnil(-1))
return retn;
retn = (int)g_clientlua.lua_tointeger(-1);
}
The clientlua thing is an object that basically just allows me to call a method which calls it's lua_* function equivalent and fills the lua_state pointer parameter with a member variable that is a pointer to the lua state.
Every time I call this, it complains about me causing a lua stack leak. To solve this, I tried adding a lua_pop(3) to the end, but then it just crashes my program without reporting an error, so I assume I am doing something wrong.
Anyone have any words of wisdom for me? Kinda lost here. I doubt the above code is even written properly, how would I write the above lua call in C?
You need to call Func1 before you try to get Func2 as Func2 comes from the table that Func1 returns (and not from the global table).
Then you need to call Func2 and look up Table1 in that returned value, etc.
What "stack leak" complaint are you getting? If you are calling this function from C directly then yes, you need to be sure that anything you put on the lua stack (that isn't for consumption by the caller, etc.) is popped from the lua stack before you return.
The GetNumber function isn't doing exactly the same as the lua snippet you're going for. Specifically GetNumber is getting the value of "Func2" from the registry while your lua snippet is getting the value of "Func2" from the table returned by Func1(). Unless you're certain that registry.Player.Func2 == Func1().Func2 is always true, your C++ version will not have the same behavior.
Let's break down Func1():Func2().Table1.value1 into more explicit steps to help with the C translation:
Get function associated with _G.Func1
Call that function and get a table back
Get function associated with "Func2" from the returned table in step 2
Call that function and pass as argument the table from step 2. Get another table back as result
I found it helpful to track what the stack contains as a side-comment as the operations are performed:
int GetNumber()
{
// Func1()
gclientlua.lua_getfield(LUA_GLOBALSINDEX, "Func1"); // Func1
g_clientlua.lua_call(0, 1); // {}
// Func2( {} )
g_clientlua.lua_getfield(-1, "Func2"); // {}, Func2
g_clientlua.lua_insert(-2); // Func2, {}
g_clientlua.lua_call(1, 1); // {}
if( g_clientlua.lua_type(-1) != LUA_TTABLE )
{
g_clientlua.lua_pop(1);
return 0;
}
// {}.Table1
g_clientlua.lua_getfield(-1, "Table1"); // {}, {}(Table1)
if( g_clientlua.lua_type(-1) != LUA_TTABLE )
{
g_clientlua.lua_pop(2);
return 0;
}
// tonumber( Table1.value1 )
g_clientlua.lua_getfield(-1, "value1"); // {}, {}(Table1), value1
int retn = g_clientlua.lua_tointeger(-1);
g_clientlua.lua_pop(3);
return retn;
}
Notice that GetNumber pops off all the arguments it places on the stack before returning. This ensures that GetNumber leaves the lua stack the way it was found. This can probably be automated with RAII if you're using C++.

How to override the external function?

I'm doing some exercises and I came across a problem. I have got DLL file which will be injected into exe file. I have to override one function from that exe, by my function from DLL file. I can't interfere in exe file, but in DLL I can. I got address of function which I have to replace (got it by GetProcAddress() function ) and now I have to redirect this address to my function. What I want to achievie is when exe will call function, he will call not his internal function, but my func, from dll. I hope that I made my myself clear. That's how head of function looks like:
int ( func )( float, int );
I tried to do it like that:
typedef int ( *func_ptr )( float, int );
func_ptr myFunction;
myFunction = (*func_ptr)GetProcAddress(hModule, func_name);
*myFunction = newFunction;
You might want to have a look at Detours: http://research.microsoft.com/en-us/projects/detours/
Or manually patch the target function with a jump to your replacement.

Obfuscate External API Calls C++

I have a code in C++ that calls functions from external library. The function I called is CreateProcess like below.
CreateProcess(NULL,pProcessName,NULL,NULL,false,CREATE_SUSPENDED,
NULL,NULL,&suStartUpInformation,&piProcessInformation)
Now when I compile the code and dissemble it, the assembly shows the plain text as CreateProcess(args1, args2, ...). Is there any way to obfuscate or encrypt the function call to API so that if someone dissembles it then he won't ever know which functions are called.
Thanks!
Any function that is imported by name will always have the name embedded into the binary (in the import descriptor thunk to be exact), the detailed parameter info is gotten from the pdbs as Steve mentioned (however analysing debuggers like ollydbg can deduce args, due to the symbol name being available). The only ways to avoid this is to either encrypt to IAT (using 3rd party packers/virtualizers/binary protection systems etc, like enigma) or use a custom version of GetModuleHandle (basically just a PEB spelunking tool) and GetProcAddress (a PE spelunking tool this time), then by storing all the api calls you need as runtime encrypted strings, you can then call whatever you need without plain text giving you away (securerom does this, though it uses GetProcAddress directly, along with some binary obfuscation).
Update:
for compile-time 'obfuscated' strings, you can use something like this (really simple, but it should be portable, if you use C++0x, this is a lot easier):
#define c(x) char((x) - 1) //really simple, complexity is up to the coder
#define un(x) char((x) + 1)
typedef int (WINAPI* MSGBOX)(HWND, LPCSTR, LPCSTR, UINT);
const int ORD_MASK = 0x10101010;
const char szMessageBoxA[] = {c('M'),c('e'),c('s'),c('s'),c('a'),c('g'),c('e'),c('B'),c('o'),c('x'),c('A')};
FARPROC GetProcAddressEncrypted(HMODULE hModule, const char* szName, BOOL bOrd = FALSE)
{
if(bOrd)
return GetProcAddress(hModule,reinterpret_cast<const char*>(reinterpret_cast<int>(szName) ^ ORD_MASK)); //this requires that ordinals be stored as ordinal ^ ORD_MASK
char szFunc[128] = {'\0'};
for(int i = 0; *szName; i++)
szFunc[i] = uc(*szName++);
return GetProcAddress(hModule,szName);
}
MSGBOX pfMsgBox = static_cast<MSGBOX>(GetProcAddressEncrypted(GetHandleEncrypted(szUser32),szMessageBox));
Optionally you may want to use MSVC's EncodePointer to hide the values in the global function pointers (just remember to use DecodePointer when you call them).
note: code is untested, as its just off the top of my head
You might use dynamic linking. In Windows, use LoadLibrary, LoadLibraryEx, GetProcAddress. Now in you code, include some form in obfuscated form of name instead of the real lib/symbol names and unofuscate it at runtime.
You might want to use dynamic dispatch (function pointers) so that the function called cannot be deduced easily from the code.
You might delegate the work of calling this function to another thread (using some IPC mechanism).
But it's quite useless, using a debugger it will very simple to find that this function has been called. And it will be very simple to detect that a process has been created.
Ok! here is the solution. Lets say I want to call "MessageBoxA" from "user32.dll".
So here is how I will do it using LoadLibraryA & GetProcAddress .
//Ok here you can see.
//I am passing DLL name(user32.dll) and DLL function(MessageBoxA) as String
//So I can also perform Encrypt & Decrypt operation on Strings and obfuscate it.
//Like i can encrypt the string "user32.dll" and at runtime decrypt it and pass it as
//an argument to "LoadLibraryA" and same for the Function name "MessageBoxA".
//The code is compiled in DevC++ 4.9.9.2.
#include <windows.h>
#include <iostream>
using namespace std;
void HelloWorld()
{
char* szMessage = "Hello World!";
char* szCaption = "Hello!";
HMODULE hModule = LoadLibraryA( "user32.dll" );
FARPROC fFuncProc = GetProcAddress( hModule, "MessageBoxA" );
( ( int ( WINAPI *)( HWND, LPCSTR, LPCSTR, UINT ) ) fFuncProc )( 0, szMessage, szCaption, 0 );
}
int main()
{
HelloWorld();
}