Example #1
0
int CMemUtil::GetProcessBaseAddr(int processId)
{
	HANDLE dwHandle = gethandle(processId);
	if (processId == m_prevProcessIdBase && m_prevProcessIdBase != -1 && m_prevBaseAddr != NULL)
	{
		return m_prevBaseAddr;
	}
	else
	{
		m_prevProcessIdBase = -1;
		m_prevBaseAddr = NULL;
	}

	int ret = 0;
	int isNotFromNormalScan = 0;
	if (dwHandle)
	{
		unsigned long moduleCount = 0;
		EnumProcessModules(dwHandle, NULL, 0, &moduleCount);
		moduleCount = moduleCount / sizeof(HMODULE);

		HMODULE *modules = (HMODULE*)calloc(moduleCount, sizeof(HMODULE));
		char moduleName[64];
		EnumProcessModules(dwHandle, modules, moduleCount * sizeof(HMODULE), &moduleCount);
		for (unsigned long i = 0; i < moduleCount; i++)
		{
			GetModuleBaseName(dwHandle, modules[i], moduleName, sizeof(moduleName));
			if (_strcmpi(moduleName, "Tibia.exe") == 0)
			{
				MODULEINFO moduleInfo;
				GetModuleInformation(dwHandle, modules[i], &moduleInfo, sizeof(moduleInfo));
				//isNotFromNormalScan=0; // commented to see if Tibia.exe in sometimes not first
				ret = (int)moduleInfo.lpBaseOfDll;
				break;
			}
			if (i == 0) // catches first module in case Tibia.exe does not exist
			{
				MODULEINFO moduleInfo;
				GetModuleInformation(dwHandle, modules[i], &moduleInfo, sizeof(moduleInfo));
				isNotFromNormalScan = 1;
				ret = (int)moduleInfo.lpBaseOfDll;
			}
		}
		free(modules);
		modules = NULL;
	}
	if (isNotFromNormalScan)
		AfxMessageBox("While finding base address, main module was no first or was not named \"Tibia.exe\".");
	if (ret)
	{
		m_prevBaseAddr = ret;
		m_prevProcessIdBase = processId;
	}
	return ret;
}
Example #2
0
int GetProcessBaseAddr()
{
	static HANDLE dwHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, ::GetCurrentProcessId());
	if (dwHandle == NULL)
	{
		CloseHandle(dwHandle);
		AfxMessageBox("Unable to read Tibia memory!");
	}


	int ret = 0;
	int isNotFromNormalScan = 0;
	if (dwHandle)
	{
		unsigned long moduleCount = 0;
		EnumProcessModules(dwHandle, NULL, 0, &moduleCount);
		moduleCount = moduleCount / sizeof(HMODULE);

		HMODULE *modules = (HMODULE*)calloc(moduleCount, sizeof(HMODULE));
		char moduleName[64];
		unsigned long dummy;
		EnumProcessModules(dwHandle, modules, moduleCount * sizeof(HMODULE), &dummy);
		for (size_t i = 0; i < moduleCount; i++)
		{
			GetModuleBaseName(dwHandle, modules[i], moduleName, sizeof(moduleName));
			if (_strcmpi(moduleName, "Tibia.exe") == 0)
			{
				MODULEINFO moduleInfo;
				GetModuleInformation(dwHandle, modules[i], &moduleInfo, sizeof(moduleInfo));
				isNotFromNormalScan = 0; // commented to see if Tibia.exe in sometimes not first
				ret = (int)moduleInfo.lpBaseOfDll;
				break;
			}
			if (i == 0) // catches first module in case Tibia.exe does not exist
			{
				MODULEINFO moduleInfo;
				GetModuleInformation(dwHandle, modules[i], &moduleInfo, sizeof(moduleInfo));
				isNotFromNormalScan = 1;
				ret = (int)moduleInfo.lpBaseOfDll;
			}
		}
		free(modules);
		modules = NULL;
	}
	if (isNotFromNormalScan)
		AfxMessageBox("While finding base address, main module was no first or was not named \"Tibia.exe\".");
	return ret;
}
Example #3
0
void mainFunction()
{

	MODULEINFO moduleInfo;
	bool bSuccess;
	MH_STATUS status;

	Log::Init();
	
	GetModuleInformation(GetCurrentProcess(), GetModuleHandle(NULL), &moduleInfo, sizeof(MODULEINFO));
	Log::Write(Log::Type::Debug, "Base address is at: %I64X", moduleInfo.lpBaseOfDll);

	funcToHookOn = Pattern::Scan(moduleInfo, "48 89 5C 24 ? 57 48 83 EC 20 44 0F B7 05 ? ? ? ? 33 D2");
	Log::Write(Log::Type::Debug, "The code is found at: %I64X", funcToHookOn);
	
	status = MH_Initialize();

	Log::Write(Log::Type::Debug, "MinHook intialization was: ", status != MH_STATUS::MH_OK ? "Not successful" : "Successful");

	status = MH_CreateHook((void*)funcToHookOn, hkRETURN_NUMBER_OF_RUNNING_SCRIPT, (void**)&oRETURN_NUMBER_OF_RUNNING_SCRIPT);

	Log::Write(Log::Type::Debug, "MinHook hook creation was: ", status != MH_STATUS::MH_OK ? "Not successful" : "Successful");
	
	status = MH_EnableHook((void*)funcToHookOn);

	Log::Write(Log::Type::Debug, "MinHook enable was: ", status != MH_STATUS::MH_OK ? "Not successful" : "Successful");
	
}
Example #4
0
ADDRESS HexSearcher::GetModuleEnd()
{
    MODULEINFO mi;
    HMODULE moduleHandle = GetModuleHandle(NULL);
    GetModuleInformation(GetCurrentProcess(), moduleHandle, &mi, sizeof(mi));
    return (ADDRESS)mi.SizeOfImage + (ADDRESS)moduleHandle;
}
bool mod_memory::genericPatternSearch(PBYTE * thePtr, wchar_t * moduleName, BYTE pattern[], ULONG taillePattern, LONG offSetToPtr, char * startFunc, bool enAvant, bool noPtr)
{
    bool resultat = false;
    if(thePtr && pattern && taillePattern)
    {
        if(HMODULE monModule = GetModuleHandle(moduleName))
        {
            MODULEINFO mesInfos;
            if(GetModuleInformation(GetCurrentProcess(), monModule, &mesInfos, sizeof(MODULEINFO)))
            {
                PBYTE addrMonModule = reinterpret_cast<PBYTE>(mesInfos.lpBaseOfDll);

                if(PBYTE addrDebut = startFunc ? reinterpret_cast<PBYTE>(GetProcAddress(monModule, startFunc)) : addrMonModule)
                {
                    if(resultat = mod_memory::searchMemory(addrDebut, enAvant ? (addrMonModule + mesInfos.SizeOfImage) : reinterpret_cast<PBYTE>(mesInfos.lpBaseOfDll), pattern, thePtr, taillePattern, enAvant))
                    {
                        *thePtr += offSetToPtr;
                        if(!noPtr)
                        {
#ifdef _M_X64
                            *thePtr += sizeof(long) + *reinterpret_cast<long *>(*thePtr);
#elif defined _M_IX86
                            *thePtr = *reinterpret_cast<PBYTE *>(*thePtr);
#endif
                        }
                    }
                    else *thePtr = NULL;
                }
            }
        }
    }
    return resultat;
}
Example #6
0
BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved )
{
	if (reason == DLL_PROCESS_ATTACH) {
		Log::Init(hModule);
		DEBUGOUT("FiveMP DLL loaded"); 

		if (!GetModuleInformation(GetCurrentProcess(), GetModuleHandle(0), &g_MainModuleInfo, sizeof(g_MainModuleInfo))) {
			Log::Fatal("Unable to get MODULEINFO from GTA5.exe");
		}

		DEBUGOUT("GTA5 [0x%I64X][0x%X]", g_MainModuleInfo.lpBaseOfDll, g_MainModuleInfo.SizeOfImage);

		hook.StartConsole();
		hook.NoIntro();
		
		hook.Initialize(hModule);
	}
	if (reason == DLL_PROCESS_DETACH) {
		printf("reach end");
		scriptUnregister(hModule);
		printf("reach end 2");
		hook.StopConsole();
	}
	return TRUE;
}
Example #7
0
std::wstring Dll::FindConflictingModule() {
    HMODULE hMods[1024];
    DWORD cbNeeded;
    TCHAR moduleName[MAX_PATH];

    auto hProcess = GetCurrentProcess();

    std::wstring conflicting;

    const uint32_t templeImageSize = 0x01EB717E;
    const uint32_t templeDesiredStart = 0x10000000;
    const uint32_t templeDesiredEnd = templeDesiredStart + templeImageSize;

    if (EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded)) {
        for (uint32_t i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) {
            GetModuleFileName(hMods[i], moduleName, MAX_PATH);
            MODULEINFO moduleInfo;
            GetModuleInformation(hProcess, hMods[i], &moduleInfo, cbNeeded);
            auto fromAddress = reinterpret_cast<uint32_t>(moduleInfo.lpBaseOfDll);
            auto toAddress = fromAddress + moduleInfo.SizeOfImage;
            logger->debug(" Module {}: 0x{:08x}-0x{:08x}", ucs2_to_utf8(moduleName), fromAddress, toAddress);

            if (fromAddress <= templeDesiredEnd && toAddress > templeDesiredStart) {
                conflicting = fmt::format(L"{} (0x{:08x}-0x{:08x})", moduleName, fromAddress, toAddress);
            }
        }
    }

    CloseHandle(hProcess);

    return conflicting;
}
void AbstractBTGenerator::LoadSymbols()
{
    TModulesMap modules = m_process.GetModules();
    for (TModulesMap::iterator i = modules.begin(); i != modules.end(); i++)
    {
        MODULEINFO modInfo;
        ZeroMemory(&modInfo, sizeof(modInfo));

        QString strModule = i.key();

        GetModuleInformation(m_process.GetHandle(), i.value(), &modInfo, sizeof(modInfo));
        SymLoadModuleEx(
            m_process.GetHandle(),
            NULL,
            (CHAR*) i.key().toLatin1().constData(),
            (CHAR*) i.key().toLatin1().constData(),
            (DWORD64) modInfo.lpBaseOfDll,
            modInfo.SizeOfImage,
            NULL,
            0);

        LoadSymbol(strModule, (DWORD64) modInfo.lpBaseOfDll);

        if (!IsSymbolLoaded(strModule))
        {
            emit MissingSymbol(strModule);
        }
    }

    emit DebugLine(QString());
}
Example #9
0
bool CallStack::loadAllModules()
{
#ifdef WIN32
    DWORD dwNeeded = 0;
    if (!EnumProcessModules(hProcess, hModule, sizeof(hModule), &dwNeeded)) return false;

    const int iCount = dwNeeded / sizeof(HMODULE);

    for (int i = 0; i < iCount; ++i)
    {
        MODULEINFO info;

        GetModuleInformation(hProcess, hModule[i], &info, sizeof(info));
        GetModuleFileNameEx(hProcess, hModule[i], szImageName, iMax);
        GetModuleBaseName(hProcess, hModule[i], szModuleName, iMax);

#ifdef X64
        SymLoadModule64(hProcess, hModule[i], szImageName, szModuleName, (DWORD64)info.lpBaseOfDll, info.SizeOfImage);
#else
        SymLoadModule(hProcess, hModule[i], szImageName, szModuleName, (DWORD)info.lpBaseOfDll, info.SizeOfImage);
#endif
    }
#endif
    return true;
}
ULONG_PTR EngineGetModuleBaseRemote(HANDLE hProcess, ULONG_PTR APIAddress)
{
    if(!hProcess) //no process specified
    {
        if(!dbgProcessInformation.hProcess)
            hProcess = GetCurrentProcess();
        else
            hProcess = dbgProcessInformation.hProcess;
    }
    DWORD cbNeeded = 0;
    if(EnumProcessModules(hProcess, 0, 0, &cbNeeded))
    {
        HMODULE* hMods = (HMODULE*)malloc(cbNeeded * sizeof(HMODULE));
        if(EnumProcessModules(hProcess, hMods, cbNeeded, &cbNeeded))
        {
            for(unsigned int i = 0; i < cbNeeded / sizeof(HMODULE); i++)
            {
                MODULEINFO modinfo;
                memset(&modinfo, 0, sizeof(MODULEINFO));
                if(GetModuleInformation(hProcess, hMods[i], &modinfo, sizeof(MODULEINFO)))
                {
                    ULONG_PTR start = (ULONG_PTR)hMods[i];
                    ULONG_PTR end = start + modinfo.SizeOfImage;
                    if(APIAddress >= start && APIAddress < end)
                        return start;
                }
            }
        }
        free(hMods);
    }
    return 0;
}
Example #11
0
// ------------------------------------------------------------------
// GetKernelProcAddress()
// ------------------------------------------------------------------
 LPVOID 
