Ejemplo n.º 1
0
bool ProcessAccessHelp::getProcessModules(HANDLE hProcess, std::vector<ModuleInfo> &moduleList)
{
    ModuleInfo module;
    WCHAR filename[MAX_PATH*2] = {0};
    DWORD cbNeeded = 0;
    bool retVal = false;
    DeviceNameResolver deviceNameResolver;

    moduleList.reserve(20);

    EnumProcessModules(hProcess, 0, 0, &cbNeeded);

    HMODULE* hMods=(HMODULE*)malloc(cbNeeded*sizeof(HMODULE));

    if (hMods)
    {
        if(EnumProcessModules(hProcess, hMods, cbNeeded, &cbNeeded))
        {
            for(unsigned int i = 1; i < (cbNeeded/sizeof(HMODULE)); i++) //skip first module!
            {
                module.modBaseAddr = (DWORD_PTR)hMods[i];
                module.modBaseSize = (DWORD)getSizeOfImageProcess(hProcess, module.modBaseAddr);
                module.isAlreadyParsed = false;
                module.parsing = false;

                filename[0] = 0;
                module.fullPath[0] = 0;

                if (GetMappedFileNameW(hProcess, (LPVOID)module.modBaseAddr, filename, _countof(filename)) > 0)
                {
                    if (!deviceNameResolver.resolveDeviceLongNameToShort(filename, module.fullPath))
                    {
                        if (!GetModuleFileNameExW(hProcess, (HMODULE)module.modBaseAddr, module.fullPath, _countof(module.fullPath)))
                        {
                            wcscpy_s(module.fullPath, filename);
                        }
                    }
                }
                else
                {
                    GetModuleFileNameExW(hProcess, (HMODULE)module.modBaseAddr, module.fullPath, _countof(module.fullPath));
                }

                moduleList.push_back(module);
            }

            retVal = true;
        }

        free(hMods);
    }

    return retVal;
}
Ejemplo n.º 2
0
static void fetch_module_name(void* name_addr, BOOL unicode, void* mod_addr,
                              WCHAR* buffer, size_t bufsz, BOOL is_pcs)
{
    static WCHAR        pcspid[] = {'P','r','o','c','e','s','s','_','%','0','8','x',0};
    static WCHAR        dlladdr[] = {'D','L','L','_','%','0','8','l','x',0};

    memory_get_string_indirect(dbg_curr_process, name_addr, unicode, buffer, bufsz);
    if (!buffer[0] &&
            !GetModuleFileNameExW(dbg_curr_process->handle, mod_addr, buffer, bufsz))
    {
        if (is_pcs)
        {
            HMODULE h;
            WORD (WINAPI *gpif)(HANDLE, LPWSTR, DWORD);

            /* On Windows, when we get the process creation debug event for a process
             * created by winedbg, the modules' list is not initialized yet. Hence,
             * GetModuleFileNameExA (on the main module) will generate an error.
             * Psapi (starting on XP) provides GetProcessImageFileName() which should
             * give us the expected result
             */
            if (!(h = GetModuleHandleA("psapi")) ||
                    !(gpif = (void*)GetProcAddress(h, "GetProcessImageFileNameW")) ||
                    !(gpif)(dbg_curr_process->handle, buffer, bufsz))
                snprintfW(buffer, bufsz, pcspid, dbg_curr_pid);
        }
        else
            snprintfW(buffer, bufsz, dlladdr, (unsigned long)mod_addr);
    }
}
Ejemplo n.º 3
0
STDMETHODIMP CBProcess::get_FileName(BSTR* newVal)
{
	CBString str;
	DWORD dwLen;

	//GetProcessImageFileName For Windows 5.1(XP 2003) later
	DWORD (WINAPI *GetModuleFileNameExW)(HANDLE,HMODULE,LPWSTR,DWORD) = NULL;
	HMODULE hmod = ::LoadLibrary("Psapi.dll");
	if(hmod == NULL)
		return HRESULT_FROM_WIN32(GetLastError());

	GetModuleFileNameExW = (DWORD (WINAPI *)(HANDLE,HMODULE,LPWSTR,DWORD))GetProcAddress(hmod, "GetModuleFileNameExW");
	if(GetModuleFileNameExW == NULL)
	{
		FreeLibrary(hmod);
		return HRESULT_FROM_WIN32(GetLastError());
	}

	if (!(dwLen = GetModuleFileNameExW(m_hProcess, NULL, str.GetBufferSetLength(MAX_PATH), MAX_PATH)))
	{
		FreeLibrary(hmod);
		str.ReleaseBuffer(0);
		return HRESULT_FROM_WIN32(GetLastError());
	}
	FreeLibrary(hmod);
	str.ReleaseBuffer(dwLen);
	*newVal = str.AllocSysString();
	return S_OK;
}
Ejemplo n.º 4
0
BOOL AudioVolume::IsQzoneMusicProcess(DWORD processId)
{
    HANDLE hrocess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ , FALSE, processId);
    WCHAR fileName[MAX_PATH];
    DWORD ret = GetModuleFileNameExW(hrocess, NULL, fileName, MAX_PATH);
    BOOL bFind = (ret > 0 && wcsstr(fileName, L"QzoneMusic.exe") != NULL);
    CloseHandle(hrocess);
    return bFind;
}
Ejemplo n.º 5
0
ErrorCode Process::enumerateSharedLibraries(
    std::function<void(SharedLibraryInfo const &)> const &cb) {
  BOOL rc;
  std::vector<HMODULE> modules;
  DWORD bytesNeeded;

  rc = EnumProcessModules(_handle, modules.data(),
                          modules.size() * sizeof(HMODULE), &bytesNeeded);
  if (!rc)
    return Platform::TranslateError();

  modules.resize(bytesNeeded / sizeof(HMODULE));

  rc = EnumProcessModules(_handle, modules.data(),
                          modules.size() * sizeof(HMODULE), &bytesNeeded);
  if (!rc)
    return Platform::TranslateError();

  for (auto m : modules) {
    SharedLibraryInfo sl;

    sl.main = (m == modules[0]);

    WCHAR nameStr[MAX_PATH];
    DWORD nameSize;
    nameSize = GetModuleFileNameExW(_handle, m, nameStr, sizeof(nameStr));
    if (nameSize == 0)
      return Platform::TranslateError();
    sl.path = Platform::WideToNarrowString(std::wstring(nameStr, nameSize));

    // The following two transforms ensure that the paths we return to the
    // debugger look like unix paths. This shouldn't be required but LLDB seems
    // to be having trouble with paths when the host and the remote don't use
    // the same path separator.
    if (sl.path.length() >= 2 && sl.path[0] >= 'A' && sl.path[0] <= 'Z' &&
        sl.path[1] == ':')
      sl.path.erase(0, 2);
    for (auto &c : sl.path)
      if (c == '\\')
        c = '/';

    // Modules on Windows only have one "section", which is the address of the
    // module itself.
    sl.sections.push_back(reinterpret_cast<uint64_t>(m));

    cb(sl);
  }

  return kSuccess;
}
Ejemplo n.º 6
0
BOOL injection(DWORD pid, char *szDllName)
{
	HANDLE hProc;
	hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pid);
	if (hProc == NULL)
	{
		errorLOG("OpenProcess()");
		return FALSE;
	}

	TCHAR szProcessName[MAX_PATH];
	if (GetModuleFileNameExW(hProc, NULL, szProcessName, MAX_PATH) == 0)
	{
		errorLOG("GetModuleFileNameExW()");
		return FALSE;
	}
	wprintf(L"path : %s\n", szProcessName);

	LPVOID pRemoteBuf = NULL;
	DWORD dwBufSize = strlen(szDllName) + sizeof(char);
	pRemoteBuf = VirtualAllocEx(hProc, NULL, dwBufSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
	if (pRemoteBuf == NULL)
	{
		errorLOG("VirtualAllocEx()");
		return FALSE;
	}

	if (WriteProcessMemory(hProc, pRemoteBuf, (LPVOID)szDllName, dwBufSize, NULL) == FALSE)
	{
		errorLOG("WriteProcessMemory()");
		return FALSE;
	}

	FARPROC pThreadProc = NULL;
	pThreadProc = GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryA");
	if (pThreadProc == NULL)
	{
		errorLOG("GetProcAddress()");
		return FALSE;
	}

	if (CreateRemoteThread(hProc, NULL, 0, (LPTHREAD_START_ROUTINE)pThreadProc, pRemoteBuf, 0, NULL) == NULL)
	{
		errorLOG("CreateRemoteThread()");
		return FALSE;
	}

	return TRUE;
}
Ejemplo n.º 7
0
  /// get the name of the process.
  // @param full true if you want the full path; otherwise returns the base name.
  // @function get_process_name
  def get_process_name(Boolean full) {
    HMODULE hMod;
    DWORD cbNeeded;
    wchar_t modname[MAX_PATH];

    if (EnumProcessModules(this->hProcess, &hMod, sizeof(hMod), &cbNeeded)) {
      if (full) {
        GetModuleFileNameExW(this->hProcess, hMod, modname, sizeof(modname));
      } else {
        GetModuleBaseNameW(this->hProcess, hMod, modname, sizeof(modname));
      }
      return push_wstring(L,modname);
    } else {
      return push_error(L);
    }
  }
