检测当前程序权限和用户类型的说明

首先先向大家介绍一下


  
  
  1. typedef enum  {
  2.   TokenElevationTypeDefault   = 1,
  3.   TokenElevationTypeFull,
  4.   TokenElevationTypeLimited 
  5. } TOKEN_ELEVATION_TYPE , *PTOKEN_ELEVATION_TYPE;

Constants

TokenElevationTypeDefault

The token does not have a linked token.

TokenElevationTypeFull

The token is an elevated token.

TokenElevationTypeLimited

The token is a limited token.

在windows 7上,如果当前登录账号为管理员账号,则系统会分配两个访问令牌给用户,一个是受限的访问令牌(对应TokenElevationTypeLimited),一个是有完整管理员权限的访问令牌(对应TokenElevationTypeFull),如果程序没有以管理员身份运行,则程序会与受限的访问令牌关联,否则与另外一个关联。若当前登录账号为标准用户,则系统只会给用户一个默认访问令牌(对应TokenElevationTypeDefault)。

 

以下代码为msdn拷贝:

// AdminRole.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <Windows.h>

/*---------------------------------------------------------------------------
Application that demonstrates how to call IsElevatedAdministrator() and 
IsMemberOfAdministratorsGroup() and check for errors.Example code applies to   
Windows 7, Windows Vista, Windows XP   Windows Server 2008 R2, Windows Server 2008, 
Windows Server 2003
---------------------------------------------------------------------------*/   
BOOL IsElevatedAdministrator (HANDLE hInputToken);       
BOOL IsMemberOfAdministratorsGroup (HANDLE hInputToken);               

int wmain (int argc, wchar_t *argv[])       
{          
	HANDLE hToken;                  
	//========================================================================          
	// IsElevatedAdministrator()                  
	// Example 1:  Determine whether the current process is running as a full           
	//             administrator.          
	try           
	{            
		if (IsElevatedAdministrator (NULL))                
			wprintf (L"User is an administrator with an elevated token\n");             
		else                
			wprintf (L"User is not an administrator with an elevated token\n");          
	}          
	catch (DWORD lastError)          
	{             
		wprintf (L"IsElevatedAdministrator() failed with error %lu\n",lastError);          
	}                  
	
	// Example 2:  Determine whether a specific token is running as a full           
	//             administrator.          
	if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken))         
	{            
		try              
		{                
			if (IsElevatedAdministrator (hToken))                   
				wprintf (L"User is an administrator with an elevated token\n");               
			else                   
				wprintf (L"User is not an administrator with an elevated token\n");             
		}             
		catch (DWORD lastError)             
		{                
			wprintf (L"IsElevatedAdministrator() failed with error %lu\n",lastError);      
		}                     
		CloseHandle (hToken);          
	}                 
	
	//========================================================================          
	// IsMemberOfAdministratorsGroup()                  
	// Example 1:  Determine whether the current process is running as a           
	//             member of the local Administrators group.          
	
	try           
	{             
		if (IsMemberOfAdministratorsGroup (NULL))                
			wprintf (L"User is a member of the Administrators group\n");             
		else               
			wprintf (L"User is not a member of the Administrators group\n");          
	}          
	catch (DWORD lastError)         
	{             
		wprintf (L"IsMemberOfAdministratorsGroup() failed with error %lu\n", lastError);  
	}                  
	
	// Example 2:  Determine whether a specific token handle is member of the           
	//             local Administrators group.          
	if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY|TOKEN_DUPLICATE, &hToken))         
	{             
		try              
		{                
			if (IsMemberOfAdministratorsGroup (hToken))                   
				wprintf (L"User is a member of the Administrators group\n");                
			else                   
				wprintf (L"User is not a member of the Administrators group\n");             
		}             
		catch (DWORD lastError)             
		{                
			wprintf (L"IsMemberOfAdministratorsGroup() failed with error %lu\n",lastError);
		}                    
		CloseHandle (hToken);         
	}                  
	
	return 0;       
}                       
/*---------------------------------------------------------------------------
IsElevatedAdministrator (hInputToken)Checks whether the access token belongs to a user account 
that is a member of the local Administrators group and is elevated.  
Parameters   hInputToken [in, optional]      A handle to an access token.  
It must be opened with TOKEN_QUERY and       TOKEN_DUPLICATE access.  If this parameter is NULL,
the token of the       calling thread is used if it is impersonating; otherwise, the token of 
the calling process is used.Return Value   Returns TRUE if the token belongs to a user
who is a member of the local    Administrators group and is elevated.  
Returns FALSE otherwise.Exceptions Thrown   If this function fails, 
it throws a C++ DWORD exception that contains    the Win32 error code of the failure. 
For example, if hInputToken is an    invalid handle, the error code will be 
ERROR_INVALID_HANDLE.
---------------------------------------------------------------------------*/       

BOOL IsElevatedAdministrator (HANDLE hInputToken)       
{          
	BOOL fIsAdmin = FALSE;          
	HANDLE hTokenToCheck = NULL;          
	DWORD  lastErr;                    
	// If the caller supplies a token, duplicate it as an impersonation token,           
	// because CheckTokenMembership requires an impersonation token.         
	if (hInputToken)          
	{             
		if (!DuplicateToken (hInputToken, SecurityIdentification,   
			&hTokenToCheck))             
		{                
			lastErr = GetLastError();                
			goto CLEANUP;             
		}          
	}                  
	
	DWORD sidLen = SECURITY_MAX_SID_SIZE;          
	BYTE localAdminsGroupSid[SECURITY_MAX_SID_SIZE];                  
	if (!CreateWellKnownSid (WinBuiltinAdministratorsSid, NULL,
		localAdminsGroupSid, &sidLen))          
	{            
		lastErr = GetLastError();             
		goto CLEANUP;          
	}                  
	
	// Now, determine whether the user is an administrator.          
	if (CheckTokenMembership (hTokenToCheck, localAdminsGroupSid, &fIsAdmin))         
	{             
		lastErr = ERROR_SUCCESS;          
	}         
	else         
	{             
		lastErr = GetLastError();          
	}               
CLEANUP:          // Close the impersonation token only if we opened it.          
	if (hTokenToCheck)          
	{             
		CloseHandle (hTokenToCheck);             
		hTokenToCheck = NULL;          
	}                  
	
	if (ERROR_SUCCESS != lastErr)          
	{            
		throw (lastErr);          
	}                   
	return (fIsAdmin);      
}                       