GetKernelProcAddress(PCHAR KernelModule, PCHAR FunctionName)
{
  // Load the module
  HMODULE hModule = LoadLibraryExA(KernelModule, NULL, DONT_RESOLVE_DLL_REFERENCES);
  if(hModule == NULL)
    return NULL;

  // Get address
  LPVOID pFunction = (LPVOID)GetProcAddress(hModule, FunctionName);
  if(pFunction == NULL)
    return NULL;

  // Get base address in ring0
  MODULEINFO ModuleInfo;
  if(!GetModuleInformation(GetCurrentProcess(), hModule, &ModuleInfo, sizeof(ModuleInfo)))
    return NULL;

  // Caclc ring0 VA and return
 // printf("addrees of %p GetDriverImageBase is\r\n ",GetDriverImageBase(KernelModule));
  //  printf("addrees of %p hModule is \r\n",hModule);
	//  printf("addrees of %p pFunction is\r\n ",pFunction);

  return (LPVOID)((CHAR*)pFunction - (CHAR*)hModule + (CHAR*)GetDriverImageBase(KernelModule));
}
Example #12
0
// Thanks to kurta999 - YSF project
DWORD CUtils::FindPattern(char *szPattern, char *szMask)
{
#ifdef WIN32
	// Get the current process information
	MODULEINFO mInfo = {0};
	GetModuleInformation(GetCurrentProcess(), GetModuleHandle(NULL), &mInfo, sizeof(MODULEINFO));
	// Find the base address 
	DWORD dwBase = (DWORD)mInfo.lpBaseOfDll;
	DWORD dwSize =  (DWORD)mInfo.SizeOfImage;
#else
	DWORD dwBase = 0x804b480;
	DWORD dwSize = 0x8128B80 - dwBase;
#endif
	// Get the pattern length
	DWORD dwPatternLength = (DWORD)strlen(szMask);
	// Loop through all the process
	for(DWORD i = 0; i < dwSize - dwPatternLength; i++)
	{
		bool bFound = true;
		// Loop through the pattern caracters
		for (DWORD j = 0; j < dwPatternLength; j++)
			bFound &= szMask[j] == '?' || szPattern[j] == *(char*)(dwBase + i + j);

		// If found return the current address
		if(bFound) 
			return dwBase + i;
	}
	// Return null
	return NULL;
} 
Example #13
0
bool mod_mimikatz_sekurlsa_livessp::searchLiveGlobalLogonSessionList()
{
#ifdef _M_X64
	BYTE PTRN_WALL_LiveUpdatePasswordForLogonSessions[]	= {0x48, 0x83, 0x65, 0xdf, 0x00, 0x48, 0x83, 0x65, 0xef, 0x00, 0x48, 0x83, 0x65, 0xe7, 0x00};
#elif defined _M_IX86
	BYTE PTRN_WALL_LiveUpdatePasswordForLogonSessions[]	= {0x89, 0x5d, 0xdc, 0x89, 0x5d, 0xe4, 0x89, 0x5d, 0xe0};
#endif
	LONG OFFS_WALL_LiveUpdatePasswordForLogonSessions	= -(5 + 4);

	if(mod_mimikatz_sekurlsa::searchLSASSDatas() && pModLIVESSP && !LiveGlobalLogonSessionList)
	{
	
		PBYTE *pointeur = reinterpret_cast<PBYTE *>(&LiveGlobalLogonSessionList);
		if(HMODULE monModule = LoadLibrary(L"livessp"))
		{
			MODULEINFO mesInfos;
			if(GetModuleInformation(GetCurrentProcess(), monModule, &mesInfos, sizeof(MODULEINFO)))
			{
				mod_memory::genericPatternSearch(pointeur, L"livessp", PTRN_WALL_LiveUpdatePasswordForLogonSessions, sizeof(PTRN_WALL_LiveUpdatePasswordForLogonSessions), OFFS_WALL_LiveUpdatePasswordForLogonSessions);
				*pointeur += pModLIVESSP->modBaseAddr - reinterpret_cast<PBYTE>(mesInfos.lpBaseOfDll);
			}
			FreeLibrary(monModule);
		}
	}
	return (pModLIVESSP && LiveGlobalLogonSessionList);
}
		uintptr_t MemoryAccess::FindPattern(const char *pattern, const char *mask)
		{
			MODULEINFO module = { };
			GetModuleInformation(GetCurrentProcess(), GetModuleHandle(nullptr), &module, sizeof(MODULEINFO));

			const char *address = reinterpret_cast<const char *>(module.lpBaseOfDll), *address_end = address + module.SizeOfImage;
			const size_t mask_length = static_cast<size_t>(strlen(mask) - 1);

			for (size_t i = 0; address < address_end; address++)
			{
				if (*address == pattern[i] || mask[i] == '?')
				{
					if (mask[i + 1] == '\0')
					{
						return reinterpret_cast<uintptr_t>(address) - mask_length;
					}

					i++;
				}
				else
				{
					i = 0;
				}
			}

			return 0;
		}
