还是Ring3下的老代码,使用DuplicateHandle()获得文件句柄,复制到其他进程当中,在删除被保护文件时,会提示无法删除,在保护进程中打开。
Win XP下可以打开system进程,而这个进程PID是固定的数值4;但是Win 7下却无法打开system进程,提权后也无法打开,所以这里将句柄复制到winlogon.exe进行保护。
#include <windows.h>
#include <Psapi.h>
#include <stdio.h>
#pragma comment(lib,"Psapi.lib")
#pragma comment(lib, "Advapi32.lib")
VOID EnablePriv()
{
HANDLE hToken;
if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, &hToken))
{
TOKEN_PRIVILEGES tkp;
LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &tkp.Privileges[0].Luid);
tkp.PrivilegeCount = 1;
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
AdjustTokenPrivileges(hToken, FALSE, &tkp, sizeof(tkp), NULL, NULL);
printf("EnablePriv Ok\n");
return ;
}
printf("EnablePriv Error\n");
}
DWORD GetProcessIdByName(CHAR *ProcessName)
{
DWORD ProcessArray[1024], ArraySize, ReturnSize;
HANDLE hProcess;
HMODULE hModule;
CHAR NormalName[MAX_PATH] = {"UnknownProcess"};
if(!EnumProcesses(ProcessArray, sizeof(ProcessArray), &ArraySize))
{
return -1;
}
ReturnSize = ArraySize/sizeof(DWORD);
for(unsigned int i=0; i<ReturnSize; i++)
{
hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, ProcessArray[i]);
if(hProcess)
{
if(EnumProcessModules(hProcess, &hModule, sizeof(hModule), &ArraySize))
{
GetModuleBaseName(hProcess, hModule, NormalName, sizeof(NormalName));
if(!strcmp(NormalName, ProcessName))
{
CloseHandle(hProcess);
return ProcessArray[i];
}
}
}
}
CloseHandle(hProcess);
return 0;
}
BOOL OccupyFile(CHAR * FileName, CHAR *ProcessName)
{
BOOL bRet;
EnablePriv();
HANDLE hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, 4);
if (hProcess == NULL)
{
printf("OpenProcess PID=4 Error\n");
hProcess = OpenProcess(PROCESS_DUP_HANDLE, FALSE, GetProcessIdByName(ProcessName));
if (hProcess == NULL)
{
printf("OpenProcess PID=ProcessName Error\n");
return FALSE;
}
}
HANDLE hFile;
HANDLE hTargetHandle;
hFile = CreateFile(FileName, GENERIC_READ, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("CreateFile Error\n");
CloseHandle(hProcess);
return FALSE;
}
bRet = DuplicateHandle(GetCurrentProcess(), hFile, hProcess, &hTargetHandle,
0, FALSE, DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
CloseHandle( hProcess );
return bRet;
}
int main()
{
OccupyFile("c:\\t.txt", "winlogon.exe");
return 0;
}