Esempio n. 1
0
        /// <summary>
        ///  Generic call to Win32.GetTokenInformation. The returned object contains the
        ///  token information in unmanaged heap (UnmanagedHeapAlloc).
        ///  It must be disposed by the caller.
        /// </summary>
        /// <param name="TokenInformationClass">The type of info to retrieve</param>
        /// <returns>The ptr to the token information in unmanaged memory</returns>
        private UnmanagedHeapAlloc GetTokenInformation(TokenInformationClass TokenInformationClass)
        {
            DWORD cbLength;
            BOOL  rc = Win32.GetTokenInformation(_handle, TokenInformationClass, IntPtr.Zero, 0, out cbLength);

            switch (Marshal.GetLastWin32Error())
            {
            case Win32.SUCCESS:
                throw new ArgumentException("Unexpected error code returned by GetTokenInformation");

            case Win32.ERROR_BAD_LENGTH:
                // Special case for TokenSessionId. Win32 doesn't want to return
                // us the size of a DWORD.
                cbLength = (DWORD)Marshal.SizeOf(typeof(DWORD));
                goto case Win32.ERROR_INSUFFICIENT_BUFFER;

            case Win32.ERROR_INSUFFICIENT_BUFFER:
                UnmanagedHeapAlloc res = new UnmanagedHeapAlloc(cbLength);
                try
                {
                    rc = Win32.GetTokenInformation(_handle, TokenInformationClass, res.Ptr, res.Size, out cbLength);
                    Win32.CheckCall(rc);
                }
                catch
                {
                    res.Dispose();
                    throw;
                }
                return(res);

            default:
                Win32.ThrowLastError();
                return(null);                        // uneeded
            }
        }
Esempio n. 2
0
        internal static SafeBuffer GetTokenInformation(SafeTokenHandle tokenHandle, TokenInformationClass informationClass)
        {
            Debug.Assert(tokenHandle != null && !tokenHandle.IsClosed && !tokenHandle.IsInvalid);

            // Figure out how much memory we need to hold this token information
            int bufferSize;

            UnsafeNativeMethods.GetTokenInformation(tokenHandle,
                                                    informationClass,
                                                    SafeBuffer.InvalidBuffer,
                                                    0,
                                                    out bufferSize);

            // Allocate a buffer and get the token information
            SafeBuffer buffer = SafeBuffer.Allocate(bufferSize);

            if (!UnsafeNativeMethods.GetTokenInformation(tokenHandle,
                                                         informationClass,
                                                         buffer,
                                                         bufferSize,
                                                         out bufferSize))
            {
                Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
            }

            return(buffer);
        }
Esempio n. 3
0
 // ReSharper disable once TooManyArguments
 public static extern bool GetTokenInformation(
     IntPtr tokenHandle,
     TokenInformationClass tokenInformationClass,
     ref TokenElevationType tokenElevationTypeInformation,
     int tokenInformationLength,
     out int returnLength
     );
 internal static extern bool GetTokenInformation(
     /* _In_  HANDLE                  */ [In] SafeTokenHandle tokenHandle,
     /* _In_  TOKEN_INFORMATION_CLASS */ [In] TokenInformationClass tokenInformationClass,
     /* _Out_ LPVOID                  */ [In][Out] IntPtr tokenInformation,
     /* _In_  DWORD                   */ [In] uint tokenInformationLength,
     /* _Out_ PDWORD                  */ [Out] out uint returnLength
     );
Esempio n. 5
0
 private static extern bool GetTokenInformation(
     SafeTokenHandle TokenHandle,
     TokenInformationClass TokenInformationClass,
     IntPtr TokenInformation,
     int TokenInformationLength,
     out int ReturnLength
     );
 private T GetTokenInformation <T>(TokenInformationClass tokenInformationClass) where T : struct
 {
     using (SafeLocalAllocHandle handle = GetTokenInformation(this.m_safeTokenHandle, tokenInformationClass))
     {
         return(handle.Read <T>(0L));
     }
 }
Esempio n. 7
0
        private Sid[] GetGroupsInternal(TokenInformationClass infoClass)
        {
            int retLen = 0;

            Win32.GetTokenInformation(this, infoClass, IntPtr.Zero, 0, out retLen);

            using (MemoryAlloc data = new MemoryAlloc(retLen))
            {
                if (!Win32.GetTokenInformation(this, infoClass, data,
                                               data.Size, out retLen))
                {
                    Win32.Throw();
                }

                int   count = data.ReadStruct <TokenGroups>().GroupCount;
                Sid[] sids  = new Sid[count];

                for (int i = 0; i < count; i++)
                {
                    var saa = data.ReadStruct <SidAndAttributes>(TokenGroups.GroupsOffset, i);
                    sids[i] = new Sid(saa.Sid, saa.Attributes);
                }

                return(sids);
            }
        }
