internal static extern bool AdjustTokenPrivileges(
     IntPtr TokenHandle,
     [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges,
     ref TOKEN_PRIVILEGES NewState,
     uint BufferLength,
     out TOKEN_PRIVILEGES PreviousState,
     out uint ReturnLength);
示例#2
0
        public RegistryInterop(RegistryHives hive, string subKey, string filePath)
        {
            int token = 0;
            int retval = 0;

            TOKEN_PRIVILEGES TP = new TOKEN_PRIVILEGES();
            TOKEN_PRIVILEGES TP2 = new TOKEN_PRIVILEGES();
            LUID RestoreLuid = new LUID();
            LUID BackupLuid = new LUID();

            retval = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token);
            retval = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestoreLuid);
            retval = LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackupLuid);
            TP.PrivilegeCount = 1;
            TP.Attributes = SE_PRIVILEGE_ENABLED;
            TP.Luid = RestoreLuid;
            TP2.PrivilegeCount = 1;
            TP2.Attributes = SE_PRIVILEGE_ENABLED;
            TP2.Luid = BackupLuid;

            retval = AdjustTokenPrivileges(token, 0, ref TP, 1024, 0, 0);
            retval = AdjustTokenPrivileges(token, 0, ref TP2, 1024, 0, 0);

            uint regHive = (uint)hive;

            this.Hive = hive;
            this.SubKey = subKey;
            RegLoadKey(regHive, subKey, filePath);
            this.IsUnloaded = false;
        }
示例#3
0
        public static bool SetPrivileges()
        {
            IntPtr hProc;
            IntPtr hToken;
            long luid_Security;
            TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();

            // get the process token
            hProc = Process.GetCurrentProcess().Handle;
            hToken = IntPtr.Zero;
            if (!(OpenProcessToken(hProc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref hToken)))
            {
                return false;
            }

            // lookup the ID for the privilege we want to enable
            luid_Security = 0;
            //if (!(LookupPrivilegeValue(null, SE_SECURITY_NAME, ref luid_Security)))
            if (!(LookupPrivilegeValue(null, SE_DEBUG_NAME, ref luid_Security)))
            {
                return false;
            }

            tp.PrivilegeCount = 1;
            tp.Privilege1.Luid = luid_Security;
            tp.Privilege1.Attributes = SE_PRIVILEGE_ENABLED;

            // enable the privilege
            if (!(AdjustTokenPrivileges(hToken, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero)))
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// Load RegistryHive from file.
        /// </summary>
        /// <param name="hivename">RegistryHive name</param>
        /// <param name="filepath">RegistyHive filepath</param>
        /// <param name="rkey">Registrykey</param>
        /// <returns>When loading is failed, return false. When loading is succeeded, return true.</returns>
        public static bool LoadHive(string hivename, string filepath, ExRegistryKey rkey)
        {
            int tokenHandle = 0;
            LUID serLuid = new LUID();
            LUID sebLuid = new LUID();
            OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle);
            TOKEN_PRIVILEGES tokenp = new TOKEN_PRIVILEGES();

            tokenp.PrivilegeCount = 1;
            LookupPrivilegeValue(null, "SeBackupPrivilege", ref sebLuid);
            tokenp.Luid = sebLuid;
            tokenp.Attributes = SE_PRIVILEGE_ENABLED;
            AdjustTokenPrivileges(tokenHandle, false, ref tokenp, 0, 0, 0);

            tokenp.PrivilegeCount = 1;
            LookupPrivilegeValue(null, "SeRestorePrivilege", ref serLuid);
            tokenp.Luid = serLuid;
            tokenp.Attributes = SE_PRIVILEGE_ENABLED;
            AdjustTokenPrivileges(tokenHandle, false, ref tokenp, 0, 0, 0);
            CloseHandle(tokenHandle);
            int rtn = RegLoadKey((uint)rkey, hivename + "\\", filepath);

            if (rtn == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
示例#5
0
        public static bool SetPrivilege(string lpszPrivilege, bool
			bEnablePrivilege )
        {
            bool retval = false;
            int ltkpOld = 0;
            IntPtr hToken = IntPtr.Zero;
            TOKEN_PRIVILEGES tkp = new TOKEN_PRIVILEGES();
            tkp.Privileges = new int[3];
            TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();
            tkpOld.Privileges = new int[3];
            LUID tLUID = new LUID();
            tkp.PrivilegeCount = 1;
            if (bEnablePrivilege)
                tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
            else
                tkp.Privileges[2] = 0;
            if(LookupPrivilegeValue(null , lpszPrivilege , ref tLUID))
            {
                Process proc = Process.GetCurrentProcess();
                if(proc.Handle != IntPtr.Zero)
                {
                    if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY,
                        ref hToken) != 0)
                    {
                        tkp.PrivilegeCount = 1;
                        tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
                        tkp.Privileges[1] = tLUID.HighPart;
                        tkp.Privileges[0] = tLUID.LowPart;
                        const int bufLength = 256;
                        IntPtr tu = Marshal.AllocHGlobal( bufLength );
                        Marshal.StructureToPtr(tkp, tu, true);
                        if(AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref
                            ltkpOld) != 0)
                        {
                            // successful AdjustTokenPrivileges doesn't mean privilege could be	changed
                                if (Marshal.GetLastWin32Error() == 0)
                                {
                                    retval = true; // Token changed
                                }
                        }
                        TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES) Marshal.PtrToStructure(tu,
                            typeof(TOKEN_PRIVILEGES) );
                        Marshal.FreeHGlobal( tu );
                    }
                }
            }
            if (hToken != IntPtr.Zero)
            {
                CloseHandle(hToken);
            }
            return retval;
        }
示例#6
0
 public static void SetDebugPrivilege()
 {
     IntPtr handle = Kernel32.OpenProcess(PROCESS_QUERY_INFORMATION, false, (uint)Process.GetCurrentProcess().Id);
     IntPtr tokenHandle;
     OpenProcessToken(handle, TOKEN_ADJUST_PRIVILEGES, out tokenHandle);
     LUID luid;
     LookupPrivilegeValueW(null, SE_DEBUG_NAME, out luid);
     TOKEN_PRIVILEGES privileges = new TOKEN_PRIVILEGES();
     privileges.PrivilegeCount = 1;
     privileges.Privileges = new LUID_AND_ATTRIBUTES[] { new LUID_AND_ATTRIBUTES() };
     privileges.Privileges[0].Luid = luid;
     privileges.Privileges[0].Attributes = (int)SE_PRIVILEGE_ENABLED;
     IntPtr pPrivileges = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(TOKEN_PRIVILEGES)));
     Marshal.StructureToPtr(privileges, pPrivileges, false);
     uint returnLength = 0;
     AdjustTokenPrivileges(tokenHandle, false, pPrivileges, 0, IntPtr.Zero, ref returnLength);
     Marshal.FreeHGlobal(pPrivileges);
     Kernel32.CloseHandle(tokenHandle);
     Kernel32.CloseHandle(handle);
 }
示例#7
0
        private static void AdjustToken()
        {
            const uint TOKEN_ADJUST_PRIVILEGES = 0x20;
            const uint TOKEN_QUERY = 0x8;
            const int SE_PRIVILEGE_ENABLED = 0x2;
            const string SE_SHUTDOWN_NAME = "SeShutdownPrivilege";

            if (Environment.OSVersion.Platform != PlatformID.Win32NT) return;

            IntPtr procHandle = GetCurrentProcess();

            IntPtr tokenHandle;
            OpenProcessToken(procHandle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, out tokenHandle);
            TOKEN_PRIVILEGES tp = new TOKEN_PRIVILEGES();
            tp.Attributes = SE_PRIVILEGE_ENABLED;
            tp.PrivilegeCount = 1;
            LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, out tp.Luid);
            AdjustTokenPrivileges(tokenHandle, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero);

            CloseHandle(tokenHandle);
        }
