猫博

猫也博客-c++ kernel ddk ifs
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

取得当前用户的权限(privileges)

Posted on 2004-03-04 10:33  catlog  阅读(957)  评论(0编辑  收藏  举报

在Windows中如何取得用户的权限呢?

在MSDN中有如下的API可以帮助我们做到这些:

1,打开Token,OpenProcessToken得到HANDLE hToken

2.取得GetTokenInformation

3.遍历得到LookupPrivilegeName,LookupPrivilegeDisplayName

以下为示例:

#include <windows.h>
#include <stdio.h>
#pragma hdrstop

void main()
{
 HANDLE hToken;
 LUID setcbnameValue;
 TOKEN_PRIVILEGES tkp;
 DWORD errcod;
 LPVOID lpMsgBuf;
 LPCTSTR msgptr;
 
 UCHAR InfoBuffer[1000];
 PTOKEN_PRIVILEGES ptgPrivileges = (PTOKEN_PRIVILEGES) InfoBuffer;
 DWORD infoBufferSize;
 DWORD privilegeNameSize;
 DWORD displayNameSize;
 char privilegeName[500];
 char displayName[500];
 DWORD langId;
 UINT i;
 
 if ( ! OpenProcessToken( GetCurrentProcess(),
  TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken ) )
 {
  puts( "OpenProcessToken" );
  return;
 }
 
 // ---------------------------------------------------------------------
 // enumerate currently held privs (NOTE: not *enabled* privs, just the
 // ones you _could_ enable as in the last part)
 
 GetTokenInformation( hToken, TokenPrivileges, InfoBuffer,
  sizeof InfoBuffer, &infoBufferSize);
 
 printf( "Account privileges: \n\n" );
 for( i = 0; i < ptgPrivileges->PrivilegeCount; i ++ )
 {
  privilegeNameSize = sizeof privilegeName;
  displayNameSize = sizeof displayName;
  LookupPrivilegeName( NULL, &ptgPrivileges->Privileges[i].Luid,
   privilegeName, &privilegeNameSize );
  LookupPrivilegeDisplayName( NULL, privilegeName,
   displayName, &displayNameSize, &langId );
  printf( "%40s (%s)\n", displayName, privilegeName );
 }
 
 //----------------------------------------------------------------------
 // enable SeTcbPrivilege: lookup, adjust token privs
 
 if ( !LookupPrivilegeValue( NULL, SE_TCB_NAME, &setcbnameValue ) )
 {
  puts( "LookupPrivilegeValue" );
  return;
 }
 
 tkp.PrivilegeCount = 1;
 tkp.Privileges[0].Luid = setcbnameValue;
 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
 
 AdjustTokenPrivileges( hToken, FALSE, &tkp, sizeof tkp,
  NULL, NULL );
 
 errcod = GetLastError();
 if ( errcod != ERROR_SUCCESS )
 {
  FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER |
   FORMAT_MESSAGE_FROM_SYSTEM, NULL, errcod,
   MAKELANGID( LANG_NEUTRAL, SUBLANG_DEFAULT ),
   (LPTSTR) &lpMsgBuf, 0, NULL );
  
  msgptr = (LPCTSTR) lpMsgBuf;
  printf( "err %d: %s\n", errcod, msgptr );
  return;
 }
}

在VC6.0 Sp5 Win200Pro 下编译测试通过。