Пример #1
0
        /// <summary>
        /// Enables or disables the privilege with given key for this process
        /// </summary>
        /// <param name="key">The privilege key</param>
        /// <param name="enable">Whether to enable or disable the privilege</param>
        public void SetPrivilege(String key, Boolean enable)
        {
            AdvApi32.Luid luid = new AdvApi32.Luid();
            if (!AdvApi32.LookupPrivilegeValue(null, key, ref luid))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not perform lookup of privilege value");
            }

            IntPtr handle = IntPtr.Zero;

            if (!AdvApi32.OpenProcessToken(Handle.DangerousGetHandle(), TokenAccessLevels.AdjustPrivileges, ref handle))
            {
                throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not open process token");
            }

            using (SafeAccessTokenHandle tokenHandle = new SafeAccessTokenHandle(handle))
            {
                AdvApi32.TokenPrivileges privileges = new AdvApi32.TokenPrivileges();
                privileges.PrivilegeCount = 1;
                privileges.Luid           = luid;
                privileges.State          = enable ? PrivilegeState.Enabled : PrivilegeState.Removed;

                if (!AdvApi32.AdjustTokenPrivileges(tokenHandle.DangerousGetHandle(), false, ref privileges, 0,
                                                    IntPtr.Zero, IntPtr.Zero))
                {
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Could not adjust token privileges");
                }
            }
        }
        /// <summary>
        ///   Checks whether the primary access token of the process belongs to a user account that is a member of the local Administrator group, even if it currently is not elevated.
        /// </summary>
        /// <returns>
        ///   True if the primary access token of the process belongs to a user account that is a member of the Administrators group; false otherwise.
        /// </returns>
        public static bool IsUserInAdminGroup()
        {
            // Default token's received aren't impersonation tokens, we are looking for an impersonation token.
            bool isImpersonationToken = false;

            // Open the access token of the current process.
            SafeTokenHandle processToken;

            if (!AdvApi32.OpenProcessToken(Process.GetCurrentProcess().Handle, (uint)(TokenAccessLevels.Query | TokenAccessLevels.Duplicate), out processToken))
            {
                MarshalHelper.ThrowLastWin32ErrorException();
            }

            // Starting from Vista linked tokens are supported which need to be checked.
            if (EnvironmentHelper.VistaOrHigher)
            {
                // Determine token type: limited, elevated, or default.
                int marshalSize         = sizeof(AdvApi32.TokenElevationType);
                var elevationTypeHandle = SafeUnmanagedMemoryHandle.FromNewlyAllocatedMemory(marshalSize);
                if (!AdvApi32.GetTokenInformation(processToken, AdvApi32.TokenInformationClass.TokenElevationType, elevationTypeHandle.DangerousGetHandle(), marshalSize, out marshalSize))
                {
                    MarshalHelper.ThrowLastWin32ErrorException();
                }
                var tokenType = (AdvApi32.TokenElevationType)Marshal.ReadInt32(elevationTypeHandle.DangerousGetHandle());

                // If limited, get the linked elevated token for further check.
                if (tokenType == AdvApi32.TokenElevationType.TokenElevationTypeLimited)
                {
                    // Get the linked token.
                    marshalSize = IntPtr.Size;
                    var linkedTokenHandle = SafeUnmanagedMemoryHandle.FromNewlyAllocatedMemory(marshalSize);
                    if (!AdvApi32.GetTokenInformation(processToken, AdvApi32.TokenInformationClass.TokenLinkedToken, linkedTokenHandle.DangerousGetHandle(), marshalSize, out marshalSize))
                    {
                        MarshalHelper.ThrowLastWin32ErrorException();
                    }
                    processToken         = new SafeTokenHandle(Marshal.ReadIntPtr(linkedTokenHandle.DangerousGetHandle()));
                    isImpersonationToken = true;                     // Linked tokens are already impersonation tokens.
                }
            }

            // We need an impersonation token in order to check whether it contains admin SID.
            if (!isImpersonationToken)
            {
                SafeTokenHandle impersonatedToken;
                if (!AdvApi32.DuplicateToken(processToken, AdvApi32.SecurityImpersonationLevel.SecurityIdentification, out impersonatedToken))
                {
                    MarshalHelper.ThrowLastWin32ErrorException();
                }
                processToken = impersonatedToken;
            }

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

            return(principal.IsInRole(WindowsBuiltInRole.Administrator));
        }
