self-modifying under windows issue overwrite - c++

I am writting a self-mutation code , and its original value before overwrite is 1,but after the overwrite should be 42. I think I am missing some aspecs because I got 1 on both original and mutation overwrite. my complete code looks like this gist link , but the original source was written under *unix https://shanetully.com/2013/12/writing-a-self-mutating-x86_64-c-program/
#include <windows.h>
#include <iostream>
using namespace std;
int getpagesize();
void foo(void);
int change_page_permissions_of_address(void *addr);
int getpagesize() {
SYSTEM_INFO si;
GetSystemInfo(&si);
return unsigned(si.dwPageSize);
}
void foo(void) {
int i = 0;
i++;
printf("i: %d\n", i);
}
int change_page_permissions_of_address(void *addr) {
// Get total function size
int page_size = getpagesize();
DWORD dwOldProtect;
// Obtain the addresses for the functions so we can calculate size.
uintptr_t tmp = (uintptr_t)addr-(uintptr_t)addr%page_size;
addr = (void*)tmp;
// We need to give ourselves access to modifify data at the given address
if (VirtualProtect(addr, page_size, PAGE_EXECUTE_READWRITE, &dwOldProtect) == -1) {
return -1;
}
return 0;
}
int main() {
void *foo_addr = (void*)foo;
if (change_page_permissions_of_address(foo_addr) == -1) {
printf("Error while changing page permissions of foo(): %s\n");
return 1;
}
// Call the unmodified foo()
puts("Calling foo...");
foo();
// Change the immediate value in the addl instruction in foo() to 42
unsigned char *instruction = (unsigned char*)foo_addr + 18;
*instruction = 0x2A;
puts("Calling foo..., but I am the self-modifying");
foo();
cin.get();
return 0;
}

Check of VirtualProtect is incorrect as it returns FALSE, not -1 in case of an error. Also I suspect that you will need to obtain a pointer to a starting page of the region of pages that foo belongs to and it is not clear where did you get offset 18 from.

Related

Writing to multilevel pointer crashes .exe

I'm trying to edit pointer's value with dll but it crashes the program. Pointer is 100% correct (checked and tested with cheat engine). My goal is to change its value to 1 (I can do it via cheat engine, but I need to convert it to code).
typedef void(__fastcall* _wh)(int val);
_wh wh;
uintptr_t FinalAddress(uintptr_t ptr, std::vector<DWORD> offsets)
{
uintptr_t addr = ptr;
for (unsigned int i = 0; i < offsets.size(); ++i)
{
addr = *(uintptr_t*)addr;
addr += offsets[i];
}
return addr; // returns the main pointer from needed assets
}
DWORD WINAPI HackThread(HMODULE hModule)
{
AllocConsole();
FILE* f;
freopen_s(&f, "CONOUT$", "w", stdout);
std::cout << "dll injected\n" << std::endl;
uintptr_t moduleBase = (uintptr_t)GetModuleHandle(L"Soria2.pl.exe");
uintptr_t adres = FinalAddress(moduleBase + 0x267D94, {0xC, 0x66C});
wh = (_wh)adres; // access the pointer's pointer to edit the value;
std::cout << wh;
while (true)
{
if (GetAsyncKeyState(VK_SHIFT) & 1)
{
wh(1);
}
Sleep(10);
}
fclose(f);
FreeConsole();
FreeLibraryAndExitThread(hModule, 0);
return 0;
}
Ok I've figured it out. It turned out that the thing I wanted was just a variable and I wanted to call the function. This part was problematic:
wh = (_wh)adres; // access the pointer's pointer to edit the value;
I changed it to:
int* wallHack = (int*)adres
and simply changed the value to:
*wallhack = 1

self-mutating issues at the moment of change permisions