示例#8
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Base">The existing hive root to load as a subkey of.</param>
        /// <param name="NewHive">The registry hive file to mount/load.</param>
        /// <returns>String containing the subkey from the Base where NewHive was mounted.  Null if unsuccessful.</returns>
        public static string LoadHive(RegistryHive Base, string NewHive)
        {
            try
            {
                int token = 0;
                LUID RestLUID = new LUID();
                LUID BackLUID = new LUID();
                TOKEN_PRIVILEGES RestPriv = new TOKEN_PRIVILEGES { Attributes = SE_PRIVILEGE_ENABLED, PrivilegeCount = 1 };
                TOKEN_PRIVILEGES BackPriv = new TOKEN_PRIVILEGES { Attributes = SE_PRIVILEGE_ENABLED, PrivilegeCount = 1 };

                OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token);
                LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestLUID);
                LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackLUID);
                RestPriv.Luid = RestLUID;
                BackPriv.Luid = BackLUID;
                AdjustTokenPrivileges(token, false, ref RestPriv, 0, 0, 0);
                AdjustTokenPrivileges(token, false, ref BackPriv, 0, 0, 0);

                string reference = (Path.GetFileNameWithoutExtension(NewHive) + DateTime.Now.Ticks + '-' + new Random().Next());
                return RegLoadKey((uint)Base, reference, NewHive) == 0 ? reference : null;
            }
            catch (Exception)
            { return null; }
        }
示例#9
0
        bool SetPrivilege(string privilege, bool allow)
        {
            bool success = false;
            IntPtr token = IntPtr.Zero;
            TOKEN_PRIVILEGES tokenPrivileges = new TOKEN_PRIVILEGES();

            success = OpenProcessToken(GetCurrentProcess(), (uint)TOKEN_PRIVILEGES_ENUM.TOKEN_ADJUST_PRIVILEGES | (uint)TOKEN_PRIVILEGES_ENUM.TOKEN_QUERY, out token);
            if (success)
            {
                if (allow)
                {
                    LUID luid;
                    LookupPrivilegeValueA(null, privilege, out luid);
                    tokenPrivileges.PrivilegesCount = 1;
                    tokenPrivileges.Privileges = new LUID_AND_ATTRIBUTES[1];
                    tokenPrivileges.Privileges[0].Luid = luid;
                    tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
                }
                success = AdjustTokenPrivileges(token, false, ref tokenPrivileges, 0, IntPtr.Zero, IntPtr.Zero);
            }
            if (token != IntPtr.Zero)
            {
                CloseHandle(token);
            }
            return success;
        }
 internal static unsafe extern bool AdjustTokenPrivileges(SafeCloseHandle tokenHandle, bool disableAllPrivileges, TOKEN_PRIVILEGES* newState, int bufferLength, IntPtr previousState, IntPtr returnLength);
示例#11
0
        /// <summary>
        /// Internal helper function that returns two values relating to the SeBackupPrivilege
        /// </summary>
        /// <param name="hasPrivilege">True if the calling proccess has the SeBackupPrivilege, false otherwise</param>
        /// <param name="isEnabled">True if the SeBackupPrivilege is enabled, false otherwise</param>
        private static void GetBackupPrivilege(out bool hasPrivilege, out bool isEnabled)
        {
            int token = 0;
            int outsize = 0;

            TOKEN_PRIVILEGES TP = new TOKEN_PRIVILEGES();
            LUID backupLuid = new LUID();

            if (OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token) == 0)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            if (LookupPrivilegeValue(null, SE_BACKUP_NAME, ref backupLuid) == 0)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            if (GetTokenInformation(token, TOKEN_INFORMATION_CLASS_PRIVILEGES, ref TP, Marshal.SizeOf(typeof(TOKEN_PRIVILEGES)), ref outsize) == 0)
                throw new Win32Exception(Marshal.GetLastWin32Error());

            #if DEBUG
            Console.WriteLine("Read token information:");
            PrintTokenInformation(TP);
            #endif

            for (int i = 0; i < TP.PrivilegeCount; i++)
                if (TP.Privileges[i].Luid.LowPart == backupLuid.LowPart && TP.Privileges[i].Luid.HighPart == backupLuid.HighPart)
                {
                    isEnabled = (TP.Privileges[i].Attributes & SE_PRIVILEGE_ENABLED) == SE_PRIVILEGE_ENABLED;
                    hasPrivilege = true;
                    return;
                }

            hasPrivilege = false;
            isEnabled = false;
        }
示例#12
0
 public static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
    ref TOKEN_PRIVILEGES NewState, UInt32 BufferLengthInBytes, ref TOKEN_PRIVILEGES PreviousState, out UInt32 ReturnLengthInBytes);
