原文鏈接地址:http://blog.csdn.net/xbgprogrammer/article/details/7276760
我們有很多操作需要用到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進程)
關於TOKEN_PRIVILEGES結構
typedef struct _TOKEN_PRIVILEGES { DWORD PrivilegeCount; LUID_AND_ATTRIBUTES Privileges[ANYSIZE_ARRAY]; } TOKEN_PRIVILEGES, *PTOKEN_PRIVILEGES;