共用方式為


在 C++ 中使用 ACL 驗證用戶端存取

下列範例示範伺服器如何檢查 安全性描述元 允許客戶端的訪問許可權。 此範例使用 ImpersonateNamedPipeClient 函式,但它能以任何其他模擬函式達到同樣效果。 模擬客戶端之後,此範例會呼叫 OpenThreadToken 函式,以取得 模擬令牌。 然後,它會呼叫 MapGenericMask 函式,根據 GENERIC_MAPPING 結構中指定的對應,將任何泛型存取權轉換為對應的特定和標準存取權。

AccessCheck 函式會根據安全性描述元 DACL 中用戶端所允許的許可權,檢查所要求的訪問許可權。 若要檢查存取權並在安全事件日誌中產生項目,請使用 AccessCheckAndAuditAlarm 函式。

#include <windows.h>
#pragma comment(lib, "advapi32.lib")

BOOL ImpersonateAndCheckAccess(
  HANDLE hNamedPipe,               // handle of pipe to impersonate
  PSECURITY_DESCRIPTOR pSD,        // security descriptor to check
  DWORD dwAccessDesired,           // access rights to check
  PGENERIC_MAPPING pGeneric,       // generic mapping for object
  PDWORD pdwAccessAllowed          // returns allowed access rights
) 
{
   HANDLE hToken;
   PRIVILEGE_SET PrivilegeSet;
   DWORD dwPrivSetSize = sizeof( PRIVILEGE_SET );
   BOOL fAccessGranted=FALSE;

// Impersonate the client.

   if (! ImpersonateNamedPipeClient(hNamedPipe) ) 
      return FALSE;

// Get an impersonation token with the client's security context.

   if (! OpenThreadToken( GetCurrentThread(), TOKEN_ALL_ACCESS,
         TRUE, &hToken ))
   {
      goto Cleanup;
   }

// Use the GENERIC_MAPPING structure to convert any 
// generic access rights to object-specific access rights.

   MapGenericMask( &dwAccessDesired, pGeneric );

// Check the client's access rights.

   if( !AccessCheck( 
      pSD,                 // security descriptor to check
      hToken,              // impersonation token
      dwAccessDesired,     // requested access rights
      pGeneric,            // pointer to GENERIC_MAPPING
      &PrivilegeSet,       // receives privileges used in check
      &dwPrivSetSize,      // size of PrivilegeSet buffer
      pdwAccessAllowed,    // receives mask of allowed access rights
      &fAccessGranted ))   // receives results of access check
   {
      goto Cleanup;
   }

Cleanup:

   RevertToSelf();

   if (hToken != INVALID_HANDLE_VALUE)
      CloseHandle(hToken);  

   return fAccessGranted;
}