コード例 #1
0
        public static int LogOnInteractiveUser([NotNull] this NetworkCredential credential, out SafeTokenHandle userToken)
        {
            Contract.Requires(credential != null);
            Contract.Ensures((Contract.Result<int>() != 0) || (Contract.ValueAtReturn(out userToken) != null));

            return LogOnInteractiveUser(credential.UserName, credential.Domain, credential.Password, out userToken);
        }
コード例 #2
0
        public static int LogOnInteractiveUser(string userName, string domain, string password, out SafeTokenHandle userToken)
        {
            Contract.Ensures((Contract.Result<int>() != 0) || (Contract.ValueAtReturn(out userToken) != null));

            ParseUserDomain(ref userName, ref domain);

            IntPtr pUserToken;
            if (NativeMethods.LogonUser(userName, domain, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, out pUserToken))
            {
                userToken = new SafeTokenHandle(pUserToken);
                return 0;
            }

            userToken = null;
            var error = Marshal.GetHRForLastWin32Error();
            return error == 0 ? E_FAIL : error;
        }
コード例 #3
0
 public static extern bool GetTokenInformation(SafeTokenHandle hToken, TOKEN_INFORMATION_CLASS tokenInfoClass, IntPtr pTokenInfo, int tokenInfoLength, out int returnLength);
コード例 #4
0
 public static extern bool DuplicateToken(SafeTokenHandle existingTokenHandle, SECURITY_IMPERSONATION_LEVEL impersonationLevel, out IntPtr duplicateTokenHandle);
コード例 #5
0
        public static int GetProcessIntegrityLevel()
        {
            IntPtr phToken;
            // Open the access token of the current process with TOKEN_QUERY.
            if (!NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_QUERY, out phToken))
            {
                throw new Win32Exception();
            }

            using (var hToken = new SafeTokenHandle(phToken))
            {
                // Then we must query the size of the integrity level information 
                // associated with the token. Note that we expect GetTokenInformation 
                // to return false with the ERROR_INSUFFICIENT_BUFFER error code 
                // because we've given it a null buffer. On exit cbTokenIntegrityLevel will tell 
                // the size of the group information.
                int cbTokenIntegrityLevel;
                if (!NativeMethods.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, IntPtr.Zero, 0, out cbTokenIntegrityLevel))
                {
                    var error = Marshal.GetLastWin32Error();
                    if (error != ERROR_INSUFFICIENT_BUFFER)
                    {
                        // When the process is run on operating systems prior to 
                        // Windows Vista, GetTokenInformation returns false with the 
                        // ERROR_INVALID_PARAMETER error code because 
                        // TokenIntegrityLevel is not supported on those OS's.
                        throw new Win32Exception(error);
                    }
                }

                // Now we allocate a buffer for the integrity level information.
                using (var pTokenIntegrityLevel = new SafeNativeMemory<TOKEN_MANDATORY_LABEL>(cbTokenIntegrityLevel))
                {
                    // Now we ask for the integrity level information again. This may fail 
                    // if an administrator has added this account to an additional group 
                    // between our first call to GetTokenInformation and this one.
                    if (!NativeMethods.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, pTokenIntegrityLevel))
                    {
                        throw new Win32Exception();
                    }

                    // Marshal the TOKEN_MANDATORY_LABEL struct from native to .NET object.
                    var tokenIntegrityLevel = (TOKEN_MANDATORY_LABEL)pTokenIntegrityLevel;

                    // Integrity Level SIDs are in the form of S-1-16-0xXXXX. (e.g. 
                    // S-1-16-0x1000 stands for low integrity level SID). There is one 
                    // and only one sub-authority.
                    var pIntegrityLevel = NativeMethods.GetSidSubAuthority(tokenIntegrityLevel.Label.Sid, 0);
                    return Marshal.ReadInt32(pIntegrityLevel);
                }
            }
        }
コード例 #6
0
        public static bool IsProcessElevated()
        {
            IntPtr phToken;

            // Open the access token of the current process with TOKEN_QUERY.
            if (!NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_QUERY, out phToken))
            {
                throw new Win32Exception();
            }

            using (var hToken = new SafeTokenHandle(phToken))
            {
                // Allocate a buffer for the elevation information.
                using (var pTokenElevation = new SafeNativeMemory<TOKEN_ELEVATION>())
                {
                    // Retrieve token elevation information.
                    if (!NativeMethods.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevation, pTokenElevation))
                    {
                        // When the process is run on operating systems prior to Windows 
                        // Vista, GetTokenInformation returns false with the error code 
                        // ERROR_INVALID_PARAMETER because TokenElevation is not supported 
                        // on those operating systems.
                        if ((Marshal.GetLastWin32Error() & 0xFFFF) == ERROR_INVALID_PARAMETER)
                        {
                            // => so on XP we are always "Elevated"!
                            return true;
                        }

                        throw new Win32Exception();
                    }

                    // Marshal the TOKEN_ELEVATION struct from native to .NET object.
                    var elevation = (TOKEN_ELEVATION)pTokenElevation;

                    // TOKEN_ELEVATION.TokenIsElevated is a non-zero value if the token 
                    // has elevated privileges; otherwise, a zero value.
                    return (elevation.TokenIsElevated != 0);
                }
            }
        }