Пример #3
0
        public static void Exit(ShutdownFlags Flags = ShutdownFlags.Shutdown, int Reason = 0)
        {
            var    tp = new TokPriv1Luid(1, 0, AdvApi32.SE_PRIVILEGE_ENABLED);
            IntPtr hproc = Kernel32.CurrentProcess, htok = IntPtr.Zero;

            AdvApi32.OpenProcessToken(hproc, AdvApi32.TOKEN_ADJUST_PRIVILEGES | AdvApi32.TOKEN_QUERY, ref htok);
            AdvApi32.LookupPrivilegeValue(null, "SeShutdownPrivilege", ref tp.Luid);
            AdvApi32.AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);

            User32.ExitWindows(Flags, 0);
        }
Пример #4
0
        private static SafeFileHandle OpenReparsePoint(string path, bool writeAccess)
        {
            using (Process currentProcess = Process.GetCurrentProcess())
            {
                IntPtr tokenHandle = IntPtr.Zero;
                try
                {
                    tokenHandle = AdvApi32.OpenProcessToken(currentProcess.Handle, TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query);

                    Luid luid       = AdvApi32.LookupPrivilegeValue(writeAccess ? PrivilegeName.Restore : PrivilegeName.Backup);
                    var  privileges = new TokenPrivileges
                    {
                        PrivilegeCount = 1,
                        Privileges     = new []
                        {
                            new Privilege()
                            {
                                Luid       = luid,
                                Attributes = Privilege.EnabledAttribute,
                            }
                        }
                    };

                    AdvApi32.AdjustTokenPrivileges(tokenHandle, privileges);
                }
                finally
                {
                    if (tokenHandle != IntPtr.Zero)
                    {
                        Kernel32.CloseHandle(tokenHandle);
                    }
                }
            }

            GenericAccessRights access = GenericAccessRights.Read;

            if (writeAccess)
            {
                access |= GenericAccessRights.Write;
            }

            SafeFileHandle handle = Kernel32.CreateFile(path, access, FileShare.None,
                                                        FileMode.Open, FileAttributes.Normal, FileFlags.OpenReparsePoint | FileFlags.BackupSemantics);

            return(handle);
        }
Пример #5
0
        public static void AcquireSystemPrivilege(string name)
        {
            AdvApi32.TOKEN_PRIVILEGES tkp;
            IntPtr token;

            tkp.Privileges = new AdvApi32.LUID_AND_ATTRIBUTES[1];
            AdvApi32.LookupPrivilegeValue(
                IntPtr.Zero,
                name,
                out tkp.Privileges[0].Luid
                );

            tkp.PrivilegeCount = 1;

            tkp.Privileges[0].Attributes = (uint)AdvApi32.Se_Privilege.ENABLED;

            if (!AdvApi32.OpenProcessToken(
                    Process.GetCurrentProcess().Handle,
                    (uint)(AdvApi32.Token.ADJUST_PRIVILEGES |
                           AdvApi32.Token.QUERY),
                    out token))
            {
                Win32Error.Set("OpenProcessToken");
                throw new Exception(Win32Error.GetFullErrMsg());
            }

            if (!AdvApi32.AdjustTokenPrivileges(
                    token,
                    false,
                    ref tkp,
                    0,
                    IntPtr.Zero,
                    IntPtr.Zero))
            {
                Win32Error.Set("AdjustTokenPrivileges");
                throw new Exception(Win32Error.GetFullErrMsg());
            }
        }