I am creating a self-mutation under Windows, but when I try to change my permissions page boundaries, it works under Dev C++, but the same code doesn't work under Visual Studio 2017. Once I compile it works, but it always return me original function result 1, mutation 1 when it should be 42.
Dev C++
int change_page_permissions_of_address(void *addr) {
// Move the pointer to the page boundary
int page_size = getpagesize();
DWORD dwOldProtect;
addr -= (unsigned uintptr_t)addr % page_size; // it works under dev c++
if(VirtualProtect(addr, page_size, PAGE_EXECUTE_READWRITE,&dwOldProtect) == -1) {
return -1;
}
return 0;
}
Visual Studio 2017
int change_page_permissions_of_address(void* address) {
// Move the pointer to the page boundary
unsigned char* addr = reinterpret_cast<unsigned char *>(address); // cast before operation
int page_size = getpagesize();
DWORD dwOldProtect;
addr -= (uintptr_t)addr % page_size; // doesnt work under visual studio
if (VirtualProtect(addr, page_size, PAGE_EXECUTE_READWRITE, &dwOldProtect) == -1) {
return -1;
}
return 0;
}
main
int main(){
void *foo_addr = (void*)foo;
if(change_page_permissions_of_address(foo_addr) == -1) {
fprintf(stderr, "Error while changing page permissions of foo(): %s\n", strerror(errno));
return 1;
}
// Call the unmodified foo()
puts("Calling foo...");
foo();
// Change the immediate value in the addl instruction in foo() to 42
unsigned char *instruction = (unsigned char*)foo_addr + 18;
*instruction = 0x2A;
// Call the modified foo()
puts("Calling foo..., but I am the self-modifying");
foo();
return 0;
}
self-mutation_visual

looping function giving error of "return’ with a value, in function returning void"

original code is
#define MAX_FRAMES 10000
#define MS_BETWEEN_FRAMES CONFIG_FB_MSM_LOGO_ANIMATE_FPS
int load_565rle_image(char *filename, bool bf_supported);
struct delayed_work rle_animate_work;
static void load_565rle_animate(struct work_struct *work)
{
int i, ret = 0, bf_supported = 0;
char filename [20];
struct fb_info *info = registered_fb[0];
set_fs(KERNEL_DS);
printk(KERN_INFO "Starting kernel boot animation\n");
for (i = 1; i < MAX_FRAMES; i++) {
sprintf(filename, "/res/bootlogo/%d.rle", i);
ret = load_565rle_image(filename, bf_supported);
sys_unlink(filename);
if (ret == -ENOENT)
break;
info->fbops->fb_open(info, 0);
info->fbops->fb_pan_display(&info->var, info);
msleep(MS_BETWEEN_FRAMES);
}
}
static int __init logo_animate_init(void)
{
INIT_DELAYED_WORK(&rle_animate_work, load_565rle_animate);
schedule_delayed_work(&rle_animate_work, 5 * HZ);
return 0;
}
static void __exit logo_animate_exit(void)
{
return;
}
this make kernel logo animated, by loading series of *.rle image continuously ie 1.rle>2.rle>3.rle>4.rle>5.rle and so on.
the way it was originally written is to stop loading those images when it reaches end of image filename, ie if last filename is 5.rle, it stops and halted there.
basicaly what i'm trying to do now is looping, when it reaches last file (5.rle) it'll continue loading from the beginning again (1.rle).
so i added CONFIG_FB_MSM_LOGO_ANIMATE_LOOP
static void load_565rle_animate(struct work_struct *work)
{
int i, ret = 0, bf_supported = 0;
char filename [20];
struct fb_info *info = registered_fb[0];
set_fs(KERNEL_DS);
printk(KERN_INFO "Starting kernel boot animation\n");
for (i = 1; i < MAX_FRAMES; i++) {
sprintf(filename, "/res/bootlogo/%d.rle", i);
ret = load_565rle_image(filename, bf_supported);
sys_unlink(filename);
if (ret == -ENOENT)
#ifdef CONFIG_FB_MSM_LOGO_ANIMATE_LOOP
return ret;
#else
break;
#endif
info->fbops->fb_open(info, 0);
info->fbops->fb_pan_display(&info->var, info);
msleep(MS_BETWEEN_FRAMES);
}
}
but when the CONFIG_FB_MSM_LOGO_ANIMATE_LOOP is enable, it give compile error of 'warning: ‘return’ with a value, in function returning void [enabled by default]'
which halted the compile process. any thoughts?
#ifdef CONFIG_FB_MSM_LOGO_ANIMATE_LOOP
return ret;
#else
break;
#endif
this is beeing preprocessed by preprocessr and result in returning int ret from your function when CONFIG_FB_MSM_LOGO_ANIMATE_LOOP is defined. So
‘return’ with a value, in function returning void
seems to be quite reasonable hint.
solution:
change also function returned type then or change it to:
#ifdef `CONFIG_FB_MSM_LOGO_ANIMATE_LOOP`
return;
#else
break;
#endif

