Solved C++ Manual Map Injection

Hexui Undetected CSGO Cheats Sinkicheat PUBG Cheat

VirtualCoder

Newbie
Mar 3, 2016
4
32
0
https://www.youtube.com/watch?v=qo_ezg2SOw4

memlib.h
C++:
#include <windows.h>

typedef void* HCUSTOMMODULE;

typedef HCUSTOMMODULE(*MemLoadLibraryFn)(LPCSTR, void *);
typedef FARPROC(*MemGetProcAddressFn)(HANDLE, LPCSTR, void *);
typedef void(*MemFreeLibraryFn)(HANDLE, void *);

typedef BOOL(WINAPI *DllEntryProc)(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved);
typedef int (WINAPI *ExeEntryProc)(void);


typedef struct {
	PIMAGE_NT_HEADERS headers;
	unsigned char *codeBase;
	HCUSTOMMODULE *modules;
	int numModules;
	BOOL initialized;
	BOOL isDLL;
	BOOL isRelocated;
	MemLoadLibraryFn loadLibrary;
	MemGetProcAddressFn getProcAddress;
	MemFreeLibraryFn freeLibrary;
	void *userdata;
	ExeEntryProc exeEntry;
	DWORD pageSize;
} MEMORYMODULE, *PMEMORYMODULE;

typedef struct {
	LPVOID address;
	LPVOID alignedAddress;
	DWORD size;
	DWORD characteristics;
	BOOL last;
} SECTIONFINALIZEDATA, *PSECTIONFINALIZEDATA;

class CWin32PE
{
protected:
	int CheckSize(size_t size, size_t expected);
    DWORD GetRealSectionSize(PMEMORYMODULE module, PIMAGE_SECTION_HEADER section);
	int CopySections(const unsigned char *data, size_t size, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module);
	int FinalizeSection(PMEMORYMODULE module, PSECTIONFINALIZEDATA sectionData);
	int FinalizeSections(PMEMORYMODULE module);
	int ExecuteTLS(PMEMORYMODULE module);
	int PerformBaseRelocation(PMEMORYMODULE module, ptrdiff_t delta);
	int BuildImportTable(PMEMORYMODULE module);
};

class CLoad : protected CWin32PE
{
private:
	HANDLE MemLoadLibraryEx(const void *data, size_t size, MemLoadLibraryFn loadLibrary,
		MemGetProcAddressFn getProcAddress, MemFreeLibraryFn freeLibrary, void *userdata);
public:
	HANDLE LoadFromMemory(const void* , size_t);
	HANDLE LoadFromResources(int IDD_RESOUCE);
	HANDLE LoadFromFile(LPCSTR filename);

	FARPROC GetProcAddressFromMemory(HANDLE hModule, LPCSTR ProcName);

	int CallEntryPointFromMemory(HANDLE hModule);
	void FreeLibraryFromMemory(HANDLE hModule);
};
C++:
// Crypter.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "MemLoadLibrary.h"

typedef void(_cdecl* func)();


unsigned char rawData[6656] = {
	0x4D, 0x5A, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00,
	0xFF, 0xFF, 0x00, 0x00, 0xB8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};


int _tmain(int argc, _TCHAR* argv[])
{
	CLoad lib;
	HANDLE hLibrary = 0;
	hLibrary = lib.LoadFromMemory(rawData, sizeof(rawData)); // loaded the dll from byte array.
	func fn = (func)lib.GetProcAddressFromMemory(hLibrary, "testfunc");
	fn();
	lib.FreeLibraryFromMemory(hLibrary);
	return 0;
}
memlib.cpp: https://pastebin.com/KP9BP066
 

Broihon

Escobar Tier VIP
Fleep Tier Donator
Dec 22, 2013
1,760
41,528
321
Credits go to publicity and me. [...] Also, I don't remember taking any credit for it, simply spreading the knowledge.
What?

Spreading the knowledge is good and welcome and instead of posting this you could've simply linked Joachim Bauch's github:
fancycode/MemoryModule
Or at least mention his github since the code you posted is 99% his.

