 |
Cheat Engine The Official Site of Cheat Engine
|
| View previous topic :: View next topic |
| Author |
Message |
BanMe Master Cheater
Reputation: 0
Joined: 29 Nov 2005 Posts: 375 Location: Farmington NH, USA
|
Posted: Tue Sep 16, 2008 8:04 pm Post subject: Linked List Hooks..? |
|
|
well ive been working on almagamating this code for some time its the bastard child of many projects sig^2(SDT Restore(Load and Align) redwolf for the hooklib and eclicz for his nice paper on Hot Patching.. and its all most glued together by me.. code is also commented by me or authors, the idea in the code is to inventory remote process (modules load into them specifically) then i was gonna try to use RtlRemoteCall(unimplemnted as of yet) and force a thread to be redirected to the callsite LoadLibrary with param, I also need to pass the Thread Context so that I may restore the Thread Execution State Prior to being hijacked..(i was think of storing the CONTEXT structure in the Shared Section but thats not done yet either) so upon the load of the dll into target the dll will detect server and issue a Connection request to a Shared Section Created Within the Host Process by the Server dll(first one loaded)...
now i have the framework mostly complete...
but would enjoy user input as to new ideas or critisism's
(also there may be a little bit of (Casper the Friendly ****** (not 5 letters 6 in there to... just some of the coding techniques used therin.
ok so after all that crap here the code in all its ugly glory
[FileName: SLList.h]
| Code: |
#define _CRT_SECURE_NO_DEPRECATE
#define _X86_
#include <windows.h>
#include <tlhelp32.h>
#include <commctrl.h>
#include <aclapi.h>
#include "HookLib.h"
#define NTSTATUS ULONG
#define NT_SUCCESS(Status) ((NTSTATUS)(Status) >= 0)
#define ExpAff extern "C" _declspec(dllexport)
#define PORTCONNECTNAME L"\\BaseNamedObjects\\LPC_SHARE_PORT_CONNECT"
#define PORTDATANAME L"\\BaseNamedObjects\\LPC_SHARE_PORT_DATA"
#define LPCEVENT L"\\LPC_SHARE_EVENT"
typedef struct _STRING {
USHORT Length;
USHORT MaximumLength;
PCHAR Buffer;
} ANSI_STRING, *PANSI_STRING;
typedef struct _UNICODE_STRING {
USHORT Length;
USHORT MaximumLength;
PWSTR Buffer;
} UNICODE_STRING, *PUNICODE_STRING;
typedef struct _OBJECT_ATTRIBUTES {
ULONG Length;
HANDLE RootDirectory;
PUNICODE_STRING ObjectName;
ULONG Attributes;
PVOID SecurityDescriptor; // Points to type SECURITY_DESCRIPTOR
PVOID SecurityQualityOfService; // Points to type SECURITY_QUALITY_OF_SERVICE
} OBJECT_ATTRIBUTES;
typedef OBJECT_ATTRIBUTES *POBJECT_ATTRIBUTES;
typedef struct ACCESS_TOKEN
{
HANDLE Token;
HANDLE Thread;
} ACCESS_TOKEN;
typedef enum _SECTION_INHERIT
{
ViewShare = 1,
ViewUnmap = 2
}SECTION_INHERIT;
struct PE_Header
{
unsigned long signature;
unsigned short machine;
unsigned short numSections;
unsigned long timeDateStamp;
unsigned long pointerToSymbolTable;
unsigned long numOfSymbols;
unsigned short sizeOfOptionHeader;
unsigned short characteristics;
};
struct PE_ExtHeader
{
unsigned short magic;
unsigned char majorLinkerVersion;
unsigned char minorLinkerVersion;
unsigned long sizeOfCode;
unsigned long sizeOfInitializedData;
unsigned long sizeOfUninitializedData;
unsigned long addressOfEntryPoint;
unsigned long baseOfCode;
unsigned long baseOfData;
unsigned long imageBase;
unsigned long sectionAlignment;
unsigned long fileAlignment;
unsigned short majorOSVersion;
unsigned short minorOSVersion;
unsigned short majorImageVersion;
unsigned short minorImageVersion;
unsigned short majorSubsystemVersion;
unsigned short minorSubsystemVersion;
unsigned long reserved1;
unsigned long sizeOfImage;
unsigned long sizeOfHeaders;
unsigned long checksum;
unsigned short subsystem;
unsigned short DLLCharacteristics;
unsigned long sizeOfStackReserve;
unsigned long sizeOfStackCommit;
unsigned long sizeOfHeapReserve;
unsigned long sizeOfHeapCommit;
unsigned long loaderFlags;
unsigned long numberOfRVAAndSizes;
unsigned long exportTableAddress;
unsigned long exportTableSize;
unsigned long importTableAddress;
unsigned long importTableSize;
unsigned long resourceTableAddress;
unsigned long resourceTableSize;
unsigned long exceptionTableAddress;
unsigned long exceptionTableSize;
unsigned long certFilePointer;
unsigned long certTableSize;
unsigned long relocationTableAddress;
unsigned long relocationTableSize;
unsigned long debugDataAddress;
unsigned long debugDataSize;
unsigned long archDataAddress;
unsigned long archDataSize;
unsigned long globalPtrAddress;
unsigned long globalPtrSize;
unsigned long TLSTableAddress;
unsigned long TLSTableSize;
unsigned long loadConfigTableAddress;
unsigned long loadConfigTableSize;
unsigned long boundImportTableAddress;
unsigned long boundImportTableSize;
unsigned long importAddressTableAddress;
unsigned long importAddressTableSize;
unsigned long delayImportDescAddress;
unsigned long delayImportDescSize;
unsigned long COMHeaderAddress;
unsigned long COMHeaderSize;
unsigned long reserved2;
unsigned long reserved3;
};
struct SectionHeader
{
unsigned char sectionName[8];
unsigned long virtualSize;
unsigned long virtualAddress;
unsigned long sizeOfRawData;
unsigned long pointerToRawData;
unsigned long pointerToRelocations;
unsigned long pointerToLineNumbers;
unsigned short numberOfRelocations;
unsigned short numberOfLineNumbers;
unsigned long characteristics;
};
struct MZHeader
{
unsigned short signature;
unsigned short partPag;
unsigned short pageCnt;
unsigned short reloCnt;
unsigned short hdrSize;
unsigned short minMem;
unsigned short maxMem;
unsigned short reloSS;
unsigned short exeSP;
unsigned short chksum;
unsigned short exeIP;
unsigned short reloCS;
unsigned short tablOff;
unsigned short overlay;
unsigned char reserved[32];
unsigned long offsetToPE;
};
struct ImportDirEntry
{
DWORD importLookupTable;
DWORD timeDateStamp;
DWORD fowarderChain;
DWORD nameRVA;
DWORD importAddressTable;
};
typedef struct _LPC_MESSAGE_HEADER
{
WORD DataLength;
WORD TotalLength;
WORD MessageType;
WORD DataInfoOffset;
DWORD ClientPId;
DWORD ClientTId;
DWORD MessageId;
DWORD CallBackId;
}LPC_MESSAGE_HEADER, *PLPC_MESSAGE_HEADER;
typedef struct _LPC_MESSAGE
{
LPC_MESSAGE_HEADER MsgHeader;
BYTE MessageData[255];
}LPC_MESSAGE;
typedef LPC_MESSAGE *PLPC_MESSAGE;
typedef struct _LPC_SECTION_OWNER_MEMORY {
DWORD Length;
HANDLE SectionHandle;
DWORD OffsetInSection;
DWORD SectionSize;
DWORD ClientBaseAddress;
DWORD ServerBaseAddress;
}LPC_SECTION_OWNER_MEMORY,*PLPC_SECTION_OWNER_MEMORY;
typedef struct _LPC_SECTION_MEMORY
{
DWORD Length;
DWORD SectionSize;
DWORD ServerBaseAddress;
} LPC_SECTION_MEMORY, *PLPC_SECTION_MEMORY;
typedef enum LPC_MESSAGE_TYPE {
LPC_REQUEST = 0,
LPC_REPLY = 1,
LPC_DATAGRAM = 2,
LPC_LOST_REPLY = 3,
LPC_PORT_CLOSED = 4,
LPC_CLIENT_DIED = 5,
LPC_EXCEPTION = 6,
LPC_DEBUG_EVENT = 7,
LPC_ERROR_EVENT = 8,
LPC_CONNECTION_REQUEST = 9
};
char *cProcessName;//current target process name..
byte DataBuffer[0x100];
static HANDLE hLPCEventPair;
HANDLE hClientLPCEventPair,cAcceptPort,hCProcess,hCThread = INVALID_HANDLE_VALUE;
HANDLE hSnapShot,tSnapShot,MEXACUTE,hToken,SecObj = INVALID_HANDLE_VALUE;
OBJECT_ATTRIBUTES oa;
SECURITY_QUALITY_OF_SERVICE qos;
UNICODE_STRING UString;
HANDLE hServerDataPort,hServerConnectionPort;
DWORD DataSize = sizeof(DataBuffer);
DWORD ClientPid,ClientTid;
LPC_MESSAGE LPCMSG;
LPC_SECTION_OWNER_MEMORY SectOwner;
LPC_SECTION_MEMORY SectMemory;
LARGE_INTEGER SecSize;
int CurNumProc = 0;//place holder for num of processes
PROCESSENTRY32 PE;//Strucures for PROCESS
THREADENTRY32 TE;//THREAD
MODULEENTRY32 ME;//and MODULE Detection methods
ACCESS_TOKEN AT;//LOCAL ACCESS TOKEN
HANDLE TOKEN;//LOCAL HANDLE to Process or Thread TOKEN
TOKEN_PRIVILEGES TP;//PRIVLEDGES of our PROCESS or THREAD
LUID luid;
NTSTATUS Status;
bool SetPrivilege(
HANDLE hToken, // token handle
LPCTSTR Privilege, // Privilege to enable/disable
BOOL bEnablePrivilege // TRUE to enable. FALSE to disable
);
ExpAff bool UsrLLInit(
HWND hListBox
);
ExpAff HANDLE UsrDrOpenProcess(
char *ProcN
);
bool UsrReadPEInfo(
char*,
MZHeader*,
PE_Header*,
PE_ExtHeader*,
SectionHeader**
);
int UsrCalcImageSize(
MZHeader*,
PE_Header*,
PE_ExtHeader*,
SectionHeader*
);
unsigned long UsrGetAlignedSize(
unsigned long,
unsigned long
);
bool UsrLoadFile(
char*,MZHeader*,
PE_Header*,
PE_ExtHeader*,
SectionHeader*,
LPVOID
);
DWORD myStrlenA(char *ptr)
{
DWORD len = 0;
while(*ptr)
{
len++;
ptr++;
}
return len;
}
BOOL myStrcmpA(char *str1, char *str2)
{
while(*str1 && *str2)
{
if(*str1 == *str2)
{
str1++;
str2++;
}
else
{
return FALSE;
}
}
if(*str1 && !*str2)
{
return FALSE;
}
else if(*str2 && !*str1)
{
return FALSE;
}
return TRUE;
}
//Import API
NTSYSAPI
void
NTAPI
RtlInitUnicodeString(
IN OUT PUNICODE_STRING DestinationStr,
IN PCWSTR InputString
);
NTSYSAPI
NTSTATUS
NTAPI
NtCreatePort(
PHANDLE PortHandle,
POBJECT_ATTRIBUTES ObjectAttributes,
ULONG MaxConnectInfoLength,
ULONG MaxDataLength,
PULONG Reserved
);
NTSYSAPI
NTSTATUS
NTAPI
NtAcceptConnectPort(
PHANDLE ServerPortHandle,
HANDLE AlternativeReceivePortHandle OPTIONAL,
PLPC_MESSAGE ConnectionReply,
BOOLEAN AcceptConnection,
PLPC_SECTION_OWNER_MEMORY ServerSharedMemory OPTIONAL,
PLPC_SECTION_MEMORY ClientSharedMemory
);
NTSYSAPI
NTSTATUS
NTAPI
NtReplyWaitReceivePort(
HANDLE PortHandle,
PHANDLE ReceivePortHandle,
PLPC_MESSAGE Reply,
PLPC_MESSAGE IncomingRequest
);
NTSYSAPI
NTSTATUS
NTAPI
NtCreateEventPair(
PHANDLE EventPairHandle,
ACCESS_MASK DesiredAccess,
POBJECT_ATTRIBUTES ObjectAttributes
);
NTSYSAPI
NTSTATUS
NTAPI
NtOpenSection(
OUT PHANDLE SectionHandle,
IN DWORD DesiredAccess,
IN POBJECT_ATTRIBUTES ObjAttr
);
NTSYSAPI
NTSTATUS
NTAPI
NtCreateSection(
OUT PHANDLE SectionHandle,
IN ACCESS_MASK DesiredAccess,
IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,
IN PLARGE_INTEGER MaximumSize OPTIONAL,
IN ULONG SectionPageProtection,
IN ULONG AllocationAttributes,
IN HANDLE FileHandle OPTIONAL
);
NTSYSAPI
NTSTATUS
NTAPI
NtMapViewOfSection(
IN HANDLE SectionHandle,
IN HANDLE ProcessHandle,
IN OUT PVOID *BaseAddress,
IN ULONG_PTR ZeroBits,
IN SIZE_T CommitSize,
IN OUT PLARGE_INTEGER SectionOffset OPTIONAL,
IN OUT PSIZE_T ViewSize,
IN SECTION_INHERIT InheritDisposition,
IN ULONG AllocationType,
IN ULONG Win32Protect
);
NTSYSAPI
NTSTATUS
NTAPI
NtSetInformationThread(
HANDLE ThreadHandle,
DWORD ThreadInfoClass,
PVOID ThreadInformation,
ULONG ThreadInformationLength
);
NTSYSAPI
NTSTATUS
NTAPI
NtUnmapViewOfSection(
IN HANDLE ProcessHandle,
IN PVOID BaseAddress
);
/*-------------Linked List Class by -----------
Name : Justin Deltener
Email : [email protected]
HomePage : http://www.fm-net.com/inversereality
-----------------------------------------------
-------------Begin Linked List Class-----------*/
typedef struct List
{
DWORD idL;
DWORD PID;
List* Next;
List()
{
Next=NULL;
PID = 0;
idL = 0;
}
}List;
typedef List *ListPtr;
class SLList
{ public:
SLList();
~SLList();
ListPtr Previous(ListPtr);
ListPtr Previous(long);
void Advance();
void Rewind();
void AddANode();
void DeleteANode(ListPtr);
ListPtr Head,Tail,CurrentPtr;
};
SLList:: SLList()
{
Head = new List;
Head->idL = 0;
Tail=Head;
CurrentPtr = Head;
}
SLList:: ~SLList()
{
ListPtr temp = Head;
CurrentPtr = Head;
while(CurrentPtr != NULL)
{
CurrentPtr = CurrentPtr->Next;
delete temp;
temp=CurrentPtr;
}
}
void SLList::AddANode()
{
Tail->Next = new List;
Tail=Tail->Next;
Tail->idL += 1;
}
ListPtr SLList::Previous(ListPtr index)
{
ListPtr temp=Head;
if(index==Head) //special case, index IS the head :)
{
return Head;
}
while(temp->Next != index)
{
temp=temp->Next;
}
return temp;
}
ListPtr SLList::Previous(long index)
{
ListPtr temp=Head;
for(long count=0;count<index-1;count++)
{
temp=temp->Next;
}
return temp;
}
void SLList::Advance()
{
if(CurrentPtr->Next != NULL)
{
CurrentPtr=CurrentPtr->Next;
}
}
void SLList::Rewind()
{ if(CurrentPtr != Head)
{
CurrentPtr=Previous(CurrentPtr);
}
}
void SLList::DeleteANode(ListPtr corpse) //<-- i thought it was funny :)
{
ListPtr temp;
if(corpse == Head) //case 1 corpse = Head
{temp=Head;
Head=Head->Next;
delete temp;
}
else if(corpse == Tail) //case 2 corpse is at the end
{ temp=Previous(corpse);
temp->Next=NULL;
delete corpse;
Tail=temp;
}
else //case 3 corpse is in middle somewhere
{temp=Previous(corpse);
temp->Next=corpse->Next;
delete corpse;
}
CurrentPtr=Head; //Reset the class currentptr
}
/*------------End Linked List Class ---------------------*/
/*------------By BanMe-----------------------------------*/
/*------------Begin Linked List Hooking Class -----------*/
typedef struct cLLHook {
DWORD Installed;//0 is not installed 1 if installed
BYTE bJmp;//e9 jmp e8 call
DWORD TProcessId;//Targets ProcessId
DWORD hkTAddress;//Target Function to Hook
DWORD hkAddress;//Hook
DWORD hkSz;//our hook size generally 5 bytes byte+dword
cLLHook *NextHook;//ptr to Next Hook In List..
cLLHook()//initialize everything to 0
{
bJmp = 0;
TProcessId = 0;
hkTAddress = 0;
hkAddress = 0;
hkSz = 0;
Installed = 0;
NextHook = 0;
}
}cLLHook;
typedef cLLHook *PcLLHook;
class hLLHook
{ public:
hLLHook();//Constructor
~hLLHook();//Destructor
PcLLHook hLLAddEntryForHook();//Adds another hook to our Linked List
void hLLSetTargetExeName(char *);//Sets Global Exe Name used for process opening by exe name...
PcLLHook Previous(PcLLHook);//gets previose hook structure
PcLLHook Previous(long);//same as above
void DeleteNode(PcLLHook);//Delete hook link off our list
bool hLLInitSection();//Initializes Our Shared Section
bool hLLInitServer();
bool hLLConnectRequest(PLPC_MESSAGE,PHANDLE);
LPVOID CleanBuffer(PBYTE,DWORD);//obvious
LPVOID UsrShareFile(char*);//Places files into share
DWORD UsrGetSharedExportAddr(char*);
DWORD UsrGetProcAddr(LPCSTR ,char*);
DWORD UsrGetRemoteExportAddr(DWORD,char*,char*);
bool UsrHookExportAddr(PcLLHook);
//bool hLLRemoveHook(PcLLHook);
PcLLHook hkHead,hkTail,hkCurrentPtr;
};
hLLHook HkClass;//local hooking class
PcLLHook PLLHook;//temp placeholder for hooking class
SLList PIList;//Process Info Linked List
ListPtr PITemp;//temp place holder for Process Info Linked List
//in InitFunction Initialize head to tail the constructor...
hLLHook:: hLLHook()
{
hkHead = new cLLHook;//OnInit Initialize hkHead to a new Structure
hkTail=hkHead;//make head equal ass to create linked List
hkCurrentPtr = hkHead;//Make Current Pointer equal to the Head of the Beast
}
//the destructor
hLLHook:: ~hLLHook()
{
PLLHook = hkHead;
hkCurrentPtr = hkHead;
while(hkCurrentPtr != NULL)
{
hkCurrentPtr = hkCurrentPtr->NextHook;
delete PLLHook;
PLLHook=hkCurrentPtr;
}
}
//returns pointer to new cLL Structure..
PcLLHook hLLHook::hLLAddEntryForHook()
{
hkTail->NextHook = new cLLHook;
hkTail=hkTail->NextHook;
return (PcLLHook)hkTail;
}
void hLLHook::hLLSetTargetExeName(char *TargetProcName)
{
cProcessName = TargetProcName;
}
PcLLHook hLLHook::Previous(PcLLHook index)
{
PLLHook=hkHead;
if(index==hkHead) //special case, index IS the head :)
{
return hkHead;
}
while(PLLHook->NextHook != index)
{
PLLHook=PLLHook->NextHook;
}
return PLLHook;
}
PcLLHook hLLHook::Previous(long index)
{
PLLHook=hkHead;
for(long count=0;count<index-1;count++)
{
PLLHook=PLLHook->NextHook;
}
return PLLHook;
}
void hLLHook::DeleteNode(PcLLHook DeadNode) //<-- i thought it was funny :)
{
if(DeadNode == hkHead) //case 1 corpse = Head
{PLLHook=hkHead;
hkHead=hkHead->NextHook;
delete PLLHook;
}
else if(DeadNode == hkTail) //case 2 corpse is at the end
{ PLLHook=Previous(DeadNode);
PLLHook->NextHook=NULL;
delete DeadNode;
hkTail=PLLHook;
}
else //case 3 corpse is in middle somewhere
{PLLHook=Previous(DeadNode);
PLLHook->NextHook=DeadNode->NextHook;
delete DeadNode;
}
hkCurrentPtr=hkHead; //Reset the class CurrentPtr
}
LPVOID hLLHook::CleanBuffer(PBYTE DataBuffer,DWORD DataBufferSize)
{
LPVOID MemPtr;
MemPtr = memset(DataBuffer,0,DataBufferSize);
if(!MemPtr)
{
MemPtr = 0;
return MemPtr;
}
return MemPtr;
}
bool hLLHook::hLLInitSection()//Our Shared section Init Function
{
SecSize.LowPart = 0x10000;
SecSize.HighPart = 0x0;
Status = NtCreateSection(&SecObj,SECTION_ALL_ACCESS,NULL,&SecSize,PAGE_EXECUTE_READWRITE,SEC_IMAGE|SEC_COMMIT,NULL);
if(!NT_SUCCESS(Status))
{
return FALSE;
}
memset(&oa,0,sizeof(OBJECT_ATTRIBUTES));
oa.Length = sizeof(OBJECT_ATTRIBUTES);
RtlInitUnicodeString(&UString,LPCEVENT);
oa.ObjectName = &UString;
Status = NtCreateEventPair(&hLPCEventPair,STANDARD_RIGHTS_REQUIRED | SYNCHRONIZE ,&oa);
if(!NT_SUCCESS(Status))
{
return FALSE;
}
Status = NtSetInformationThread(GetCurrentThread(),8,&hLPCEventPair,4);
if(!NT_SUCCESS(Status))
{
return FALSE;
}
return TRUE;
}
//much work needed here :P im coming though..
bool hLLHook::hLLConnectRequest(LPC_MESSAGE LpcMessage,PHANDLE pAcceptPortHandle)
*pAcceptPortHandle=NULL;
Status = NtReplyWaitReceivePort(hServerConnectionPort,NULL,NULL,&LPCMSG);
if(!NT_SUCCESS(Status))
{
return FALSE;
}
switch(LPC_MESSAGE_TYPE)
{
case LPC_CONNECTION_REQUEST:
Status = NtAcceptConnectPort(&hServerConnectionPort,0,&LPCMSG,1,&SectOwner,NULL);
if(!NT_SUCCESS(Status))
{
return FALSE;
}
Status = NtAcceptConnectPort(&hServerDataPort,0,&LPCMSG,1,&SectOwner,NULL);
if(!NT_SUCCESS(Status))
{
return FALSE;
}
Status = NtCompleteConnectPort(cAcceptPort);
if (!NT_SUCCESS(Status))
{
CloseHandle(cAcceptPort);
return FALSE;
}
*pAcceptPortHandle = cAcceptPort;
return TRUE;
}
}
bool hLLHook::hLLInitServer()
{
if(!hLLHook::hLLInitSection())
{
return FALSE;
}
CleanBuffer(SectOwner,sizeof(LPC_SECTION_OWNER_MEMORY));
memset(&SectMemory,0,sizeof(LPC_SECTION_MEMORY));
memset(&oa,0,sizeof(OBJECT_ATTRIBUTES));
SectOwner.Length = sizeof(LPC_SECTION_OWNER_MEMORY);
SectOwner.SectionHandle = SecObj;
SectOwner.SectionSize = SecSize.LowPart;
oa.Length = sizeof(OBJECT_ATTRIBUTES);
RtlInitUnicodeString(&UString, PORTCONNECTNAME);
oa.ObjectName = &UString;
Status = NtCreatePort(&hServerConnectionPort,&oa,40,sizeof(LPC_MESSAGE),0x0);
if(!NT_SUCCESS(Status))
{
return FALSE;
}
memset(&oa,0,sizeof(OBJECT_ATTRIBUTES));
oa.Length = sizeof(OBJECT_ATTRIBUTES);
RtlInitUnicodeString(&UString,PORTDATANAME);
oa.ObjectName = &UString;
ULONG Reserve;
Status = NtCreatePort(&hServerDataPort,&oa,40,sizeof(LPC_MESSAGE),0x0);
if(!NT_SUCCESS(Status))
{
return FALSE;
}
return TRUE;
}
|
[filename: Hooklib.h By Redwolf]
| Code: |
#ifndef _HOOKLIB_H_
#define _HOOKLIB_H_
extern "C"
{
void* __stdcall SetIATHookAddr(HMODULE hModuleToHook, char* strHookedModule, void* oldFuncAddr, void* newFuncAddr);
void* __stdcall SetEATHook(HMODULE hModule, char* funcName, void* newFuncAddr);
bool __stdcall SetHPHook(void* oldFuncAddr, void* newFuncAddr);
bool __stdcall ClearHPHook(void* funcAddr);
}
#endif //_HOOKLIB_H_
|
[filename: affectionate.cpp]
| Code: |
#pragma once
#include "SLList.h"
//SIG^2 Code here minor mods ;]
//*******************************************************************************************************
// Fills the various structures with info of a PE image. The PE image is located at modulePos.
//
//*******************************************************************************************************
bool UsrReadPEInfo(char *modulePos, MZHeader *outMZ, PE_Header *outPE, PE_ExtHeader *outpeXH,
SectionHeader **outSecHdr)
{
// read MZ Header
MZHeader *mzH;
mzH = (MZHeader *)modulePos;
if(mzH->signature != 0x5a4d) // MZ
{
//printf("File does not have MZ header\n");
return false;
}
// read PE Header
PE_Header *peH;
peH = (PE_Header *)(modulePos + mzH->offsetToPE);
if(peH->sizeOfOptionHeader != sizeof(PE_ExtHeader))
{
//printf("Unexpected option header size.\n");
return false;
}
// read PE Ext Header
PE_ExtHeader *peXH;
peXH = (PE_ExtHeader *)((char *)peH + sizeof(PE_Header));
// read the sections
SectionHeader *secHdr = (SectionHeader *)((char *)peXH + sizeof(PE_ExtHeader));
*outMZ = *mzH;
*outPE = *peH;
*outpeXH = *peXH;
*outSecHdr = secHdr;
return true;
}
//*******************************************************************************************************
// Returns the total size required to load a PE image into memory
//
//*******************************************************************************************************
int UsrCalcImageSize(MZHeader *inMZ, PE_Header *inPE, PE_ExtHeader *inpeXH,
SectionHeader *inSecHdr)
{
int result = 0;
int alignment = inpeXH->sectionAlignment;
if(inpeXH->sizeOfHeaders % alignment == 0)
result += inpeXH->sizeOfHeaders;
else
{
int val = inpeXH->sizeOfHeaders / alignment;
val++;
result += (val * alignment);
}
for(int i = 0; i < inPE->numSections; i++)
{
if(inSecHdr[i].virtualSize)
{
if(inSecHdr[i].virtualSize % alignment == 0)
result += inSecHdr[i].virtualSize;
else
{
int val = inSecHdr[i].virtualSize / alignment;
val++;
result += (val * alignment);
}
}
}
return result;
}
//*******************************************************************************************************
// Returns the aligned size of a section
//
//*******************************************************************************************************
unsigned long UsrGetAlignedSize(unsigned long curSize, unsigned long alignment)
{
if(curSize % alignment == 0)
return curSize;
else
{
int val = curSize / alignment;
val++;
return (val * alignment);
}
}
//*******************************************************************************************************
// Copy a PE image from exePtr to ptrLoc with proper memory alignment of all sections
//
//*******************************************************************************************************
bool UsrLoadFile(char *exePtr, MZHeader *inMZ, PE_Header *inPE, PE_ExtHeader *inpeXH,
SectionHeader *inSecHdr, LPVOID ptrLoc)
{
char *outPtr = (char *)ptrLoc;
memcpy(outPtr, exePtr, inpeXH->sizeOfHeaders);
outPtr += UsrGetAlignedSize(inpeXH->sizeOfHeaders, inpeXH->sectionAlignment);
for(int i = 0; i < inPE->numSections; i++)
{
if(inSecHdr[i].sizeOfRawData > 0)
{
unsigned long toRead = inSecHdr[i].sizeOfRawData;
if(toRead > inSecHdr[i].virtualSize)
toRead = inSecHdr[i].virtualSize;
memcpy(outPtr, exePtr + inSecHdr[i].pointerToRawData, toRead);
outPtr += UsrGetAlignedSize(inSecHdr[i].virtualSize, inpeXH->sectionAlignment);
}
}
return true;
}
//*******************************************************************************************************
// Loads the file into Shared memory and aligns it xD
//
//*******************************************************************************************************
ExpAff LPVOID UsrShareFile(char *DllPathName)
{
char moduleFilename[MAX_PATH + 1];
LPVOID ptrLoc = NULL;
MZHeader mzH2;
PE_Header peH2;
PE_ExtHeader peXH2;
SectionHeader *secHdr2;
if( myStrlenA(DllPathName) >= MAX_PATH )
{
return NULL;
}
strcpy(moduleFilename, DllPathName);
// load this EXE into memory because we need its original Import Hint Table
HANDLE fp;
MEMORY_BASIC_INFORMATION MBI;
fp = CreateFile( moduleFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if( fp != INVALID_HANDLE_VALUE )
{
HANDLE fmo = OpenFileMapping( SECTION_ALL_ACCESS,false,"MEXACUTE" );
VirtualQuery( fmo, &MBI, sizeof(MEMORY_BASIC_INFORMATION));
BY_HANDLE_FILE_INFORMATION fileInfo;
BY_HANDLE_FILE_INFORMATION pagefileinfo;
GetFileInformationByHandle(fp, &fileInfo);
GetFileInformationByHandle(fmo, &pagefileinfo);
DWORD pagefileSize = pagefileinfo.nFileSizeLow;
DWORD fileSize = fileInfo.nFileSizeLow;
//printf("Size = %d\n", fileSize);
if(fileSize)
{
LPVOID exePtr = HeapAlloc(GetProcessHeap(), 0, fileSize);
if(exePtr)
{
DWORD read;
if(ReadFile(fp, exePtr, fileSize, &read, NULL) && read == fileSize)
{
if(!UsrReadPEInfo((char *)exePtr, &mzH2, &peH2, &peXH2, &secHdr2))
{
return NULL;
}
int imageSize = UsrCalcImageSize(&mzH2, &peH2, &peXH2, secHdr2);
//ptrLoc = VirtualAlloc(NULL, imageSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
ptrLoc = fmo;
if(ptrLoc)
{
if(!UsrLoadFile((char *)exePtr, &mzH2, &peH2, &peXH2, secHdr2, ptrLoc))
{
return NULL;
}
}
}
HeapFree(GetProcessHeap(), 0, exePtr);
}
}
CloseHandle(fp);
}
return ptrLoc;
}
DWORD UsrGetExportAddr(HMODULE hModule, char *apiName)
{
if(!hModule || !apiName)
return 0;
char *ptr = (char *)hModule;
ptr += 0x3c; // offset 0x3c contains offset to PE header
ptr = (char *)(*(DWORD *)ptr) + (DWORD)hModule + 0x78; // offset 78h into PE header contains addr of export table
ptr = (char *)(*(DWORD *)ptr) + (DWORD)hModule; // ptr now points to export directory table
// offset 24 into the export directory table == number of entries in the Export Name Pointer Table
// table
DWORD numEntries = *(DWORD *)(ptr + 24);
//printf("NumEntries = %d\n", numEntries);
DWORD *ExportNamePointerTable = (DWORD *)(*(DWORD *)(ptr + 32) + hModule); // offset 32 into export directory contains offset to Export Name Pointer Table
DWORD ordinalBase = *((DWORD *)(ptr + 16));
//printf("OrdinalBase is %d\n", ordinalBase);
WORD *ExportOrdinalTable = (WORD *)((*(DWORD *)(ptr + 36)) + hModule); // offset 36 into export directory contains offset to Ordinal Table
DWORD *ExportAddrTable = (DWORD *)((*(DWORD *)(ptr + 28)) + hModule); // offset 28 into export directory contains offset to Export Addr Table
for(DWORD i = 0; i < numEntries; i++)
{
char *exportName = (char *)(ExportNamePointerTable[i] + hModule);
if(myStrcmpA(exportName, apiName) == TRUE)
{
WORD ordinal = ExportOrdinalTable[i];
//printf("%s (i = %d) Ordinal = %d at %X\n", exportName, i, ordinal, ExportAddrTable[ordinal]);
return (DWORD)(ExportAddrTable[ordinal]);
}
}
return 0;
}
//returns null on failure and positive integer relating to the API Sought
ExpAff DWORD UsrGetProcAddr(LPCSTR ModName, char *apiname)
{
DWORD pfn = NULL;
HMODULE hMod;
hMod = GetModuleHandle(ModName);
if(hMod == INVALID_HANDLE_VALUE)
{
return pfn;
}
pfn = UsrGetExportAddr(hMod,apiname);
if(pfn == NULL)
{
return pfn;
}
return pfn;
}
HANDLE UsrDupModuleHandle(DWORD pId, char *module)
{
HANDLE RemMod = INVALID_HANDLE_VALUE;
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pId);
ME.dwSize = sizeof(MODULEENTRY32);
Module32First(hSnapShot, &ME);
do
{
if(stricmp(ME.szModule, module)== 0)
{
if(DuplicateHandle(UsrDrOpenProcess(cProcessName),(HANDLE)ME.hModule,GetCurrentProcess(),&RemMod,NULL,true,DUPLICATE_SAME_ACCESS)==0)
{
return NULL;
}
if(RemMod == INVALID_HANDLE_VALUE)
{
return NULL;
}
return RemMod;
}
ME.dwSize = sizeof(MODULEENTRY32);
} while(Module32Next(hSnapShot, &ME));
CloseHandle(hSnapShot);
return NULL;
}
/*-----------Uses hotpatching to globally From HookLib by RedWolf at rootkit.com
modify functions in all process loaded b4 or after this is done--------*/
//DWORD index = UsrGetExportAddr(GetModuleHandle("ntdll.dll"),"NtMapViewOfSection")+1;
ExpAff bool UsrHookByHotPatch(char *ModName,char*apiname,LPVOID HookRoutine,LPVOID *origTargetProc)
{
DWORD oProtect, nProtect = NULL;
LPVOID TargetProc = (LPVOID)UsrGetProcAddr(ModName, apiname);
origTargetProc = &TargetProc;
if(!SetHPHook(TargetProc,HookRoutine))
{
return false;
}
return true;
}
ExpAff DWORD UsrGetRemoteProcAddr(DWORD process_identifier,char* module_name,char* procedure_name)
{
HANDLE handle_snapshot_module;
MODULEENTRY32 module_entry;
IMAGE_DOS_HEADER dos_header;
IMAGE_NT_HEADERS nt_header;
IMAGE_EXPORT_DIRECTORY export_directory;
int rpm_result;
DWORD bytes_read;
DWORD counter;
WORD function_ordinal = 0;
DWORD address_of_names;
DWORD function_address = 0;
char function_name[MAX_PATH];
bool function_found = false;
if(process_identifier==0||module_name==0||procedure_name==0)
{
return 0;
}
handle_snapshot_module = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,process_identifier);
if(handle_snapshot_module==INVALID_HANDLE_VALUE)
{
return 0;
}
module_entry.dwSize = sizeof(module_entry);
if(Module32First(handle_snapshot_module,&module_entry)==0)
{
goto END_FAIL;
}
do
{
if(lstrcmpi(module_name,module_entry.szModule)==0)
{
rpm_result = Toolhelp32ReadProcessMemory
(
process_identifier,
(void*)module_entry.modBaseAddr,
&dos_header,
sizeof(dos_header),
&bytes_read
);
if(rpm_result==0||bytes_read!=sizeof(dos_header))
{
goto END_FAIL;
}
rpm_result = Toolhelp32ReadProcessMemory
(
process_identifier,
(void*)(module_entry.modBaseAddr+dos_header.e_lfanew),
&nt_header,
sizeof(nt_header),
&bytes_read
);
if(rpm_result==0||bytes_read!=sizeof(nt_header))
{
goto END_FAIL;
}
rpm_result = Toolhelp32ReadProcessMemory
(
process_identifier,
(void*)(module_entry.modBaseAddr+nt_header.OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress),
&export_directory,
sizeof(export_directory),
&bytes_read
);
if(rpm_result==0||bytes_read!=sizeof(export_directory))
{
goto END_FAIL;
}
if(procedure_name<=(const char*)0x0000FFFF)
{
for(counter = 0;counter<export_directory.NumberOfFunctions;counter++)
{
rpm_result = Toolhelp32ReadProcessMemory
(
process_identifier,
(void*)(module_entry.modBaseAddr+export_directory.AddressOfNameOrdinals+counter*2),
&function_ordinal,
sizeof(function_ordinal),
&bytes_read
);
if(rpm_result==0||bytes_read!=sizeof(function_ordinal))
{
goto END_FAIL;
}
if(LOWORD((DWORD)procedure_name)==function_ordinal+1)
{
function_found = true;
break;
}
}
}
else
{
for(counter = 0;counter<export_directory.NumberOfNames;counter++)
{
rpm_result = Toolhelp32ReadProcessMemory
(
process_identifier,
(void*)(module_entry.modBaseAddr+export_directory.AddressOfNames+counter*4),
&address_of_names,
sizeof(address_of_names),
&bytes_read
);
if(rpm_result==0||bytes_read!=sizeof(address_of_names))
{
goto END_FAIL;
}
rpm_result = Toolhelp32ReadProcessMemory
(
process_identifier,
(void*)(module_entry.modBaseAddr+address_of_names),
&function_name,
sizeof(function_name),
&bytes_read
);
if(rpm_result==0||bytes_read!=sizeof(function_name))
{
goto END_FAIL;
}
if(lstrcmpi(procedure_name,function_name)==0)
{
rpm_result = Toolhelp32ReadProcessMemory
(
process_identifier,
(void*)(module_entry.modBaseAddr+export_directory.AddressOfNameOrdinals+counter*2),
&function_ordinal,
sizeof(function_ordinal),
&bytes_read
);
if(rpm_result==0||bytes_read!=sizeof(function_ordinal))
{
goto END_FAIL;
}
function_found = true;
break;
}
}
}
if(function_found)
{
rpm_result = Toolhelp32ReadProcessMemory
(
process_identifier,
(void*)(module_entry.modBaseAddr+export_directory.AddressOfFunctions+function_ordinal*4),
&function_address,
sizeof(function_address),
&bytes_read
);
if(rpm_result==0||bytes_read!=sizeof(function_address))
{
goto END_FAIL;
}
function_address += (DWORD)module_entry.modBaseAddr;
}
break;
}
}
while(Module32Next(handle_snapshot_module,&module_entry)!=0);
END_FAIL:
CloseHandle(handle_snapshot_module);
return function_address;
}
ExpAff PcLLHook UsrHkInit(char* ProcessName)
{
if(!HkClass.hLLInitSection())
{
return false;
}
HkClass.hLLSetTargetExeName(ProcessName);
PcLLHook InitialEntry = HkClass.hLLAddEntryForHook();
if(InitialEntry == 0)
{
return 0;
}
return InitialEntry;
}
ExpAff PcLLHook UsrSetHkParams(DWORD tAddr,DWORD HkAddr,DWORD HkSz,cLLHook *HkStruct)
{
cLLHook *cHk;
cHk = HkStruct;
cHk->bJmp = 0xE8;
cHk->hkTAddress = tAddr;
cHk->hkAddress = HkAddr;
cHk->TProcessId = GetProcessId(UsrDrOpenProcess(cProcessName));
cHk->NextHook = HkClass.hLLAddEntryForHook();
return cHk;
}
ExpAff bool UsrInstallHook(PcLLHook HkParams)
{
DWORD nbw;
DWORD oProt;
LPVOID HkMem;
if(!VirtualProtectEx(UsrDrOpenProcess(cProcessName),(LPVOID)HkParams->hkTAddress,HkParams->hkSz,PAGE_EXECUTE_READWRITE,&oProt))
{
return false;
}
HkMem = VirtualAllocEx(UsrDrOpenProcess(cProcessName),NULL,(SIZE_T)HkParams->hkSz,MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE);
if(!WriteProcessMemory(UsrDrOpenProcess(cProcessName),HkMem,&HkParams->hkAddress,HkParams->hkSz,&nbw))
{
return false;
}
HkParams->Installed = 1;
return true;
}
ExpAff bool UsrLLInit(HWND hListBox)
{
LVITEM lvi;
char *lStr;
int Row = 0;
lvi.mask = LVIF_TEXT+LVIF_PARAM;
lvi.iItem = Row;
lvi.iSubItem = 0;
lvi.lParam = Row;
hSnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS,0 );
if ( hSnapShot == INVALID_HANDLE_VALUE )
{
return false;
}
RtlZeroMemory( &PE,sizeof( PROCESSENTRY32 ));
PE.dwSize = sizeof( PROCESSENTRY32 );
if( Process32First( hSnapShot,&PE ) != false)
{
PIList.AddANode();
if( PE.szExeFile == NULL )
{
lvi.pszText = "[SYSTEM PROCESS]";
PIList.Tail->PID = PE.th32ProcessID;
SendMessage( hListBox, LVM_INSERTITEM,0,(LPARAM)&lvi );
goto NextProc;
}
}
NextProc:
while( Process32Next( hSnapShot,&PE ) != false )
{
lvi.iItem = Row;
lvi.iSubItem = 0;
lvi.lParam = Row;
PIList.AddANode();
PIList.Tail->PID = PE.th32ProcessID;
lvi.pszText = PE.szExeFile;
SendMessage( hListBox,LB_ADDSTRING,0,(LPARAM)&lvi);
Row = Row + 1;
}
CurNumProc = PIList.Tail->idL;
CloseHandle( hSnapShot );
return true;
}
/* UsrLLOpenProcess Takes the Index From a List View of the ProcessNames
and compares it to the idL feild of the PIList(Process Info List)
which are thankfully both zero based and each time a node is added the idL field
of that node is incremented (so if u dont get the idea..
dont bother using this... ;p)*/
ExpAff HANDLE UsrLLOpenProcess( DWORD ProcessIndex )
{
HANDLE hLocal = INVALID_HANDLE_VALUE;
int mCmp;
if( PIList.CurrentPtr == NULL );
{
return INVALID_HANDLE_VALUE;
}
tMemCmp:
mCmp = memcmp( (void*)PIList.CurrentPtr->idL, (void*)ProcessIndex,sizeof(DWORD));
if( mCmp == 0 )
{
PITemp = PIList.CurrentPtr;
hLocal = OpenProcess( PROCESS_ALL_ACCESS,false,PITemp->PID );
if( hLocal == INVALID_HANDLE_VALUE )
{
return INVALID_HANDLE_VALUE;
}
return hLocal;
}
if(PIList.Tail->Next != NULL )
{
PIList.Advance();
goto tMemCmp;
}
return INVALID_HANDLE_VALUE;
}
// UsrDrOpenProcess Opens a Process Directly by its ExeFileName
// Standard shit here... ;)
HANDLE UsrDrOpenProcess(char *ProcN)
{
HANDLE hLocal = INVALID_HANDLE_VALUE;
int tS = 0;
BOOL tB = false;
hSnapShot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS,0 );
PE.dwSize = sizeof( PROCESSENTRY32 );
tB = Process32First( hSnapShot,&PE );
if(!tB)
{
return INVALID_HANDLE_VALUE;
}
while( Process32Next( hSnapShot,&PE ) != false)
{
tS = strcmp( ProcN,PE.szExeFile );
if(tS == 0)
{
hLocal = OpenProcess( PROCESS_ALL_ACCESS,false,PE.th32ProcessID );
CloseHandle(hSnapShot);
return hLocal;
}
}
CloseHandle(hSnapShot);
return INVALID_HANDLE_VALUE;
}
bool SetPrivilege(
HANDLE hToken, // token handle
LPCTSTR Privilege, // Privilege to enable/disable
BOOL bEnablePrivilege // TRUE to enable. FALSE to disable
)
{
TOKEN_PRIVILEGES tp = { 0 };
// Initialize everything to zero
LUID luid;
DWORD cb=sizeof( TOKEN_PRIVILEGES );
if(!LookupPrivilegeValue( NULL, Privilege, &luid ))
return FALSE;
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if(bEnablePrivilege) {
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
} else {
tp.Privileges[0].Attributes = 0;
}
AdjustTokenPrivileges( hToken, FALSE, &tp, cb, NULL, NULL );
if ( GetLastError() != ERROR_SUCCESS )
return FALSE;
return TRUE;
}
//Entry Point Sets Privs... :]
BOOL WINAPI DllMain(HINSTANCE hInstance,DWORD fwdReason, LPVOID lpvReserved)
{
switch(fwdReason)
{
case DLL_PROCESS_ATTACH:
break;
case DLL_THREAD_ATTACH:
break;
case DLL_PROCESS_DETACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
|
any who can contribute please do, any who can see coding errors or want to add usages of the tool please post any bugs here.. :]
thank you and Greetz to all ;}
BanMe
|
|
| Back to top |
|
 |