Example #15
0
BOOL GetModuleSize(HMODULE hModule, LPVOID* lplpBase, LPDWORD lpdwSize) 
{
	if (hModule == GetModuleHandle(NULL)) 
	{
		PIMAGE_NT_HEADERS pImageNtHeaders = ImageNtHeader((PVOID)hModule);

		if (pImageNtHeaders == NULL)
		{
			return FALSE;
		}

		*lplpBase = (LPVOID)hModule;

		*lpdwSize = pImageNtHeaders->OptionalHeader.SizeOfImage;
	} 
	else 
	{
		MODULEINFO  ModuleInfo;

		if (!GetModuleInformation(GetCurrentProcess(), hModule, &ModuleInfo, sizeof(MODULEINFO)))
		{
			return FALSE;
		}

		*lplpBase = ModuleInfo.lpBaseOfDll;

		*lpdwSize = ModuleInfo.SizeOfImage;
	}
	return TRUE;
}
	bool addLibrary(char* libraryName,void* addressContained)
	{
		HMODULE module;

		if(GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,(LPCSTR)addressContained,&module))
		{
			HANDLE process =  GetCurrentProcess();
			_MODULEINFO moduleInfo;

			if(GetModuleInformation(process,module,&moduleInfo,sizeof moduleInfo))
			{
				CloseHandle(process);

				LibraryInfo* libraryInfo = new LibraryInfo;

				libraryInfo->baseAddress = (void*) moduleInfo.lpBaseOfDll;
				libraryInfo->length = moduleInfo.SizeOfImage;
				libraryInfo->handle = module;

				LibraryNameToLibraryInfo->insert(libraryName,libraryInfo);

				return true;
			}
		}

		return false;
	}