Esempio n. 8
0
 public static extern bool GetTokenInformation(
     IntPtr hToken,
     TokenInformationClass tokenInfoDesire,
     IntPtr pTokenInfo, // a pointer to a win32 struct depending on the value in tokenInfoDesire
     uint dwTokenInfoLength,
     out uint dwTokenResultLength
     );
Esempio n. 9
0
 private void SetInformationInt32(TokenInformationClass infoClass, int value)
 {
     Win32.NtSetInformationToken(
         this,
         infoClass,
         ref value,
         sizeof(int)
         ).ThrowIf();
 }
Esempio n. 10
0
        private IntPtr GetInformationIntPtr(TokenInformationClass infoClass)
        {
            NtStatus status;

            IntPtr value = this.GetInformationIntPtr(infoClass, out status);

            status.ThrowIf();

            return(value);
        }
Esempio n. 11
0
        private int GetInformationInt32(TokenInformationClass infoClass)
        {
            NtStatus status;

            int value = this.GetInformationInt32(infoClass, out status);

            status.ThrowIf();

            return(value);
        }
Esempio n. 12
0
        internal unsafe void GetTokenInformation <T>(TokenInformationClass infoClass, out T buff) where T : unmanaged
        {
            fixed(void *buffP = &buff)
            {
                bool success = GetTokenInformation(tokenHandle, infoClass, buffP, (uint)sizeof(T), out _);

                if (!success)
                {
                    throw new Win32Exception();
                }
            }
        }
Esempio n. 13
0
        private int GetInformationInt32(TokenInformationClass infoClass)
        {
            int value;
            int retLen;

            if (!Win32.GetTokenInformation(this, infoClass, out value, sizeof(int), out retLen))
            {
                Win32.ThrowLastError();
            }

            return(value);
        }
Esempio n. 14
0
        /// <summary>
        ///   Get a property from the current token
        /// </summary>

        private T GetTokenInformation <T>(TokenInformationClass tokenInformationClass) where T : struct
        {
            Debug.Assert(!_safeTokenHandle.IsInvalid && !_safeTokenHandle.IsClosed, "!m_safeTokenHandle.IsInvalid && !m_safeTokenHandle.IsClosed");

            using (SafeLocalAllocHandle information = GetTokenInformation(_safeTokenHandle, tokenInformationClass))
            {
                Debug.Assert(information.ByteLength >= (ulong)Marshal.SizeOf <T>(),
                             "information.ByteLength >= (ulong)Marshal.SizeOf(typeof(T))");

                return(information.Read <T>(0));
            }
        }
Esempio n. 15
0
        private void SetInformationInt32(TokenInformationClass infoClass, int value)
        {
            NtStatus status;

            if ((status = Win32.NtSetInformationToken(
                     this,
                     infoClass,
                     ref value,
                     sizeof(int)
                     )) >= NtStatus.Error)
            {
                Win32.Throw(status);
            }
        }
Esempio n. 16
0
        private IntPtr GetInformationIntPtr(TokenInformationClass infoClass)
        {
            NtStatus status;
            IntPtr   value;

            value = this.GetInformationIntPtr(infoClass, out status);

            if (status >= NtStatus.Error)
            {
                Win32.Throw(status);
            }

            return(value);
        }
Esempio n. 17
0
        private IntPtr GetInformationIntPtr(TokenInformationClass infoClass, out NtStatus status)
        {
            IntPtr value;
            int    retLength;

            status = Win32.NtQueryInformationToken(
                this,
                infoClass,
                out value,
                IntPtr.Size,
                out retLength
                );

            return(value);
        }
Esempio n. 18
0
        private int GetInformationInt32(TokenInformationClass infoClass, out NtStatus status)
        {
            int value;
            int retLength;

            status = Win32.NtQueryInformationToken(
                this,
                infoClass,
                out value,
                sizeof(int),
                out retLength
                );

            return(value);
        }