示例#13
0
    // Source: http://ithoughthecamewithyou.com/post/Reboot-computer-in-C-NET.aspx
    public static void ExitWindowsEx(EXIT_WINDOWS exitMode)
    {
      IntPtr tokenHandle = IntPtr.Zero;

      try
      {
        // Get process token
        if (!OpenProcessToken(System.Diagnostics.Process.GetCurrentProcess().Handle,
            TOKEN_QUERY | TOKEN_ADJUST_PRIVILEGES,
            out tokenHandle))
        {
          throw new Win32Exception(Marshal.GetLastWin32Error(),
              "Failed to open process token handle");
        }

        // Lookup the shutdown privilege
        TOKEN_PRIVILEGES tokenPrivs = new TOKEN_PRIVILEGES();
        tokenPrivs.PrivilegeCount = 1;
        tokenPrivs.Privileges = new LUID_AND_ATTRIBUTES[1];
        tokenPrivs.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

        if (!LookupPrivilegeValue(null,
            SE_SHUTDOWN_NAME,
            out tokenPrivs.Privileges[0].Luid))
        {
          throw new Win32Exception(Marshal.GetLastWin32Error(),
              "Failed to open lookup shutdown privilege");
        }

        // Add the shutdown privilege to the process token
        if (!AdjustTokenPrivileges(tokenHandle,
            false,
            ref tokenPrivs,
            0,
            IntPtr.Zero,
            IntPtr.Zero))
        {
          throw new Win32Exception(Marshal.GetLastWin32Error(),
              "Failed to adjust process token privileges");
        }

        // Perform the exit operation
        if (!ExitWindowsEx(exitMode,
                ShutdownReason.MajorApplication |
        ShutdownReason.MinorInstallation |
        ShutdownReason.FlagPlanned))
        {
          throw new Win32Exception(Marshal.GetLastWin32Error(),
              String.Format("Failed to exit the system ({0})", exitMode));
        }
      }
      finally
      {
        // Close the process token
        if (tokenHandle != IntPtr.Zero)
        {
          CloseHandle(tokenHandle);
        }
      }
    }
        public static bool EnablePrivilege(string lpszPrivilege, bool bEnablePrivilege)
        {
            bool             retval  = false;
            int              ltkpOld = 0;
            IntPtr           hToken  = IntPtr.Zero;
            TOKEN_PRIVILEGES tkp     = new TOKEN_PRIVILEGES();

            tkp.Privileges = new int[3];
            TOKEN_PRIVILEGES tkpOld = new TOKEN_PRIVILEGES();

            tkpOld.Privileges = new int[3];
            LUID tLUID = new LUID();

            tkp.PrivilegeCount = 1;
            if (bEnablePrivilege)
            {
                tkp.Privileges[2] = SE_PRIVILEGE_ENABLED;
            }
            else
            {
                tkp.Privileges[2] = 0;
            }

            try
            {
                if (LookupPrivilegeValue(null, lpszPrivilege, ref tLUID))
                {
                    Process proc = Process.GetCurrentProcess();
                    if (proc.Handle != IntPtr.Zero)
                    {
                        if (OpenProcessToken(proc.Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY,
                                             ref hToken) != 0)
                        {
                            tkp.PrivilegeCount = 1;
                            tkp.Privileges[2]  = SE_PRIVILEGE_ENABLED;
                            tkp.Privileges[1]  = tLUID.HighPart;
                            tkp.Privileges[0]  = tLUID.LowPart;
                            const int bufLength = 256;
                            IntPtr    tu        = Marshal.AllocHGlobal(bufLength);
                            Marshal.StructureToPtr(tkp, tu, true);
                            try
                            {
                                if (AdjustTokenPrivileges(hToken, 0, tu, bufLength, IntPtr.Zero, ref ltkpOld) != 0)
                                {
                                    // successful AdjustTokenPrivileges doesn't mean privilege could be changed
                                    if (Marshal.GetLastWin32Error() == 0)
                                    {
                                        retval = true; // Token changed
                                    }
                                }
                                TOKEN_PRIVILEGES tokp = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tu, typeof(TOKEN_PRIVILEGES));
                            }
                            finally
                            {
                                Marshal.FreeHGlobal(tu);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (hToken != IntPtr.Zero)
                {
                    CloseHandle(hToken);
                }
            }

            return(retval);
        }
        /// <summary>
        /// Set lock pages privilege
        /// </summary>
        /// <param name="process">process</param>
        /// <param name="enable"></param>
        static public void SetLockPagesPrivilege(Process process, bool enable)
        {
            IntPtr token;

            TOKEN_PRIVILEGES info = new TOKEN_PRIVILEGES();

            // Open the token.

            bool result = General.OpenProcessToken(process.Handle,
                                                   General.TOKEN_ADJUST_PRIVILEGES,
                                                   out token);

            if (!result)
            {
                throw new LoggedSetLockPagesPrivilegeException("Cannot open process token.",
                                                               LoggedSetLockPagesPrivilegeException.Reason.CannotOpenProcessToken);
            }

            info.PrivilegeCount = 1;
            info.Privileges     = new LUID_AND_ATTRIBUTES[1];

            // Enable or disable?

            if (enable)
            {
                info.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
            }
            else
            {
                info.Privileges[0].Attributes = 0;
            }


            // Get the LUID.
            result = LookupPrivilegeValue(null, SE_LOCK_MEMORY_NAME,
                                          out info.Privileges[0].Luid);

            if (!result)
            {
                General.CloseHandle(token);
                throw new LoggedSetLockPagesPrivilegeException("Cannot get privilege.",
                                                               LoggedSetLockPagesPrivilegeException.Reason.CannotGetPrivilege);
            }

            // Adjust the privilege.

            result = AdjustTokenPrivileges(token, false,
                                           ref info,
                                           0, IntPtr.Zero, IntPtr.Zero);

            // Check the result.

            if (!result)
            {
                General.CloseHandle(token);
                throw new LoggedSetLockPagesPrivilegeException(string.Format("Cannot adjust token privileges {0}.", General.GetLastError()),
                                                               LoggedSetLockPagesPrivilegeException.Reason.CannotAdjustTokenPrivileges);
            }
            else
            {
                int lastError = General.GetLastError();

                if (lastError != General.ERROR_SUCCESS)
                {
                    General.CloseHandle(token);
                    throw new LoggedSetLockPagesPrivilegeException(string.Format("Cannot enable the SE_LOCK_MEMORY_NAME privilege {0}; please check the local policy.", lastError),
                                                                   LoggedSetLockPagesPrivilegeException.Reason.Unknown);
                }
            }

            General.CloseHandle(token);
        }
示例#16
0
 public static extern int AdjustTokenPrivileges(int tokenhandle, int disableprivs, [MarshalAs(UnmanagedType.Struct)] ref TOKEN_PRIVILEGES Newstate, int bufferlength, int PreivousState, int Returnlength);
示例#17
0
        private static void SetPrivilege(uint privilege)
        {
            Process process = Process.GetCurrentProcess();
            IntPtr tokenHandle = IntPtr.Zero;
            bool success = OpenProcessToken(process.Handle, TOKEN_ADJUST_PRIVILEGES, out tokenHandle);
            if (!success)
                throw new Win32Exception();
            GC.KeepAlive(process);                      // TODO get on SafeHandles. 

            TOKEN_PRIVILEGES privileges = new TOKEN_PRIVILEGES();
            privileges.PrivilegeCount = 1;
            privileges.Luid.LowPart = privilege;
            privileges.Attributes = SE_PRIVILEGE_ENABLED;

            success = AdjustTokenPrivileges(tokenHandle, false, ref privileges, 0, IntPtr.Zero, IntPtr.Zero);
            CloseHandle(tokenHandle);
            if (!success)
                throw new Win32Exception();
        }
示例#18
0
 public static extern bool AdjustTokenPrivileges(IntPtr htok, bool disableAllPrivileges, ref TOKEN_PRIVILEGES newState, uint len, IntPtr prev, IntPtr relen);
示例#19
0
 public static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, ref TOKEN_PRIVILEGES newst, int len, IntPtr prev, IntPtr relen);
示例#20
0
 internal static extern bool AdjustTokenPrivileges(IntPtr tokenhandle,
                                                   [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges,
                                                   [MarshalAs(UnmanagedType.Struct)] ref TOKEN_PRIVILEGES newstate,
                                                   uint bufferlength, IntPtr previousState, IntPtr returnlength);
示例#21
0
 private static extern bool _AdjustTokenPrivileges(IntPtr hToken, bool bDisable, ref TOKEN_PRIVILEGES currentState, int lastStateLength, IntPtr hLastState, IntPtr currentStateLength);
示例#22
0
        public static bool UpdateChangePermissions([In, Out] WindowsIdentity _context, bool _disable, [In, Out] TOKEN_PRIVILEGES _tokenPrivileges)
        {
            IntPtr _returnSize = IntPtr.Zero;

            if (_AdjustTokenPrivileges(_context.Token, _disable, ref _tokenPrivileges, 1024, IntPtr.Zero, _returnSize))
            {
                var lastError = (uint)Marshal.GetLastWin32Error();
                if (lastError == (uint)NTSTATUS.ERROR_NOT_ALL_ASSIGNED)
                {
                    var win32Exception = new Win32Exception();
                    throw new InvalidOperationException("AdjustTokenPrivileges failed.", win32Exception);
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                var win32Exception = new Win32Exception();
                throw new InvalidOperationException("AdjustTokenPrivileges failed.", win32Exception);
            }
        }
示例#23
0
		internal static extern bool AdjustTokenPrivileges(IntPtr tokenhandle, [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges, ref TOKEN_PRIVILEGES newstate, uint bufferlength, IntPtr previousState, IntPtr returnlength);
示例#24
0
 static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
     [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
     ref TOKEN_PRIVILEGES NewState,
     Int32 BufferLength,
     //ref TOKEN_PRIVILEGES PreviousState,					!! for some reason this won't accept null
     IntPtr PreviousState,
     IntPtr ReturnLength);
示例#25
0
 private static extern bool AdjustTokenPrivileges(IntPtr tokenhandle, int disableprivs, ref TOKEN_PRIVILEGES Newstate, int BufferLengthInBytes, int PreviousState, int ReturnLengthInBytes);
示例#26
0
        /// <summary>
        /// Extracts Token information from a thread's memory by wrapping GetTokenInformation(). Returns token information specified by the tokenInformationClass param
        /// </summary>
        /// <param name="hToken"></param>
        /// <param name="tokenInformationClass"></param>
        /// <returns>String containing the requested token information</returns>
        static string QueryToken(IntPtr hToken, TOKEN_INFORMATION_CLASS tokenInformationClass)
        {
            int tokenInformationLength = 0;

            // First need to get the length of TokenInformation - won't return true
            bool result = GetTokenInformation(hToken, tokenInformationClass, IntPtr.Zero, tokenInformationLength, out tokenInformationLength);
            // Buffer for the struct
            IntPtr tokenInformation = Marshal.AllocHGlobal(tokenInformationLength);

            // Make call to GetTokenInformation() and get particular Struct
            switch (tokenInformationClass)
            {
            case TOKEN_INFORMATION_CLASS.TokenUser:

                // Store the requested token information in the buffer
                result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenUser, tokenInformation, tokenInformationLength, out tokenInformationLength);

                if (result)
                {
                    // Marshal the buffer to TOKEN_USER Struct
                    TOKEN_USER tokenUser = (TOKEN_USER)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_USER));

                    // Extract SID from the TOKEN_USER struct
                    IntPtr pSID = IntPtr.Zero;
                    ConvertSidToStringSid(tokenUser.User.Sid, out pSID);
                    string SID = Marshal.PtrToStringAuto(pSID);

                    return(SID);
                }
                else
                {
                    return(null);
                }

            case TOKEN_INFORMATION_CLASS.TokenPrivileges:

                result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenPrivileges, tokenInformation, tokenInformationLength, out tokenInformationLength);

                if (result)
                {
                    TOKEN_PRIVILEGES tokenPrivileges = (TOKEN_PRIVILEGES)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_PRIVILEGES));

                    StringBuilder stringBuilder = new StringBuilder();

                    for (int i = 0; i < tokenPrivileges.PrivilegeCount; i++)
                    {
                        // Bitwise AND comparison to check that each token privilege attribute for SE_PRIVILEGE_ENABLED
                        if (((LUID_ATTRIBUTES)tokenPrivileges.Privileges[i].Attributes & LUID_ATTRIBUTES.SE_PRIVILEGE_ENABLED) == LUID_ATTRIBUTES.SE_PRIVILEGE_ENABLED)
                        {
                            // Append the privilege to the stringBuilder
                            stringBuilder.Append($", {tokenPrivileges.Privileges[i].Luid.LowPart.ToString()}");
                        }
                    }

                    return(stringBuilder.ToString().Remove(0, 2));
                }
                else
                {
                    return(null);
                }

            case TOKEN_INFORMATION_CLASS.TokenIntegrityLevel:

                // Mandatory Level SIDs for QueryToken()
                // https://support.microsoft.com/en-au/help/243330/well-known-security-identifiers-in-windows-operating-systems#allsids
                Dictionary <string, string> tokenIntegritySIDs = new Dictionary <string, string>
                {
                    { "S-1-16-0", "Untrusted Mandatory Level" },
                    { "S-1-16-4096", "Low Mandatory Level" },
                    { "S-1-16-8192", "Medium Mandatory Level" },
                    { "S-1-16-8448", "Medium Plus Mandatory Level" },
                    { "S-1-16-12288", "High Mandatory Level" },
                    { "S-1-16-16384", "System Mandatory Level" },
                    { "S-1-16-20480", "Protected Process Mandatory Level" },
                    { "S-1-16-28672", "Secure Process Mandatory Level" }
                };

                result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, tokenInformation, tokenInformationLength, out tokenInformationLength);

                if (result)
                {
                    TOKEN_MANDATORY_LABEL tokenMandatoryLabel = (TOKEN_MANDATORY_LABEL)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_MANDATORY_LABEL));

                    // Extract SID string from TOKEN_MANDATORY_LABEL
                    IntPtr pSID = IntPtr.Zero;
                    ConvertSidToStringSid(tokenMandatoryLabel.label.Sid, out pSID);
                    string SID = Marshal.PtrToStringAuto(pSID);

                    if (tokenIntegritySIDs.ContainsKey(SID))
                    {
                        return(tokenIntegritySIDs[SID]);
                    }
                    else
                    {
                        return(null);
                    }
                }
                else
                {
                    return(null);
                }

            case TOKEN_INFORMATION_CLASS.TokenOrigin:

                result = GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenOrigin, tokenInformation, tokenInformationLength, out tokenInformationLength);

                if (result)
                {
                    TOKEN_ORIGIN tokenOrigin = (TOKEN_ORIGIN)Marshal.PtrToStructure(tokenInformation, typeof(TOKEN_ORIGIN));
                    string       logonId     = tokenOrigin.OriginatingLogonSession.LowPart.ToString();
                    return(logonId);
                }
                else
                {
                    return(null);
                }
            }
            return(null);
        }
