我们会遇到OpenProcess函数失败的情况,通过GetLastError函数发现其错误代码为5,VS查看之后发现拒绝访问:
这是因为用OpenProcess打开一些普通进程是可以的,但是要打开的是系统安全进程(如System、Winlogon、smss、csrss、services、lsass等)或是一些注册为服务的进程时,就会遇到拒绝访问的情况。此时我们该如何解决这个问题呢?
解决这个问题只需要当前进程具有SeDebugPrivilege权限就可以了。打开权限相关的函数有:
- OpenProcessToken
- LookupPrivilegeValue
- AdjustTokenPrivileges
附上提权代码(参考开源项目TitanEngine):
BOOL KtSetDebugPrivilege(HANDLE ProcessHandle, BOOL IsEnable)
{
DWORD LastError = 0;
HANDLE TokenHandle = 0;
if (!OpenProcessToken(ProcessHandle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &TokenHandle))
{
LastError = GetLastError();
if (TokenHandle)
{
CloseHandle(TokenHandle);
}
return LastError;
}
TOKEN_PRIVILEGES TokenPrivileges;
memset(&TokenPrivileges, 0, sizeof(TOKEN_PRIVILEGES));
LUID v1;//权限类型,本地独有标识
if (!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &v1))
{
LastError = GetLastError();
CloseHandle(TokenHandle);
return LastError;
}
TokenPrivileges.PrivilegeCount = 1;
TokenPrivileges.Privileges[0].Luid = v1;
if (IsEnable)
{
TokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
}
else
{
TokenPrivileges.Privileges[0].Attributes = 0;
}
AdjustTokenPrivileges(TokenHandle, FALSE, &TokenPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL);
LastError = GetLastError();
CloseHandle(TokenHandle);
return LastError;
}
“Some of the most devastating things that happen to you will teach you the most.”