Esempio n. 19
0
        public unsafe SidAndAttributes[] GetGroupsTokenInformation(TokenInformationClass tokenInformationClass)
        {
            if (tokenInformationClass != TokenInformationClass.TokenGroups &&
                tokenInformationClass != TokenInformationClass.TokenRestrictedSids &&
                tokenInformationClass != TokenInformationClass.TokenLogonSid &&
                tokenInformationClass != TokenInformationClass.TokenCapabilities &&
                tokenInformationClass != TokenInformationClass.TokenDeviceGroups &&
                tokenInformationClass != TokenInformationClass.TokenRestrictedDeviceGroups)
            {
                throw new ArgumentException(string.Format("{0} is not a valid Group token information class", tokenInformationClass), "tokenInformationClass");
            }

            int tokenSize;

            if (!NativeMethods.GetTokenInformation(handle, tokenInformationClass, IntPtr.Zero, 0, out tokenSize) &&
                Marshal.GetLastWin32Error() != (int)SystemErrorCode.ErrorInsufficientBuffer)
            {
                ErrorHelper.ThrowCustomWin32Exception();
            }

            IntPtr tokenInformationPtr = Marshal.AllocHGlobal(tokenSize);

            try
            {
                if (!NativeMethods.GetTokenInformation(handle, tokenInformationClass, tokenInformationPtr, tokenSize, out tokenSize))
                {
                    ErrorHelper.ThrowCustomWin32Exception();
                }
                var    groupStructure = (NativeTokenGroups)Marshal.PtrToStructure(tokenInformationPtr, typeof(NativeTokenGroups));
                IntPtr offset         = Marshal.OffsetOf(typeof(NativeTokenGroups), "Groups");
                var    groups         = new SidAndAttributes[groupStructure.GroupCount];
                long   start          = new IntPtr(tokenInformationPtr.ToInt64() + offset.ToInt64()).ToInt64();
                for (int i = 0; i < groupStructure.GroupCount; i++)
                {
                    var arrayElementPtr = new IntPtr(start + i * sizeof(NativeSidAndAttributes));
                    var group           = (NativeSidAndAttributes)Marshal.PtrToStructure(arrayElementPtr, typeof(NativeSidAndAttributes));
                    groups[i] = new SidAndAttributes(group.Attributes, group.Sid);
                }
                return(groups);
            }
            finally
            {
                Marshal.FreeHGlobal(tokenInformationPtr);
            }
        }
Esempio n. 20
0
        private TResult GetTokenInformation <T, TResult>(TokenInformationClass type, Func <IntPtr, T, TResult> func) where T : struct
        {
            if (!NativeMethods.GetTokenInformation(_token, type, IntPtr.Zero, 0, out var dwLength))
            {
                var errorCode = Marshal.GetLastWin32Error();
                switch (errorCode)
                {
                case NativeMethods.ERROR_BAD_LENGTH:
                // special case for TokenSessionId. Falling through
                case NativeMethods.ERROR_INSUFFICIENT_BUFFER:
                    var handle = Marshal.AllocHGlobal((int)dwLength);
                    try
                    {
                        if (handle == IntPtr.Zero)
                        {
                            throw new OutOfMemoryException();
                        }

                        if (!NativeMethods.GetTokenInformation(_token, type, handle, dwLength, out dwLength))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }

                        var s = Marshal.PtrToStructure <T>(handle);
                        return(func(handle, s));
                    }
                    finally
                    {
                        if (handle != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(handle);
                        }
                    }

                case NativeMethods.ERROR_INVALID_HANDLE:
                    throw new ArgumentException("Argument_InvalidImpersonationToken");

                default:
                    throw new Win32Exception(errorCode);
                }
            }

            return(default);
Esempio n. 21
0
        static SafeHGlobalHandle GetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, out uint dwLength)
        {
            SafeHGlobalHandle safeAllocHandle = SafeHGlobalHandle.InvalidHandle;

            dwLength = (uint)Marshal.SizeOf(typeof(uint));
            bool result = NativeMethods.GetTokenInformation(tokenHandle,
                                                            (uint)tokenInformationClass,
                                                            safeAllocHandle,
                                                            0,
                                                            out dwLength);
            int dwErrorCode = Marshal.GetLastWin32Error();

            switch (dwErrorCode)
            {
            case NativeMethods.ERROR_BAD_LENGTH:
            // special case for TokenSessionId. Falling through
            case NativeMethods.ERROR_INSUFFICIENT_BUFFER:
                safeAllocHandle = SafeHGlobalHandle.AllocHGlobal(dwLength);
                result          = NativeMethods.GetTokenInformation(tokenHandle,
                                                                    (uint)tokenInformationClass,
                                                                    safeAllocHandle,
                                                                    dwLength,
                                                                    out dwLength);
                dwErrorCode = Marshal.GetLastWin32Error();
                if (!result)
                {
                    safeAllocHandle.Close();
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(dwErrorCode));
                }
                break;

            default:
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new Win32Exception(dwErrorCode));
            }
            return(safeAllocHandle);
        }