CryptGenRandom output not getting same as rand() call

I tried to create random number using CryptGenRandom() call for avoiding cryptographic attack.
I tried to run follwing code which prints both rand call and CryptGenRandom() call.
HCRYPTPROV hProvider = 0;
const DWORD dwLength = 5;
BYTE pbBuffer[dwLength] = {};
if (!::CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT|CRYPT_SILENT))
return 1;
srand((unsigned)time (0));
for(int i=0; i<10; ++i)
cout<<"rand()::"<<i<<":"<<rand()<<endl;
for (DWORD i = 0; i < dwLength; ++i)
{
if (!::CryptGenRandom(hProvider, dwLength, pbBuffer))
{
::CryptReleaseContext(hProvider, 0);
return 1;
}
std::cout << "windows::"<<i<<"::"<<static_cast<unsigned int>(pbBuffer[0])<< std::endl;
}
if (!::CryptReleaseContext(hProvider, 0))
return 1;
but output of this getting for rand() call is
rand()::0:9754
rand()::1:526
rand()::2:29162
rand()::3:10461
rand()::4:31585
rand()::5:15594
rand()::6:12157
rand()::7:19178
rand()::8:5413
rand()::9:16157
and CryptGenRandom() call is giving
windows::0::167
windows::1::138
windows::2::197
windows::3::101
windows::4::44
Can anyone help me to get same output which is giving rand() call using CryptGenRandom?
CryptGenRandom() is giving only 3 digit random numbers which not sufficient for setting values for sleep calls which I am using in my code.
The problem is your use of pBuffer[0] here.
static_cast<unsigned int>(pbBuffer[0])
As your code shows, pBuffer[0] is a single BYTE. That's why you're not getting values greater than 255.
If you want any representable unsigned int, you'll want this.
const DWORD dwLength = sizeof(unsigned int);
And this, to use all the bytes in pBuffer.
*static_cast<unsigned int*>(pbBuffer)
Uhm, it's only giving 3 digit numbers because you are taking only one byte and converting it to an unsigned int when you do this: static_cast<unsigned int>(pbBuffer[0]) and a BYTE (i.e. an unsigned char) can only fit values between 0 and 255.
You can change your approach slightly:
unsigned int MyGoodRand()
{
// We make this a static so we don't have
// to initialize it all the time because
// that is expensive.
static HCRYPTPROV hProvider = 0;
if(hProvider == NULL)
{
if(!::CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT|CRYPT_SILENT))
return 0;
}
unsigned int randval = 0;
if (!::CryptGenRandom(hProvider, sizeof(unsigned int), static_cast<PBYTE>(&randval)))
randval = 0; // Failure!
return randval;
}
This function will return 0 on failure which is a problem, because 0 is also a possible result from CryptGenRandom and additionally will leak the HCRYPTPROV because it's only available inside the function and once allocated there's no way to release it.
We could augmented it to return true or false accordingly and accept randval by reference from its caller, but that wouldn't solve the HCRYPTPROV leak. Let's instead make a class which has the HCRYPTPROV as a member along with an operator() which will be used to generate new numbers.
Something like this:
class MYPRNG
{
private:
HCRYPTPROV hProvider;
// declare but not define a private copy constructor to
// prevent copy-construction of this object. If you're
// using C++11 you can use the =delete syntax instead.
MYPRNG(const MYPRNG &o) = delete;
// Same with the default assignment operator.
MYPRNG& operator=(const MYPRNG& o)
public:
MYPRNG()
: hProvider(NULL)
{
if(!::CryptAcquireContext(&hProvider, 0, 0, PROV_RSA_FULL,
CRYPT_VERIFYCONTEXT|CRYPT_SILENT))
hProvider = NULL; // ensure that it's NULL
}
~MYPRNG()
{
if(hProvider)
CryptReleaseContext(hProvider, 0);
}
bool operator()(unsigned int &randval)
{
if(hProvider == NULL)
return false;
if (!::CryptGenRandom(hProvider,
sizeof(unsigned int),
static_cast<PBYTE>(&randval)))
return false;
return true;
}
};
Now we have no leaks and we can easily generate random numbers and determine if the operation succeeded or failed reliably. We can use it like this:
MYPRNG prng;
unsigned int rval;
for(int i = 0; i < 10; i++)
{ // try to get 10 random numbers!
if(!prng(rval))
{
// FAILED TO GENERATE A NEW RANDOM NUMBER!
}
else
{
// A new random number is now in rval. Use it
}
}

