Beispiel #1
0
        public static bool IsProcessElevated(IntPtr handle)
        {
            if (!IsUacEnabled)
            {
                WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                return(principal.IsInRole(WindowsBuiltInRole.Administrator));
            }

            if (!OpenProcessToken(handle, TOKEN_READ, out IntPtr tokenHandle))
            {
                throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
            }

            TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

            int    elevationResultSize = Marshal.SizeOf((int)elevationResult);
            IntPtr elevationTypePtr    = Marshal.AllocHGlobal(elevationResultSize);
            bool   success             = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out _);

            if (!success)
            {
                throw new ApplicationException("Unable to determine the current elevation.");
            }

            elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
            return(elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull);
        }
Beispiel #2
0
        public static bool IsRunningVistaProtectedMode()
        {
            if (!VistaTools.IsReallyVista())
            {
                return(false);                // It wasn't Vista
            }
            //if (!VistaTools.IsElevated())
            //	return false; // We're elevated, so no protected mode

            TOKEN_ELEVATION_TYPE type = VistaTools.GetElevationType();

            switch (type)
            {
            case TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault:
                return(false);

            case TOKEN_ELEVATION_TYPE.TokenElevationTypeFull:
                return(false);

            case TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited:
                return(true);

            default:
                throw new NotImplementedException();
            }
        }
Beispiel #3
0
        public static bool IsProcessElevated()
        {
            CheckEnviroment();

            if (IsUACEnabled())
            {
                IntPtr tokenHandle      = IntPtr.Zero;
                IntPtr elevationTypePtr = IntPtr.Zero;
                Int32  win32Err;
                try
                {
                    if (!OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out tokenHandle))
                    {
                        win32Err = Marshal.GetLastWin32Error();
                        throw new ApplicationException("Could not get process token.  Win32 Error Code: " + win32Err.ToString("X"));
                    }

                    TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

                    int  elevationResultSize = Marshal.SizeOf(Enum.GetUnderlyingType(typeof(TOKEN_ELEVATION_TYPE)));
                    uint returnedSize        = 0;
                    elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);

                    bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                    if (success)
                    {
                        elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                        bool isProcessElevated = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
                        return(isProcessElevated);
                    }
                    else
                    {
                        win32Err = Marshal.GetLastWin32Error();
                        throw new ApplicationException("Unable to determine the current elevation: " + win32Err.ToString("X"));
                    }
                }
                finally
                {
                    if (tokenHandle != IntPtr.Zero)
                    {
                        CloseHandle(tokenHandle);
                    }
                    if (elevationTypePtr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(elevationTypePtr);
                    }
                }
            }
            else
            {
                using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
                {
                    WindowsPrincipal principal = new WindowsPrincipal(identity);
                    bool             result    = principal.IsInRole(WindowsBuiltInRole.Administrator) ||
                                                 principal.IsInRole(0x200); //Domain Administrator
                    return(result);
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Returns information about process elevation
        /// </summary>
        /// <param name="processHandle">target process id</param>
        /// <returns>true if elevated, null if unknown</returns>
        public static bool?IsProcessElevated(IntPtr processHandle)
        {
            if (processHandle == IntPtr.Zero)
            {
                return(null);
            }

            IntPtr tokenHandle = IntPtr.Zero;

            if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_READ, out tokenHandle))
            {
                return(null);
            }

            try
            {
                TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

                int  elevationResultSize = Marshal.SizeOf((int)elevationResult);
                uint returnedSize        = 0;

                IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
                try
                {
                    bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType,
                                                       elevationTypePtr, (uint)elevationResultSize,
                                                       out returnedSize);
                    if (success)
                    {
                        elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                        bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
                        return(isProcessAdmin);
                    }
                    else
                    {
                        return(null);
                    }
                }
                finally
                {
                    if (elevationTypePtr != IntPtr.Zero)
                    {
                        Marshal.FreeHGlobal(elevationTypePtr);
                    }
                }
            }
            finally
            {
                if (tokenHandle != IntPtr.Zero)
                {
                    CloseHandle(tokenHandle);
                }
            }
        }
