OpenProcessToken (advapi32)
Last changed: -149.173.6.25

.
Summary
Opens a handle to the access token associated with a process.

C# Signature:

[DllImport("advapi32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool OpenProcessToken(IntPtr ProcessHandle,
    UInt32 DesiredAccess, out IntPtr TokenHandle);

VB Signature:

<DllImport("advapi32.dll", SetLastError:=True)> _
Private Function OpenProcessToken( _
    ByVal ProcessHandle As IntPtr, _
    ByVal DesiredAccess As Integer, _
    ByRef TokenHandle As IntPtr _
    ) As Boolean
End Function

(alternate/older style)
Declare Function OpenProcessToken Lib "advapi32.dll" ( _
    ProcessHandle As IntPtr, _
    DesiredAccess As Integer, _
    ByRef TokenHandle As IntPtr _
) As Boolean

Notes:

The access token handle that is returned by TokenHandle should be closed using CloseHandle (kernel32) when you are finished using it.

Tips & Tricks:

    //Use these for DesiredAccess
    public const UInt32 STANDARD_RIGHTS_REQUIRED = 0x000F0000;
    public const UInt32 STANDARD_RIGHTS_READ = 0x00020000;
    public const UInt32 TOKEN_ASSIGN_PRIMARY = 0x0001;
    public const UInt32 TOKEN_DUPLICATE = 0x0002;
    public const UInt32 TOKEN_IMPERSONATE = 0x0004;
    public const UInt32 TOKEN_QUERY = 0x0008;
    public const UInt32 TOKEN_QUERY_SOURCE = 0x0010;
    public const UInt32 TOKEN_ADJUST_PRIVILEGES = 0x0020;
    public const UInt32 TOKEN_ADJUST_GROUPS = 0x0040;
    public const UInt32 TOKEN_ADJUST_DEFAULT = 0x0080;
    public const UInt32 TOKEN_ADJUST_SESSIONID = 0x0100;
    public const UInt32 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
    public const UInt32 TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
        TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
        TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
        TOKEN_ADJUST_SESSIONID);
    Source: Link to ''http://groups.google.com/group/microsoft.public.dotnet.general/browse_thread/thread/5742d50ec2e9f798/c702b8d7771f9016lnk=st&q=OpenProcessToken+0x00020000&rnum=1&hl=en#c702b8d7771f9016''

OR instead of using the above code for DesiredAccess, simply use the System.Security.Principal.TokenAccessLevels enumeration!!! - Trevor Sullivan 4/19/2010

VB Code:

    Private Const READ_CONTROL As Integer = &H20000
    Private Const STANDARD_RIGHTS_REQUIRED As Integer = &HF0000
    Private Const STANDARD_RIGHTS_READ As Integer = READ_CONTROL
    Private Const STANDARD_RIGHTS_WRITE As Integer = READ_CONTROL
    Private Const STANDARD_RIGHTS_EXECUTE As Integer = READ_CONTROL
    Private Const STANDARD_RIGHTS_ALL As Integer = &H1F0000
    Private Const SPECIFIC_RIGHTS_ALL As Integer = &HFFFF
    Private Const TOKEN_ASSIGN_PRIMARY As Integer = &H1
    Private Const TOKEN_DUPLICATE As Integer = &H2
    Private Const TOKEN_IMPERSONATE As Integer = &H4
    Private Const TOKEN_QUERY As Integer = &H8
    Private Const TOKEN_QUERY_SOURCE As Integer = &H10
    Private Const TOKEN_ADJUST_PRIVILEGES As Integer = &H20
    Private Const TOKEN_ADJUST_GROUPS As Integer = &H40
    Private Const TOKEN_ADJUST_DEFAULT As Integer = &H80
    Private Const TOKEN_ADJUST_SESSIONID As Integer = &H100

Sample Code:

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool OpenProcessToken(IntPtr ProcessHandle, UInt32 DesiredAccess, out IntPtr TokenHandle);
    private static uint STANDARD_RIGHTS_REQUIRED = 0x000F0000;
    private static uint STANDARD_RIGHTS_READ = 0x00020000;
    private static uint TOKEN_ASSIGN_PRIMARY = 0x0001;
    private static uint TOKEN_DUPLICATE = 0x0002;
    private static uint TOKEN_IMPERSONATE = 0x0004;
    private static uint TOKEN_QUERY = 0x0008;
    private static uint TOKEN_QUERY_SOURCE = 0x0010;
    private static uint TOKEN_ADJUST_PRIVILEGES = 0x0020;
    private static uint TOKEN_ADJUST_GROUPS = 0x0040;
    private static uint TOKEN_ADJUST_DEFAULT = 0x0080;
    private static uint TOKEN_ADJUST_SESSIONID = 0x0100;
    private static uint TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY);
    private static uint TOKEN_ALL_ACCESS = (STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY |
        TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE |
        TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT |
        TOKEN_ADJUST_SESSIONID);

     [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool GetTokenInformation(IntPtr TokenHandle, TOKEN_INFORMATION_CLASS TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);
    public enum TOKEN_INFORMATION_CLASS
    {
        TokenUser = 1,
        TokenGroups,
        TokenPrivileges,
        TokenOwner,
        TokenPrimaryGroup,
        TokenDefaultDacl,
        TokenSource,
        TokenType,
        TokenImpersonationLevel,
        TokenStatistics,
        TokenRestrictedSids,
        TokenSessionId,
        TokenGroupsAndPrivileges,
        TokenSessionReference,
        TokenSandBoxInert,
        TokenAuditPolicy,
        TokenOrigin
    }

    public static byte[] GetSIDByteArr(IntPtr processHandle)
    {
        int MAX_INTPTR_BYTE_ARR_SIZE = 512;
        IntPtr tokenHandle;
        byte[] sidBytes;

        // Get the Process Token
        if (!OpenProcessToken(processHandle, TOKEN_READ, out tokenHandle))
        throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());

        uint tokenInfoLength = 0;
        bool result;
        result = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenUser, IntPtr.Zero, tokenInfoLength, out tokenInfoLength);  // get the token info length
        IntPtr tokenInfo = Marshal.AllocHGlobal((int)tokenInfoLength);
        result = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenUser, tokenInfo, tokenInfoLength, out tokenInfoLength);  // get the token info

        // Get the User SID
        if (result)
        {
        TOKEN_USER tokenUser = (TOKEN_USER)Marshal.PtrToStructure(tokenInfo, typeof(TOKEN_USER));
        sidBytes = new byte[MAX_INTPTR_BYTE_ARR_SIZE];  // Since I don't yet know how to be more precise w/ the size of the byte arr, it is being set to 512
        Marshal.Copy(tokenUser.User.Sid, sidBytes, 0, MAX_INTPTR_BYTE_ARR_SIZE);  // get a byte[] representation of the SID
        }
        else throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());

        return sidBytes;
    }

    // ******** Example: Call GetSIDByteArr() *************//
    Process[] myProcesses = Process.GetProcesses();
    foreach (Process myProcess in myProcesses)
    {
        byte[] sidBytes = Utility.GetSIDByteArr(myProcess.Handle);
    }
    // ****************************************************//

Alternative Managed API:

Do you know one? Please contribute it!

Documentation