コード例 #7
0
        /// <summary>
        /// The function checks whether the object associated with the access token belongs
        /// to a user account that is a member of the local Administrators group, even if
        /// it currently is not elevated.
        /// </summary>
        /// <param name="userToken">The user token.</param>
        /// <returns>
        /// Returns true if the object associated with the access token belongs to user
        /// account that is a member of the local Administrators group. Returns false
        /// if the token does not.
        /// </returns>
        /// <exception cref="Win32Exception">
        /// </exception>
        /// <exception cref="System.ComponentModel.Win32Exception">When any native Windows API call fails, the function throws a Win32Exception with the last error code.</exception>
        public static bool IsUserInAdminGroup([NotNull] SafeTokenHandle userToken)
        {
            Contract.Requires(userToken != null);

            // Determine whether system is running Windows Vista or later operating 
            // systems (major version >= 6) because they support linked tokens, but 
            // previous versions (major version < 6) do not.
            var version = Environment.OSVersion.Version;
            
            if ((version != null) && (version.Major >= 6))
            {
                // Running Windows Vista or later (major version >= 6). 
                // Determine token type: limited, elevated, or default. 

                // Allocate a buffer for the elevation type information.
                using (var pElevationType = new SafeNativeMemory(sizeof(TOKEN_ELEVATION_TYPE)))
                {
                    // Retrieve token elevation type information.
                    if (!NativeMethods.GetTokenInformation(userToken, TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType))
                    {
                        throw new Win32Exception();
                    }

                    // Marshal the TOKEN_ELEVATION_TYPE enum from native to .NET.
                    var elevType = pElevationType.ReadInt32().ToEnum<TOKEN_ELEVATION_TYPE>();

                    // If limited, get the linked elevated token for further check.
                    if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
                    {
                        // Allocate a buffer for the linked token.
                        using (var pLinkedToken = new SafeNativeMemory(IntPtr.Size))
                        {
                            // Get the linked token.
                            if (!NativeMethods.GetTokenInformation(userToken, TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken))
                            {
                                throw new Win32Exception();
                            }

                            // Marshal the linked token value from native to .NET.
                            var hLinkedToken = pLinkedToken.ReadIntPtr();
                            using (var linkedToken = new SafeTokenHandle(hLinkedToken))
                            {
                                return IsAdministrator(linkedToken);
                            }
                        }
                    }
                }
            }

            // CheckTokenMembership requires an impersonation token. If we just got 
            // a linked token, it already is an impersonation token.  If we did not 
            // get a linked token, duplicate the original into an impersonation 
            // token for CheckTokenMembership.
            IntPtr phTokenToCheck;

            if (!NativeMethods.DuplicateToken(userToken, SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, out phTokenToCheck))
            {
                throw new Win32Exception();
            }

            using (var hTokenToCheck = new SafeTokenHandle(phTokenToCheck))
            {
                // Check if the token to be checked contains admin SID.
                return IsAdministrator(hTokenToCheck);
            }
        }
コード例 #8
0
        /// <summary>
        /// The function checks whether the primary access token of the process belongs 
        /// to a user account that is a member of the local Administrators group, even if 
        /// it currently is not elevated.
        /// </summary>
        /// <returns>
        /// Returns true if the primary access token of the process belongs to user 
        /// account that is a member of the local Administrators group. Returns false 
        /// if the token does not.
        /// </returns>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// When any native Windows API call fails, the function throws a Win32Exception with the last error code.
        /// </exception>
        public static bool IsCurrentUserInAdminGroup()
        {
            IntPtr phToken;

            // Open the access token of the current process for query and duplicate.
            if (!NativeMethods.OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_QUERY | TOKEN_DUPLICATE, out phToken))
            {
                throw new Win32Exception();
            }

            using (var hToken = new SafeTokenHandle(phToken))
            {
                return IsUserInAdminGroup(hToken);
            }
        }