Beispiel #5
0
        /// <summary>
        /// TokenElevationTypeDefault - User is not using a "split" token.
        ///This value indicates that either UAC is disabled, or the process is started
        ///by a standard user (not a member of the Administrators group).

        ///The following two values can be returned only if both the UAC is enabled and
        ///the user is a member of the Administrator's group (that is, the user has a "split" token):

        ///TokenElevationTypeFull - the process is running elevated.

        ///TokenElevationTypeLimited - the process is not running elevated.
        /// </summary>
        /// <returns>TokenElevationType</returns>
        internal static TOKEN_ELEVATION_TYPE GetElevationType()
        {
            if (!IsReallyVista())
            {
                throw new VistaToolsException("Function requires Vista or higher");
            }

            bool   bRetVal  = false;
            IntPtr hToken   = IntPtr.Zero;
            IntPtr hProcess = GetCurrentProcess();

            if (hProcess == IntPtr.Zero)
            {
                throw new VistaToolsException("Error getting current process handle");
            }

            bRetVal = OpenProcessToken(hProcess, TOKEN_QUERY, out hToken);


            if (!bRetVal)
            {
                throw new VistaToolsException("Error opening process token");
            }
            try
            {
                TOKEN_ELEVATION_TYPE tet = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

                UInt32 dwReturnLength = 0;
                UInt32 tetSize        = (uint)System.Runtime.InteropServices.Marshal.SizeOf((int)tet);
                IntPtr tetPtr         = Marshal.AllocHGlobal((int)tetSize);
                try
                {
                    bRetVal = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, tetPtr, tetSize, out dwReturnLength);

                    if ((!bRetVal) | (tetSize != dwReturnLength))
                    {
                        throw new VistaToolsException("Error getting token information");
                    }

                    tet = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tetPtr);
                }
                finally
                {
                    Marshal.FreeHGlobal(tetPtr);
                }

                return(tet);
            }
            finally
            {
                CloseHandle(hToken);
            }
        }
Beispiel #6
0
            /// <summary>
            /// The function checks whether the primary access token of the process belongs
            /// to 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 IsUserInAdminGroup()
            {
                bool            fInAdminGroup = false;
                SafeTokenHandle hTokenToCheck = null;

                // Open the access token of the current process for query and duplicate.
                SafeTokenHandle hToken = SafeTokenHandle.FromCurrentProcess(AccessTypes.TokenQuery | AccessTypes.TokenDuplicate);

                // 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.
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    // Running Windows Vista or later (major version >= 6).
                    // Determine token type: limited, elevated, or default.

                    // Marshal the TOKEN_ELEVATION_TYPE enum from native to .NET.
                    TOKEN_ELEVATION_TYPE elevType = hToken.GetInfo <TOKEN_ELEVATION_TYPE>(TOKEN_INFORMATION_CLASS.TokenElevationType);

                    // If limited, get the linked elevated token for further check.
                    if (elevType == TOKEN_ELEVATION_TYPE.Limited)
                    {
                        // Marshal the linked token value from native to .NET.
                        IntPtr hLinkedToken = hToken.GetInfo <IntPtr>(TOKEN_INFORMATION_CLASS.TokenLinkedToken);
                        hTokenToCheck = new SafeTokenHandle(hLinkedToken);
                    }
                }

                // 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.
                if (hTokenToCheck == null)
                {
                    if (!NativeMethods.DuplicateToken(hToken, SECURITY_IMPERSONATION_LEVEL.Identification, out hTokenToCheck))
                    {
                        throw new Win32Exception();
                    }
                }

                // Check if the token to be checked contains admin SID.
                WindowsIdentity  id        = new WindowsIdentity(hTokenToCheck.DangerousGetHandle());
                WindowsPrincipal principal = new WindowsPrincipal(id);

                fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator);

                return(fInAdminGroup);
            }
        public static bool HasAdministratorAuthorization()
        {
            if (IsAdministrator())
            {
                return(true);
            }

            TOKEN_ELEVATION_TYPE type = GetTokenElevationType();

            if (type == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
            {
                return(false);
            }

            return(true);
        }
Beispiel #8
0
        public static int IsProcessElevated_ID(int procid)
        {
            if (IsUacEnabled)
            {
                IntPtr tokenHandle = new IntPtr();

                try {
                    if (!OpenProcessToken(Process.GetProcessById(procid).Handle, TOKEN_READ, out tokenHandle))
                    {
                        throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
                    }
                }
                catch {
                    return(99);
                }

                TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

                int    elevationResultSize = Marshal.SizeOf((int)elevationResult);
                uint   returnedSize        = 0;
                IntPtr elevationTypePtr    = Marshal.AllocHGlobal(elevationResultSize);

                bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                if (success)
                {
                    elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                    bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
                    return(isProcessAdmin ? 1 : 0);
                }
                else
                {
                    try {
                        throw new ApplicationException("Unable to determine the current elevation.");
                    }
                    catch {
                        return(99);
                    }
                }
            }
            else
            {
                WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                bool             result    = principal.IsInRole(WindowsBuiltInRole.Administrator);
                return(result ? 1 : 0);
            }
        }
Beispiel #9
0
#pragma warning restore

        /// <summary>
        /// Check UAC elevated (for Windows).
        /// </summary>
        private static bool CheckUAC()
        {
            TOKEN_ELEVATION_TYPE tet = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;
            uint   tetSize           = (uint)Marshal.SizeOf((int)tet);
            IntPtr tetPtr            = Marshal.AllocHGlobal((int)tetSize);

            try
            {
                if (GetTokenInformation(WindowsIdentity.GetCurrent().Token, TOKEN_INFORMATION_CLASS.TokenElevationType, tetPtr, tetSize, out _))
                {
                    tet = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tetPtr);
                }
            }
            finally
            {
                Marshal.FreeHGlobal(tetPtr);
            }

            return(tet == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull);
        }