Running multiple objects each on their own thread appears to run the same object multiple times

I'm trying to create 12 new instances of a class and run each of them it's a own thread, but they seam to share the same data.
all 12 instances are on the same X and Y position, but they each should move on a random direction.
as you can see in the code, i tried various apraoches and i can't find out why.
what am i doing wrong here?
p.s. yes ... i know there are still some unused variables.
p.s.s i have looked at many places and also here before i posted the question
enemy.cpp
#include "enemy.h"
#include <time.h>
#include <windows.h>
FILE* pEnemyFile = fopen ("enemylog.txt","w");
Enemy::Enemy(const MouseServer& mServer, int& lastMousePosX, int& lastMousePosY, int& winSizeX, int& winSizeY )
:mouseServer(mServer),
lastMouseX( ( lastMousePosX ) ? lastMousePosX : 0 ), // evaluate if we get the reference
lastMouseY( ( lastMousePosY ) ? lastMousePosY : 0 ),
myPositionX(0),
myPositionY(0),
winSizeX(winSizeX),
winSizeY(winSizeY),
x(0),
y(0)
{
// original source:
// http://msdn.microsoft.com/en-us/library/windows/desktop/ms682516(v=vs.85).aspx
// Allocate memory for thread data.
EDATA threadEnemyData = (EDATA) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,sizeof(enemyData));
// http://www.codeproject.com/Articles/14746/Multithreading-Tutorial
// http://www.codeguru.com/cpp/w-d/dislog/win32/article.php/c9823/Win32-Thread-Synchronization-Part-I-Overview.htm
// usefull information
// http://msdn.microsoft.com/en-us/library/z3x8b09y(v=vs.100).aspx
if( threadEnemyData == NULL )
{
//If the array allocation fails, the system is out of memory
//so there is no point in trying to print an error message.
//Just terminate execution.
ExitProcess(2);
}
threadEnemyData->X = 0;
threadEnemyData->Y = 0;
this->hThread = CreateThread(
NULL,
0,
this->MyThreadFunction,
this,
/*threadEnemyData,*/
0,
&this->dwThreadID
);
// Check the return value for success.
// If CreateThread fails, terminate execution.
// This will automatically clean up threads and memory.
if (this->hThread== NULL)
{
ErrorHandler(TEXT("CreateThread"));
ExitProcess(3);
}
//End of main thread creation loop.
}
Enemy::~Enemy()
{
// Wait until all threads have terminated.
WaitForSingleObject(this->hThread,INFINITE);
// Close all thread handles and free memory allocations.
this->hDefaultProcessHeap = GetProcessHeap();
if (this->hDefaultProcessHeap == NULL) {
}
CloseHandle(this->hThread);
//if(threadEnemyData != NULL)
//{
// HeapFree(GetProcessHeap(), 0, threadEnemyData);
// hThread = NULL; // Ensure address is not reused.
//}
// close debug file
fclose (pEnemyFile);
}
void Enemy::Draw(D3DGraphics& gfx)
{
gfx.PutPixel(this->x + 0,this->y,255,255,255);
gfx.PutPixel(this->x + 1,this->y,255,255,255);
gfx.PutPixel(this->x + 2,this->y,255,255,255);
gfx.PutPixel(this->x + 3,this->y,255,255,255);
gfx.PutPixel(this->x + 4,this->y,255,255,255);
gfx.PutPixel(this->x + 5,this->y,255,255,255);
gfx.PutPixel(this->x + 6,this->y,255,255,255);
gfx.PutPixel(this->x + 7,this->y,255,255,255);
}
// read
// http://www.tek-tips.com/viewthread.cfm?qid=1068278
DWORD WINAPI Enemy::MyThreadFunction( void* param )
{
Enemy* self = (Enemy*) param;
////self-> // <-- "this"
return self->NewThread();
}
/* initialize random seed: */
// the itelligence loop of your enemy/object
DWORD Enemy::NewThread()
{
do
{
srand ( time(NULL) );
/* generate random number: */
//self->x += rand() % 4;
//self->y += rand() % 4;
this->x += rand() % 4;
this->y += rand() % 4;
// debug stuff
char buffer[ 64 ];
sprintf_s(buffer, "enemy: x: %d Y: %d id: %d\n", (char)this->x, (char)this->y, (char)this->dwThreadID);
fputs (buffer,pEnemyFile);
// allow processor time to other threads
Sleep(100);
}while(true); // endles loop
}
void Enemy::ErrorHandler(LPTSTR lpszFunction)
{
// Retrieve the system error message for the last-error code.
this->dw = GetLastError();
// todo
}
enemy.h
#pragma once
#include "timer.h"
#include "D3DGraphics.h"
#include "D3DGraphics.h"
#include "Mouse.h"
/////// thread stuf
#include <tchar.h>
#include <strsafe.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
class Enemy
{
public:
Enemy();
Enemy(const MouseServer& mServer, int& lastMousePos, int& lastMousePosY, int& winSizeX, int& winSizeY);
~Enemy();
static DWORD WINAPI MyThreadFunction( LPVOID lpParam );
DWORD Enemy::NewThread();
void ErrorHandler(LPTSTR lpszFunction);
void lookingForFood();
void Draw(D3DGraphics& gfx);
int Enemy::correctX(int xParam);
int Enemy::correctY(int yParam);
private:
int myPositionX;
int myPositionY;
int lastMouseX;
int lastMouseY;
int winSizeX;
int winSizeY;
//int moveToX; // todo
//int moveToY;
int x;
int y;
// threading stuff
typedef struct ENEMYDATA // don't forget "typedef "
{
int X;
int Y; // test
} enemyData, *EDATA;
// Cast the parameter to the correct data type.
// The pointer is known to be valid because
// it was checked for NULL before the thread was created.
static Enemy* self;
HANDLE hThread;
DWORD dwThreadID;
HANDLE hDefaultProcessHeap;
DWORD dw; // error message
EDATA* threadEnemyData;
MouseClient mouseServer;
//D3DGraphics& grafix;
Timer timer;
};
It's commented out in your thread proc, but looks like you were on the right track:
srand ( time(NULL) );
It didn't work for you because all the threads start so fast that they end up with time(NULL) returning the same value for each thread. This means they're all using the same random sequence. Try seeding rand with the thread ID (or some other source that's unique per thread) and you should see unique pseudorandom number sequences.