But yeah, why give credits when one can simply pretend it's yours and if someone calls you out for it say "Credits go to publicity and me.". The hostility? Because shit like this pisses me off. There's nothing wrong with using someone else's code, there's nothing wrong with writing your own code based on someone else's.
We all do that all the time. But why not give the original coder credits? I credited that repo you ripped of for the gh injector even after completely rewriting everything and modifying the whole loading process simply because without that repo I wouldn't know how to manually map. You copied 99%, added a useless class wrapper, renamed some macros/variables and called it a day. A then you give me this "credits go to publicity and me" bullcrap.


btw


https://guidedhacking.com/threads/manual-mapping-dll-injection-tutorial.10009/
 
Last edited by a moderator:
  • Like
Reactions: Akaion

Fleep

Founder
Meme Tier VIP
May 20, 2012
572
11,023
6
I believe this is better positioned here

All below By:Sleinzel

Yeah, it's undetectable...

Maybe some theorie first, so everybody can understand it:

There's a Windows Function called LoadLibrary, which allows you to inject Dynamic Linked Librarys (.dlls) into a target Process, so you can let a specific process run your own code without having access to the source code. Also you can hook, rewrite and call functions...

Since LoadLibrary is a WindowsAPI Function every Process could hook this function. So basicly what Anti-Cheat Systems do here is:

IF LoadLibrary is called they check into which process it is loaded, if it is loaded into the Process the Anticheat tries to prevent from beeing injected, it bans you.

ManualMapping is a way to Inject Librarys without calling LoadLibary. Since the Anticheat doesn't exactly know which process/function is doing the injecting part, it cannot be hooked...

ManualMapping was developed by a talented individual called Darawk to prevent Warden from detecting his DLL's in Diablo2

Is it still detectable:

YES the original method is detectable by taking a look image_sections_table.

But you can prevent your dll from beeing detected by not sending the PE-Header for example...

Basically the Steps to inject your dll undetectable are:

1. Allocate space for the module in the remote process
2. fix imports
3. fix relocs
4. Map the sections into the remote process
5. call entry point of your DLL


Here is some code I threw together really quickly (still sending the PE-HEader and such stuff):

It does Inject a basic library without any problems, but there's a problem with the imports/relocs... So you cannot inject a DirectX dll... I don't know what I'm doing wrong... I tested it using this dll included in this post (test_module.dll (it shows a messageBox saying Injected if the dll was injected successfully).

My Code:
https://pastebin.com/qM5sE7zY