Beispiel #10
0
        /// <summary>
        /// Get elevation type.
        /// </summary>
        /// <returns>TokenElevationType</returns>
        public static TOKEN_ELEVATION_TYPE GetElevationType()
        {
            bool   bRetVal  = false;
            IntPtr hToken   = IntPtr.Zero;
            IntPtr hProcess = NativeMethods.GetCurrentProcess();

            if (hProcess == IntPtr.Zero)
            {
                throw new ApplicationException("Error getting current process handle");
            }
            bRetVal = NativeMethods.OpenProcessToken(hProcess, WinNT.TOKEN_QUERY, out hToken);
            if (!bRetVal)
            {
                throw new ApplicationException("Error opening process token");
            }
            try
            {
                TOKEN_ELEVATION_TYPE tet = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;
                UInt32 dwReturnLength    = 0;
                UInt32 tetSize           = (uint)Marshal.SizeOf((int)tet);
                IntPtr tetPtr            = Marshal.AllocHGlobal((int)tetSize);
                try
                {
                    bRetVal = NativeMethods.GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, tetPtr, tetSize, out dwReturnLength);
                    if ((!bRetVal) | (tetSize != dwReturnLength))
                    {
                        throw new ApplicationException("Error getting token information");
                    }
                    tet = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tetPtr);
                }
                finally
                {
                    Marshal.FreeHGlobal(tetPtr);
                }
                return(tet);
            }
            finally
            {
                NativeMethods.CloseHandle(hToken);
            }
        }
