我们有很多操作需要用到OpenProcess函数,而为了使程序有权限使用这个函数,我们经常利用AdjustTokenPrivileges提升权限(准确的说不是提升,而是将访问令牌中禁用的权限启用),
BOOL SetPrivilege(
HANDLE hToken, // access token handle
LPCTSTR lpszPrivilege, // name of privilege to enable/disable
BOOL bEnablePrivilege // to enable or disable privilege
)
{
TOKEN_PRIVILEGES tp;
LUID luid;
if ( !LookupPrivilegeValue(
NULL, // lookup privilege on local system
lpszPrivilege, // privilege to lookup
&luid ) ) // receives LUID of privilege
{
printf("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) )
{
printf("AdjustTokenPrivileges error: %u\n", GetLastError() );
return FALSE;
}
if (GetLastError() == ERROR_NOT_ALL_ASSIGNED)
{
printf("The token does not have the specified privilege. \n");
return FALSE;
}
return TRUE;
}
void main( )
{
HANDLE hToken;
BOOL bRet = OpenProcessToken(GetCurrentProcess(),TOKEN_ALL_ACCESS,&hToken);
SetPrivilege(hToken,SE_DEBUG_NAME,TRUE);
}
这段代码在xp上没有问题,但如果在windows 7 或者vista上,如果程序以标准用户启动,AdjustTokenPrivileges将会调用失败,以管理员省份启动没有问题。
这是因为在Windows 7上,标准用户权限很少,没有Debug权限,更无从谈起启用Debug权限,用户可以以管理员和标准用户两种方式启用控制台,输入命令whoami /ALL
来查看两种权限下权限的不同
PS:即使提升调试权限,也不意味着对其它进程调用OpenProcess会成功(例如win7系统下的system和audiodg进程)