C++:
////////////////////////////////////////////////////////////////////////////////////////////
// MapRemoteModuleW
////////////////////////////////////////////////////////////////////////////////////////////
BOOL
MapRemoteModuleW(
	DWORD dwProcessId,
	LPCWSTR lpModulePath
	)
{
	BOOL bRet = FALSE;
	HANDLE hFile = 0;
	DWORD fileSize = 0;
	BYTE *dllBin = 0;
	PIMAGE_NT_HEADERS nt_header = 0;
	PIMAGE_DOS_HEADER dos_header = 0;
	HANDLE hProcess = 0;
	LPVOID lpModuleBase = 0;

	PIMAGE_IMPORT_DESCRIPTOR pImgImpDesc = 0;
	PIMAGE_BASE_RELOCATION pImgBaseReloc = 0;
	PIMAGE_TLS_DIRECTORY pImgTlsDir = 0;

	__try
	{
		// Get a handle for the target process.
		hProcess = OpenProcess(
			PROCESS_QUERY_INFORMATION	|	// Required by Alpha
			PROCESS_CREATE_THREAD		|	// For CreateRemoteThread
			PROCESS_VM_OPERATION		|	// For VirtualAllocEx/VirtualFreeEx
			PROCESS_VM_WRITE			|	// For WriteProcessMemory
			PROCESS_VM_READ,
			FALSE, 
			dwProcessId);
		if(!hProcess)
		{
			PRINT_ERROR_MSGA("Could not get handle to process (PID: 0x%X).", dwProcessId);
			__leave;
		}

		hFile = CreateFileW(
			lpModulePath,
			GENERIC_READ,
			FILE_SHARE_READ | FILE_SHARE_WRITE,
			NULL,
			OPEN_EXISTING,
			FILE_ATTRIBUTE_NORMAL,
			NULL);
		if(hFile == INVALID_HANDLE_VALUE)
		{
			PRINT_ERROR_MSGA("CreateFileW failed.");
			__leave;
		}

		if(GetFileAttributesW(lpModulePath) & FILE_ATTRIBUTE_COMPRESSED)
		{
			fileSize = GetCompressedFileSizeW(lpModulePath, NULL);
		}
		else
		{
			fileSize = GetFileSize(hFile, NULL);
		}

		if(fileSize == INVALID_FILE_SIZE)
		{
			PRINT_ERROR_MSGA("Could not get size of file.");
			__leave;
		}

		dllBin = (BYTE*)malloc(fileSize);

		{
			DWORD NumBytesRead = 0;
			if(!ReadFile(hFile, dllBin, fileSize, &NumBytesRead, FALSE))
			{
				PRINT_ERROR_MSGA("ReadFile failed.");
			}
		}
	
		dos_header = (PIMAGE_DOS_HEADER)dllBin;
		
		// Make sure we got a valid DOS header
		if(dos_header->e_magic != IMAGE_DOS_SIGNATURE)
		{
			PRINT_ERROR_MSGA("Invalid DOS header.");
			__leave;
		}
		
		// Get the real PE header from the DOS stub header
		nt_header = (PIMAGE_NT_HEADERS)( (DWORD_PTR)dllBin +
			dos_header->e_lfanew);

		// Verify the PE header
		if(nt_header->Signature != IMAGE_NT_SIGNATURE)
		{
			PRINT_ERROR_MSGA("Invalid PE header.");
			__leave;
		}

		// Allocate space for the module in the remote process
		lpModuleBase = VirtualAllocEx(
			hProcess,
			NULL, 
			nt_header->OptionalHeader.SizeOfImage, 
			MEM_COMMIT | MEM_RESERVE, 
			PAGE_EXECUTE_READWRITE);
		if(!lpModuleBase)
		{
			PRINT_ERROR_MSGA("Could not allocate memory in remote process.");
			__leave;
		}
		
		// fix imports
		pImgImpDesc = (PIMAGE_IMPORT_DESCRIPTOR)GetPtrFromRVA(
			nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress,
			nt_header,
			(PBYTE)dllBin);
		if(nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].Size)
		{
			if(!FixIAT(dwProcessId, hProcess, (PBYTE)dllBin, nt_header, pImgImpDesc))
			{
				PRINT_ERROR_MSGA("@Fixing imports.");
				__leave;
			}
		}
		
		// fix relocs
		pImgBaseReloc = (PIMAGE_BASE_RELOCATION)GetPtrFromRVA(
			(DWORD)(nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].VirtualAddress),
			nt_header,
			(PBYTE)dllBin);
		if(nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_BASERELOC].Size)
		{
			if(!FixRelocations(dllBin, lpModuleBase, nt_header, pImgBaseReloc))
			{
				PRINT_ERROR_MSGA("@Fixing relocations.");
				__leave;
			}
		}

		// Write the PE header into the remote process's memory space
		{
			SIZE_T NumBytesWritten = 0;
			SIZE_T nSize = nt_header->FileHeader.SizeOfOptionalHeader +
				sizeof(nt_header->FileHeader) +
				sizeof(nt_header->Signature);
			
			if(!WriteProcessMemory(hProcess, lpModuleBase, dllBin, nSize, &NumBytesWritten) ||
				NumBytesWritten != nSize)
			{
				PRINT_ERROR_MSGA("Could not write to memory in remote process.");
				__leave;
			}
		}

		// Map the sections into the remote process(they need to be aligned
		// along their virtual addresses)
		if(!MapSections(hProcess, lpModuleBase, dllBin, nt_header))
		{
			PRINT_ERROR_MSGA("@Map sections.");
			__leave;
		}

		// call all tls callbacks
		//
		pImgTlsDir = (PIMAGE_TLS_DIRECTORY)GetPtrFromRVA(
			nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].VirtualAddress,
			nt_header,
			(PBYTE)dllBin);
		if(nt_header->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS].Size)
		{
			if(!CallTlsInitializers(dllBin, nt_header, hProcess, (HMODULE)lpModuleBase, DLL_PROCESS_ATTACH, pImgTlsDir))
			{
				PRINT_ERROR_MSGA("@Call TLS initializers.");
				__leave;
			}
		}

		// call entry point
		if(!RemoteDllMainCall(
			hProcess,
			(LPVOID)( (DWORD_PTR)lpModuleBase + nt_header->OptionalHeader.AddressOfEntryPoint),
			(HMODULE)lpModuleBase, 1, 0))
		{
			PRINT_ERROR_MSGA("@Call DllMain.");
			__leave;
		}

		bRet = TRUE;

		wprintf(L"Successfully injected (%s | PID: %x):\n\n"
			L" AllocationBase:\t0x%p\n"
			L" EntryPoint:\t\t0x%p\n"
			L" SizeOfImage:\t\t0x%p\n"
			L" CheckSum:\t\t0x%p\n",
			lpModulePath,
			dwProcessId,
			lpModuleBase,
			(DWORD_PTR)lpModuleBase + nt_header->OptionalHeader.AddressOfEntryPoint,
			nt_header->OptionalHeader.SizeOfImage,
			nt_header->OptionalHeader.CheckSum);
	}
	__finally
	{
		if(hFile)
		{
			CloseHandle(hFile);
		}

		if(dllBin)
		{
			free(dllBin);
		}

		if(hProcess)
		{
			CloseHandle(hProcess);
		}
	}
	
	return bRet;
}
 