Beispiel #11
0
        public static bool IsUacEnabled()
        {
            IntPtr hProcess = GetCurrentProcess();
            IntPtr hToken   = OpenProcessTokenNet(hProcess, TOKEN_QUERY);

            try
            {
                TOKEN_ELEVATION_TYPE elevationType = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;
                uint   dwReturnLength = 0;
                uint   size           = (uint)Marshal.SizeOf((int)elevationType);
                IntPtr pElevationType = Marshal.AllocHGlobal((int)size);
                try
                {
                    GetTokenInformationNet(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType,
                                           pElevationType, size, out dwReturnLength);
                    if (dwReturnLength != size)
                    {
                        throw new System.ComponentModel.Win32Exception("Returned length was incorrect");
                    }
                    elevationType = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(pElevationType);
                }
                finally
                {
                    Marshal.FreeHGlobal(pElevationType);
                }

                if (elevationType == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull ||
                    elevationType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            finally
            {
                CloseHandleNet(hToken);
            }
        }
Beispiel #12
0
        /// <summary>
        /// 昇格トークンの種類を取得する
        /// </summary>
        /// <returns>昇格トークンの種類を示すTOKEN_ELEVATION_TYPE。
        /// 取得に失敗した時でもTokenElevationTypeDefaultを返す。</returns>
        public static TOKEN_ELEVATION_TYPE GetTokenElevationType()
        {
            TOKEN_ELEVATION_TYPE returnValue =
                TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

            //Windows Vista以上か確認
            if (Environment.OSVersion.Platform != PlatformID.Win32NT ||
                Environment.OSVersion.Version.Major < 6)
            {
                return(returnValue);
            }

            TOKEN_ELEVATION_TYPE tet =
                TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;
            uint   returnLength = 0;
            uint   tetSize      = (uint)Marshal.SizeOf((int)tet);
            IntPtr tetPtr       = Marshal.AllocHGlobal((int)tetSize);

            try
            {
                //アクセストークンに関する情報を取得
                if (GetTokenInformation(
                        System.Security.Principal.WindowsIdentity.GetCurrent().Token,
                        TOKEN_INFORMATION_CLASS.TokenElevationType,
                        tetPtr, tetSize, out returnLength))
                {
                    //結果を取得
                    returnValue = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(tetPtr);
                }
            }
            finally
            {
                //解放する
                Marshal.FreeHGlobal(tetPtr);
            }

            return(returnValue);
        }
        public bool?IsElevated()
        {
            if (Marshal.GetLastWin32Error() == 5)
            {
                //access denied
                return(null);
                //throw new UnauthorizedAccessException();
            }

            MySafeHandle tokenHandle;

            if (!Win32Api.OpenProcessToken(_pHandle, Win32Api.TOKEN_READ, out tokenHandle))
            {
                return(null);
                //throw new ApplicationException("Could not get process token.  Win32 Error Code: " + Marshal.GetLastWin32Error());
            }

            TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

            int    elevationResultSize = Marshal.SizeOf((int)elevationResult);
            uint   returnedSize        = 0;
            IntPtr elevationTypePtr    = Marshal.AllocHGlobal(elevationResultSize);

            bool success = Win32Api.GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);

            if (success)
            {
                elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
                return(isProcessAdmin);
            }
            else
            {
                throw new ApplicationException("Unable to determine the current elevation.");
            }
        }
Beispiel #14
0
        public static bool IsProcessElevated(IntPtr handle)
        {
            if (IsUacEnabled)
            {
                IntPtr tokenHandle;
                if (!OpenProcessToken(handle, TOKEN_READ, out tokenHandle))
                {
                    return(false);
                }

                TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

                int    elevationResultSize = Marshal.SizeOf((int)elevationResult);
                uint   returnedSize        = 0;
                IntPtr elevationTypePtr    = Marshal.AllocHGlobal(elevationResultSize);

                bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, (uint)elevationResultSize, out returnedSize);
                if (success)
                {
                    elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                    bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
                    return(isProcessAdmin);
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                bool             result    = principal.IsInRole(WindowsBuiltInRole.Administrator);
                return(result);
            }
        }
Beispiel #15
0
 public static extern bool GetTokenInformation(
     IntPtr TokenHandle,
     TOKEN_INFORMATION_CLASS TokenInformationClass,
     out TOKEN_ELEVATION_TYPE TokenInformation,
     uint TokenInformationLength,
     out uint ReturnLength);
Beispiel #16
0
        private void GetElevatedToken(ref IntPtr hToken, bool elevate)
        {         // get linked token from unelevated token
            TOKEN_ELEVATION_TYPE requestedElevation = TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited;

            if (!elevate)
            {
                requestedElevation = TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
            }

            uint   dwSize           = (uint)sizeof(TOKEN_ELEVATION_TYPE);
            IntPtr TokenInformation = Marshal.AllocHGlobal((int)dwSize);

            // retrieve information "TokenElevationType" for token hToken
            if (GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, TokenInformation, dwSize, out dwSize))
            {
                TOKEN_ELEVATION_TYPE currentElevation = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(TokenInformation);
                if (currentElevation == requestedElevation)
                {                 // UAC enabled and linked token exist. Token has not the requested state so we must retrieve linked token
                    WriteVerboseToLog("Token has not the desired elevation state, retrieving linked token.");

                    TOKEN_LINKED_TOKEN linkedToken;
                    linkedToken.LinkedToken = IntPtr.Zero;
                    dwSize = (uint)Marshal.SizeOf(linkedToken);

                    // we have to hand unmanaged memory to GetTokenInformation, so we have to marshal
                    IntPtr tokenBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(linkedToken));
                    Marshal.StructureToPtr(linkedToken, tokenBuffer, false);

                    if (GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenLinkedToken, tokenBuffer, dwSize, out dwSize))
                    {                     // retrieve linked token
                        // token is stored in unmanaged memory, convert to managed
                        linkedToken = (TOKEN_LINKED_TOKEN)Marshal.PtrToStructure(tokenBuffer, typeof(TOKEN_LINKED_TOKEN));

                        IntPtr hElevated;
                        if (DuplicateTokenEx(linkedToken.LinkedToken, 0, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hElevated))
                        {                         // linked token successfully duplicated, free original token and return linked token
                            CloseHandle(hToken);
                            hToken = hElevated;
                            WriteVerboseToLog("Successfully gained elevated token.");
                        }

                        // close handle
                        CloseHandle(linkedToken.LinkedToken);
                    }
                    else
                    {
                        WriteVerboseToLog("Could not retrieve linked token. Error: " + Marshal.GetLastWin32Error().ToString());
                    }

                    // Free the unmanaged memory
                    Marshal.FreeHGlobal(tokenBuffer);
                }
                else
                {                 // UAC enabled and token has the desired state
                    if (currentElevation == TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault)
                    {             // UAC disabled or token is not administrative or token belongs to LOCALSYSTEM
                        WriteVerboseToLog("Cannot change elevation: UAC is disabled or token is not administrative or token belongs to LOCALSYSTEM.");
                    }
                    else
                    {                     // token already has the desired state, nothing to do
                        WriteVerboseToLog("Token already has the desired elevation state.");
                    }
                }
            }
            else
            {             // Error getting information on token
                WriteVerboseToLog("Could not get token information. Error: " + Marshal.GetLastWin32Error().ToString());
            }

            // Free the unmanaged memory.
            Marshal.FreeHGlobal(TokenInformation);
        }