/*---------------------------------------------------------------------------
IsMemberOfAdministratorsGroup (hInputToken)Checks whether the access token belongs to
a user account that is a member of the local Administrators group even if it is not currently 
elevated.  Parameters   hInputToken [in, optional]      A handle to an access token.  
It must be opened with TOKEN_QUERY and       TOKEN_DUPLICATE access.  If this parameter is NULL,
the token of the       calling thread is used if it is impersonating; otherwise, the token of 
the calling process is used.Return Value   Returns TRUE if the token belongs to a user 
who is a member of the local    Administrators group.  Returns FALSE otherwise.Exceptions Thrown
If this function fails, it throws a C++ DWORD exception that contains   
the Win32 error code of the failure.  For example, if hInputToken is an    invalid handle,
the error code will be ERROR_INVALID_HANDLE.
---------------------------------------------------------------------------*/       
BOOL IsMemberOfAdministratorsGroup (HANDLE hInputToken)       
{          
	BOOL fIsAdmin = FALSE;          
	HANDLE hTokenToCheck = NULL;          
	HANDLE hToken = hInputToken;          
	DWORD lastErr;                  
	// If the caller didn't supply a token, open the current thread's token           
	// (if present) or the token of the current process otherwise.          
	if (!hToken)          
	{             
		if (!OpenThreadToken (GetCurrentThread(), TOKEN_QUERY|TOKEN_DUPLICATE, 
			TRUE, &hToken))           
		{               
			if (!OpenProcessToken(GetCurrentProcess(),            
				TOKEN_QUERY|TOKEN_DUPLICATE, &hToken))            
			{                 
				lastErr = GetLastError();     
				goto CLEANUP;               
			}            
		}          
	}                 
	
	/*      Determine whether the system is running Windows Vista or later     
	(major version >= 6) because they support linked tokens, but previous     
	versions do not.  If running Windows Vista or later and the token is a      
	limited token, get its linked token and check it.  Otherwise, just      
	check the token we have.   */          
	OSVERSIONINFO osver;         
	osver.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);          
	if (!GetVersionEx (&osver))          
	{           
		lastErr = GetLastError();     
		goto CLEANUP;       
	}                 
	if (osver.dwMajorVersion >= 6)    
	{            
		TOKEN_ELEVATION_TYPE elevType;    
		DWORD cbSize;        
		if (!GetTokenInformation (hToken, TokenElevationType, &elevType,  
			sizeof(TOKEN_ELEVATION_TYPE), &cbSize))            
		{                
			lastErr = GetLastError();             
			goto CLEANUP;            
		}                    
		
		if (TokenElevationTypeLimited == elevType)         
		{      
			wprintf(L"Elevation Type = TokenElevationTypeLimited\n");
			if (!GetTokenInformation (hToken, TokenLinkedToken, &hTokenToCheck,
				sizeof(HANDLE), &cbSize))              
			{                 
				lastErr = GetLastError();       
				goto CLEANUP;            
			}           
		}  
		else if (TokenElevationTypeDefault == elevType)
		{
			wprintf(L"Elevation Type = TokenElevationTypeDefault\n");
		}
		else
		{
			wprintf(L"Elevation Type = TokenElevationTypeFull\n");
		}
	}               
	
	/*      
	CheckTokenMembership requires an impersonation token. If we just got a    
	linked token, it already is an impersonation token.  If we didn't get a       
	linked token, duplicate the original as an impersonation token for      
	CheckTokenMembership.   */         
	if (!hTokenToCheck && !DuplicateToken (hToken, SecurityIdentification,    
		&hTokenToCheck))         
	{           
		lastErr = GetLastError();      
		goto CLEANUP;         
	}               
	
	DWORD sidLen = SECURITY_MAX_SID_SIZE;         
	BYTE localAdminsGroupSid[SECURITY_MAX_SID_SIZE];        
	if (!CreateWellKnownSid (WinBuiltinAdministratorsSid, NULL,    
		localAdminsGroupSid, &sidLen))        
	{             
		lastErr = GetLastError();            
		goto CLEANUP;         
	}               
	
	// Now, determine whether the user is an administrator.        
	if (CheckTokenMembership (hTokenToCheck, localAdminsGroupSid, &fIsAdmin))      
	{            
		lastErr = ERROR_SUCCESS;   
	}       
	else        
	{           
		lastErr = GetLastError();     
	}              

CLEANUP:          
	// Close the thread/process token handle only if we opened it.  We open          
	// a token handle only when a caller passes NULL in the hInputToken           
	// parameter.          
	if (!hInputToken && hToken)          
	{             
		CloseHandle (hToken);          
		hToken = NULL;  
		
		// Set variable to same state as resource.         
	}          
	if (hTokenToCheck)         
	{            
		CloseHandle (hTokenToCheck);         
		hTokenToCheck = NULL;       
	}               
	
	if (ERROR_SUCCESS != lastErr)         
	{           
		throw (lastErr);      
	}                
	return (fIsAdmin);      

 }


 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值