winapivb6group-membership

CheckTokenMembership in VB6


I'm having a hard time converting this C++ code to VB6 code. I've search the net and haven't found anything. PInvoke.net only has reference to VB.NET code. Here's the code from MSDN:

BOOL IsUserAdmin(VOID)
/*++ 
Routine Description: This routine returns TRUE if the caller's
process is a member of the Administrators local group. Caller is NOT
expected to be impersonating anyone and is expected to be able to
open its own process and process token. 
Arguments: None. 
Return Value: 
   TRUE - Caller has Administrators local group. 
   FALSE - Caller does not have Administrators local group. --
*/
{
    BOOL b;
    SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
    PSID AdministratorsGroup; 
    b = AllocateAndInitializeSid(
        &NtAuthority,
        2,
        SECURITY_BUILTIN_DOMAIN_RID,
        DOMAIN_ALIAS_RID_ADMINS,
        0, 0, 0, 0, 0, 0,
        &AdministratorsGroup); 
    if(b) 
    {
        if (!CheckTokenMembership( NULL, AdministratorsGroup, &b)) 
        {
             b = FALSE;
        } 
        FreeSid(AdministratorsGroup); 
    }
    
    return(b);
}

It would be great if somebody can help out in converting this to VB6 code.

Thanks!

EDIT:
I was originally going to use that function but MSDN says:

This function is a wrapper for CheckTokenMembership. It is recommended to call that function directly to determine Administrator group status rather than calling IsUserAnAdmin.


Solution

  • Try this

    Option Explicit
    
    Private Const SECURITY_BUILTIN_DOMAIN_RID       As Long = &H20
    Private Const DOMAIN_ALIAS_RID_ADMINS           As Long = &H220
    
    Private Declare Function AllocateAndInitializeSid Lib "advapi32.dll" (pIdentifierAuthority As Any, ByVal nSubAuthorityCount As Byte, ByVal nSubAuthority0 As Long, ByVal nSubAuthority1 As Long, ByVal nSubAuthority2 As Long, ByVal nSubAuthority3 As Long, ByVal nSubAuthority4 As Long, ByVal nSubAuthority5 As Long, ByVal nSubAuthority6 As Long, ByVal nSubAuthority7 As Long, lpPSid As Long) As Long
    Private Declare Sub FreeSid Lib "advapi32.dll" (ByVal pSid As Long)
    Private Declare Function CheckTokenMembership Lib "advapi32.dll" (ByVal hToken As Long, ByVal pSidToCheck As Long, pbIsMember As Long) As Long
    
    Private Type SID_IDENTIFIER_AUTHORITY
        Value(0 To 5)            As Byte
    End Type
    
    Private Function pvIsAdmin() As Boolean
        Dim uAuthNt         As SID_IDENTIFIER_AUTHORITY
        Dim pSidAdmins      As Long
        Dim lResult         As Long
    
        uAuthNt.Value(5) = 5
        If AllocateAndInitializeSid(uAuthNt, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, pSidAdmins) <> 0 Then
            If CheckTokenMembership(0, pSidAdmins, lResult) <> 0 Then
                pvIsAdmin = (lResult <> 0)
            End If
            Call FreeSid(pSidAdmins)
        End If
    End Function