Beispiel #17
0
        /// <summary>
        /// 即使在还没有为当前用户提升权限的前提下,此函数检测拥有此进程的主访
        /// 问令牌的用户是否是本地管理员组的成员。
        /// </summary>
        /// <returns>
        /// 如果拥有主访问令牌的用户是管理员组成员则返回TRUE,反之则返回FALSE。
        /// </returns>
        /// <exception cref="System.ComponentModel.Win32Exception">
        /// 如果任何原生的Windows API函数出错,此函数会抛出一个包含最后错误代码的Win32Exception。
        /// </exception>
        internal bool IsUserInAdminGroup()
        {
            bool            fInAdminGroup  = false;
            SafeTokenHandle hToken         = null;
            SafeTokenHandle hTokenToCheck  = null;
            IntPtr          pElevationType = IntPtr.Zero;
            IntPtr          pLinkedToken   = IntPtr.Zero;
            int             cbSize         = 0;

            try
            {
                // 打开此进程的主访问令牌(使用TOKEN_QUERY | TOKEN_DUPLICATE)
                if (!NativeMethod.OpenProcessToken(Process.GetCurrentProcess().Handle,
                                                   NativeMethod.TOKEN_QUERY | NativeMethod.TOKEN_DUPLICATE, out hToken))
                {
                    throw new Win32Exception();
                }

                // 检测是否此系统是Windows Vista或后续版本(主版本号 >= 6)。这是由于自
                // Windows Vista开始支持链接令牌(LINKED TOKEN),而之前的版本不支持。
                // (主版本 < 6)
                if (Environment.OSVersion.Version.Major >= 6)
                {
                    // 运行于Windows Vista 或后续版本(主版本 >= 6).
                    // 检测令牌类型:受限(limited),(已提升)elevated,
                    // 或者默认(default)

                    // 为提升类别信息对象分配内存
                    cbSize         = sizeof(TOKEN_ELEVATION_TYPE);
                    pElevationType = Marshal.AllocHGlobal(cbSize);
                    if (pElevationType == IntPtr.Zero)
                    {
                        throw new Win32Exception();
                    }

                    // 获取令牌提升类别信息
                    if (!NativeMethod.GetTokenInformation(hToken,
                                                          TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType,
                                                          cbSize, out cbSize))
                    {
                        throw new Win32Exception();
                    }

                    // 转换TOKEN_ELEVATION_TYPE枚举类型(从原生到.Net)
                    TOKEN_ELEVATION_TYPE elevType = (TOKEN_ELEVATION_TYPE)
                                                    Marshal.ReadInt32(pElevationType);

                    // 如果为受限的,获取相关联的已提升令牌以便今后使用。
                    if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
                    {
                        // 为连接令牌分配内存
                        cbSize       = IntPtr.Size;
                        pLinkedToken = Marshal.AllocHGlobal(cbSize);
                        if (pLinkedToken == IntPtr.Zero)
                        {
                            throw new Win32Exception();
                        }

                        // 获取连接令牌
                        if (!NativeMethod.GetTokenInformation(hToken,
                                                              TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken,
                                                              cbSize, out cbSize))
                        {
                            throw new Win32Exception();
                        }

                        // 转换连接令牌的值(从原生到.Net)
                        IntPtr hLinkedToken = Marshal.ReadIntPtr(pLinkedToken);
                        hTokenToCheck = new SafeTokenHandle(hLinkedToken);
                    }
                }

                // CheckTokenMembership要求一个伪装令牌。如果我们仅得到一个链接令牌,那
                // 它就是一个伪装令牌。如果我们没有得到一个关联式令牌,我们需要复制当前
                // 令牌以便得到一个伪装令牌。
                if (hTokenToCheck == null)
                {
                    if (!NativeMethod.DuplicateToken(hToken,
                                                     SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                                                     out hTokenToCheck))
                    {
                        throw new Win32Exception();
                    }
                }

                // 检测是否被检测的令牌包含管理员组SID
                WindowsIdentity  id        = new WindowsIdentity(hTokenToCheck.DangerousGetHandle());
                WindowsPrincipal principal = new WindowsPrincipal(id);
                fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            finally
            {
                // 集中清理所有已分配的内存资源
                if (hToken != null)
                {
                    hToken.Close();
                    hToken = null;
                }
                if (hTokenToCheck != null)
                {
                    hTokenToCheck.Close();
                    hTokenToCheck = null;
                }
                if (pElevationType != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pElevationType);
                    pElevationType = IntPtr.Zero;
                }
                if (pLinkedToken != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pLinkedToken);
                    pLinkedToken = IntPtr.Zero;
                }
            }

            return(fInAdminGroup);
        }