示例#27
0
 private static extern int AdjustTokenPrivileges(
   IntPtr TokenHandle,
   int DisableAllPrivileges,
   ref TOKEN_PRIVILEGES NewState,
   int BufferLength,
   ref TOKEN_PRIVILEGES PreviousState,
   ref int ReturnLength);
示例#28
0
 AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges,
                       [MarshalAs(UnmanagedType.Struct)] ref TOKEN_PRIVILEGES NewState, int BufferLength,
                       IntPtr PreviousState, ref int ReturnLength);
示例#29
0
        public static bool CreateProcessInConsoleSession(String CommandLine, bool bElevate)
        {
            PROCESS_INFORMATION pi;

            bool   bResult = false;
            uint   dwSessionId, winlogonPid = 0;
            IntPtr hUserToken = IntPtr.Zero, hUserTokenDup = IntPtr.Zero, hPToken = IntPtr.Zero, hProcess = IntPtr.Zero;

            Debug.Print("CreateProcessInConsoleSession");
            // Log the client on to the local computer.
            dwSessionId = WTSGetActiveConsoleSessionId();

            // Find the winlogon process
            var procEntry = new PROCESSENTRY32();

            uint hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);

            if (hSnap == INVALID_HANDLE_VALUE)
            {
                return(false);
            }

            procEntry.dwSize = (uint)Marshal.SizeOf(procEntry); //sizeof(PROCESSENTRY32);

            if (Process32First(hSnap, ref procEntry) == 0)
            {
                return(false);
            }

            String strCmp = "explorer.exe";

            do
            {
                if (strCmp.IndexOf(procEntry.szExeFile) == 0)
                {
                    // We found a winlogon process...make sure it's running in the console session
                    uint winlogonSessId = 0;
                    if (ProcessIdToSessionId(procEntry.th32ProcessID, ref winlogonSessId) &&
                        winlogonSessId == dwSessionId)
                    {
                        winlogonPid = procEntry.th32ProcessID;
                        break;
                    }
                }
            }while (Process32Next(hSnap, ref procEntry) != 0);

            //Get the user token used by DuplicateTokenEx
            WTSQueryUserToken(dwSessionId, ref hUserToken);

            var si = new STARTUPINFO();

            si.cb        = Marshal.SizeOf(si);
            si.lpDesktop = "winsta0\\default";
            var tp   = new TOKEN_PRIVILEGES();
            var luid = new LUID();

            hProcess = OpenProcess(MAXIMUM_ALLOWED, false, winlogonPid);

            if (
                !OpenProcessToken(hProcess,
                                  TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY
                                  | TOKEN_ADJUST_SESSIONID | TOKEN_READ | TOKEN_WRITE, ref hPToken))
            {
                Debug.Print(String.Format("CreateProcessInConsoleSession OpenProcessToken error: {0}",
                                          Marshal.GetLastWin32Error()));
            }

            if (!LookupPrivilegeValue(IntPtr.Zero, SE_DEBUG_NAME, ref luid))
            {
                Debug.Print(String.Format("CreateProcessInConsoleSession LookupPrivilegeValue error: {0}",
                                          Marshal.GetLastWin32Error()));
            }

            var sa = new SECURITY_ATTRIBUTES();

            sa.Length = Marshal.SizeOf(sa);

            if (!DuplicateTokenEx(hPToken, MAXIMUM_ALLOWED, ref sa,
                                  (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification, (int)TOKEN_TYPE.TokenPrimary,
                                  ref hUserTokenDup))
            {
                Debug.Print(
                    String.Format(
                        "CreateProcessInConsoleSession DuplicateTokenEx error: {0} Token does not have the privilege.",
                        Marshal.GetLastWin32Error()));
                CloseHandle(hProcess);
                CloseHandle(hUserToken);
                CloseHandle(hPToken);
                return(false);
            }

            if (bElevate)
            {
                //tp.Privileges[0].Luid = luid;
                //tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

                tp.PrivilegeCount = 1;
                tp.Privileges     = new int[3];
                tp.Privileges[2]  = SE_PRIVILEGE_ENABLED;
                tp.Privileges[1]  = luid.HighPart;
                tp.Privileges[0]  = luid.LowPart;

                //Adjust Token privilege
                if (
                    !SetTokenInformation(hUserTokenDup, TOKEN_INFORMATION_CLASS.TokenSessionId, ref dwSessionId,
                                         (uint)IntPtr.Size))
                {
                    Debug.Print(
                        String.Format(
                            "CreateProcessInConsoleSession SetTokenInformation error: {0} Token does not have the privilege.",
                            Marshal.GetLastWin32Error()));
                    //CloseHandle(hProcess);
                    //CloseHandle(hUserToken);
                    //CloseHandle(hPToken);
                    //CloseHandle(hUserTokenDup);
                    //return false;
                }
                if (
                    !AdjustTokenPrivileges(hUserTokenDup, false, ref tp, Marshal.SizeOf(tp), /*(PTOKEN_PRIVILEGES)*/
                                           IntPtr.Zero, IntPtr.Zero))
                {
                    int nErr = Marshal.GetLastWin32Error();

                    if (nErr == ERROR_NOT_ALL_ASSIGNED)
                    {
                        Debug.Print(
                            String.Format(
                                "CreateProcessInConsoleSession AdjustTokenPrivileges error: {0} Token does not have the privilege.",
                                nErr));
                    }
                    else
                    {
                        Debug.Print(String.Format("CreateProcessInConsoleSession AdjustTokenPrivileges error: {0}", nErr));
                    }
                }
            }

            uint   dwCreationFlags = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
            IntPtr pEnv            = IntPtr.Zero;

            if (CreateEnvironmentBlock(ref pEnv, hUserTokenDup, true))
            {
                dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
            }
            else
            {
                pEnv = IntPtr.Zero;
            }
            // Launch the process in the client's logon session.
            bResult = CreateProcessAsUser(hUserTokenDup,        // client's access token
                                          null,                 // file to execute
                                          CommandLine,          // command line
                                          ref sa,               // pointer to process SECURITY_ATTRIBUTES
                                          ref sa,               // pointer to thread SECURITY_ATTRIBUTES
                                          false,                // handles are not inheritable
                                          (int)dwCreationFlags, // creation flags
                                          pEnv,                 // pointer to new environment block
                                          null,                 // name of current directory
                                          ref si,               // pointer to STARTUPINFO structure
                                          out pi                // receives information about new process
                                          );
            // End impersonation of client.

            //GetLastError should be 0
            int iResultOfCreateProcessAsUser = Marshal.GetLastWin32Error();

            //Close handles task
            CloseHandle(hProcess);
            CloseHandle(hUserToken);
            CloseHandle(hUserTokenDup);
            CloseHandle(hPToken);

            return((iResultOfCreateProcessAsUser == 0) ? true : false);
        }
 private static extern bool AdjustTokenPrivileges([In] IntPtr accessTokenHandle, [In] bool disableAllPrivileges,
                                                  [In] ref TOKEN_PRIVILEGES newState, [In] int bufferLength, [In, Out] ref TOKEN_PRIVILEGES previousState, [In, Out] ref int returnLength);
