Esempio n. 1
0
        /// <summary>
        /// Gets the current user security identifier.
        /// </summary>
        /// <returns></returns>
        internal static SecurityIdentifierSafePtr GetCurrentUserSid()
        {
            using ProcessTokenSafeHandle currentProcessHandle = Native.GetCurrentProcess();

            if (!Native.OpenProcessToken(currentProcessHandle, Native.AccessRights.TokenQuery, out AccessTokenSafeHandle tokenHandle))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            using AccessTokenSafeHandle scopedTokenHandle = tokenHandle;

            // Get the token user.
            //
            if (!Native.GetTokenInformation(tokenHandle, Native.TokenInformationClass.TokenUser, IntPtr.Zero, 0, out uint returnLength))
            {
                if (Marshal.GetLastWin32Error() != Native.ErrorInsufficientBuffer)
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }
            }

            using LocalAllocSafePtr tokenUserPtr = Native.LocalAlloc(Native.LocalMemoryFlags.Fixed | Native.LocalMemoryFlags.ZeroInit, returnLength);
            if (tokenUserPtr.IsInvalid)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!Native.GetTokenInformation(tokenHandle, Native.TokenInformationClass.TokenUser, tokenUserPtr.DangerousGetHandle(), returnLength, out returnLength))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            Native.TOKEN_USER tokenUser = Marshal.PtrToStructure <Native.TOKEN_USER>(tokenUserPtr.DangerousGetHandle());

            uint userSidLength = Native.GetLengthSid(tokenUser.User.Sid);

            SecurityIdentifierSafePtr currentUserSidPtr = Native.AllocSecurityIdentifier(Native.LocalMemoryFlags.Fixed | Native.LocalMemoryFlags.ZeroInit, userSidLength);

            if (currentUserSidPtr.IsInvalid)
            {
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            if (!Native.CopySid(userSidLength, currentUserSidPtr, tokenUser.User.Sid))
            {
                currentUserSidPtr.Dispose();
                throw new Win32Exception(Marshal.GetLastWin32Error());
            }

            return(currentUserSidPtr);
        }
Esempio n. 2
0
 internal static extern bool GetTokenInformation(
     [In] AccessTokenSafeHandle tokenHandle,
     [In] TokenInformationClass tokenInformationClass,
     [In] IntPtr tokenInformation,
     [In] uint tokenInformationLength,
     [Out] out uint returnLength);
Esempio n. 3
0
 public static extern bool OpenProcessToken(
     ProcessTokenSafeHandle processHandle,
     AccessRights desiredAccess,
     out AccessTokenSafeHandle tokenHandle);