rapion124 Grandmaster Cheater Supreme
Reputation: 0
Joined: 25 Mar 2007 Posts: 1095
|
Posted: Tue Sep 16, 2008 8:10 pm Post subject: |
|
|
You should add header annotations. It makes your functions much easier to call and helps the compiler catch some runtime errors, especially because you are doing so much "unsafe" stuff.
We all hate mysterious process crashes due to overwriting the PEB
|
|
| Back to top |
|
 |
BanMe Master Cheater
Reputation: 0
Joined: 29 Nov 2005 Posts: 375 Location: Farmington NH, USA
|
Posted: Tue Sep 16, 2008 8:18 pm Post subject: |
|
|
--edit-- is this what you wanted?
| Code: |
//Sets or unsets a Privilege
bool SetPrivilege(
__in HANDLE hToken, // token handle
__in LPCTSTR Privilege, // Privilege to enable/disable
__in BOOL bEnablePrivilege // TRUE to enable. FALSE to disable
);
//usage:
//SetPrivilege(TokenHandle,SE_DEBUG_NAME,1);
//Inits LinkedList it Passed in the Handle to a List
//it will Fill in a ListBox with Process Names
ExpAff bool UsrLLInit(
__in HWND hListBox
);
//opens a Process By its ExeName
ExpAff HANDLE UsrDrOpenProcess(
__in char *ProcN
);
//Reads Pe Info
bool UsrReadPEInfo(
__in char*,
__in MZHeader*,
__in PE_Header*,
__in PE_ExtHeader*,
__inout SectionHeader**
);
//obviouse
int UsrCalcImageSize(
__in MZHeader*,
__in PE_Header*,
__in PE_ExtHeader*,
__in SectionHeader*
);
//same as above
unsigned long UsrGetAlignedSize(
__in unsigned long,
__in unsigned long
);
//Loads a File and return the Handle to it
bool UsrLoadFile(
__in char*,
__in MZHeader*,
__in PE_Header*,
__in PE_ExtHeader*,
__in SectionHeader*,
__inout LPVOID
);
class hLLHook
{
public:
hLLHook();//Constructor
~hLLHook();//Destructor
PcLLHook hLLAddEntryForHook();//Adds another hook to our Linked List
void hLLSetTargetExeName(__in char *);//Sets Global Exe Name used for process opening by exe name...
PcLLHook Previous(__inout PcLLHook);//gets previose hook structure
PcLLHook Previous(__inout long);//same as above
void DeleteNode(__in PcLLHook);//Delete hook link off our list
bool hLLInitSection();//Initializes Our Shared Section
bool hLLInitServer();
bool hLLConnectRequest(__in PLPC_MESSAGE,__inout PHANDLE);
LPVOID CleanBuffer(PBYTE,DWORD);//obvious
LPVOID UsrShareFile(__in char*);//Places files into share
DWORD UsrGetSharedExportAddr(__in char*);
DWORD UsrGetProcAddr(__in LPCSTR ,__in char*);
//Manuel GetProcess Address
DWORD UsrGetRemoteExportAddr(__in DWORD,__in char*,__in char*);
bool UsrHoPatchAddr(__in PcLLHook);
//bool hLLRemoveHook(PcLLHook);
PcLLHook hkHead,hkTail,hkCurrentPtr;
};
|
|
|
| Back to top |
|
 |
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum You cannot attach files in this forum You can download files in this forum
|
|