示例#31
0
        /// <summary>
        /// Enable/disable debug level access
        /// </summary>
        /// <param name="Enable">bool: enable/disable</param>
        /// <returns>bool</returns>
        public bool EnableAccess(bool Enable)
        {
            IntPtr hToken = IntPtr.Zero;
            IntPtr hProcess = IntPtr.Zero;
            LUID tLuid = new LUID();
            TOKEN_PRIVILEGES NewState = new TOKEN_PRIVILEGES();
            uint uPriv = (uint)(ETOKEN_PRIVILEGES.TOKEN_ADJUST_PRIVILEGES | ETOKEN_PRIVILEGES.TOKEN_QUERY | ETOKEN_PRIVILEGES.TOKEN_QUERY_SOURCE);

            try
            {
                hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, GetCurrentProcessId());
                if (hProcess == IntPtr.Zero)
                    return false;
                if (OpenProcessToken(hProcess, uPriv, ref hToken))
                    return false;
                // Get the local unique id for the privilege.
                if (LookupPrivilegeValue(0, SE_DEBUG_NAME, ref tLuid))
                    return false;
                // Assign values to the TOKEN_PRIVILEGE structure.
                NewState.PrivilegeCount = 1;
                NewState.Privileges.pLuid = tLuid;
                NewState.Privileges.Attributes = (Enable ? SE_PRIVILEGE_ENABLED : 0);
                // Adjust the token privilege.
                return (AdjustTokenPrivileges(hToken, 0, ref NewState, Marshal.SizeOf(NewState), 0, 0));
            }
            finally
            {
                if (hToken != IntPtr.Zero)
                    CloseHandle(hToken);
                if (hProcess != IntPtr.Zero)
                    CloseHandle(hProcess);
            }
        }
示例#32
0
 static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
                                          [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges,
                                          ref TOKEN_PRIVILEGES NewState,
                                          UInt32 BufferLength,
                                          IntPtr PreviousState,
                                          IntPtr ReturnLength);
示例#33
0
 public static extern bool AdjustTokenPrivileges(int TokenHandle, int DisableAllPrivileges,
     ref TOKEN_PRIVILEGES NewState, int BufferLength,
     int PreviousState, int ReturnLength);
示例#34
0
 static extern bool AdjustTokenPrivileges(SafeObjectHandle handle, bool disableAllPrivileges, ref TOKEN_PRIVILEGES newState, int bufferLength, IntPtr previousState, IntPtr teturnLength);
示例#35
0
 private static extern int AdjustTokenPrivileges(IntPtr tokenHandle, bool disableAllPrivleges, ref TOKEN_PRIVILEGES newState, uint bufferLength, out TOKEN_PRIVILEGES previousState, out uint returnLength);
示例#36
0
 private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, uint Zero, IntPtr Null1, IntPtr Null2);
示例#37
0
文件: advapi32.cs 项目: QCX51/Hotspot
 private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges,
                                                  ref TOKEN_PRIVILEGES NewState, uint BufferLength, UIntPtr PreviousState, UIntPtr ReturnLength);
示例#38
0
 public static extern bool AdjustTokenPrivileges(IntPtr tokenHandle,
                                                 [MarshalAs(UnmanagedType.Bool)] bool disableAllPrivileges,
                                                 ref TOKEN_PRIVILEGES newState,
                                                 UInt32 bufferLengthInBytes,
                                                 ref TOKEN_PRIVILEGES previousState,
                                                 out UInt32 returnLengthInBytes);
示例#39
0
        private static void PrintTokenInformation(TOKEN_PRIVILEGES tp)
        {
            int outsize;
            StringBuilder sbname = new StringBuilder(1024 * 4);

            for (int i = 0; i < tp.PrivilegeCount; i++)
            {
                LUID id = tp.Privileges[i].Luid;

                outsize = sbname.Capacity;
                if (LookupPrivilegeName(null, ref id, sbname, ref outsize) == 0)
                    Console.WriteLine("Invalid LUID {0}:{1}: {2}", id.HighPart, id.LowPart, new Win32Exception(Marshal.GetLastWin32Error()).Message);
                else
                    Console.WriteLine("{0}, status {1}", sbname, tp.Privileges[i].Attributes);
            }
        }
示例#40
0
 private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
                                                  [MarshalAs(UnmanagedType.Bool)] bool DisableAllPrivileges,
                                                  ref TOKEN_PRIVILEGES NewState,
                                                  UInt32 BufferLengthInBytes,
                                                  IntPtr prev,
                                                  IntPtr relen);
示例#41
0
 private static void EnableToken(string privilege)
 {
     if (!CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges")) return;
     IntPtr tokenHandle = IntPtr.Zero;
     var privilegeLUID = new LUID();
     var newPrivileges = new TOKEN_PRIVILEGES();
     TOKEN_PRIVILEGES tokenPrivileges = default(TOKEN_PRIVILEGES);
     if ((OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref  tokenHandle)) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error()));
     if ((LookupPrivilegeValue("", privilege, ref privilegeLUID)) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error()));
     tokenPrivileges.PrivilegeCount = 1;
     tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED;
     tokenPrivileges.Privileges.pLuid = privilegeLUID;
     int Size = 4;
     if ((AdjustTokenPrivileges(tokenHandle, 0, ref tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), ref newPrivileges, ref Size)) == 0) throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error()));
 }
 internal static extern bool AdjustTokenPrivileges(IntPtr tokenHandle, bool disableAllPrivileges, ref TOKEN_PRIVILEGES newState, uint bufferLength, IntPtr previousState, ref uint returnLength);