Beispiel #18
0
        public static bool CheckProcessElevated()
        {
            if (CheckUAC())
            {
                IntPtr tokenHandle = IntPtr.Zero;
                if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_QUERY, out tokenHandle))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not get process token.");
                }

                try
                {
                    uint returnedSize = sizeof(TOKEN_ELEVATION_TYPE);

                    IntPtr elevationTypePtr = Marshal.AllocHGlobal((int)returnedSize);
                    try
                    {
                        if (GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType, elevationTypePtr, returnedSize, out returnedSize))
                        {
                            TOKEN_ELEVATION_TYPE elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                            switch (elevationResult)
                            {
                            case TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault:
                                //Token is not split; if user is admin, we're admin.
                                WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                                return(principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200));    //Domain Administrator

                            case TOKEN_ELEVATION_TYPE.TokenElevationTypeFull:
                                //Token is split, but we're admin.
                                return(true);

                            case TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited:
                                //Token is split, and we're limited.
                                return(false);

                            default:
                                throw new Exception("Unknown elevation type!");
                            }
                        }
                        else
                        {
                            throw new ApplicationException("Unable to determine the current elevation.");
                        }
                    }
                    finally
                    {
                        if (elevationTypePtr != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(elevationTypePtr);
                        }
                    }
                }
                finally
                {
                    if (tokenHandle != IntPtr.Zero)
                    {
                        CloseHandle(tokenHandle);
                    }
                }
            }
            else
            {
                WindowsPrincipal principal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
                return(principal.IsInRole(WindowsBuiltInRole.Administrator) || principal.IsInRole(0x200)); //Domain Administrator
            }
        }
Beispiel #19
0
        public static bool IsProcessElevated(this Process process)
        {
            if (IsUacEnabled)
            {
                IntPtr tokenHandle = IntPtr.Zero;
                // next line will throw access denied if process is elevated (and calling process isn't)
                try
                {
                    if (!OpenProcessToken(process.Handle, TOKEN_READ, out tokenHandle))
                    {
                        throw new ApplicationException("Could not get process token.  Win32 Error Code: " +
                                                       Marshal.GetLastWin32Error());
                    }
                }
                // code smell?
                catch (System.ComponentModel.Win32Exception ex)
                {
                    if (ex.NativeErrorCode == 5)
                    {
                        return(true);
                    }                                             // 5 == ACCESS_DENIED
                }

                try
                {
                    TOKEN_ELEVATION_TYPE elevationResult = TOKEN_ELEVATION_TYPE.TokenElevationTypeDefault;

                    //int elevationResultSize = Marshal.SizeOf(typeof(TOKEN_ELEVATION_TYPE)); // doesn't work in .Net 4.5
                    int  elevationResultSize = Marshal.SizeOf((int)elevationResult);
                    uint returnedSize        = 0;

                    IntPtr elevationTypePtr = Marshal.AllocHGlobal(elevationResultSize);
                    try
                    {
                        bool success = GetTokenInformation(tokenHandle, TOKEN_INFORMATION_CLASS.TokenElevationType,
                                                           elevationTypePtr, (uint)elevationResultSize,
                                                           out returnedSize);
                        if (success)
                        {
                            elevationResult = (TOKEN_ELEVATION_TYPE)Marshal.ReadInt32(elevationTypePtr);
                            bool isProcessAdmin = elevationResult == TOKEN_ELEVATION_TYPE.TokenElevationTypeFull;
                            return(isProcessAdmin);
                        }
                        else
                        {
                            throw new ApplicationException("Unable to determine the current elevation.");
                        }
                    }
                    finally
                    {
                        if (elevationTypePtr != IntPtr.Zero)
                        {
                            Marshal.FreeHGlobal(elevationTypePtr);
                        }
                    }
                }
                finally
                {
                    if (tokenHandle != IntPtr.Zero)
                    {
                        CloseHandle(tokenHandle);
                    }
                }
            }
            else
            {
                WindowsIdentity  identity  = WindowsIdentity.GetCurrent();
                WindowsPrincipal principal = new WindowsPrincipal(identity);
                bool             result    = principal.IsInRole(WindowsBuiltInRole.Administrator) ||
                                             principal.IsInRole(0x200); //Domain Administrator
                return(result);
            }
        }