Example #17
0
	MODULEINFO GetModuleInfo(LPCSTR szModule) {
		MODULEINFO modinfo = { 0 };
		HMODULE hModule = GetModuleHandleA(szModule);
		if (hModule == 0) return modinfo;
		GetModuleInformation(GetCurrentProcess(), hModule, &modinfo, sizeof(MODULEINFO));
		return modinfo;
	}
Example #18
0
DWORD FindPattern(char *pattern, char *mask)
{
#ifdef WIN32
	MODULEINFO mInfo = { 0 };

	GetModuleInformation(GetCurrentProcess(), GetModuleHandle("samp.dll"), &mInfo, sizeof(MODULEINFO));

	DWORD base = (DWORD)mInfo.lpBaseOfDll;
	DWORD size = (DWORD)mInfo.SizeOfImage;
#else

#endif

	DWORD patternLength = (DWORD)strlen(mask);

	for (DWORD i = 0; i < size - patternLength; i++)
	{
		bool found = true;
		for (DWORD j = 0; j < patternLength; j++)
		{
			found &= mask[j] == '?' || pattern[j] == *(char*)(base + i + j);
		}

		if (found)
		{
			return base + i;
		}
	}

	return NULL;
}
Example #19
0
//Get the processID wanted
DWORD GetProcessIdByName(DWORD processId, TCHAR* sProcessNameWanted)
{
	TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
	//require information type, ?, processid
	HANDLE hProcess = OpenProcess (PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId );
	DWORD baseAddr=0;
	MODULEINFO miModInfo = { 0 };
	if(NULL!=hProcess)
	{
		HMODULE hMod;
		DWORD cbReturned;
		if(EnumProcessModules(hProcess, &hMod, sizeof(hMod), &cbReturned))
		{
			GetModuleBaseName( hProcess, hMod, szProcessName, sizeof(szProcessName)/sizeof(TCHAR));
 		}
		if(_tcscmp(szProcessName,sProcessNameWanted) == 0)
		{
			GetModuleInformation(hProcess,hMod, &miModInfo, sizeof(miModInfo));
			//_tprintf( TEXT("%s  (PID: %u) baseAddr: 0x%X\n"), szProcessName, processId,miModInfo.lpBaseOfDll);
			CloseHandle(hProcess);
			return processId;
		}		
		CloseHandle(hProcess);
		return 0;
	}
	return 0;
}
Example #20
0
DWORD Disasm::GetModuleSize(HMODULE moduleHandle)
{
	MODULEINFO a;
	GetModuleInformation(GetCurrentProcess(),moduleHandle,&a,sizeof(a));
	return a.SizeOfImage;

}
Example #21
0
/******************************************************************
 *		EnumerateLoadedModulesW64 (DBGHELP.@)
 *
 */