S

Sleinzel

Thank you Fleep.

I'm gonna create a video tutorial this weekend, if I can fix my bad english accent and if I get ManualMap to work with imports/relocs.
 

Fleep

Founder
Meme Tier VIP
May 20, 2012
572
11,023
6
Im sure your voice will be fine, talk slowly if you have to as long as people can see what your doing they can puzzle it all together.

Look forward to seeing this method in action

Fleep
 
S

Sleinzel

Fleep said:
Im sure your voice will be fine, talk slowly if you have to as long as people can see what your doing they can puzzle it all together.

Look forward to seeing this method in action

Fleep
Yeah. I hope it will come out good ;)
 

supercjb1

Newbie
Full Member
May 25, 2012
19
254
0
Personally I think it would be a great thing if you posted the video, it would help a lot of people, who cares about your accent, as long as its understandable, it doesn't matter. Your doing this to help people out, so if they dont listen to it, its their loss. :)
 
S

Sleinzel

I'm still fixing some major errors... But it seems like there's no way to get it to work on 64-bit... :(
 

Fleep

Founder
Meme Tier VIP
May 20, 2012
572
11,023
6
Sleinzel said:
I'm still fixing some major errors... But it seems like there's no way to get it to work on 64-bit... :(
Ah that's unfortunate :/ I haven't got much experience in dealing with 64bit specific code so cant help you much on that.

Fleep
 

Rake

I'm not your friend
Administrator
Jan 21, 2014
12,519
78,998
2,420
You inspired me to finally make a picture to show new members that we have syntax highlighting:

 

Broihon

Escobar Tier VIP
Fleep Tier Donator
Dec 22, 2013
1,760
41,528
321
It's simply leeched. Where are the credits to the creator of the mapping code? VirtualCopyPaster is a better name for you.
 

VirtualCoder

Newbie
Mar 3, 2016
4
32
0
Вroihon;41781 said:
It's simply leeched. Where are the credits to the creator of the mapping code? VirtualCopyPaster is a better name for you.
Credits go to publicity and me. There are quite few open libraries available to the public regarding this subject, go look it up. Anyways, why the hostility?
Also, I don't remember taking any credit for it, simply spreading the knowledge. Just chill out dude.
 
Last edited:

iKeey

Full Member
Nov 18, 2018
5
274
0
Last edited:
Attention! Before you post:

Read the How to Ask Questions Guide
99% of questions are answered in the Beginner's Guide, do it before asking a question.

No Hack Requests. Post in the correct section.  Search the forum first. Read the rules.

How to make a good post:

  • Fill out the form correctly
  • Tell us the game name & coding language
  • Post everything we need to know to help you
  • Ask specific questions, be descriptive
  • Post errors, line numbers & screenshots
  • Post code snippets using code tags
  • If it's a large project, zip it up and attach it

If you do not comply, your post may be deleted.  We want to help, please make a good post and we will do our best to help you.

Community Mods