Beispiel #20
0
 public static extern bool GetTokenInformation(
     IntPtr TokenHandle,
     TOKEN_INFORMATION_CLASS TokenInformationClass,
     out TOKEN_ELEVATION_TYPE TokenInformation,
     uint TokenInformationLength,
     out uint ReturnLength);
Beispiel #21
0
        internal bool IsUserInAdminGroup()
        {
            fInAdminGroup = false;

            SafeTokenHandle hToken         = null;
            SafeTokenHandle hTokenToCheck  = null;
            IntPtr          pElevationType = IntPtr.Zero;
            IntPtr          pLinkedToken   = IntPtr.Zero;
            int             cbSize         = 0;

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

                // 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.
                if (Environment.OSVersion.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.
                    cbSize         = sizeof(TOKEN_ELEVATION_TYPE);
                    pElevationType = Marshal.AllocHGlobal(cbSize);
                    if (pElevationType == IntPtr.Zero)
                    {
                        throw new Win32Exception();
                    }

                    // Retrieve token elevation type information.
                    if (!NativeMethods.GetTokenInformation(hToken,
                                                           TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType,
                                                           cbSize, out cbSize))
                    {
                        throw new Win32Exception();
                    }

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

                    // If limited, get the linked elevated token for further check.
                    if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
                    {
                        // Allocate a buffer for the linked token.
                        cbSize       = IntPtr.Size;
                        pLinkedToken = Marshal.AllocHGlobal(cbSize);
                        if (pLinkedToken == IntPtr.Zero)
                        {
                            throw new Win32Exception();
                        }

                        // Get the linked token.
                        if (!NativeMethods.GetTokenInformation(hToken,
                                                               TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken,
                                                               cbSize, out cbSize))
                        {
                            throw new Win32Exception();
                        }

                        // Marshal the linked token value from native to .NET.
                        IntPtr hLinkedToken = Marshal.ReadIntPtr(pLinkedToken);
                        hTokenToCheck = new SafeTokenHandle(hLinkedToken);
                    }
                }

                // 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.
                if (hTokenToCheck == null)
                {
                    if (!NativeMethods.DuplicateToken(hToken,
                                                      SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                                                      out hTokenToCheck))
                    {
                        throw new Win32Exception();
                    }
                }

                // Check if the token to be checked contains admin SID.
                WindowsIdentity  id        = new WindowsIdentity(hTokenToCheck.DangerousGetHandle());
                WindowsPrincipal principal = new WindowsPrincipal(id);
                fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator);
            }
            finally
            {
                // Centralized cleanup for all allocated resources.
                if (hToken != null)
                {
                    hToken.Close();
                    hToken = null;
                }
                if (hTokenToCheck != null)
                {
                    hTokenToCheck.Close();
                    hTokenToCheck = null;
                }
                if (pElevationType != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pElevationType);
                    pElevationType = IntPtr.Zero;
                }
                if (pLinkedToken != IntPtr.Zero)
                {
                    Marshal.FreeHGlobal(pLinkedToken);
                    pLinkedToken = IntPtr.Zero;
                }
            }

            return(fInAdminGroup);
        }