Ejemplo n.º 8
0
void CTask::SendTask(SOCKET sock)
{
	MSGINFO_S msg;
	TASK task;
	memset(&msg, 0, sizeof(MSGINFO_S));
	msg.Msg_id = TASKLIST;

	DWORD needed;
	HANDLE hProcess;
	HMODULE hModule;
	wchar_t path[260] = _T("");
	HANDLE hToken;

	HANDLE  hProcessSnap = NULL;
	PROCESSENTRY32 pe32;
	pe32.dwSize = sizeof(PROCESSENTRY32);
	hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

	if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
	{
		EnablePrivilege(hToken,SE_DEBUG_NAME); //尝试提升权限
		Process32First(hProcessSnap, &pe32);
		do
		{
			memset(&task, 0, sizeof(TASK));
			memset(msg.context, 0, sizeof(msg.context));
			hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pe32.th32ProcessID);
			if (hProcess)
			{
				EnumProcessModules(hProcess, &hModule, sizeof(hModule), &needed);
				GetModuleFileNameExW(hProcess, hModule, path, sizeof(path));
				wcscpy_s(task.TaskPath, _countof(path), path);
			}
			wcscpy_s(task.TaskName, _countof(pe32.szExeFile), pe32.szExeFile); //进程名
			task.TaskID = pe32.th32ProcessID;
			task.flag = false;
			memcpy(msg.context, &task, sizeof(TASK));
			m_sock.MySend(sock, (char*)&msg, sizeof(MSGINFO_S));
		} while (Process32Next(hProcessSnap, &pe32));
	}
	CloseHandle(hProcess);
	CloseHandle(hModule);

	task.flag = true;
	memcpy(msg.context, &task, sizeof(TASK));
	m_sock.MySend(sock, (char*)&msg, sizeof(MSGINFO_S));
}
Ejemplo n.º 9
0
ULONG_PTR EngineGetProcAddressRemote(HANDLE hProcess, const wchar_t* szDLLName, const char* szAPIName)
{
    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++)
            {
                wchar_t szModuleName[MAX_PATH] = L"";
                if(GetModuleFileNameExW(hProcess, hMods[i], szModuleName, _countof(szModuleName)))
                {
                    wchar_t* dllName = wcsrchr(szModuleName, L'\\');
                    if(dllName)
                    {
                        dllName++;
                        if(!_wcsicmp(dllName, szDLLName))
                        {
                            HMODULE hModule = LoadLibraryExW(szModuleName, 0, DONT_RESOLVE_DLL_REFERENCES | LOAD_LIBRARY_AS_DATAFILE);
                            if(hModule)
                            {
                                ULONG_PTR funcAddress = (ULONG_PTR)GetProcAddress(hModule, szAPIName);
                                if(funcAddress)
                                {
                                    funcAddress -= (ULONG_PTR)hModule; //rva
                                    FreeLibrary(hModule);
                                    return funcAddress + (ULONG_PTR)hMods[i]; //va
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
        free(hMods);
    }
    return 0;
}
Ejemplo n.º 10
0
bool ProcessLister::getAbsoluteFilePath(HANDLE hProcess, Process * process)
{
	WCHAR processPath[MAX_PATH];
	bool retVal = false;

	wcscpy_s(process->fullPath, L"Unknown path");

	if(!hProcess)
	{
		//missing rights
		return false;
	}

    

	if (GetProcessImageFileNameW(hProcess, processPath, _countof(processPath)) > 0)
	{
		if (!deviceNameResolver->resolveDeviceLongNameToShort(processPath, process->fullPath))
		{
#ifdef DEBUG_COMMENTS
			Scylla::debugLog.log(L"getAbsoluteFilePath :: resolveDeviceLongNameToShort failed with path %s", processPath);
#endif
			//some virtual volumes

            MessageBoxW(0, processPath, L"Cannot resolve this path!", MB_ICONERROR);        
		}
		else
		{
			retVal = true;
		}
	}
	else
	{
#ifdef DEBUG_COMMENTS
		Scylla::debugLog.log(L"getAbsoluteFilePath :: GetProcessImageFileName failed %u", GetLastError());
#endif
		if (GetModuleFileNameExW(hProcess, 0, process->fullPath, _countof(process->fullPath)) != 0)
		{
			retVal = true;
		}
	}

	return retVal;
}
Ejemplo n.º 11
0
static bool WindowsGetModuleFileNameEx(HANDLE p_process, HMODULE p_module, MCStringRef& r_path)
{
	bool t_success;
	t_success = true;

	// For some unfathomable reason, it is not possible find out how big a
	// buffer you might need for a module file name. Instead we loop until
	// we are sure we have the whole thing.
	WCHAR *t_path;
	uint32_t t_path_length;
	t_path_length = 0;
	t_path = nil;
	while(t_success)
	{
		t_path_length += 256;
		MCMemoryDeleteArray(t_path);

		if (t_success)
			t_success = MCMemoryNewArray(t_path_length, t_path);

		DWORD t_result;
		t_result = 0;
		if (t_success)
		{
			// If the buffer is too small, the result will equal the input
			// buffer size.
			t_result = GetModuleFileNameExW(p_process, p_module, t_path, t_path_length);
			if (t_result == 0)
				t_success = false;
			else if (t_result == t_path_length)
				continue;
		}

		if (t_success)
			break;
	}

	if (t_success)
		t_success = MCStringCreateWithWString(t_path, r_path);
	
	MCMemoryDeleteArray(t_path);

	return t_success;
}
Ejemplo n.º 12
0
bool TerminateProcessFromPathFilename ( const SString& strPathFilename )
{
    DWORD dwProcessIDs[250];
    DWORD pBytesReturned = 0;
    if ( EnumProcesses ( dwProcessIDs, 250 * sizeof(DWORD), &pBytesReturned ) )
    {
        DWORD id1 = GetCurrentProcessId();
        for ( unsigned int i = 0; i < pBytesReturned / sizeof ( DWORD ); i++ )
        {
            DWORD id2 = dwProcessIDs[i];
            if ( id2 == id1 )
                continue;
            // Skip 64 bit processes to avoid errors
            if ( !Is32bitProcess ( dwProcessIDs[i] ) )
                continue;
            // Open the process
            HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, dwProcessIDs[i]);
            if ( hProcess )
            {
                HMODULE pModule;
                DWORD cbNeeded;
                if ( EnumProcessModules ( hProcess, &pModule, sizeof ( HMODULE ), &cbNeeded ) )
                {
                    WCHAR szModuleName[MAX_PATH*2] = L"";
                    if ( GetModuleFileNameExW( hProcess, pModule, szModuleName, NUMELMS(szModuleName) ) )
                    {
                        SString strModuleName = ToUTF8( szModuleName );
                        if ( stricmp ( strModuleName, strPathFilename ) == 0 )
                        {
                            TerminateProcess ( hProcess, 0 );
                            CloseHandle ( hProcess );
                            return true;
                        } 
                    }
                }

                // Close the process
                CloseHandle ( hProcess );
            }
        }
    }

    return false;
}
Ejemplo n.º 13
0
HANDLE GetProcessHandleFromName(LPWSTR procName){
	// Assuming that the computer this runs on wont have more than 2048 processes.
	DWORD dwProcessIds[2048];
	DWORD dwProcessIdBytes;
	EnumProcesses(dwProcessIds, sizeof(dwProcessIds), &dwProcessIdBytes);

	// Now we look at each process.
	for(DWORD i=0;i<dwProcessIdBytes/sizeof(DWORD);i++){
		HANDLE proc = OpenProcess(PROCESS_INJECT_PERMISSIONS, FALSE, dwProcessIds[i]);

		// We probably don't have permissions to mess with it.
		if(proc == INVALID_HANDLE_VALUE){
			continue;
		}

		// Lets get the name of the process.
		WCHAR procQueryName[MAX_PATH];
		WCHAR *procFileName;
		GetModuleFileNameExW(proc, 0, procQueryName, MAX_PATH);

		// No idea what these processes are, maybe something to do with x64 processes hiding from x86 processes??
		if(wcslen(procQueryName) == 284 || wcslen(procQueryName) == 285){
			continue;
		}

		procFileName = GetFileName(procQueryName);

		if(wcscmp(procFileName, procName) == 0){
			// Break if the name matches the one we are searching for.
			return proc;
		} else {
			// Otherwise close the handle.
			CloseHandle(proc);
		}
	}

	return NULL;
}
Ejemplo n.º 14
0
BOOL CALLBACK enumWindowsProc(HWND hWnd, LPARAM lParam)
{
	WCHAR buffer[1024] = { L"\0" };
	INT32 len = GetWindowTextW(hWnd, buffer, ARRAYSIZE(buffer));
	if (!len || 
		(std::wstring(buffer) == _Nena_Ignore_DefaultImeW) ||
		(std::wstring(buffer) == _Nena_Ignore_MsctfimeW))
		return TRUE;

	std::string bufferconv;
	std::wstring bufferwconv = buffer;
	Nena::Converter::String16To8(bufferconv, bufferwconv);
	g_windows[hWnd] = bufferconv;

	GetClassNameW(hWnd, buffer, ARRAYSIZE(buffer));
	bufferwconv = buffer;
	Nena::Converter::String16To8(bufferconv, bufferwconv);
	g_classes[hWnd] = bufferconv;

	DWORD processId;
	GetWindowThreadProcessId(hWnd, &processId);

	HANDLE processHandle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_VM_READ, FALSE, processId);

	if (processHandle)
	{
		BOOL ok;
		DWORD size;

		size = GetModuleFileNameExW(processHandle, NULL, buffer, ARRAYSIZE(buffer));
		bufferwconv = buffer;
		Nena::Converter::String16To8(bufferconv, bufferwconv);
		g_images[hWnd] = bufferconv;
	}

	CloseHandle(processHandle);
	return TRUE;
}
Ejemplo n.º 15
0
ULONG_PTR EngineGetAddressLocal(HANDLE hProcess, ULONG_PTR Address)
{
    HMODULE remoteModuleBase = (HMODULE)EngineGetModuleBaseRemote(hProcess, Address);
    if(remoteModuleBase)
    {
        wchar_t szModuleName[MAX_PATH] = L"";
        if(GetModuleFileNameExW(hProcess, remoteModuleBase, szModuleName, _countof(szModuleName)))
        {
            wchar_t* dllName = wcsrchr(szModuleName, L'\\');
            if(dllName)
            {
                dllName++;
                ULONG_PTR localModuleBase = EngineGetModuleBaseRemote(GetCurrentProcess(), dllName);
                if(localModuleBase)
                {
                    Address -= (ULONG_PTR)remoteModuleBase; //rva
                    return Address + localModuleBase;
                }
            }
        }
    }
    return 0;
}
Ejemplo n.º 16
0
DWORD
WINAPI
GetModuleFileNameExA(
    HANDLE hProcess,
    HMODULE hModule,
    LPSTR lpFilename,
    DWORD nSize
    )
{
    LPWSTR lpwstr;
    DWORD cwch;
    DWORD cch;

    lpwstr = (LPWSTR) LocalAlloc(LMEM_FIXED, nSize * 2);

    if (lpwstr == NULL) {
        return(0);
        }

    cwch = cch = GetModuleFileNameExW(hProcess, hModule, lpwstr, nSize);

    if (cwch < nSize) {
        //
        // Include NULL terminator
        //

        cwch++;
        }

    if (!WideCharToMultiByte(CP_ACP, 0, lpwstr, cwch, lpFilename, nSize, NULL, NULL)) {
        cch = 0;
        }

    LocalFree((HLOCAL) lpwstr);

    return(cch);
}
Ejemplo n.º 17
0
/******************************************************************
 *		add_module
 *
 * Add a module to a dump context
 */
static BOOL add_module(struct dump_context* dc, const WCHAR* name,
                       DWORD64 base, DWORD size, DWORD timestamp, DWORD checksum,
                       BOOL is_elf)
{
    if (!dc->modules)
    {
        dc->alloc_modules = 32;
        dc->modules = HeapAlloc(GetProcessHeap(), 0,
                                dc->alloc_modules * sizeof(*dc->modules));
    }
    else if(dc->num_modules >= dc->alloc_modules)
    {
        dc->alloc_modules *= 2;
        dc->modules = HeapReAlloc(GetProcessHeap(), 0, dc->modules,
                                  dc->alloc_modules * sizeof(*dc->modules));
    }
    if (!dc->modules)
    {
        dc->alloc_modules = dc->num_modules = 0;
        return FALSE;
    }
    if (is_elf ||
        !GetModuleFileNameExW(dc->hProcess, (HMODULE)(DWORD_PTR)base,
                              dc->modules[dc->num_modules].name,
                              sizeof(dc->modules[dc->num_modules].name) / sizeof(WCHAR)))
        lstrcpynW(dc->modules[dc->num_modules].name, name,
                  sizeof(dc->modules[dc->num_modules].name) / sizeof(WCHAR));
    dc->modules[dc->num_modules].base = base;
    dc->modules[dc->num_modules].size = size;
    dc->modules[dc->num_modules].timestamp = timestamp;
    dc->modules[dc->num_modules].checksum = checksum;
    dc->modules[dc->num_modules].is_elf = is_elf;
    dc->num_modules++;

    return TRUE;
}
Ejemplo n.º 18
0
ULONG_PTR EngineGetModuleBaseRemote(HANDLE hProcess, const wchar_t* szDLLName)
{
    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++)
            {
                wchar_t szModuleName[MAX_PATH] = L"";
                if(GetModuleFileNameExW(hProcess, hMods[i], szModuleName, _countof(szModuleName)))
                {
                    wchar_t* dllName = wcsrchr(szModuleName, L'\\');
                    if(dllName)
                    {
                        dllName++;
                        if(!_wcsicmp(dllName, szDLLName))
                        {
                            return (ULONG_PTR)hMods[i];
                        }
                    }
                }
            }
        }
        free(hMods);
    }
    return 0;
}
Ejemplo n.º 19
0
void DumpMemoryGui::getMemoryList()
{
	DWORD_PTR address = 0;
	MEMORY_BASIC_INFORMATION memBasic = {0};
	Memory memory;
	HMODULE * hMods = 0;
	WCHAR target[MAX_PATH];

	if (memoryList.empty())
	{
		memoryList.reserve(20);
	}
	else
	{
		memoryList.clear();
	}

	memory.filename[0] = 0;
	memory.peSection[0] = 0;
	memory.mappedFilename[0] = 0;

	while(VirtualQueryEx(ProcessAccessHelp::hProcess,(LPCVOID)address,&memBasic,sizeof(memBasic)))
	{
		memory.address = (DWORD_PTR)memBasic.BaseAddress;
		memory.type = memBasic.Type;
		memory.state = memBasic.State;
		memory.size = (DWORD)memBasic.RegionSize;
		memory.protect = memBasic.Protect;
		

		if (memory.type == MEM_MAPPED)
		{
			if (!getMappedFilename(&memory))
			{
				memory.mappedFilename[0] = 0;
			}
		}

		memoryList.push_back(memory);

		memory.mappedFilename[0] = 0;

		address += memBasic.RegionSize;
	}

	DWORD numHandles = ProcessAccessHelp::getModuleHandlesFromProcess(ProcessAccessHelp::hProcess, &hMods);
	if (numHandles == 0)
	{
		return;
	}

	for (DWORD i = 0; i < numHandles; i++)
	{
		if (GetModuleFileNameExW(ProcessAccessHelp::hProcess, hMods[i], target, _countof(target)))
		{
			setModuleName((DWORD_PTR)hMods[i],target);
			setAllSectionNames((DWORD_PTR)hMods[i],target);
		}
		else
		{
#ifdef DEBUG_COMMENTS
			Scylla::debugLog.log(L"getMemoryList :: GetModuleFileNameExW failed 0x%X", GetLastError());
#endif
		}
	}

	delete [] hMods;
}
Ejemplo n.º 20
0
void SymDownloadAllSymbols(const char* SymbolStore)
{
    // Default to Microsoft's symbol server
    if(!SymbolStore)
        SymbolStore = "http://msdl.microsoft.com/download/symbols";

    // Build the vector of modules
    std::vector<SYMBOLMODULEINFO> modList;

    if(!SymGetModuleList(&modList))
        return;

    // Skip loading if there aren't any found modules
    if(modList.size() <= 0)
        return;

    // Backup the current symbol search path
    char oldSearchPath[MAX_PATH];

    if(!SafeSymGetSearchPath(fdProcessInfo->hProcess, oldSearchPath, MAX_PATH))
    {
        dputs("SymGetSearchPath failed!");
        return;
    }

    // Use the custom server path and directory
    char customSearchPath[MAX_PATH * 2];
    sprintf_s(customSearchPath, "SRV*%s*%s", szSymbolCachePath, SymbolStore);

    if(!SafeSymSetSearchPath(fdProcessInfo->hProcess, customSearchPath))
    {
        dputs("SymSetSearchPath (1) failed!");
        return;
    }

    // Reload
    for(auto & module : modList)
    {
        dprintf("Downloading symbols for %s...\n", module.name);

        wchar_t modulePath[MAX_PATH];
        if(!GetModuleFileNameExW(fdProcessInfo->hProcess, (HMODULE)module.base, modulePath, MAX_PATH))
        {
            dprintf("GetModuleFileNameExW("fhex") failed!\n", module.base);
            continue;
        }

        if(!SafeSymUnloadModule64(fdProcessInfo->hProcess, (DWORD64)module.base))
        {
            dprintf("SymUnloadModule64("fhex") failed!\n", module.base);
            continue;
        }

        if(!SafeSymLoadModuleEx(fdProcessInfo->hProcess, 0, StringUtils::Utf16ToUtf8(modulePath).c_str(), 0, (DWORD64)module.base, 0, 0, 0))
        {
            dprintf("SymLoadModuleEx("fhex") failed!\n", module.base);
            continue;
        }
    }

    // Restore the old search path
    if(!SafeSymSetSearchPath(fdProcessInfo->hProcess, oldSearchPath))
        dputs("SymSetSearchPath (2) failed!");
}
Ejemplo n.º 21
0
/* _al_win_get_path:
 *  Returns full path to various system and user diretories
 */