示例#43
0
 public static void EnableDisablePrivilege(string PrivilegeName, bool EnableDisable)
 {
     var htok = IntPtr.Zero;
     if (!OpenProcessToken(Process.GetCurrentProcess().Handle, TokenAccessLevels.AdjustPrivileges | TokenAccessLevels.Query, out htok))
     {
         Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
         return;
     }
     var tkp = new TOKEN_PRIVILEGES { PrivilegeCount = 1, Privileges = new LUID_AND_ATTRIBUTES[1] };
     LUID luid;
     if (!LookupPrivilegeValue(null, PrivilegeName, out luid))
     {
         Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
         return;
     }
     tkp.Privileges[0].LUID = luid;
     tkp.Privileges[0].Attributes = (uint)(EnableDisable ? 2 : 0);
     if (!AdjustTokenPrivileges(htok, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
     {
         Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
         return;
     }
 }
示例#44
0
        public SystemLocationHandler()
            : base()
        {
            // The global variables
            if (Environment.GetEnvironmentVariable("ProgramW6432") != null)
            {
                global.setEvFolder(EnvironmentVariable.ProgramFiles, Environment.GetEnvironmentVariable("ProgramW6432"));
                global.setEvFolder(EnvironmentVariable.ProgramFilesX86, Environment.GetEnvironmentVariable("PROGRAMFILES(X86)"));
            }
            else
            {
                global.setEvFolder(EnvironmentVariable.ProgramFiles, Environment.GetEnvironmentVariable("PROGRAMFILES"));
                //global.setEvFolder(EnvironmentVariable.ProgramFilesX86,Environment.GetEnvironmentVariable("PROGRAMFILES"));
            }
            if (Environment.GetEnvironmentVariable("LOCALAPPDATA") != null)
            {
                xp = false;
            }
            else
            {
                xp = true;
            }
            if (xp)
            {
                platform_version = "WindowsXP";
            }
            else
            {
                platform_version = "WindowsVista";
            }

            global.setEvFolder(EnvironmentVariable.StartMenu, Environment.GetFolderPath(Environment.SpecialFolder.CommonStartMenu));

            // Not really used
            //common_program_files = Environment.GetEnvironmentVariable("COMMONPROGRAMFILES");

            foreach (DriveInfo look_here in DriveInfo.GetDrives())
            {
                if (look_here.IsReady && (look_here.DriveType == DriveType.Fixed || look_here.DriveType == DriveType.Removable))
                {
                    drives.Add(look_here.Name);
                }
            }


            //host_name = Environment.GetEnvironmentVariable("COMPUTERNAME");
            global.setEvFolder(EnvironmentVariable.AllUsersProfile, Environment.GetEnvironmentVariable("ALLUSERSPROFILE"));

            if (platform_version == "WindowsVista")
            {
                global.setEvFolder(EnvironmentVariable.Public, Environment.GetEnvironmentVariable("PUBLIC"));
            }

            global.setEvFolder(EnvironmentVariable.CommonApplicationData, Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));

            if (!xp)
            {
                RegistryHandler uac_status = new RegistryHandler("local_machine", @"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", false);
                if (uac_status.getValue("EnableLUA") == "1")
                {
                    uac_enabled = true;
                }
            }
            string[] split = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).Split(Path.DirectorySeparatorChar);

            StringBuilder user_root = new StringBuilder(split[0]);

            if (xp)
            {
                for (int i = 1; i < split.Length - 2; i++)
                {
                    user_root.Append(Path.DirectorySeparatorChar + split[i]);
                }
            }
            else
            {
                for (int i = 1; i < split.Length - 3; i++)
                {
                    user_root.Append(Path.DirectorySeparatorChar + split[i]);
                }
            }


            // Global ubisoft save location
            DirectoryInfo   ubisoft_save = null;
            RegistryHandler ubi_reg      = new RegistryHandler("local_machine", @"SOFTWARE\Ubisoft\Launcher", false);

            if (!ubi_reg.key_found)
            {
                ubi_reg = new RegistryHandler("local_machine", @"SOFTWARE\Wow6432Node\Ubisoft\Launcher", false);
            }

            if (ubi_reg.getValue("InstallDir") != null && Directory.Exists(Path.Combine(ubi_reg.getValue("InstallDir"), "savegames")))
            {
                uac_enabled  = true;
                ubisoft_save = new DirectoryInfo(Path.Combine(ubi_reg.getValue("InstallDir"), "savegames"));
            }
            else if (Environment.GetEnvironmentVariable("ProgramW6432") != null && Directory.Exists(Path.Combine(Environment.GetEnvironmentVariable("ProgramW6432"), "Ubisoft", "Ubisoft Game Launcher")))
            {
                ubisoft_save = new DirectoryInfo(Path.Combine(Environment.GetEnvironmentVariable("ProgramW6432"), "Ubisoft", "Ubisoft Game Launcher", "savegames"));
            }
            else if (Directory.Exists(Path.Combine(Environment.GetEnvironmentVariable("PROGRAMFILES"), "Ubisoft", "Ubisoft Game Launcher")))
            {
                ubisoft_save = new DirectoryInfo(Path.Combine(Environment.GetEnvironmentVariable("PROGRAMFILES"), "Ubisoft", "Ubisoft Game Launcher", "savegames"));
            }


            if (ubisoft_save != null && ubisoft_save.Exists)
            {
                global.setEvFolder(EnvironmentVariable.UbisoftSaveStorage, ubisoft_save, true);
            }


            //Per-user variables
            loadUsersData("current_user", null);

            if (Core.StaticAllUsersMode)
            {
                // All this crap lets me get data from other user's registries
                IntPtr token  = new IntPtr(0);
                int    retval = 0;

                TOKEN_PRIVILEGES TP          = new TOKEN_PRIVILEGES();
                TOKEN_PRIVILEGES TP2         = new TOKEN_PRIVILEGES();
                LUID             RestoreLuid = new LUID();
                LUID             BackupLuid  = new LUID();

                int return_length = 0;
                TOKEN_PRIVILEGES oldPriveleges = new TOKEN_PRIVILEGES();

                System.Diagnostics.Process process = System.Diagnostics.Process.GetCurrentProcess();
                //IntPtr hndle = GetModuleHandle(null);

                //retval = OpenProcessToken(hndle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token);
                retval = OpenProcessToken(process.Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token);

                retval                   = LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestoreLuid);
                TP.PrivilegeCount        = 1;
                TP.Privileges.attributes = SE_PRIVILEGE_ENABLED;
                TP.Privileges.luid       = RestoreLuid;
                retval                   = AdjustTokenPrivileges(token, 0, ref TP, TP.Size(), ref oldPriveleges, ref return_length);
                if (retval == 0)
                {
                    throw new TranslateableException("ProcessRestorePermissionError", retval.ToString());
                }

                retval                    = LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackupLuid);
                TP2.PrivilegeCount        = 1;
                TP2.Privileges.attributes = SE_PRIVILEGE_ENABLED;
                TP2.Privileges.luid       = BackupLuid;
                retval                    = AdjustTokenPrivileges(token, 0, ref TP2, TP2.Size(), ref oldPriveleges, ref return_length);
                if (retval == 0)
                {
                    throw new TranslateableException("ProcessBackupPermissionError", retval.ToString());
                }


                Console.WriteLine(retval);

                foreach (DirectoryInfo user_folder in new DirectoryInfo(user_root.ToString()).GetDirectories())
                {
                    if (user_folder.Name.ToLower() == "default user")
                    {
                        continue;
                    }
                    if (user_folder.Name.ToLower() == "default")
                    {
                        continue;
                    }
                    if (user_folder.Name.ToLower() == "all users")
                    {
                        continue;
                    }

                    string hive_file = Path.Combine(user_folder.FullName, "NTUSER.DAT");
                    if (!File.Exists(hive_file))
                    {
                        continue;
                    }


                    int h = RegLoadKey(HKEY_USERS, user_folder.Name, hive_file);
                    //int h = RegLoadAppKey(hive_file,out hKey, RegSAM.AllAccess,REG_PROCESS_APPKEY,0);

                    if (h == 32)
                    {
                        continue;
                    }

                    if (h != 0)
                    {
                        throw new TranslateableException("UserRegistryLoadError", user_folder.Name, h.ToString());
                    }

                    //sub_key = new RegistryHandler(hKey);
                    //sub_key = new RegistryHandler(RegRoot.users,user_folder.Name,false);
                    loadUsersData("users", user_folder.Name);
                    string result = RegUnLoadKey(HKEY_USERS, user_folder.Name).ToString();
                }
            }

            initialized = true;
        }
示例#45
0
        public static bool UnloadHive(RegistryHive Base, string Reference)
        {
            try
            {
                int token = 0;
                LUID RestLUID = new LUID();
                LUID BackLUID = new LUID();
                TOKEN_PRIVILEGES RestPriv = new TOKEN_PRIVILEGES { Attributes = SE_PRIVILEGE_ENABLED, PrivilegeCount = 1 };
                TOKEN_PRIVILEGES BackPriv = new TOKEN_PRIVILEGES { Attributes = SE_PRIVILEGE_ENABLED, PrivilegeCount = 1 };

                OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref token);
                LookupPrivilegeValue(null, SE_RESTORE_NAME, ref RestLUID);
                LookupPrivilegeValue(null, SE_BACKUP_NAME, ref BackLUID);
                RestPriv.Luid = RestLUID;
                BackPriv.Luid = BackLUID;
                AdjustTokenPrivileges(token, false, ref RestPriv, 0, 0, 0);
                AdjustTokenPrivileges(token, false, ref BackPriv, 0, 0, 0);

                return RegUnLoadKey((uint)Base, Reference) == 0;
            }
            catch (Exception)
            { return false; }
        }
