CheckTokenMembership in VB6 - Crashing on FreeSID

2020-02-16 02:51发布

问题:

I am using the CheckTokenMembership Windows API to check if the user is an Administrator.

Here's the code:

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

Problem is that on Windows 7 and Windows 2008 SP2, the call to FreeSID is causing the app to crash. The crash is intermittent.

Has anyone encountered this problem?

Thanks!

EDIT:

I just rechecked my code and I found out that I declared FreeSID as such:

Private Declare Sub FreeSid Lib "advapi32.dll" (pSid As Long)

As compared to the above code, the pSid parameter here is not flagged as ByVal. I added the ByVal flag and the problem is no longer present. Somehow, I am not convinced that this fixed the problem. Can this possibly have fixed the problem?

回答1:

Separate pvIsAdmin in a completely separate module and copy function declarations verbatim from the snippet. In AllocateAndInitializeSid lpPSid is ByRef. In FreeSid param is ByVal.