суббота, 5 мая 2012 г.

Programming Windows Security

Reading this old but still good book I stumbled upon this code sample:

HANDLE getEffectiveToken(
 DWORD dwDesiredAccess,
 BOOL bWantlmpToken,
 SECURITY_IMPERSONATION_LEVEL impLevel)
{
 HANDLE htok;

 // Try to get thread token
 if (OpenThreadToken(GetCurrentThread(), dwDesiredAccess, TRUE, &htok))
 {
  return htok;
 }
 else if (ERROR_NO_TOKEN == GetLastError())
 {
  // No thread tokens, we must get process token
  DWORD grfAccess = bWantlmpToken ?
      TOKEN_DUPLICATE : dwDesiredAccess;
  if (OpenProcessToken(GetCurrentProcess(), grfAccess, &htok))   
  {
   if (bWantImpToken)
   {
    // convert primary to impersonation token
    HANDLE htokImp;
    if (!DuplicateTokenEx(htok, dwDesiredAccess, 0,
     impLevel, TokenImpersonation, &htokImp))   
    {
     htokImp = 0;
    }
    CloseHandle(htok);
    return htokImp;
   }
   else
   {
    return htok;
   }
  }
 }
 return 0;
}

BOOL WINAPI CheckTokenMembership(HANDLE TokenHandle,
   PSID SidToCheck, PBOOL IsMember)
{
 // if no token was passed, CTM uses the effective
 // security context (the thread or process token)
 if (!TokenHandle)
 {
  TokenHandle = getEffectiveToken(
     TOKEN_QUERY, TRUE, SecurityIdentification);
 }
 if (!TokenHandle) return FALSE;
 ... // irrelevant code skipped
 return AccessCheck(&sd, TokenHandle, 1, &gm, &ps, &cb, &ga, IsMember);
}

Can you see handles leakage here ?
This code missed CloseHandle(TokenHandle) when TokenHandle was obtained from getEffectiveToken

2 комментария: