Exemplo n.º 1
0
        internal static IntPtr GetCurrentUserSid()
        {
            IntPtr pTokenHandle = IntPtr.Zero;
            IntPtr pBuffer      = IntPtr.Zero;

            try
            {
                //
                // Get the current user's SID
                //
                int error = 0;

                // Get the current thread's token
                if (!UnsafeNativeMethods.OpenThreadToken(
                        UnsafeNativeMethods.GetCurrentThread(),
                        0x8,         // TOKEN_QUERY
                        true,
                        ref pTokenHandle
                        ))
                {
                    if ((error = Marshal.GetLastWin32Error()) == 1008) // ERROR_NO_TOKEN
                    {
                        Debug.Assert(pTokenHandle == IntPtr.Zero);

                        // Current thread doesn't have a token, try the process
                        if (!UnsafeNativeMethods.OpenProcessToken(
                                UnsafeNativeMethods.GetCurrentProcess(),
                                0x8,         // TOKEN_QUERY
                                ref pTokenHandle
                                ))
                        {
                            int lastError = Marshal.GetLastWin32Error();
                            GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: OpenProcessToken failed, gle=" + lastError);

                            throw new PrincipalOperationException(
                                      String.Format(CultureInfo.CurrentCulture,
                                                    StringResources.UnableToOpenToken,
                                                    lastError));
                        }
                    }
                    else
                    {
                        GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: OpenThreadToken failed, gle=" + error);

                        throw new PrincipalOperationException(
                                  String.Format(CultureInfo.CurrentCulture,
                                                StringResources.UnableToOpenToken,
                                                error));
                    }
                }

                Debug.Assert(pTokenHandle != IntPtr.Zero);

                int neededBufferSize = 0;

                // Retrieve the user info from the current thread's token
                // First, determine how big a buffer we need.
                bool success = UnsafeNativeMethods.GetTokenInformation(
                    pTokenHandle,
                    1,                       // TokenUser
                    IntPtr.Zero,
                    0,
                    ref neededBufferSize);

                int getTokenInfoError = 0;
                if ((getTokenInfoError = Marshal.GetLastWin32Error()) != 122) // ERROR_INSUFFICIENT_BUFFER
                {
                    GlobalDebug.WriteLineIf(GlobalDebug.Error, "Utils", "GetCurrentUserSid: GetTokenInformation (1st try) failed, gle=" + getTokenInfoError);

                    throw new PrincipalOperationException(
                              String.Format(CultureInfo.CurrentCulture, StringResources.UnableToRetrieveTokenInfo, getTokenInfoError));
                }

                // Allocate the necessary buffer.
                Debug.Assert(neededBufferSize > 0);
                pBuffer = Marshal.AllocHGlobal(neededBufferSize);

                // Load the user info into the buffer
                success = UnsafeNativeMethods.GetTokenInformation(
                    pTokenHandle,
                    1,                       // TokenUser
                    pBuffer,
                    neededBufferSize,
                    ref neededBufferSize);

                if (!success)
                {
                    int lastError = Marshal.GetLastWin32Error();
                    GlobalDebug.WriteLineIf(GlobalDebug.Error,
                                            "Utils",
                                            "GetCurrentUserSid: GetTokenInformation (2nd try) failed, neededBufferSize=" + neededBufferSize + ", gle=" + lastError);

                    throw new PrincipalOperationException(
                              String.Format(CultureInfo.CurrentCulture, StringResources.UnableToRetrieveTokenInfo, lastError));
                }

                // Retrieve the user's SID from the user info
                UnsafeNativeMethods.TOKEN_USER tokenUser = (UnsafeNativeMethods.TOKEN_USER)Marshal.PtrToStructure(pBuffer, typeof(UnsafeNativeMethods.TOKEN_USER));
                IntPtr pUserSid = tokenUser.sidAndAttributes.pSid;   // this is a reference into the NATIVE memory (into pBuffer)

                Debug.Assert(UnsafeNativeMethods.IsValidSid(pUserSid));

                // Now we make a copy of the SID to return
                int    userSidLength  = UnsafeNativeMethods.GetLengthSid(pUserSid);
                IntPtr pCopyOfUserSid = Marshal.AllocHGlobal(userSidLength);
                success = UnsafeNativeMethods.CopySid(userSidLength, pCopyOfUserSid, pUserSid);
                if (!success)
                {
                    int lastError = Marshal.GetLastWin32Error();
                    GlobalDebug.WriteLineIf(GlobalDebug.Error,
                                            "Utils",
                                            "GetCurrentUserSid: CopySid failed, errorcode=" + lastError);

                    throw new PrincipalOperationException(
                              String.Format(CultureInfo.CurrentCulture, StringResources.UnableToRetrieveTokenInfo, lastError));
                }

                return(pCopyOfUserSid);
            }
            finally
            {
                if (pTokenHandle != IntPtr.Zero)
                {
                    UnsafeNativeMethods.CloseHandle(pTokenHandle);
                }

                if (pBuffer != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pBuffer);
                }
            }
        }
Exemplo n.º 2
0
        internal static IntPtr GetCurrentUserSid()
        {
            IntPtr intPtr;
            IntPtr zero  = IntPtr.Zero;
            IntPtr zero1 = IntPtr.Zero;

            try
            {
                if (!UnsafeNativeMethods.OpenThreadToken(UnsafeNativeMethods.GetCurrentThread(), 8, true, ref zero))
                {
                    int lastWin32Error = Marshal.GetLastWin32Error();
                    int num            = lastWin32Error;
                    if (lastWin32Error != 0x3f0)
                    {
                        object[] objArray = new object[1];
                        objArray[0] = num;
                        throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.UnableToOpenToken, objArray));
                    }
                    else
                    {
                        if (!UnsafeNativeMethods.OpenProcessToken(UnsafeNativeMethods.GetCurrentProcess(), 8, ref zero))
                        {
                            int      lastWin32Error1 = Marshal.GetLastWin32Error();
                            object[] objArray1       = new object[1];
                            objArray1[0] = lastWin32Error1;
                            throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.UnableToOpenToken, objArray1));
                        }
                    }
                }
                int  num1             = 0;
                bool tokenInformation = UnsafeNativeMethods.GetTokenInformation(zero, 1, IntPtr.Zero, 0, ref num1);
                int  lastWin32Error2  = Marshal.GetLastWin32Error();
                int  num2             = lastWin32Error2;
                if (lastWin32Error2 == 122)
                {
                    zero1            = Marshal.AllocHGlobal(num1);
                    tokenInformation = UnsafeNativeMethods.GetTokenInformation(zero, 1, zero1, num1, ref num1);
                    if (tokenInformation)
                    {
                        UnsafeNativeMethods.TOKEN_USER structure = (UnsafeNativeMethods.TOKEN_USER)Marshal.PtrToStructure(zero1, typeof(UnsafeNativeMethods.TOKEN_USER));
                        IntPtr intPtr1   = structure.sidAndAttributes.pSid;
                        int    lengthSid = UnsafeNativeMethods.GetLengthSid(intPtr1);
                        IntPtr intPtr2   = Marshal.AllocHGlobal(lengthSid);
                        tokenInformation = UnsafeNativeMethods.CopySid(lengthSid, intPtr2, intPtr1);
                        if (tokenInformation)
                        {
                            intPtr = intPtr2;
                        }
                        else
                        {
                            int      lastWin32Error3 = Marshal.GetLastWin32Error();
                            object[] objArray2       = new object[1];
                            objArray2[0] = lastWin32Error3;
                            throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.UnableToRetrieveTokenInfo, objArray2));
                        }
                    }
                    else
                    {
                        int      num3      = Marshal.GetLastWin32Error();
                        object[] objArray3 = new object[1];
                        objArray3[0] = num3;
                        throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.UnableToRetrieveTokenInfo, objArray3));
                    }
                }
                else
                {
                    object[] objArray4 = new object[1];
                    objArray4[0] = num2;
                    throw new PrincipalOperationException(string.Format(CultureInfo.CurrentCulture, StringResources.UnableToRetrieveTokenInfo, objArray4));
                }
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    UnsafeNativeMethods.CloseHandle(zero);
                }
                if (zero1 != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(zero1);
                }
            }
            return(intPtr);
        }