ALLEGRO_PATH *_al_win_get_path(int id)
{
    char path[MAX_PATH];
    wchar_t pathw[MAX_PATH];
    ALLEGRO_USTR *pathu;
    uint32_t csidl = 0;
    HRESULT ret = 0;
    ALLEGRO_PATH *cisdl_path = NULL;

    switch (id) {
    case ALLEGRO_TEMP_PATH: {
        /* Check: TMP, TMPDIR, TEMP or TEMPDIR */

        DWORD ret = GetTempPathW(MAX_PATH, pathw);
        if (ret > MAX_PATH) {
            /* should this ever happen, windows is more broken than I ever thought */
            return NULL;
        }
        pathu = al_ustr_new_from_utf16(pathw);
        al_ustr_to_buffer(pathu, path, sizeof path);
        al_ustr_free(pathu);
        return al_create_path_for_directory(path);

    }
    break;

    case ALLEGRO_RESOURCES_PATH: { /* where the program is in */
        HANDLE process = GetCurrentProcess();
        char *ptr;

        GetModuleFileNameExW(process, NULL, pathw, MAX_PATH);
        pathu = al_ustr_new_from_utf16(pathw);
        al_ustr_to_buffer(pathu, path, sizeof path);
        al_ustr_free(pathu);
        ptr = strrchr(path, '\\');
        if (!ptr) { /* shouldn't happen */
            return NULL;
        }

        /* chop off everything including and after the last slash */
        /* should this not chop the slash? */
        *ptr = '\0';

        return al_create_path_for_directory(path);
    }
    break;

    case ALLEGRO_USER_DATA_PATH: /* CSIDL_APPDATA */
    case ALLEGRO_USER_SETTINGS_PATH:
        csidl = CSIDL_APPDATA;
        break;

    case ALLEGRO_USER_HOME_PATH: /* CSIDL_PROFILE */
        csidl = CSIDL_PROFILE;
        break;

    case ALLEGRO_USER_DOCUMENTS_PATH: /* CSIDL_PERSONAL */
        csidl = CSIDL_PERSONAL;
        break;

    case ALLEGRO_EXENAME_PATH: { /* full path to the exe including its name */
        HANDLE process = GetCurrentProcess();

        GetModuleFileNameExW(process, NULL, pathw, MAX_PATH);
        pathu = al_ustr_new_from_utf16(pathw);
        al_ustr_to_buffer(pathu, path, sizeof path);
        al_ustr_free(pathu);

        return al_create_path(path);
    }
    break;

    default:
        return NULL;
    }

    ret = SHGetFolderPathW(NULL, csidl, NULL, SHGFP_TYPE_CURRENT, pathw);
    if (ret != S_OK) {
        return NULL;
    }

    pathu = al_ustr_new_from_utf16(pathw);
    al_ustr_to_buffer(pathu, path, sizeof path);
    al_ustr_free(pathu);

    cisdl_path = al_create_path_for_directory(path);
    if (!cisdl_path)
        return NULL;

    if (csidl == CSIDL_APPDATA) {
        const char *org_name = al_get_org_name();
        const char *app_name = al_get_app_name();

        if (!app_name || !app_name[0]) {
            /* this shouldn't ever happen. */
            al_destroy_path(cisdl_path);
            return NULL;
        }

        if (org_name && org_name[0]) {
            al_append_path_component(cisdl_path, org_name);
        }

        al_append_path_component(cisdl_path, app_name);
    }

    return cisdl_path;
}
Ejemplo n.º 22
0
//
//	Adds a new pressed key information into the key store.
//
WINERROR KeyStoreAdd(
	PKEY_INFO	pKeyInfo
	)
{
	WINERROR		Status = ERROR_NOT_ENOUGH_MEMORY;
	ULONG			KeyHandle;
	PKEY_CONTEXT	Ctx;
	BOOL            bDeref = FALSE;

	KeyHandle = Crc32((PCHAR)&pKeyInfo->Client, sizeof(CLIENT_INFO));
	
	if (Ctx = GetContext(KeyHandle))
	{
		bDeref = Ctx->bDirty;		
		if (Ctx->bDirty == FALSE) // just created
		{
			// Context has just been created, initializing
			HANDLE	hProcess;

			// Resolving process path
			if (hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, pKeyInfo->Client.ProcessId))
			{
				GetModuleFileNameExW(hProcess, NULL, (LPWSTR)&Ctx->ProcessPath, MAX_PATH);
				CloseHandle(hProcess);
			}

			Ctx->bActive = TRUE;

			// Saving current date and time
			GetSystemTimeAsFileTime(&Ctx->Time);
			
			// Resolving parent window text
			GetWindowTextW(pKeyInfo->Client.ParentWindow, (LPWSTR)&Ctx->WindowText, MAX_WINDOW_TEXT);
		}	// if (Ctx->bDirty == FALSE) // just created

		Ctx->bDirty = TRUE;

		if (Ctx->bActive)
		{
			if (pKeyInfo->wChar && Ctx->Count < MAX_KEY_BUFFER_SIZE)
			{
				if (pKeyInfo->wChar == VK_BACK)
				{
					if (Ctx->Count)
						Ctx->Count -= 1;
				}
				else
				{
					Ctx->KeyBuffer[Ctx->Count] = pKeyInfo->wChar;
					Ctx->Count += 1;
					DbgPrint("KEYLOG: Adding key to a buffer: 0x%x, %C\n", pKeyInfo->wChar, pKeyInfo->wChar);
				}
				Status = NO_ERROR;
			}	// if (Ctx->Count < MAX_KEY_BUFFER_SIZE)
			else
				Status = ERROR_BUFFER_OVERFLOW;

			if ( pKeyInfo->clipboard )
			{
				PCLIPBOARD_ENTRY Entry = (PCLIPBOARD_ENTRY)AppAlloc( sizeof(CLIPBOARD_ENTRY) );
				if ( Entry )
				{
					// Saving current date and time
					GetSystemTimeAsFileTime(&Entry->Time);
					Entry->Buffer = pKeyInfo->clipboard;
					pKeyInfo->clipboard = NULL; // we'll free it later
					InsertTailList(&Ctx->ClipboardChain,&Entry->qLink);
				}
			}	// if ( pKeyInfo->clipboard )
		}	// if (Ctx->bActive)

		if ( bDeref )
			// Context has been reused, dereferencing it
			ReleaseContext(Ctx);
	}	// if (Ctx = GetContext(KeyHandle))

	return(Status);
}
Ejemplo n.º 23
0
int PatchFile(const PATCHINFO* List, int Count, const char* FileName, char* Error)
{
    //
    // This function returns an int based on the number
    // of patches applied. -1 indicates a failure.
    //
    if(Count <= 0)
    {
        // Notify the user of the error
        if(Error)
            strcpy_s(Error, MAX_ERROR_SIZE, "No patches to apply");

        return -1;
    }

    // Get a copy of the first module name in the array
    char moduleName[MAX_MODULE_SIZE];
    strcpy_s(moduleName, List[0].mod);

    // Check if all patches are in the same module
    for(int i = 0; i < Count; i++)
    {
        if(_stricmp(List[i].mod, moduleName))
        {
            if(Error)
                sprintf_s(Error, MAX_ERROR_SIZE, "Not all patches are in module %s", moduleName);

            return -1;
        }
    }

    // See if the module was loaded
    duint moduleBase = ModBaseFromName(moduleName);

    if(!moduleBase)
    {
        if(Error)
            sprintf_s(Error, MAX_ERROR_SIZE, "Failed to get base of module %s", moduleName);

        return -1;
    }

    // Get the unicode version of the module's path
    wchar_t originalName[MAX_PATH];

    if(!GetModuleFileNameExW(fdProcessInfo->hProcess, (HMODULE)moduleBase, originalName, ARRAYSIZE(originalName)))
    {
        if(Error)
            sprintf_s(Error, MAX_ERROR_SIZE, "Failed to get module path of module %s", moduleName);

        return -1;
    }

    // Create a temporary backup file
    if(!CopyFileW(originalName, StringUtils::Utf8ToUtf16(FileName).c_str(), false))
    {
        if(Error)
            strcpy_s(Error, MAX_ERROR_SIZE, "Failed to make a copy of the original file (patch target is in use?)");

        return -1;
    }

    HANDLE fileHandle;
    DWORD loadedSize;
    HANDLE fileMap;
    ULONG_PTR fileMapVa;
    if(!StaticFileLoadW(StringUtils::Utf8ToUtf16(FileName).c_str(), UE_ACCESS_ALL, false, &fileHandle, &loadedSize, &fileMap, &fileMapVa))
    {
        strcpy_s(Error, MAX_ERROR_SIZE, "StaticFileLoad failed");
        return -1;
    }

    // Begin iterating all patches, applying them to a file
    int patchCount = 0;

    for(int i = 0; i < Count; i++)
    {
        // Convert the virtual address to an offset within disk file data
        unsigned char* ptr = (unsigned char*)ConvertVAtoFileOffsetEx(fileMapVa, loadedSize, moduleBase, List[i].addr, false, true);

        // Skip patches that do not have a raw address
        if(!ptr)
            continue;

        *ptr = List[i].newbyte;
        patchCount++;
    }

    // Unload the file from memory and commit changes to disk
    if(!StaticFileUnloadW(StringUtils::Utf8ToUtf16(FileName).c_str(), true, fileHandle, loadedSize, fileMap, fileMapVa))
    {
        if(Error)
            strcpy_s(Error, MAX_ERROR_SIZE, "StaticFileUnload failed");

        return -1;
    }

    // Zero the error message and return count
    if(Error)
        memset(Error, 0, MAX_ERROR_SIZE * sizeof(char));

    return patchCount;
}
Ejemplo n.º 24
0
static gboolean get_process_cmdline(gint p_pid, gchar **p_exe, gchar **p_cmd_line)
{
#ifdef DEBUG_VERBOSE
    purple_debug_info("gfire", "trace: get_process_cmdline(%d)\n", p_pid);
#endif // DEBUG_VERBOSE

    HANDLE process;
    PVOID peb;
    PVOID rtlUserProcParamsAddress;
    UNICODE_STRING cmdline;
    WCHAR *cmdline_buff;

    *p_exe = *p_cmd_line = NULL;

    if((process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, p_pid)) == 0)
    {
        // Don't handle missing permissions as an error
        if(GetLastError() != ERROR_ACCESS_DENIED)
        {
            gchar tmpError[1024];
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, tmpError, 1024, NULL);
            purple_debug_error("gfire", "get_process_cmdline: Could not open process for reading:\n(%u) %s", (guint)GetLastError(), tmpError);
        }