Beispiel #22
0
        static void Main(string[] args)
        {
            using (Impersonator imp = new Impersonator("andy2", ".", "andy2"))
            {
                bool            fInAdminGroup  = false;
                int             cbSize         = 0;
                SafeTokenHandle hToken         = null;
                SafeTokenHandle hTokenToCheck  = null;
                IntPtr          pElevationType = IntPtr.Zero;
                IntPtr          pLinkedToken   = IntPtr.Zero;
                WindowsIdentity wi             = WindowsIdentity.GetCurrent();
                IntPtr          currentToken   = wi.Token;
                hToken = new SafeTokenHandle(currentToken);
                if (Environment.OSVersion.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.
                    cbSize         = sizeof(TOKEN_ELEVATION_TYPE);
                    pElevationType = Marshal.AllocHGlobal(cbSize);
                    if (pElevationType == IntPtr.Zero)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    // Retrieve token elevation type information.
                    if (!NativeMethod.GetTokenInformation(hToken,
                                                          TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType,
                                                          cbSize, out cbSize))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

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

                    // If limited, get the linked elevated token for further check.
                    if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
                    {
                        // Allocate a buffer for the linked token.
                        cbSize       = IntPtr.Size;
                        pLinkedToken = Marshal.AllocHGlobal(cbSize);
                        if (pLinkedToken == IntPtr.Zero)
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }

                        // Get the linked token.
                        if (!NativeMethod.GetTokenInformation(hToken,
                                                              TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken,
                                                              cbSize, out cbSize))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }

                        // Marshal the linked token value from native to .NET.
                        IntPtr hLinkedToken = Marshal.ReadIntPtr(pLinkedToken);
                        hTokenToCheck = new SafeTokenHandle(hLinkedToken);
                    }
                }
                if (hTokenToCheck == null)
                {
                    if (!NativeMethod.DuplicateToken(hToken,
                                                     SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                                                     out hTokenToCheck))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }

                // Check if the token to be checked contains admin SID.
                WindowsIdentity  id        = new WindowsIdentity(hTokenToCheck.DangerousGetHandle());
                WindowsPrincipal principal = new WindowsPrincipal(id);
                fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator);
                Console.WriteLine(fInAdminGroup);
                // Console.WriteLine(AuthenticationHelper.IsUserInAdminGroup());
            }
            using (Impersonator imp = new Impersonator("onlyuser", ".", "onlyuser"))
            {
                bool            fInAdminGroup  = false;
                int             cbSize         = 0;
                SafeTokenHandle hToken         = null;
                SafeTokenHandle hTokenToCheck  = null;
                IntPtr          pElevationType = IntPtr.Zero;
                IntPtr          pLinkedToken   = IntPtr.Zero;
                WindowsIdentity wi             = WindowsIdentity.GetCurrent();
                IntPtr          currentToken   = wi.Token;
                hToken = new SafeTokenHandle(currentToken);
                if (Environment.OSVersion.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.
                    cbSize         = sizeof(TOKEN_ELEVATION_TYPE);
                    pElevationType = Marshal.AllocHGlobal(cbSize);
                    if (pElevationType == IntPtr.Zero)
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

                    // Retrieve token elevation type information.
                    if (!NativeMethod.GetTokenInformation(hToken,
                                                          TOKEN_INFORMATION_CLASS.TokenElevationType, pElevationType,
                                                          cbSize, out cbSize))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }

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

                    // If limited, get the linked elevated token for further check.
                    if (elevType == TOKEN_ELEVATION_TYPE.TokenElevationTypeLimited)
                    {
                        // Allocate a buffer for the linked token.
                        cbSize       = IntPtr.Size;
                        pLinkedToken = Marshal.AllocHGlobal(cbSize);
                        if (pLinkedToken == IntPtr.Zero)
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }

                        // Get the linked token.
                        if (!NativeMethod.GetTokenInformation(hToken,
                                                              TOKEN_INFORMATION_CLASS.TokenLinkedToken, pLinkedToken,
                                                              cbSize, out cbSize))
                        {
                            throw new Win32Exception(Marshal.GetLastWin32Error());
                        }

                        // Marshal the linked token value from native to .NET.
                        IntPtr hLinkedToken = Marshal.ReadIntPtr(pLinkedToken);
                        hTokenToCheck = new SafeTokenHandle(hLinkedToken);
                    }
                }
                if (hTokenToCheck == null)
                {
                    if (!NativeMethod.DuplicateToken(hToken,
                                                     SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                                                     out hTokenToCheck))
                    {
                        throw new Win32Exception(Marshal.GetLastWin32Error());
                    }
                }

                // Check if the token to be checked contains admin SID.
                WindowsIdentity  id        = new WindowsIdentity(hTokenToCheck.DangerousGetHandle());
                WindowsPrincipal principal = new WindowsPrincipal(id);
                fInAdminGroup = principal.IsInRole(WindowsBuiltInRole.Administrator);
                Console.WriteLine(fInAdminGroup);
                // Console.WriteLine(AuthenticationHelper.IsUserInAdminGroup());
            }
            //using (Impersonator imp = new Impersonator("andy2", ".", "andy2"))
            //{
            //    Console.WriteLine(AuthenticationHelper.IsUserInAdminGroup());
            //}
            //using (Impersonator imp2 = new Impersonator("andy", ".", "andy"))
            //{
            //    Console.WriteLine(AuthenticationHelper.IsUserInAdminGroup());
            //}
        }