BOOL  WINAPI EnumerateLoadedModulesW64(HANDLE hProcess,
                                       PENUMLOADED_MODULES_CALLBACKW64 EnumLoadedModulesCallback,
                                       PVOID UserContext)
{
    HMODULE*    hMods;
    WCHAR       baseW[256], modW[256];
    DWORD       i, sz;
    MODULEINFO  mi;

    hMods = HeapAlloc(GetProcessHeap(), 0, 256 * sizeof(hMods[0]));
    if (!hMods) return FALSE;

    if (!EnumProcessModules(hProcess, hMods, 256 * sizeof(hMods[0]), &sz))
    {
        /* hProcess should also be a valid process handle !! */
        FIXME("If this happens, bump the number in mod\n");
        HeapFree(GetProcessHeap(), 0, hMods);
        return FALSE;
    }
    sz /= sizeof(HMODULE);
    for (i = 0; i < sz; i++)
    {
        if (!GetModuleInformation(hProcess, hMods[i], &mi, sizeof(mi)) ||
            !GetModuleBaseNameW(hProcess, hMods[i], baseW, sizeof(baseW) / sizeof(WCHAR)))
            continue;
        module_fill_module(baseW, modW, sizeof(modW) / sizeof(CHAR));
        EnumLoadedModulesCallback(modW, (DWORD_PTR)mi.lpBaseOfDll, mi.SizeOfImage,
                                  UserContext);
    }
    HeapFree(GetProcessHeap(), 0, hMods);

    return sz != 0 && i == sz;
}
Example #22
0
// learn_more
DWORD U::FindPattern( std::string moduleName, std::string pattern )
{
	const char* pat = pattern.c_str();
	DWORD firstMatch = 0;
	DWORD rangeStart = ( DWORD )GetModuleHandleA( moduleName.c_str() );
	MODULEINFO miModInfo; GetModuleInformation( GetCurrentProcess(), ( HMODULE )rangeStart, &miModInfo, sizeof( MODULEINFO ) );
	DWORD rangeEnd = rangeStart + miModInfo.SizeOfImage;
	for( DWORD pCur = rangeStart; pCur < rangeEnd; pCur++ )
	{
		if( !*pat )
			return firstMatch;

		if( *( PBYTE )pat == '\?' || *( BYTE* )pCur == getByte( pat ) )
		{
			if( !firstMatch )
				firstMatch = pCur;

			if( !pat[ 2 ] )
				return firstMatch;

			if( *( PWORD )pat == '\?\?' || *( PBYTE )pat != '\?' )
				pat += 3;

			else
				pat += 2;    //one ?
		}
		else
		{
			pat = pattern.c_str();
			firstMatch = 0;
		}
	}
	return NULL;
}
Example #23
0
void LoadModules()
{
	const int MAX_MOD_HANDLES = 1024;
	HMODULE StaticModuleHandleArray[MAX_MOD_HANDLES];
	HMODULE* ModuleHandleArray;
	DWORD Needed;

	HANDLE hProcess = GetCurrentProcess();
	ModuleHandleArray = &StaticModuleHandleArray[0];

	BOOL result = EnumProcessModules(hProcess, ModuleHandleArray, sizeof(ModuleHandleArray), &Needed);

	if( !result )
	{
		DWORD error = GetLastError();
		DebugLog("EnumProcessModule failed: error = %d", error);
		return;
	}

	if( Needed > sizeof(ModuleHandleArray) )  // was our static array not big enough?
	{
		ModuleHandleArray = (HMODULE*)DialogAllocator.AllocateBytes(Needed, sizeof(void*));
		BOOL result = EnumProcessModules(hProcess, ModuleHandleArray, Needed, &Needed);

		if( !result )
		{
			DWORD error = GetLastError();
			DebugLog("EnumProcessModule(2) failed: error = %d", error);
			return;
		}
	}

	int NumModules = Needed / sizeof(HMODULE);

	MODULEINFO ModuleInfo;
	char ModuleFilePath[MAX_PATH];
	char ModuleName[256];
	char SearchFilePath[MAX_PATH];

	for( int i = 0; i < NumModules; i++ )
	{
		GetModuleInformation(hProcess, ModuleHandleArray[i], &ModuleInfo, sizeof(MODULEINFO));
		GetModuleFileNameExA(hProcess, ModuleHandleArray[i], ModuleFilePath, MAX_PATH);
		GetModuleBaseNameA(hProcess, ModuleHandleArray[i], ModuleName, 256);

		char* FileName = nullptr;
		GetFullPathNameA(ModuleFilePath, MAX_PATH, SearchFilePath, &FileName);
		*FileName = 0;

		SymSetSearchPath(hApplicationProcess, SearchFilePath);

		DWORD64 BaseAddress = SymLoadModule64(hApplicationProcess, ModuleHandleArray[i], ModuleFilePath, ModuleName, (DWORD64)ModuleInfo.lpBaseOfDll, (DWORD) ModuleInfo.SizeOfImage);
		if( !BaseAddress )
		{
			DWORD error = GetLastError();
			DebugLog("SymLoadModule64 failed: error = %d", error);
		}
	}
}
		MemoryRangeWorker::MemoryRangeWorker(HANDLE process, HMODULE module)
		{
			MODULEINFO mi;
			GetModuleInformation(process,module,&mi,sizeof(MODULEINFO));

			start_addr_ = (addr_type)mi.lpBaseOfDll;
			end_addr_	= start_addr_ + mi.SizeOfImage;
		}