#ifdef DEBUG
        else
            purple_debug_error("gfire", "get_process_cmdline: Could not open process for reading:\n Access denied\n");
#endif // DEBUG

        return FALSE;
    }

    peb = get_peb_address(process);
    if(!peb)
    {
#ifdef DEBUG
        purple_debug_error("gfire", "get_process_cmdline: bad peb address!\n");
#endif // DEBUG

        CloseHandle(process);
        return FALSE;
    }

    if(!ReadProcessMemory(process, (PCHAR)peb + 0x10, &rtlUserProcParamsAddress, sizeof(PVOID), NULL))
    {
        if(GetLastError() != ERROR_ACCESS_DENIED  && GetLastError() != ERROR_PARTIAL_COPY)
        {
            gchar tmpError[1024];
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, tmpError, 1024, NULL);
            purple_debug_error("gfire", "get_process_cmdline: Could not read the address of ProcessParameters:\n(%u) %s", (guint)GetLastError(), tmpError);
        }
#ifdef DEBUG
        else
            purple_debug_error("gfire", "get_process_cmdline: Could not read the address of ProcessParameters:\n Access denied/Partial Read\n");
#endif // DEBUG

        CloseHandle(process);
        return FALSE;
    }

    if(!ReadProcessMemory(process, (PCHAR)rtlUserProcParamsAddress + 0x40, &cmdline, sizeof(cmdline), NULL))
    {
        if(GetLastError() != ERROR_ACCESS_DENIED  && GetLastError() != ERROR_PARTIAL_COPY)
        {
            gchar tmpError[1024];
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, tmpError, 1024, NULL);
            purple_debug_error("gfire", "get_process_cmdline: Could not read CommandLine:\n(%u) %s", (guint)GetLastError(), tmpError);
        }