Esempio n. 22
0
        public static bool GetTokenInformation(IntPtr TokenHandle, TokenInformationClass InfoClass, IntPtr Info, int Size, out int InfoLength, [CallerMemberName] string callerName = "")
        {
            if (!PInvokeDebugger.LoggingEnabled)
            {
                return(PInvoke_GetTokenInformation(TokenHandle, InfoClass, Info, Size, out InfoLength));
            }

            bool             returnValue = PInvoke_GetTokenInformation(TokenHandle, InfoClass, Info, Size, out InfoLength);
            PInvokeDebugInfo debugInfo   = PInvokeDebugInfo.TraceDebugInfo(
                ModuleName,
                nameof(GetTokenInformation),
                callerName,
                returnValue,
                false,
                nameof(TokenHandle), TokenHandle,
                nameof(InfoClass), InfoClass,
                nameof(Info), Info,
                nameof(Size), Size,
                nameof(InfoLength), InfoLength
                );

            PInvokeDebugger.SafeCapture(debugInfo);
            return(returnValue);
        }
Esempio n. 23
0
 internal static extern bool GetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, IntPtr tokenInformation, int tokenInformationLength, out int returnLength);
Esempio n. 24
0
 public static extern BOOL GetTokenInformation(
     HANDLE TokenHandle,
     TokenInformationClass TokenInformationClass,
     LPVOID TokenInformation,
     DWORD TokenInformationLength,
     out DWORD ReturnLength);
Esempio n. 25
0
 public SidAndAttributes[] GetGroupsTokenInformation(TokenInformationClass tokenInformationClass)
 {
     return _handle.GetGroupsTokenInformation(tokenInformationClass);
 }
Esempio n. 26
0
 internal static extern bool SetTokenInformation(
     IntPtr hToken,
     TokenInformationClass tokenInfoClass,
     IntPtr pTokenInfo,
     int tokenInfoLength);
		public static extern bool GetTokenInformation( SafeTokenHandle tokenHandle, TokenInformationClass tokenInformationClass, IntPtr tokenInformation, int tokenInformationLength, out int returnLength );
Esempio n. 28
0
 private static extern bool GetTokenInformation(IntPtr TokenHandle, TokenInformationClass TokenInformationClass, IntPtr TokenInformation, uint TokenInformationLength, out uint ReturnLength);
 public static extern bool GetTokenInformation(IntPtr TokenHandle,
                                               TokenInformationClass TokenInformationClass, out int TokenInformation,
                                               uint TokenInformationLength, out uint ReturnLength);
Esempio n. 30
0
 public static extern int NtSetInformationToken(
     SafeKernelObjectHandle TokenHandle,
     TokenInformationClass TokenInformationClass,
     byte[] TokenInformation,
     int TokenInformationLength);
 private static extern int GetTokenInformation(IntPtr token, TokenInformationClass infoClass,
                                               ref TOKEN_LINKED_TOKEN buffer, int bufferLength,
                                               out int returnLength);
Esempio n. 32
0
        private T GetTokenInformation <T>(TokenInformationClass type) where T : struct
        {
            return(GetTokenInformation <T, T>(type, Identity));

            T Identity(T arg) => arg;
        }
Esempio n. 33
0
 internal static extern bool SetTokenInformation(
     IntPtr hToken,
     TokenInformationClass tokenInfoClass,
     IntPtr pTokenInfo,
     int tokenInfoLength);
Esempio n. 34
0
 public static extern bool GetTokenInformation(
     /* [in]  */ SafeTokenHandle token,
     /* [in]  */ TokenInformationClass tokenInfoClass,
     /* [in]  */ IntPtr tokenInformation,
     /* [in]  */ int tokeInfoLength,
     /* [out] */ out int actualSize);
Esempio n. 35
0
 public static extern bool SetTokenInformation(IntPtr tokenHandle, TokenInformationClass tokenInformationClass, uint tokenInformation, uint tokenInformationLength);
Esempio n. 36
0
 public static extern bool GetTokenInformation(IntPtr hToken, TokenInformationClass tokenInfoClass, IntPtr pTokenInfo, Int32 tokenInfoLength,
     out Int32 returnLength);
Esempio n. 37
0
 public static extern NtStatus NtQueryInformationToken(
     SafeKernelObjectHandle TokenHandle,
     TokenInformationClass TokenInformationClass,
     SafeBuffer TokenInformation,
     int TokenInformationLength,
     out int ReturnLength);