示例#46
0
        /// <summary>
        /// Change process security token access rights
        /// </summary>
        /// <param name="Enable">Boolean - Ebnable or disable a privilege</param>
        /// <returns>Boolean</returns>
        Boolean adjustToken(Boolean Enable, string[] rights)
        {
            IntPtr hToken = IntPtr.Zero;
            IntPtr hProcess = IntPtr.Zero;
            LUID tLuid = new LUID();
            TOKEN_PRIVILEGES NewState = new TOKEN_PRIVILEGES();
            UInt32 uPriv = (UInt32)(ETOKEN_PRIVILEGES.TOKEN_ADJUST_PRIVILEGES | ETOKEN_PRIVILEGES.TOKEN_QUERY | ETOKEN_PRIVILEGES.TOKEN_QUERY_SOURCE);

            try
            {
                hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, GetCurrentProcessId());
                if (hProcess == IntPtr.Zero)
                    return false;
                if (OpenProcessToken(hProcess, uPriv, ref hToken) == 0)
                    return false;
                for (Int32 i = 0; i < rights.Length; i++)
                {
                    // Get the local unique id for the privilege.
                    if (LookupPrivilegeValueW(0, rights[i], ref tLuid) == 0)
                        return false;
                }
                // Assign values to the TOKEN_PRIVILEGE structure.
                NewState.PrivilegesCount = 1;
                NewState.Privileges.pLuid = tLuid;
                NewState.Privileges.Attributes = (Enable ? SE_PRIVILEGE_ENABLED : 0);
                // Adjust the token privilege
                return (AdjustTokenPrivileges(hToken, false, ref NewState, (uint)Marshal.SizeOf(NewState), IntPtr.Zero, IntPtr.Zero));
            }
            finally
            {
                if (hToken != IntPtr.Zero)
                    CloseHandle(hToken);
                if (hProcess != IntPtr.Zero)
                    CloseHandle(hProcess);
            }
        }
        static void GrantShutdownPrivileges()
        {
            //log.Debug(m => m("Granting shutdown privileges to process user..."));

            IntPtr tokenHandle = IntPtr.Zero;

            var tkp = new TOKEN_PRIVILEGES();

            long luid = 0;
            int retLen = 0;

            try
            {
                IntPtr processHandle = Process.GetCurrentProcess().Handle;
                bool success = OpenProcessToken(processHandle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle);
                if (!success)
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to open process token.");

                LookupPrivilegeValue(null, SE_SHUTDOWN_NAME, ref luid);

                tkp.PrivilegeCount = 1;
                tkp.Privileges.Luid = luid;
                tkp.Privileges.Attributes = SE_PRIVILEGE_ENABLED;

                success = AdjustTokenPrivileges(tokenHandle, false, ref tkp, 0, IntPtr.Zero, ref retLen);
                if (!success)
                    throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to shutdown priveleges.");
            }
            finally
            {
                if (tokenHandle != IntPtr.Zero)
                    Marshal.FreeHGlobal(tokenHandle);
                //log.Debug(m => m("Done granting shutdown privileges to process user."));
            }
        }
示例#48
0
 private static extern int AdjustTokenPrivileges(IntPtr TokenHandle, int DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, int BufferLength, ref TOKEN_PRIVILEGES PreviousState, ref int ReturnLength);
示例#49
0
 /// <summary>
 /// Tries to enable the specified privilege.
 /// </summary>
 /// <param name="privilege">The privilege to enable.</param>
 /// <exception cref="PrivilegeException">There was an error while requesting a required privilege.</exception>
 /// <remarks>Thanks to Michael S. Muegel for notifying us about a bug in this code.</remarks>
 private static void EnableToken(string privilege)
 {
   if (Environment.OSVersion.Platform != PlatformID.Win32NT || !CheckEntryPoint("advapi32.dll", "AdjustTokenPrivileges"))
     return;
   IntPtr tokenHandle = IntPtr.Zero;
   LUID privilegeLUID = new LUID();
   TOKEN_PRIVILEGES newPrivileges = new TOKEN_PRIVILEGES();
   TOKEN_PRIVILEGES tokenPrivileges;
   if (OpenProcessToken(Process.GetCurrentProcess().Handle, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref tokenHandle) == 0)
     throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error()));
   if (LookupPrivilegeValue("", privilege, ref privilegeLUID) == 0)
     throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error()));
   tokenPrivileges.PrivilegeCount = 1;
   tokenPrivileges.Privileges.Attributes = SE_PRIVILEGE_ENABLED;
   tokenPrivileges.Privileges.pLuid = privilegeLUID;
   int size = 4;
   if (AdjustTokenPrivileges(tokenHandle, 0, ref tokenPrivileges, 4 + (12 * tokenPrivileges.PrivilegeCount), ref newPrivileges, ref size) == 0)
     throw new PrivilegeException(FormatError(Marshal.GetLastWin32Error()));
 }
示例#50
0
 private static extern int AdjustTokenPrivileges(int tokenhandle, int disableprivs, ref TOKEN_PRIVILEGES Newstate, int bufferlength, int PreivousState, int Returnlength);