#ifdef DEBUG
        else
            purple_debug_error("gfire", "get_process_cmdline: Could not read CommandLine:\n Access denied/Partial Read\n");
#endif // DEBUG

        CloseHandle(process);
        return FALSE;
    }

    cmdline_buff = (WCHAR*)g_malloc0(cmdline.Length);
    if(!ReadProcessMemory(process, cmdline.Buffer, cmdline_buff, cmdline.Length, NULL))
    {
        if(GetLastError() != ERROR_ACCESS_DENIED && GetLastError() != ERROR_PARTIAL_COPY)
        {
            gchar tmpError[1024];
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, tmpError, 1024, NULL);
            purple_debug_error("gfire", "get_process_cmdline: Could not read the command line string:\n(%u) %s", (guint)GetLastError(), tmpError);
        }
#ifdef DEBUG
        else
            purple_debug_error("gfire", "get_process_cmdline: Could not read the command line string:\n Access denied/Partial Read\n");
#endif // DEBUG

        g_free(cmdline_buff);
        CloseHandle(process);
        return FALSE;
    }

    *p_cmd_line = g_utf16_to_utf8((gunichar2*)cmdline_buff, cmdline.Length / 2, NULL, NULL, NULL);
    g_free(cmdline_buff);

#ifdef DEBUG
    if(!*p_cmd_line)
        purple_debug_error("gfire", "get_process_cmdline: g_utf16_to_utf8 failed on cmdline\n");
#endif // DEBUG

    // Get process executable
    cmdline_buff = (WCHAR*)g_malloc(2048);
    DWORD len = GetModuleFileNameExW(process, NULL, cmdline_buff, 1024);
    if(len == 0)
    {
        if(GetLastError() != ERROR_ACCESS_DENIED)
        {
            gchar tmpError[1024];
            FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), 0, tmpError, 1024, NULL);
            purple_debug_error("gfire", "get_process_cmdline: Could not read the executable filename string:\n(%u) %s", (guint)GetLastError(), tmpError);
        }
#ifdef DEBUG
        else
            purple_debug_error("gfire", "get_process_cmdline: Could not read the executable filename string:\n Access denied\n");
#endif // DEBUG

        g_free(cmdline_buff);
        g_free(*p_cmd_line);
        *p_cmd_line = NULL;
        CloseHandle(process);
        return FALSE;
    }

    *p_exe = g_utf16_to_utf8((gunichar2*)cmdline_buff, len, NULL, NULL, NULL);
    g_free(cmdline_buff);

#ifdef DEBUG
    if(!*p_exe)
        purple_debug_error("gfire", "get_process_cmdline: g_utf16_to_utf8 failed on exe\n");