Esempio n. 38
0
        /// <summary>
        ///  Generic call to Win32.GetTokenInformation. The returned object contains the 
        ///  token information in unmanaged heap (UnmanagedHeapAlloc). 
        ///  It must be disposed by the caller.
        /// </summary>
        /// <param name="TokenInformationClass">The type of info to retrieve</param>
        /// <returns>The ptr to the token information in unmanaged memory</returns>
        private UnmanagedHeapAlloc GetTokenInformation(TokenInformationClass TokenInformationClass)
        {
            DWORD cbLength;
            BOOL rc = Win32.GetTokenInformation(_handle, TokenInformationClass, IntPtr.Zero, 0, out cbLength);
            switch(Marshal.GetLastWin32Error())
            {
                case Win32.SUCCESS:
                    throw new ArgumentException("Unexpected error code returned by GetTokenInformation");

                case Win32.ERROR_BAD_LENGTH:
                    // Special case for TokenSessionId. Win32 doesn't want to return
                    // us the size of a DWORD.
                    cbLength = (DWORD)Marshal.SizeOf(typeof(DWORD));
                    goto case Win32.ERROR_INSUFFICIENT_BUFFER;

                case Win32.ERROR_INSUFFICIENT_BUFFER:
                    UnmanagedHeapAlloc res = new UnmanagedHeapAlloc(cbLength);
                    try
                    {
                        rc = Win32.GetTokenInformation(_handle, TokenInformationClass, res.Ptr, res.Size, out cbLength);
                        Win32.CheckCall(rc);
                    }
                    catch
                    {
                        res.Dispose();
                        throw;
                    }
                    return res;

                default:
                    Win32.ThrowLastError();
                    return null; // uneeded
            }
        }
Esempio n. 39
0
 private TResult GetTokenInformation <T, TResult>(TokenInformationClass type, Func <T, TResult> func) where T : struct
 {
     return(GetTokenInformation <T, TResult>(type, (_, arg) => func(arg)));
 }
Esempio n. 40
0
		public static extern BOOL GetTokenInformation(
			HANDLE TokenHandle, 
			TokenInformationClass TokenInformationClass, 
			LPVOID TokenInformation, 
			DWORD TokenInformationLength, 
			out DWORD ReturnLength);
 public static extern bool GetTokenInformation(
     [In] AccessTokenHandle accessTokenHandle,
     [In] TokenInformationClass tokenInformationClass,
     [Out] IntPtr tokenInformation,
     [In] int tokenInformationLength,
     [In, Out] ref int returnLength);
Esempio n. 42
0
        public unsafe SidAndAttributes[] GetGroupsTokenInformation(TokenInformationClass tokenInformationClass)
        {
            if (tokenInformationClass != TokenInformationClass.TokenGroups &&
                tokenInformationClass != TokenInformationClass.TokenRestrictedSids &&
                tokenInformationClass != TokenInformationClass.TokenLogonSid &&
                tokenInformationClass != TokenInformationClass.TokenCapabilities &&
                tokenInformationClass != TokenInformationClass.TokenDeviceGroups &&
                tokenInformationClass != TokenInformationClass.TokenRestrictedDeviceGroups)
            {
                throw new ArgumentException(string.Format("{0} is not a valid Group token information class", tokenInformationClass), "tokenInformationClass");
            }

            int tokenSize;
            if (!NativeMethods.GetTokenInformation(handle, tokenInformationClass, IntPtr.Zero, 0, out tokenSize) &&
                Marshal.GetLastWin32Error() != (int)SystemErrorCode.ErrorInsufficientBuffer)
            {
                ErrorHelper.ThrowCustomWin32Exception();
            }

            IntPtr tokenInformationPtr = Marshal.AllocHGlobal(tokenSize);
            try
            {
                if (!NativeMethods.GetTokenInformation(handle, tokenInformationClass, tokenInformationPtr, tokenSize, out tokenSize))
                {
                    ErrorHelper.ThrowCustomWin32Exception();
                }
                var groupStructure = (NativeTokenGroups)Marshal.PtrToStructure(tokenInformationPtr, typeof(NativeTokenGroups));
                IntPtr offset = Marshal.OffsetOf(typeof(NativeTokenGroups), "Groups");
                var groups = new SidAndAttributes[groupStructure.GroupCount];
                long start = new IntPtr(tokenInformationPtr.ToInt64() + offset.ToInt64()).ToInt64();
                for (int i = 0; i < groupStructure.GroupCount; i++)
                {
                    var arrayElementPtr = new IntPtr(start + i * sizeof(NativeSidAndAttributes));
                    var group = (NativeSidAndAttributes)Marshal.PtrToStructure(arrayElementPtr, typeof(NativeSidAndAttributes));
                    groups[i] = new SidAndAttributes(group.Attributes, group.Sid);
                }
                return groups;
            }
            finally
            {
                Marshal.FreeHGlobal(tokenInformationPtr);
            }
        }