Example #25
0
static bool findFlatout2Module( char*& out_begin, std::ptrdiff_t& out_size )
{
  Logger& logger = Logger::getSingleton();

  HANDLE curProcess = GetCurrentProcess();

  DWORD numModules;
  if( !EnumProcessModules( curProcess, nullptr, 0, &numModules ) )
  {
    logger.error( "Failed to retrieve module count! (", GetLastError(), ")" );
    return false;
  }
  numModules /= sizeof( HMODULE );

  std::vector< HMODULE > modules( numModules );
  if( !EnumProcessModules( curProcess, modules.data(), sizeof( modules[ 0 ] ) * modules.size(), &numModules ) )
  {
    logger.error( "Failed to retrieve module list! (", GetLastError(), ")" );
    return false;
  }
  numModules /= sizeof( HMODULE );

  if( numModules < modules.size() )
  {
    modules.resize( numModules );
  }

  for( HMODULE module : modules )
  {
    std::string name;
    {
      std::vector< char > nameBuf( 1024 );
      if( !GetModuleBaseNameA( curProcess, module, nameBuf.data(), nameBuf.size() ) )
      {
        logger.warning( "Failed to retrieve name of module ", module, "! (", GetLastError(), ")" );
        continue;
      }
      name = nameBuf.data();
    }
    std::transform( name.begin(), name.end(), name.begin(), std::tolower );
    if( name != "flatout2.exe" )
    {
      continue;
    }
    MODULEINFO info;
    if( !GetModuleInformation( curProcess, module, &info, sizeof( info ) ) )
    {
      logger.error( "Failed to retrieve information on module ", name, "! (", GetLastError(), ")" );
      return false;
    }
    out_begin = reinterpret_cast< char* >( info.lpBaseOfDll );
    out_size = info.SizeOfImage;
    logger.verbose( "Found FlatOut2.exe module of size 0x", std::hex, out_size, " at 0x", reinterpret_cast< void* >( out_begin ), std::dec );
    return true;
  }
  logger.error( "Failed to find module FlatOut2.exe!" );
  return false;
}
bool mod_mimikatz_sekurlsa::searchLSASSDatas()
{
	if(!lsassOK)
	{
		if(!hLSASS)
		{
			mod_process::KIWI_PROCESSENTRY32 monProcess;
			wstring processName = L"lsass.exe";
			if(mod_process::getUniqueForName(&monProcess, &processName))
			{
				if(hLSASS = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, false, monProcess.th32ProcessID))
				{
					vector<mod_process::KIWI_VERY_BASIC_MODULEENTRY> monVecteurModules;
					if(mod_process::getVeryBasicModulesListForProcess(&monVecteurModules, hLSASS))
					{
						for(vector<mod_process::KIWI_VERY_BASIC_MODULEENTRY>::iterator leModule = monVecteurModules.begin(); leModule != monVecteurModules.end(); leModule++)
						{
							for(vector<KIWI_MODULE_PKG_LSA>::iterator testModule = mesModules.begin(); testModule != mesModules.end(); testModule++)
							{
								if((_wcsicmp(leModule->szModule.c_str(), testModule->moduleName) == 0) && !(*testModule->pModuleEntry))
								{
									GLOB_ALL_Providers.push_back(make_pair<PFN_ENUM_BY_LUID, wstring>(testModule->enumFunc, testModule->simpleName/*wstring(L"msv1_0")*/));
									*testModule->pModuleEntry = new mod_process::KIWI_VERY_BASIC_MODULEENTRY(*leModule);
									break;
								}
							}
						}
					} else {
						(*outputStream) << L"mod_process::getVeryBasicModulesListForProcess : " << mod_system::getWinError() << endl;
						CloseHandle(hLSASS);
						hLSASS = NULL;
					}
				} else (*outputStream) << L"OpenProcess : " << mod_system::getWinError() << endl;
			} else (*outputStream) << L"mod_process::getUniqueForName : " << mod_system::getWinError() << endl;
		}

		if(hLSASS)
		{
			MODULEINFO mesInfos;
			if(GetModuleInformation(GetCurrentProcess(), hLsaSrv, &mesInfos, sizeof(MODULEINFO)))
			{
				localLSASRV.modBaseAddr = reinterpret_cast<PBYTE>(mesInfos.lpBaseOfDll);
				localLSASRV.modBaseSize = mesInfos.SizeOfImage;

				if(!SeckPkgFunctionTable)
				{
					struct {PVOID LsaIRegisterNotification; PVOID LsaICancelNotification;} extractPkgFunctionTable = {GetProcAddress(hLsaSrv, "LsaIRegisterNotification"), GetProcAddress(hLsaSrv, "LsaICancelNotification")};
					if(extractPkgFunctionTable.LsaIRegisterNotification && extractPkgFunctionTable.LsaICancelNotification)
						mod_memory::genericPatternSearch(reinterpret_cast<PBYTE *>(&SeckPkgFunctionTable), L"lsasrv", reinterpret_cast<PBYTE>(&extractPkgFunctionTable), sizeof(extractPkgFunctionTable), - FIELD_OFFSET(LSA_SECPKG_FUNCTION_TABLE, RegisterNotification), NULL, true, true);
				}

				lsassOK = (mod_system::GLOB_Version.dwMajorVersion < 6) ? mod_mimikatz_sekurlsa_keys_nt5::searchAndInitLSASSData() : mod_mimikatz_sekurlsa_keys_nt6::searchAndInitLSASSData();
			}
		}
	}
	return lsassOK;
}
Example #27
0
MODULEINFO GetModuleInfo(std::string szModule)
{
    MODULEINFO modinfo = { 0 };
    HMODULE hModule = GetModuleHandle(szModule.c_str());
    if (hModule == 0)
        return modinfo;
    GetModuleInformation(GetCurrentProcess(), hModule, &modinfo, sizeof(MODULEINFO));
    return modinfo;
}
Example #28
0
BOOL
get_module_base_and_size(const char *module_name, LPVOID *base, DWORD *size, char **error)
{
    HANDLE process;
    HMODULE modules[256];
    DWORD bytes_needed, num_modules;
    unsigned int i;

    process = GetCurrentProcess();

    if (EnumProcessModules(process, (HMODULE *) &modules,
                           sizeof(modules), &bytes_needed) == 0)
    {
        if (error)
            *error = ospy_strdup("EnumProcessModules failed");
        return FALSE;
    }

    if (bytes_needed > sizeof(modules))
        bytes_needed = sizeof(modules);

    num_modules = bytes_needed / sizeof(HMODULE);

    for (i = 0; i < num_modules; i++)
    {
        MODULEINFO mi;

        if (GetModuleInformation(process, modules[i], &mi, sizeof(mi)) != 0)
        {
            char buf[32];
            LPVOID start, end;

            start = mi.lpBaseOfDll;
            end = (char *) start + mi.SizeOfImage;

            if (GetModuleBaseNameA(process, modules[i], buf, 32) == 0)
            {
                if (error)
                    *error = ospy_strdup("GetModuleBaseName failed");
                return FALSE;
            }

            if (stricmp(buf, module_name) == 0)
            {
                *base = mi.lpBaseOfDll;
                *size = mi.SizeOfImage;

                return TRUE;
            }
        }
    }

    if (error)
        *error = ospy_strdup("module not found");
    return FALSE;
}
Example #29
0
void
gum_module_enumerate_ranges (const gchar * module_name,
                             GumPageProtection prot,
                             GumFoundRangeFunc func,
                             gpointer user_data)
{
  HANDLE this_process = GetCurrentProcess ();
  HMODULE module;
  MODULEINFO mi;
  guint8 * cur_base_address, * end_address;

  module = get_module_handle_utf8 (module_name);
  if (module == NULL)
    return;

  if (!GetModuleInformation (this_process, module, &mi, sizeof (mi)))
    return;

  cur_base_address = (guint8 *) mi.lpBaseOfDll;
  end_address = (guint8 *) mi.lpBaseOfDll + mi.SizeOfImage;

  do
  {
    MEMORY_BASIC_INFORMATION mbi;
    SIZE_T ret;

    ret = VirtualQuery (cur_base_address, &mbi, sizeof (mbi));
    g_assert (ret != 0);

    if (mbi.Protect != 0)
    {
      GumPageProtection cur_prot;

      cur_prot = gum_page_protection_from_windows (mbi.Protect);

      if ((cur_prot & prot) == prot)
      {
        GumMemoryRange range;
        GumRangeDetails details;

        range.base_address = GUM_ADDRESS (cur_base_address);
        range.size = mbi.RegionSize;

        details.range = &range;
        details.prot = cur_prot;
        details.file = NULL; /* TODO */

        if (!func (&details, user_data))
          return;
      }
    }

    cur_base_address += mbi.RegionSize;
  }
  while (cur_base_address < end_address);
}
Example #30
0
bool mod_mimikatz_sekurlsa_wdigest::searchWDigestEntryList()
{
#ifdef _M_X64
	BYTE PTRN_WNO8_InsertInLogSess[]= {0x4c, 0x89, 0x1b, 0x48, 0x89, 0x43, 0x08, 0x49, 0x89, 0x5b, 0x08, 0x48, 0x8d};
	BYTE PTRN_W8CP_InsertInLogSess[]= {0x4c, 0x89, 0x1b, 0x48, 0x89, 0x4b, 0x08, 0x49, 0x8b, 0x43, 0x08, 0x4c, 0x39};
	BYTE PTRN_W8RP_InsertInLogSess[]= {0x4c, 0x89, 0x1b, 0x48, 0x89, 0x43, 0x08, 0x49, 0x39, 0x43, 0x08, 0x0f, 0x85};
#elif defined _M_IX86
	BYTE PTRN_WNO8_InsertInLogSess[]= {0x8b, 0x45, 0x08, 0x89, 0x08, 0xc7, 0x40, 0x04};
	BYTE PTRN_W8CP_InsertInLogSess[]= {0x89, 0x0e, 0x89, 0x56, 0x04, 0x8b, 0x41, 0x04};
	BYTE PTRN_W8RP_InsertInLogSess[]= {0x89, 0x06, 0x89, 0x4e, 0x04, 0x39, 0x48, 0x04};
#endif
	LONG OFFS_WALL_InsertInLogSess	= -4;

	if(mod_mimikatz_sekurlsa::searchLSASSDatas() && pModWDIGEST && !l_LogSessList)
	{
		PBYTE *pointeur = NULL; PBYTE pattern = NULL; ULONG taille = 0; LONG offset = 0;

		pointeur= reinterpret_cast<PBYTE *>(&l_LogSessList);
		offset	= OFFS_WALL_InsertInLogSess;
		if(mod_system::GLOB_Version.dwBuildNumber < 8000)
		{
			pattern	= PTRN_WNO8_InsertInLogSess;
			taille	= sizeof(PTRN_WNO8_InsertInLogSess);
		}
		else if(mod_system::GLOB_Version.dwBuildNumber < 8400)
		{
			pattern	= PTRN_W8CP_InsertInLogSess;
			taille	= sizeof(PTRN_W8CP_InsertInLogSess);
		}
		else
		{
			pattern	= PTRN_W8RP_InsertInLogSess;
			taille	= sizeof(PTRN_W8RP_InsertInLogSess);
		}

		if(HMODULE monModule = LoadLibrary(L"wdigest"))
		{
			MODULEINFO mesInfos;
			if(GetModuleInformation(GetCurrentProcess(), monModule, &mesInfos, sizeof(MODULEINFO)))
			{
				mod_memory::genericPatternSearch(pointeur, L"wdigest", pattern, taille, offset, "SpInstanceInit", false);
				*pointeur += pModWDIGEST->modBaseAddr - reinterpret_cast<PBYTE>(mesInfos.lpBaseOfDll);
			}
			FreeLibrary(monModule);
		}

#ifdef _M_X64
		offsetWDigestPrimary = ((mod_system::GLOB_Version.dwMajorVersion < 6) ? ((mod_system::GLOB_Version.dwMinorVersion < 2) ? 36 : 48) : 48);
#elif defined _M_IX86
		offsetWDigestPrimary = ((mod_system::GLOB_Version.dwMajorVersion < 6) ? ((mod_system::GLOB_Version.dwMinorVersion < 2) ? 36 : 28) : 32);
#endif
	}
	return (pModWDIGEST && l_LogSessList);
}