#endif // DEBUG

    CloseHandle(process);

    return (*p_exe && *p_cmd_line);
}
Ejemplo n.º 25
0
Archivo: run.c Proyecto: Dimillian/wine
static HRESULT WINAPI Dispatch_Invoke(IDispatch *iface, DISPID dispIdMember, REFIID riid, LCID lcid,
				      WORD wFlags, DISPPARAMS *pdp, VARIANT *pVarResult, EXCEPINFO *pExcepInfo, UINT *puArgErr)
{
    switch(dispIdMember) {
    case DISPID_TESTOBJ_OK: {
        VARIANT *expr, *msg;

        ok(wFlags == INVOKE_FUNC, "wFlags = %x\n", wFlags);
        ok(pdp->cArgs == 2, "cArgs = %d\n", pdp->cArgs);
        ok(!pdp->cNamedArgs, "cNamedArgs = %d\n", pdp->cNamedArgs);

        expr = pdp->rgvarg+1;
        if(V_VT(expr) == (VT_VARIANT|VT_BYREF))
            expr = V_VARIANTREF(expr);

        msg = pdp->rgvarg;
        if(V_VT(msg) == (VT_VARIANT|VT_BYREF))
            msg = V_VARIANTREF(msg);

        ok(V_VT(msg) == VT_BSTR, "V_VT(psp->rgvargs) = %d\n", V_VT(msg));
        ok(V_VT(expr) == VT_BOOL, "V_VT(psp->rgvargs+1) = %d\n", V_VT(expr));
        ok(V_BOOL(expr), "%s: %s\n", script_name, wine_dbgstr_w(V_BSTR(msg)));
        if(pVarResult)
            V_VT(pVarResult) = VT_EMPTY;
        break;
    }
    case DISPID_TESTOBJ_TRACE:
        ok(wFlags == INVOKE_FUNC, "wFlags = %x\n", wFlags);
        ok(pdp->cArgs == 1, "cArgs = %d\n", pdp->cArgs);
        ok(!pdp->cNamedArgs, "cNamedArgs = %d\n", pdp->cNamedArgs);
        ok(V_VT(pdp->rgvarg) == VT_BSTR, "V_VT(psp->rgvargs) = %d\n", V_VT(pdp->rgvarg));
        trace("%s: %s\n", script_name, wine_dbgstr_w(V_BSTR(pdp->rgvarg)));
        if(pVarResult)
            V_VT(pVarResult) = VT_EMPTY;
        break;
    case DISPID_TESTOBJ_REPORTSUCCESS:
        CHECK_EXPECT(reportSuccess);

        ok(wFlags == INVOKE_FUNC, "wFlags = %x\n", wFlags);
        ok(pdp->cArgs == 0, "cArgs = %d\n", pdp->cArgs);
        ok(!pdp->cNamedArgs, "cNamedArgs = %d\n", pdp->cNamedArgs);
        if(pVarResult)
            V_VT(pVarResult) = VT_EMPTY;
        break;
    case DISPID_TESTOBJ_WSCRIPTFULLNAME:
    {
        WCHAR fullName[MAX_PATH];
        DWORD res;

        ok(wFlags == INVOKE_PROPERTYGET, "wFlags = %x\n", wFlags);
        ok(pdp->cArgs == 0, "cArgs = %d\n", pdp->cArgs);
        ok(!pdp->cNamedArgs, "cNamedArgs = %d\n", pdp->cNamedArgs);
        V_VT(pVarResult) = VT_BSTR;
        res = GetModuleFileNameExW(wscript_process, NULL, fullName, sizeof(fullName)/sizeof(WCHAR));
        if(res == 0)
            return E_FAIL;
        if(!(V_BSTR(pVarResult) = SysAllocString(fullName)))
            return E_OUTOFMEMORY;
        break;
    }
    case DISPID_TESTOBJ_WSCRIPTPATH:
    {
        WCHAR fullPath[MAX_PATH];
        DWORD res;
        const WCHAR *pos;

        ok(wFlags == INVOKE_PROPERTYGET, "wFlags = %x\n", wFlags);
        ok(pdp->cArgs == 0, "cArgs = %d\n", pdp->cArgs);
        ok(!pdp->cNamedArgs, "cNamedArgs = %d\n", pdp->cNamedArgs);
        V_VT(pVarResult) = VT_BSTR;
        res = GetModuleFileNameExW(wscript_process, NULL, fullPath, sizeof(fullPath)/sizeof(WCHAR));
        if(res == 0)
            return E_FAIL;
        pos = mystrrchr(fullPath, '\\');
        if(!(V_BSTR(pVarResult) = SysAllocStringLen(fullPath, pos-fullPath)))
            return E_OUTOFMEMORY;
        break;
    }
    case DISPID_TESTOBJ_WSCRIPTSCRIPTNAME:
    {
        char fullPath[MAX_PATH];
        char *pos;
        long res;

        ok(wFlags == INVOKE_PROPERTYGET, "wFlags = %x\n", wFlags);
        ok(pdp->cArgs == 0, "cArgs = %d\n", pdp->cArgs);
        ok(!pdp->cNamedArgs, "cNamedArgs = %d\n", pdp->cNamedArgs);
        V_VT(pVarResult) = VT_BSTR;
        res = GetFullPathNameA(script_name, sizeof(fullPath)/sizeof(WCHAR), fullPath, &pos);
        if(!res || res > sizeof(fullPath)/sizeof(WCHAR))
            return E_FAIL;
        if(!(V_BSTR(pVarResult) = SysAllocString(a2bstr(pos))))
            return E_OUTOFMEMORY;
        break;
    }
    case DISPID_TESTOBJ_WSCRIPTSCRIPTFULLNAME:
    {
        char fullPath[MAX_PATH];
        long res;

        ok(wFlags == INVOKE_PROPERTYGET, "wFlags = %x\n", wFlags);
        ok(pdp->cArgs == 0, "cArgs = %d\n", pdp->cArgs);
        ok(!pdp->cNamedArgs, "cNamedArgs = %d\n", pdp->cNamedArgs);
        V_VT(pVarResult) = VT_BSTR;
        res = GetFullPathNameA(script_name, sizeof(fullPath)/sizeof(WCHAR), fullPath, NULL);
        if(!res || res > sizeof(fullPath)/sizeof(WCHAR))
            return E_FAIL;
        if(!(V_BSTR(pVarResult) = SysAllocString(a2bstr(fullPath))))
            return E_OUTOFMEMORY;
        break;
    }
    default:
        ok(0, "unexpected dispIdMember %d\n", dispIdMember);
        return E_NOTIMPL;
    }

    return S_OK;
}
Ejemplo n.º 26
0
QList<DWORD> * getDxProcessesIDs(QList<DWORD> * processes, LPCWSTR wstrSystemRootPath) {

    DWORD aProcesses[1024];
    HMODULE hMods[1024];
    DWORD cbNeeded;
    DWORD cProcesses;
    char debug_buf[255];
    WCHAR executableName[MAX_PATH];
    unsigned int i;

    //     Get the list of process identifiers.
    processes->clear();

    if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
        return NULL;

    // Calculate how many process identifiers were returned.

    cProcesses = cbNeeded / sizeof(DWORD);

    // Print the names of the modules for each process.

    for ( i = 0; i < cProcesses; i++ )
    {
        if (aProcesses[i] != GetCurrentProcessId()) {
            HANDLE hProcess;
            hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
                                    PROCESS_VM_READ,
                                    FALSE, aProcesses[i] );
            if (NULL == hProcess)
                goto nextProcess;

            GetModuleFileNameExW(hProcess, 0, executableName, sizeof (executableName));

            if (wcsstr(executableName, wstrSystemRootPath) != NULL) {
                goto nextProcess;
            }

            PathStripPathW(executableName);

            ::WideCharToMultiByte(CP_ACP, 0, executableName, -1, debug_buf, 255, NULL, NULL);
            DEBUG_MID_LEVEL << Q_FUNC_INFO << debug_buf;

            for (unsigned k=0; k < SIZEOF_ARRAY(pwstrExcludeProcesses); k++) {
                if (wcsicmp(executableName, pwstrExcludeProcesses[k])== 0) {
                    DEBUG_MID_LEVEL << Q_FUNC_INFO << "skipping " << pwstrExcludeProcesses;
                    goto nextProcess;
                }
            }

            // Get a list of all the modules in this process.

            if( EnumProcessModules(hProcess, hMods, sizeof(hMods), &cbNeeded))
            {
                bool isDXPresent = false;
                for ( DWORD j = 0; j < (cbNeeded / sizeof(HMODULE)); j++ )
                {
                    WCHAR szModName[MAX_PATH];

                    if ( GetModuleFileNameExW( hProcess, hMods[j], szModName,
                                              sizeof(szModName) / sizeof(WCHAR)))
                    {

                        PathStripPathW(szModName);
                        ::WideCharToMultiByte(CP_ACP, 0, szModName, -1, debug_buf, 255, NULL, NULL);
                        DEBUG_HIGH_LEVEL << Q_FUNC_INFO << debug_buf;

                        if(wcsicmp(szModName, lightpackHooksDllName) == 0) {
                            goto nextProcess;
                        } else {
                            if (wcsicmp(szModName, L"d3d9.dll") == 0 ||
                                wcsicmp(szModName, L"dxgi.dll") == 0 )
                                isDXPresent = true;
                        }
                    }
                }
                if (isDXPresent)
                    processes->append(aProcesses[i]);

            }
nextProcess:
            // Release the handle to the process.
            CloseHandle( hProcess );
        }
    }

    return processes;
}
Ejemplo n.º 27
0
bool UpdateMemoryMap(void)
{
	MemMap.clear();
	MemMapCode.clear();
	MemMapData.clear();
	MemMapModule.clear();
	Exports.clear();
	CustomNames.clear();

	if (g_hProcess == NULL)
	{
		#ifdef _DEBUG
		PrintOut(_T("[UpdateMemoryMap]: Process handle NULL!"));
		#endif
		return 0;
	}

	if (!IsProcHandleValid(g_hProcess))
	{
		g_hProcess = NULL;
		#ifdef _DEBUG
		PrintOut(_T("[UpdateMemoryMap]: Process handle invalid!"));
		#endif
		return 0;
	}

	SYSTEM_INFO SysInfo;
	GetSystemInfo(&SysInfo);

	MEMORY_BASIC_INFORMATION MemInfo;
	size_t pMemory = (size_t)SysInfo.lpMinimumApplicationAddress;
	while (pMemory < (size_t)SysInfo.lpMaximumApplicationAddress)
	{
		if (VirtualQueryEx(g_hProcess, (LPCVOID)pMemory, &MemInfo, sizeof(MEMORY_BASIC_INFORMATION)) != 0)
		{
			if (MemInfo.State == MEM_COMMIT /*&& MemInfo.Type == MEM_PRIVATE*/)
			{
				MemMapInfo Mem;
				Mem.Start = (size_t)pMemory;
				Mem.End = (size_t)pMemory + MemInfo.RegionSize - 1;
				MemMap.push_back(Mem);
			}
			pMemory = (ULONG_PTR)MemInfo.BaseAddress + MemInfo.RegionSize;
		}
		else
		{
			pMemory += 1024;
		}
	}

	static HMODULE hNtDll = (HMODULE)Utils::GetLocalModuleHandle("ntdll.dll");
	static tNtQueryInformationProcess NtQueryInformationProcess = (tNtQueryInformationProcess)Utils::GetProcAddress(hNtDll, "NtQueryInformationProcess");

	PPROCESS_BASIC_INFORMATION ProcessInfo = NULL;
	PEB Peb;
	PEB_LDR_DATA LdrData;

	// Try to allocate buffer 
	HANDLE hHeap = GetProcessHeap();
	DWORD dwSize = sizeof(PROCESS_BASIC_INFORMATION);
	ProcessInfo = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS, dwSize);

	ULONG dwSizeNeeded = 0;
	NTSTATUS status = NtQueryInformationProcess(g_hProcess, ProcessBasicInformation, ProcessInfo, dwSize, &dwSizeNeeded);
	if (status >= 0 && dwSize < dwSizeNeeded)
	{
		if (ProcessInfo)
			HeapFree(hHeap, 0, ProcessInfo);

		ProcessInfo = (PPROCESS_BASIC_INFORMATION)HeapAlloc(hHeap, HEAP_ZERO_MEMORY | HEAP_GENERATE_EXCEPTIONS, dwSizeNeeded);
		if (!ProcessInfo)
		{
			#ifdef _DEBUG
			PrintOut(_T("[UpdateMemoryMap]: Couldn't allocate heap buffer!"));
			#endif
			return 0;
		}

		status = NtQueryInformationProcess(g_hProcess, ProcessBasicInformation, ProcessInfo, dwSizeNeeded, &dwSizeNeeded);
	}

	// Did we successfully get basic info on process
	if (NT_SUCCESS(status))
	{	
		// Check for PEB
		if (!ProcessInfo->PebBaseAddress)
		{
			#ifdef _DEBUG
			PrintOut(_T("[UpdateMemoryMap]: PEB is null! Aborting UpdateExports!"));
			#endif
			if (ProcessInfo)
				HeapFree(hHeap, 0, ProcessInfo);
			return 0;
		}

		// Read Process Environment Block (PEB)
		SIZE_T dwBytesRead = 0;
		if ( ReadMemory(  ProcessInfo->PebBaseAddress, &Peb, sizeof(PEB), &dwBytesRead) == 0)
		{
			#ifdef _DEBUG
			PrintOut(_T("[UpdateMemoryMap]: Failed to read PEB! Aborting UpdateExports!"));
			#endif
			if (ProcessInfo)
				HeapFree(hHeap, 0, ProcessInfo);
			return 0;
		}

		// Get Ldr
		dwBytesRead = 0;
		if ( ReadMemory( Peb.Ldr, &LdrData, sizeof(LdrData), &dwBytesRead) == 0)
		{
			#ifdef _DEBUG
			PrintOut(_T("[UpdateMemoryMap]: Failed to read PEB Ldr Data! Aborting UpdateExports!"));
			#endif
			if (ProcessInfo)
				HeapFree(hHeap, 0, ProcessInfo);
			return 0;
		}

		LIST_ENTRY *pLdrListHead = (LIST_ENTRY *)LdrData.InLoadOrderModuleList.Flink;
		LIST_ENTRY *pLdrCurrentNode = LdrData.InLoadOrderModuleList.Flink;
		do
		{
			LDR_DATA_TABLE_ENTRY lstEntry = { 0 };
			dwBytesRead = 0;
			if (! ReadMemory( (void*)pLdrCurrentNode, &lstEntry, sizeof(LDR_DATA_TABLE_ENTRY), &dwBytesRead))
			{
				#ifdef _DEBUG
				PrintOut(_T("[UpdateMemoryMap]: Could not read list entry from LDR list. Error = %s"), Utils::GetLastErrorString().GetString());
				#endif
				if (ProcessInfo)
					HeapFree(hHeap, 0, ProcessInfo);
				return 0;
			}

			pLdrCurrentNode = lstEntry.InLoadOrderLinks.Flink;

			if (lstEntry.DllBase != NULL /*&& lstEntry.SizeOfImage != 0*/)
			{
				unsigned char* ModuleBase = (unsigned char*)lstEntry.DllBase;
				DWORD ModuleSize = lstEntry.SizeOfImage;
				wchar_t wcsFullDllName[MAX_PATH] = { 0 };
				wchar_t* wcsModule = 0;
				if (lstEntry.FullDllName.Length > 0)
				{
					dwBytesRead = 0;
					if ( ReadMemory( (LPVOID)lstEntry.FullDllName.Buffer, &wcsFullDllName, lstEntry.FullDllName.Length, &dwBytesRead))
					{
						wcsModule = wcsrchr(wcsFullDllName, L'\\');
						if (!wcsModule)
							wcsModule = wcsrchr(wcsFullDllName, L'/');
						wcsModule++;

						if (g_AttachedProcessAddress == NULL)
						{
							wchar_t filename[MAX_PATH];
							GetModuleFileNameExW(g_hProcess, NULL, filename, MAX_PATH);
							if (_wcsicmp(filename, wcsFullDllName) == 0)
							{
								g_AttachedProcessAddress = (size_t)ModuleBase;
								g_AttachedProcessSize = ModuleSize;
							}
						}
					} 
				}

				// module info
				MemMapInfo Mem;
				Mem.Start = (size_t)ModuleBase;
				Mem.End = Mem.Start + ModuleSize;
				Mem.Size = ModuleSize;
				Mem.Name = wcsModule;
				Mem.Path = wcsFullDllName;

				//PrintOut(_T("%s: %IX"), Mem.Name.GetBuffer(), Mem.Start);

				MemMapModule.push_back(Mem);

				// module code
				IMAGE_DOS_HEADER DosHdr;
				IMAGE_NT_HEADERS NtHdr;

				ReadMemory( ModuleBase, &DosHdr, sizeof(IMAGE_DOS_HEADER), NULL);
				ReadMemory( ModuleBase + DosHdr.e_lfanew, &NtHdr, sizeof(IMAGE_NT_HEADERS), NULL);
				DWORD sectionsSize = (DWORD)NtHdr.FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
				PIMAGE_SECTION_HEADER sections = (PIMAGE_SECTION_HEADER)malloc(sectionsSize);
				ReadMemory( ModuleBase + DosHdr.e_lfanew + sizeof(IMAGE_NT_HEADERS), sections, sectionsSize, NULL);
				for (int i = 0; i < NtHdr.FileHeader.NumberOfSections; i++)
				{
					CString txt;
					MemMapInfo Mem;
					txt.Format(_T("%.8s"), sections[i].Name); txt.MakeLower();
					if (txt == ".text" || txt == "code")
					{
						Mem.Start = (size_t)ModuleBase + sections[i].VirtualAddress;
						Mem.End = Mem.Start + sections[i].Misc.VirtualSize;
						Mem.Name = wcsModule;
						MemMapCode.push_back(Mem);
					}
					if (txt == ".data" || txt == "data" || txt == ".rdata" || txt == ".idata")
					{
						Mem.Start = (size_t)ModuleBase + sections[i].VirtualAddress;
						Mem.End = Mem.Start + sections[i].Misc.VirtualSize;
						Mem.Name = wcsModule;
						MemMapData.push_back(Mem);
					}
				}
				delete sections;
			}

		} while (pLdrListHead != pLdrCurrentNode);
	}
	else
	{
		#ifdef _DEBUG
		PrintOut(_T("[UpdateExports]: NtQueryInformationProcess failed! Aborting..."));
		#endif
		if (ProcessInfo)
			HeapFree(hHeap, 0, ProcessInfo);
		return 0;
	}

	if (ProcessInfo)
		HeapFree(hHeap, 0, ProcessInfo);

	for (UINT i = 0; i < MemMap.size(); i++)
	{
		if (IsModule(MemMap[i].Start)) 
			MemMap[i].Name = GetModuleName(MemMap[i].Start);
	}

	return 1;
}
Ejemplo n.º 28
0
DWORD EngineGetAPIOrdinalRemote(HANDLE hProcess, ULONG_PTR APIAddress)
{
    if(!hProcess) //no process specified
    {
        if(!dbgProcessInformation.hProcess)
            hProcess = GetCurrentProcess();
        else
            hProcess = dbgProcessInformation.hProcess;
    }
    HANDLE FileHandle;
    DWORD FileSize;
    HANDLE FileMap;
    ULONG_PTR FileMapVA;
    ULONG_PTR ModuleBase = EngineGetModuleBaseRemote(hProcess, APIAddress);
    if(!ModuleBase)
        return 0;
    wchar_t szModulePath[MAX_PATH] = L"";
    if(!GetModuleFileNameExW(hProcess, (HMODULE)ModuleBase, szModulePath, _countof(szModulePath)))
        return 0;
    if(MapFileExW(szModulePath, UE_ACCESS_READ, &FileHandle, &FileSize, &FileMap, &FileMapVA, 0))
    {
        PIMAGE_DOS_HEADER DOSHeader = (PIMAGE_DOS_HEADER)FileMapVA;
        if(EngineValidateHeader(FileMapVA, NULL, NULL, DOSHeader, true))
        {
            PIMAGE_NT_HEADERS32 PEHeader32 = (PIMAGE_NT_HEADERS32)((ULONG_PTR)DOSHeader + DOSHeader->e_lfanew);
            PIMAGE_NT_HEADERS64 PEHeader64 = (PIMAGE_NT_HEADERS64)((ULONG_PTR)DOSHeader + DOSHeader->e_lfanew);
            ULONG_PTR ExportDirectoryVA;
            DWORD ExportDirectorySize;
            ULONG_PTR ImageBase;
            if(PEHeader32->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
            {
                ImageBase = PEHeader32->OptionalHeader.ImageBase;
                ExportDirectoryVA = (ULONG_PTR)PEHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
                ExportDirectorySize = (ULONG_PTR)PEHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
            }
            else //x64
            {
                ImageBase = (ULONG_PTR)PEHeader64->OptionalHeader.ImageBase;
                ExportDirectoryVA = (ULONG_PTR)PEHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
                ExportDirectorySize = (ULONG_PTR)PEHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
            }
            PIMAGE_EXPORT_DIRECTORY ExportDirectory = (PIMAGE_EXPORT_DIRECTORY)ConvertVAtoFileOffset(FileMapVA, ExportDirectoryVA + ImageBase, true);
            if(ExportDirectory)
            {
                DWORD* AddrOfFunctions = (DWORD*)ConvertVAtoFileOffset(FileMapVA, ExportDirectory->AddressOfFunctions + ImageBase, true);
                if(AddrOfFunctions)
                {
                    unsigned int NumberOfFunctions = ExportDirectory->NumberOfFunctions;
                    for(unsigned int i = 0, j = 0; i < NumberOfFunctions; i++)
                    {
                        unsigned int curRva = AddrOfFunctions[i];
                        if(!curRva)
                            continue;
                        j++; //ordinal
                        if(curRva < ExportDirectoryVA || curRva >= ExportDirectoryVA + ExportDirectorySize) //non-forwarded exports
                        {
                            if(curRva + ModuleBase == APIAddress)
                            {
                                UnMapFileEx(FileHandle, FileSize, FileMap, FileMapVA);
                                return j;
                            }
                        }
                    }
                }
            }
        }
        UnMapFileEx(FileHandle, FileSize, FileMap, FileMapVA);
    }
    return 0;
}
Ejemplo n.º 29
0
//////////////////////////////////////////////////////////
//
// CheckAntiVirusStatus
//
// Maybe warn user if no anti-virus running
//
//////////////////////////////////////////////////////////
void CheckAntiVirusStatus( void )
{
    // Get data from WMI
    std::vector < SString > enabledList;
    std::vector < SString > disabledList;
    GetWMIAntiVirusStatus( enabledList, disabledList );

    // Get status from WSC
    WSC_SECURITY_PROVIDER_HEALTH health = (WSC_SECURITY_PROVIDER_HEALTH)-1;
    if ( _WscGetSecurityProviderHealth )
    {
        _WscGetSecurityProviderHealth( WSC_SECURITY_PROVIDER_ANTIVIRUS, &health );
    }

    // Dump results
    SString strStatus( "AV health: %s (%d)", *EnumToString( health ), health );
    for ( uint i = 0 ; i < enabledList.size() ; i++ )
        strStatus += SString( " [Ena%d:%s]", i, *enabledList[i] );
    for ( uint i = 0 ; i < disabledList.size() ; i++ )
        strStatus += SString( " [Dis%d:%s]", i, *disabledList[i] );
    WriteDebugEvent( strStatus ); 

    // Maybe show dialog if av not found
    if ( enabledList.empty() && health != WSC_SECURITY_PROVIDER_HEALTH_GOOD )
    {
        bool bEnableScaremongering = ( health != WSC_SECURITY_PROVIDER_HEALTH_NOTMONITORED );

        if ( bEnableScaremongering )
        {
            const char* avProducts[] = { "antivirus", "anti-virus", "Avast", "AVG", "Avira", 
                                         "NOD32", "ESET", "F-Secure", "Faronics", "Kaspersky",
                                         "McAfee", "Norton", "Symantec", "Panda", "Trend Micro", };

            // Check for anti-virus helper dlls before actual scaremongering
            HMODULE aModules[1024];
            DWORD cbNeeded;
            if ( EnumProcessModules( GetCurrentProcess(), aModules, sizeof(aModules), &cbNeeded) )
            {
                DWORD cModules = cbNeeded / sizeof(HMODULE);
                for ( uint i = 0 ; i < cModules ; i++ )
                {
                    if( aModules[i] != 0 )
                    {
                        WCHAR szModulePathFileName[1024] = L"";
                        GetModuleFileNameExW ( GetCurrentProcess(), aModules[i], szModulePathFileName, NUMELMS(szModulePathFileName) );
                        SLibVersionInfo libVersionInfo;
                        GetLibVersionInfo ( ToUTF8( szModulePathFileName ), &libVersionInfo );

                        for( uint i = 0 ; i < NUMELMS( avProducts ) ; i++ )
                        {
                            if ( libVersionInfo.strCompanyName.ContainsI( avProducts[i] )
                                 || libVersionInfo.strProductName.ContainsI( avProducts[i] ) )
                            {
                                bEnableScaremongering = false;
                                WriteDebugEvent( SString( "AV (module) maybe found %s [%d](%s,%s)", *WStringX( szModulePathFileName ).ToAnsi(), i, *libVersionInfo.strCompanyName, *libVersionInfo.strProductName ) );
                            }
                        }
                    }
                }

                if ( bEnableScaremongering )
                    WriteDebugEvent( SString( "AV Searched %d dlls, but could not find av helper", cModules ) );
            }

            if ( bEnableScaremongering )
            {
                std::vector < DWORD > processIdList = MyEnumProcesses();
                for ( uint i = 0; i < processIdList.size (); i++ )
                {
                    DWORD processId = processIdList[i];
                    // Skip 64 bit processes to avoid errors
                    if ( !Is32bitProcess ( processId ) )
                        continue;

                    std::vector < SString > filenameList = GetPossibleProcessPathFilenames ( processId );
                    for ( uint i = 0; i < filenameList.size (); i++ )
                    {
                        const SString& strProcessPathFileName = filenameList[i];
                        SLibVersionInfo libVersionInfo;
                        if ( GetLibVersionInfo ( strProcessPathFileName, &libVersionInfo ) )
                        {
                            for( uint i = 0 ; i < NUMELMS( avProducts ) ; i++ )
                            {
                                if ( libVersionInfo.strCompanyName.ContainsI( avProducts[i] )
                                     || libVersionInfo.strProductName.ContainsI( avProducts[i] ) )
                                {
                                    bEnableScaremongering = false;
                                    WriteDebugEvent( SString( "AV (process) maybe found %s [%d](%s,%s)", *strProcessPathFileName, i, *libVersionInfo.strCompanyName, *libVersionInfo.strProductName ) );
                                }
                            }
                        }
                    }
                }
                if ( bEnableScaremongering )
                    WriteDebugEvent( SString( "AV Searched %d processes, but could not find av helper", processIdList.size() ) );
            }
        }

        ShowNoAvDialog( g_hInstance, bEnableScaremongering );
        HideNoAvDialog ();
    }
}
Ejemplo n.º 30
0
//-------------------------------------------------------------------------------------------------
EXPORT DWORD WINAPI GetModuleFileNameExWStub(HANDLE hProcess, HMODULE hModule, LPWSTR lpFilename, DWORD nSize)
{
    return GetModuleFileNameExW(hProcess, hModule, lpFilename, nSize);
}