示例#51
0
        /// <summary>
        /// Takes a full path to a reparse point and finds the target.
        /// </summary>
        /// <param name="path">Full path of the reparse point</param>
        public ReparsePoint(string path)
        {
            Debug.Assert(!string.IsNullOrEmpty(path) && path.Length > 2 && path[1] == ':' && path[2] == '\\');
            normalisedTarget = "";
            tag = TagType.None;
            bool success;
            int lastError;
            // Apparently we need to have backup privileges
            IntPtr token;
            TOKEN_PRIVILEGES tokenPrivileges = new TOKEN_PRIVILEGES();
            tokenPrivileges.Privileges = new LUID_AND_ATTRIBUTES[1];
            success = OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES, out token);
            lastError = Marshal.GetLastWin32Error();
            if (success) {
                success = LookupPrivilegeValue(null, SE_BACKUP_NAME, out tokenPrivileges.Privileges[0].Luid);			// null for local system
                lastError = Marshal.GetLastWin32Error();
                if (success) {
                    tokenPrivileges.PrivilegeCount = 1;
                    tokenPrivileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
                    success = AdjustTokenPrivileges(token, false, ref tokenPrivileges, Marshal.SizeOf(tokenPrivileges), IntPtr.Zero, IntPtr.Zero);
                    lastError = Marshal.GetLastWin32Error();
                }
                CloseHandle(token);
            }

            if (success) {
                // Open the file and get its handle
                IntPtr handle = CreateFile(path, FileAccess.Read, FileShare.None, 0, FileMode.Open, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
                lastError = Marshal.GetLastWin32Error();
                if (handle.ToInt32() >= 0) {
                    REPARSE_DATA_BUFFER buffer = new REPARSE_DATA_BUFFER();
                    // Make up the control code - see CTL_CODE on ntddk.h
                    uint controlCode = (FILE_DEVICE_FILE_SYSTEM << 16) | (FILE_ANY_ACCESS << 14) | (FSCTL_GET_REPARSE_POINT << 2) | METHOD_BUFFERED;
                    uint bytesReturned;
                    success = DeviceIoControl(handle, controlCode, IntPtr.Zero, 0, out buffer, MAXIMUM_REPARSE_DATA_BUFFER_SIZE, out bytesReturned, IntPtr.Zero);
                    lastError = Marshal.GetLastWin32Error();
                    if (success) {
                        string subsString = "";
                        string printString = "";
                        // Note that according to http://wesnerm.blogs.com/net_undocumented/2006/10/symbolic_links_.html
                        // Symbolic links store relative paths, while junctions use absolute paths
                        // however, they can in fact be either, and may or may not have a leading \.
                        Debug.Assert(buffer.ReparseTag == IO_REPARSE_TAG_SYMLINK || buffer.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT,
                            "Unrecognised reparse tag");						// We only recognise these two
                        if (buffer.ReparseTag == IO_REPARSE_TAG_SYMLINK) {
                            // for some reason symlinks seem to have an extra two characters on the front
                            subsString = new string(buffer.ReparseTarget, (buffer.SubsNameOffset / 2 + 2), buffer.SubsNameLength / 2);
                            printString = new string(buffer.ReparseTarget, (buffer.PrintNameOffset / 2 + 2), buffer.PrintNameLength / 2);
                            tag = TagType.SymbolicLink;
                        } else if (buffer.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT) {
                            // This could be a junction or a mounted drive - a mounted drive starts with "\\??\\Volume"
                            subsString = new string(buffer.ReparseTarget, buffer.SubsNameOffset / 2, buffer.SubsNameLength / 2);
                            printString = new string(buffer.ReparseTarget, buffer.PrintNameOffset / 2, buffer.PrintNameLength / 2);
                            tag = subsString.StartsWith(@"\??\Volume") ? TagType.MountPoint : TagType.JunctionPoint;
                        }
                        Debug.Assert(!(string.IsNullOrEmpty(subsString) && string.IsNullOrEmpty(printString)), "Failed to retrieve parse point");
                        // the printstring should give us what we want
                        if (!string.IsNullOrEmpty(printString)) {
                            normalisedTarget = printString;
                        } else {
                            // if not we can use the substring with a bit of tweaking
                            normalisedTarget = subsString;
                            Debug.Assert(normalisedTarget.Length > 2, "Target string too short");
                            Debug.Assert(
                                (normalisedTarget.StartsWith(@"\??\") && (normalisedTarget[5] == ':' || normalisedTarget.StartsWith(@"\??\Volume")) ||
                                (!normalisedTarget.StartsWith(@"\??\") && normalisedTarget[1] != ':')),
                                "Malformed subsString");
                            // Junction points must be absolute
                            Debug.Assert(
                                    buffer.ReparseTag == IO_REPARSE_TAG_SYMLINK ||
                                    normalisedTarget.StartsWith(@"\??\Volume") ||
                                    normalisedTarget[1] == ':',
                                "Relative junction point");
                            if (normalisedTarget.StartsWith(@"\??\")) {
                                normalisedTarget = normalisedTarget.Substring(4);
                            }
                        }
                        actualTarget = normalisedTarget;
                        // Symlinks can be relative.
                        if (buffer.ReparseTag == IO_REPARSE_TAG_SYMLINK && (normalisedTarget.Length < 2 || normalisedTarget[1] != ':')) {
                            // it's relative, we need to tack it onto the path
                            if (normalisedTarget[0] == '\\') {
                                normalisedTarget = normalisedTarget.Substring(1);
                            }
                            if (path.EndsWith(@"\")) {
                                path = path.Substring(0, path.Length - 1);
                            }
                            // Need to take the symlink name off the path
                            normalisedTarget = path.Substring(0, path.LastIndexOf('\\')) + @"\" + normalisedTarget;
                            // Note that if the symlink target path contains any ..s these are not normalised but returned as is.
                        }
                        // Remove any final slash for consistency
                        if (normalisedTarget.EndsWith("\\")) {
                            normalisedTarget = normalisedTarget.Substring(0, normalisedTarget.Length - 1);
                        }
                    }
                    CloseHandle(handle);
                } else {
                    success = false;
                }
            }
        }
示例#52
0
 private static extern int AdjustTokenPrivileges(int tokenhandle, int disableprivs, ref TOKEN_PRIVILEGES Newstate, int bufferlength, int PreivousState, int Returnlength);
示例#53
0
 private static extern bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, int BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
示例#54
0
        /// <summary>
        ///     Starts the given application *without* admin rights.
        /// </summary>
        /// <remarks>
        ///     Taken from <see cref="http://stackoverflow.com/questions/11169431/how-to-start-a-new-process-without-administrator-privileges-from-a-process-with"/>,
        ///     thanks Ahmed.
        /// </remarks>
        /// <param name="fileName"></param>
        public static void RunAsDesktopUser(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
            {
                throw new ArgumentException("Value cannot be null or whitespace.", nameof(fileName));
            }

            // To start process as shell user you will need to carry out these steps:
            // 1. Enable the SeIncreaseQuotaPrivilege in your current token
            // 2. Get an HWND representing the desktop shell (GetShellWindow)
            // 3. Get the Process ID(PID) of the process associated with that window(GetWindowThreadProcessId)
            // 4. Open that process(OpenProcess)
            // 5. Get the access token from that process (OpenProcessToken)
            // 6. Make a primary token with that token(DuplicateTokenEx)
            // 7. Start the new process with that primary token(CreateProcessWithTokenW)

            var hProcessToken = IntPtr.Zero;

            // Enable SeIncreaseQuotaPrivilege in this process.  (This won't work if current process is not elevated.)
            try
            {
                var process = GetCurrentProcess();
                if (!OpenProcessToken(process, 0x0020, ref hProcessToken))
                {
                    return;
                }

                var tkp = new TOKEN_PRIVILEGES
                {
                    PrivilegeCount = 1,
                    Privileges     = new LUID_AND_ATTRIBUTES[1]
                };

                if (!LookupPrivilegeValue(null, "SeIncreaseQuotaPrivilege", ref tkp.Privileges[0].Luid))
                {
                    return;
                }

                tkp.Privileges[0].Attributes = 0x00000002;

                if (!AdjustTokenPrivileges(hProcessToken, false, ref tkp, 0, IntPtr.Zero, IntPtr.Zero))
                {
                    return;
                }
            }
            finally
            {
                CloseHandle(hProcessToken);
            }

            // Get an HWND representing the desktop shell.
            // CAVEATS:  This will fail if the shell is not running (crashed or terminated), or the default shell has been
            // replaced with a custom shell.  This also won't return what you probably want if Explorer has been terminated and
            // restarted elevated.
            var hwnd = GetShellWindow();

            if (hwnd == IntPtr.Zero)
            {
                return;
            }

            var hShellProcess      = IntPtr.Zero;
            var hShellProcessToken = IntPtr.Zero;
            var hPrimaryToken      = IntPtr.Zero;

            try
            {
                // Get the PID of the desktop shell process.
                uint dwPID;
                if (GetWindowThreadProcessId(hwnd, out dwPID) == 0)
                {
                    return;
                }

                // Open the desktop shell process in order to query it (get the token)
                hShellProcess = OpenProcess(ProcessAccessFlags.QueryInformation, false, dwPID);
                if (hShellProcess == IntPtr.Zero)
                {
                    return;
                }

                // Get the process token of the desktop shell.
                if (!OpenProcessToken(hShellProcess, 0x0002, ref hShellProcessToken))
                {
                    return;
                }

                var dwTokenRights = 395U;

                // Duplicate the shell's process token to get a primary token.
                // Based on experimentation, this is the minimal set of rights required for CreateProcessWithTokenW (contrary to current documentation).
                if (!DuplicateTokenEx(hShellProcessToken, dwTokenRights, IntPtr.Zero,
                                      SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, out hPrimaryToken))
                {
                    return;
                }

                // Start the target process with the new token.
                var si = new STARTUPINFO();
                var pi = new PROCESS_INFORMATION();
                if (!CreateProcessWithTokenW(hPrimaryToken, 0, fileName, "", 0, IntPtr.Zero, Path.GetDirectoryName(fileName),
                                             ref si, out pi))
                {
                    return;
                }
            }
            finally
            {
                CloseHandle(hShellProcessToken);
                CloseHandle(hPrimaryToken);
                CloseHandle(hShellProcess);
            }
        }
示例#55
0
 static extern bool AdjustTokenPrivileges(IntPtr TokenHandle,
     [MarshalAs(UnmanagedType.Bool)]bool DisableAllPrivileges,
     ref TOKEN_PRIVILEGES NewState,
     UInt32 Zero,
     IntPtr Null1,
     IntPtr Null2);
示例#56
0
        public static bool AdjustTokenPrivileges(IntPtr TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, UInt32 BufferLengthInBytes, ref TOKEN_PRIVILEGES PreviousState, out UInt32 ReturnLengthInBytes)
        {
            IntPtr proc = GetProcAddress(GetAdvapi32(), "AdjustTokenPrivileges");

            NativeSysCall.Delegates.AdjustTokenPrivileges AdjustTokenPrivileges = (NativeSysCall.Delegates.AdjustTokenPrivileges)Marshal.GetDelegateForFunctionPointer(proc, typeof(NativeSysCall.Delegates.AdjustTokenPrivileges));
            return(AdjustTokenPrivileges(TokenHandle, DisableAllPrivileges, ref NewState, BufferLengthInBytes, ref PreviousState, out ReturnLengthInBytes));
        }