コード例 #1
0
        private static void ChangeRegKeyOwner(RegistryKey registryKey, IdentityReference identity)
        {
            RegistrySecurity nSubKeySec = registryKey.GetAccessControl(AccessControlSections.Owner);

            nSubKeySec.SetOwner(identity);
            registryKey.SetAccessControl(nSubKeySec);
        }
コード例 #2
0
        public void AddRegistryKey(string keyPath, string value, string data)
        {
            RegistryKey registryKey = Registry.LocalMachine;

            using (RegistryKey myRegKey = registryKey.OpenSubKey(keyPath, true))
            {
                //myRegKey.SetValue(value, data);

                //if (myRegKey.GetValueNames().Contains(value))
                //{
                //    myRegKey.SetValue(value, data);
                //}
                //else
                //{
                //    Console.WriteLine((string)registryKey.GetValue("id", "ID not found."));
                //}

                RegistryKey      rk  = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions | RegistryRights.ReadKey);
                RegistrySecurity sec = new RegistrySecurity();

                sec.AddAccessRule(new RegistryAccessRule("Administrator", RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
                rk.SetAccessControl(sec);
                rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
                sec.SetOwner(new NTAccount("Administrators"));
                rk.SetAccessControl(sec);
                rk.SetValue("AutoAdminLogon", "1");
                rk.SetValue("DefaultUserName", "admin");
                rk.SetValue("DefaultPassword", "1");
                rk.SetValue("DefaultDomainName", "INTOWINDOWS");
            }
        }
コード例 #3
0
        // It's up to the caller to obtain the needed privileges (TakeOwnership) for this operation
        public static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName)
        {
            using RegistryKey subKey = registryKey.OpenSubKeyOrThrowIfMissing(subkeyName, RegistryRights.TakeOwnership);
            RegistrySecurity accessRules = subKey.GetAccessControl();

            accessRules.SetOwner(WindowsIdentity.GetCurrent().User);
            subKey.SetAccessControl(accessRules);
        }
コード例 #4
0
        // It's up to the caller to obtain the needed privileges (TakeOwnership) for this operation
        public static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName)
        {
            using RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName, RegistryRights.TakeOwnership);
            RegistrySecurity accessRules = subKey.GetAccessControl();

            accessRules.SetOwner(RetrieveCurrentUserIdentifier());
            subKey.SetAccessControl(accessRules);
        }
コード例 #5
0
        public RegistryKey CreateRegKey(string regKeyName = "")
        {
            if (string.IsNullOrEmpty(regKeyName))
            {
                regKeyName = _regKey;
            }
            else
            {
                regKeyName = $"{this._regKey}\\{regKeyName}";
            }

            // creazione chiave
            _baseKey?.CreateSubKey(regKeyName ?? "", RegistryKeyPermissionCheck.ReadWriteSubTree)?.Close();

            // apertura con permessi per modifica permesssi
            RegistryKey key = _baseKey?.OpenSubKey(
                regKeyName,
                RegistryKeyPermissionCheck.ReadWriteSubTree,
                RegistryRights.ChangePermissions | RegistryRights.ReadKey | RegistryRights.WriteKey |
                RegistryRights.FullControl
                );

            // permessi da applicare
            RegistryRights acl = RegistryRights.WriteKey | RegistryRights.ReadKey | RegistryRights.Delete;

            // attuale policy
            if (EnvironmentUtils.IsWin())
            {
                try
                {
                    RegistrySecurity regSec = key?.GetAccessControl();

                    // aggiunta policy all'attuale
                    regSec?.AddAccessRule(
                        new RegistryAccessRule(
                            $"{Environment.UserDomainName}\\{Environment.UserName}",
                            acl,
                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                            PropagationFlags.InheritOnly,
                            AccessControlType.Allow
                            )
                        );

                    // definizione proprietario
                    regSec?.SetOwner(new NTAccount($"{Environment.UserDomainName}\\{Environment.UserName}"));

                    // applicazione della policy
                    key?.SetAccessControl(regSec);
                }
                catch
                {
                    // ignore
                }
            }

            return(key);
        }
コード例 #6
0
 private static void SetKeyOwner(RegistryKey key, string subKey, string owner)
 {
     using (RegistryKey registryKey = key.OpenSubKey(subKey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership))
     {
         RegistrySecurity registrySecurity = new RegistrySecurity();
         registrySecurity.SetOwner(new NTAccount(owner));
         registryKey.SetAccessControl(registrySecurity);
     }
 }
コード例 #7
0
        public void TakeOwnership(string regPath, RegistryHive registryHive)
        {
            var baseReg = RegistryKey.OpenBaseKey(registryHive, RegistryView.Registry64);

            try {
                /* Get the ID of the current user (aka Amin)
                 */
                WindowsIdentity id = WindowsIdentity.GetCurrent();

                /* Add the TakeOwnership Privilege
                 */
                bool blRc = Natif.MySetPrivilege(Natif.TakeOwnership, true);
                if (!blRc)
                {
                    throw new PrivilegeNotHeldException(Natif.TakeOwnership);
                }

                /* Add the Restore Privilege (must be done to change the owner)
                 */
                blRc = Natif.MySetPrivilege(Natif.Restore, true);
                if (!blRc)
                {
                    throw new PrivilegeNotHeldException(Natif.Restore);
                }

                /* Open a registry which I don't own
                 */
                RegistryKey      rkADSnapInsNodesTypes = baseReg.OpenSubKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
                RegistrySecurity regSecTempo           = rkADSnapInsNodesTypes.GetAccessControl(AccessControlSections.All);

                /* Get the real owner
                 */
                IdentityReference  oldId = regSecTempo.GetOwner(typeof(SecurityIdentifier));
                SecurityIdentifier siTrustedInstaller = new SecurityIdentifier(oldId.ToString());

                /* process user become the owner
                 */
                regSecTempo.SetOwner(id.User);
                rkADSnapInsNodesTypes.SetAccessControl(regSecTempo);

                /* Add the full control
                 */
                RegistryAccessRule regARFullAccess = new RegistryAccessRule(id.User, RegistryRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
                regSecTempo.AddAccessRule(regARFullAccess);
                rkADSnapInsNodesTypes.SetAccessControl(regSecTempo);

                /* Do something
                 */
                rkADSnapInsNodesTypes.CreateSubKey("dummy");
                rkADSnapInsNodesTypes.DeleteSubKey("dummy");
            }
            catch (Exception excpt)
            {
                throw excpt;
            }
        }
コード例 #8
0
        private static void ChangeRegKeyFullControl(RegistryKey registryKey, IdentityReference identity)
        {
            RegistrySecurity   nSubKeySec = registryKey.GetAccessControl(AccessControlSections.Access);
            RegistryAccessRule nAccRule   = new RegistryAccessRule(identity, RegistryRights.FullControl, AccessControlType.Allow);

            nSubKeySec.AddAccessRule(nAccRule);
            registryKey.SetAccessControl(nSubKeySec);
            nSubKeySec.SetOwner(identity);
            registryKey.SetAccessControl(nSubKeySec);
        }
コード例 #9
0
        private void disableButton_Click(object sender, EventArgs e)
        {
            int disable = 1;

            if (sender == enableButton)
            {
                disable = 0;
            }
#if !DEBUG
            try
#endif
            {
                var hklm = Environment.Is64BitOperatingSystem ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) : Registry.LocalMachine;
                Privileges.EnablePrivilege(SecurityEntity.SE_TAKE_OWNERSHIP_NAME);
                using (RegistryKey regKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership))
                {
                    RegistrySecurity rs = regKey.GetAccessControl(AccessControlSections.None);
                    //rs.SetGroup(new NTAccount("Administrators"));
                    rs.SetOwner(WindowsIdentity.GetCurrent().User);
                    rs.SetAccessRuleProtection(false, false);

                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.FullControl, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.WriteKey, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.ChangePermissions, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.CreateLink, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.CreateSubKey, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.Delete, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.EnumerateSubKeys, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.ExecuteKey, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.Notify, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.QueryValues, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.ReadKey, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.ReadPermissions, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.SetValue, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.TakeOwnership, AccessControlType.Allow));
                    rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.WriteKey, AccessControlType.Allow));
                    regKey.SetAccessControl(rs);
                }
                using (RegistryKey regKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.SetValue))
                {
                    regKey.SetValue("DisableAntiSpyware", disable);
                    regKey.SetValue("DisableAntiVirus", disable);
                }
                if (MessageBox.Show(this, "Done! For changes to take effect, the system needs to be restarted.\n\nWould you like to restart now?", "Done.", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
                {
                    Process.Start("shutdown", "/r /t 0");
                }
            }
#if !DEBUG
            catch (Exception ex)
            {
                MessageBox.Show(this, "Please post this to the XDA thread (link in the app):\n" + ex.Message + "\n" + ex.Source + "\n" + ex.HelpLink + "\n" + ex.StackTrace, "Operation Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
#endif
        }
コード例 #10
0
        // It's up to the caller to obtain the needed token privileges (TakeOwnership) for this operation
        public static void GrantFullControlOnSubKey(this RegistryKey registryKey, string subkeyName)
        {
            using RegistryKey subKey = registryKey.OpenSubKeyOrThrowIfMissing(subkeyName,
                                                                              RegistryRights.TakeOwnership | RegistryRights.ChangePermissions
                                                                              );
            RegistrySecurity accessRules = subKey.GetAccessControl();

            accessRules.SetOwner(WindowsIdentity.GetCurrent().User);
            accessRules.ResetAccessRule(
                new RegistryAccessRule(
                    WindowsIdentity.GetCurrent().User,
                    RegistryRights.FullControl,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None,
                    AccessControlType.Allow
                    )
                );
            subKey.SetAccessControl(accessRules);
        }
コード例 #11
0
        private bool Class_Root_Anahtar_Varmi(string ClassRoot_Anahtar)
        {
            RegistrySecurity registrySecurity = new RegistrySecurity();

            registrySecurity.AddAccessRule(new RegistryAccessRule("Administrators", RegistryRights.WriteKey, AccessControlType.Allow));
            registrySecurity.SetOwner(new NTAccount("Administrators"));
            try
            {
                using (RegistryKey key = Registry.ClassesRoot.OpenSubKey(ClassRoot_Anahtar, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.WriteKey))
                {
                    if ((key == null) && (Registry.ClassesRoot.CreateSubKey(ClassRoot_Anahtar, RegistryKeyPermissionCheck.ReadWriteSubTree, registrySecurity) != null))
                    {
                        return(true);
                    }
                }
            }
            catch (Exception exception)
            {
            }
            return(false);
        }
コード例 #12
0
        private bool anahtar_varmi(string CurrentUserAnahtar)
        {
            string           name             = CurrentUserAnahtar;
            RegistrySecurity registrySecurity = new RegistrySecurity();

            registrySecurity.AddAccessRule(new RegistryAccessRule("Administrators", RegistryRights.FullControl, AccessControlType.Allow));
            registrySecurity.SetOwner(new NTAccount("Administrators"));
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(name, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl))
                {
                    if ((key == null) && (Registry.CurrentUser.CreateSubKey(name, RegistryKeyPermissionCheck.ReadWriteSubTree, registrySecurity) != null))
                    {
                        return(true);
                    }
                }
            }
            catch
            {
                //MessageBox.Show("CurrentUser anahtar");
            }
            return(false);
        }
コード例 #13
0
        static bool RegSetOwneship(RegistryKey nParentKey, string nkey, IdentityReference nuser)
        {
            RegistryKey nSubKey = null;

            try
            {
                nSubKey = nParentKey.OpenSubKey(nkey, RegistryKeyPermissionCheck.ReadWriteSubTree,
                                                RegistryRights.TakeOwnership | RegistryRights.ReadKey | RegistryRights.ReadPermissions);
                RegistrySecurity nSubKeySec = nSubKey.GetAccessControl(AccessControlSections.Owner);
                nSubKeySec.SetOwner(nuser);
                nSubKey.SetAccessControl(nSubKeySec);
                nSubKey.Close();
                return(true);
            }
            catch
            {
                if (nSubKey != null)
                {
                    nSubKey.Close();
                }
                return(false);
            }
        }
コード例 #14
0
        private void fixRights()
        {
            // We have a private key inside the registry, therefore we should ensure only admins have access to it
            RegistryKey      regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
            RegistrySecurity regSec = regKey.GetAccessControl(AccessControlSections.All);

            regSec.SetOwner(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null));
            regSec.SetAccessRuleProtection(true, false);
            regKey.SetAccessControl(regSec);
            RegistryAccessRule adminFull = new RegistryAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), RegistryRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

            regSec.AddAccessRule(adminFull);
            adminFull = new RegistryAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), RegistryRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
            regSec.AddAccessRule(adminFull);
            string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName;

            // If we're joined to a domain, we probably need to give access to domain admins as well
            if ((domain != null) && (domain.Length > 0))
            {
                adminFull = new RegistryAccessRule(new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, null), RegistryRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
                regSec.AddAccessRule(adminFull);
            }
            regKey.SetAccessControl(regSec);
        }
コード例 #15
0
 private bool setupRegKeyRights(string currentUser, RegistryKey baseKey)
 {
     try
     {
         var rights = RegistryRights.ChangePermissions | RegistryRights.ReadKey | RegistryRights.SetValue;
         var rk     = baseKey.OpenSubKey(
             rootKey,
             RegistryKeyPermissionCheck.ReadWriteSubTree,
             rights);
         if (rk == null)
         {
             return(false);
         }
         RegistrySecurity rs = new RegistrySecurity();
         // Create access rule gIVing full control to the current user.
         rs.AddAccessRule(
             new RegistryAccessRule(currentUser,
                                    RegistryRights.FullControl,
                                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                    PropagationFlags.InheritOnly,
                                    AccessControlType.Allow));
         // Apply the new access rule to this Registry Key.
         rk.SetAccessControl(rs);
         rk = baseKey.OpenSubKey(
             rootKey,
             RegistryKeyPermissionCheck.ReadWriteSubTree,
             RegistryRights.FullControl);         // Opens the key again with full control.
         rs.SetOwner(new NTAccount(currentUser)); // Set the securits owner to be current user.
         rk.SetAccessControl(rs);                 // Set the key with the changed permission so current user is now owner.
     }
     catch                                        //(Exception e)
     {
         return(false);
     }
     return(true);
 }
コード例 #16
0
        public static void ByPassTamper()
        {
            try
            {
                // Get the ID of the current user

                WindowsIdentity id = WindowsIdentity.GetCurrent();

                // Add the TakeOwnership Privilege

                bool blRc = TokenManipulation.MySetPrivilege(TokenManipulation.TakeOwnership, true);

                if (!blRc)
                {
                    throw new PrivilegeNotHeldException(TokenManipulation.TakeOwnership);
                }


                /* Add the Restore Privilege (must be done to change the owner)
                 */
                blRc = TokenManipulation.MySetPrivilege(TokenManipulation.Restore, true);
                if (!blRc)
                {
                    throw new PrivilegeNotHeldException(TokenManipulation.Restore);
                }


                // Open a registry which I don't own

                RegistryKey OwnerShipByPass = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\Features", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);

                RegistrySecurity regSecTempo = OwnerShipByPass.GetAccessControl(AccessControlSections.All);

                // Get the real owner

                IdentityReference  oldId = regSecTempo.GetOwner(typeof(SecurityIdentifier));
                SecurityIdentifier siTrustedInstaller = new SecurityIdentifier(oldId.ToString());
                //Console.WriteLine(oldId.ToString());

                // process user become the owner

                regSecTempo.SetOwner(id.User);
                OwnerShipByPass.SetAccessControl(regSecTempo);

                RegistryAccessRule regARFullAccess = new RegistryAccessRule(id.User, RegistryRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

                regSecTempo.AddAccessRule(regARFullAccess);
                OwnerShipByPass.SetAccessControl(regSecTempo);


                #region Write to Registry (Disable  Defender and Tamper)
                DisableFender(true, true); // disable tamper and defender
                #endregion

                // Put back the original owner

                regSecTempo.SetOwner(siTrustedInstaller);
                OwnerShipByPass.SetAccessControl(regSecTempo);

                // Put back the original Rights

                regSecTempo.RemoveAccessRule(regARFullAccess);
                OwnerShipByPass.SetAccessControl(regSecTempo);
            }
            catch (Exception)
            {
                //MessageBox.Show(ex.ToString());
            }
        }
コード例 #17
0
        private bool CurrentUser_Register_Deger_Yaz(string CurrentUserYol, string anahtar, object deger, string tur)
        {
            RegistrySecurity security = new RegistrySecurity();

            security.AddAccessRule(new RegistryAccessRule("Administrators", RegistryRights.FullControl, AccessControlType.Allow));
            security.SetOwner(new NTAccount("Administrators"));
            try
            {
                using (RegistryKey key = Registry.CurrentUser.OpenSubKey(CurrentUserYol, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl))
                {
                    if (key != null)
                    {
                        if (key.GetValue(anahtar) != null)
                        {
                            key.DeleteValue(anahtar);
                        }
                        if (tur == "")
                        {
                            key.SetValue(anahtar, deger);
                        }
                        else if (tur == "str")
                        {
                            key.SetValue(anahtar, deger, RegistryValueKind.String);
                        }
                        else if (tur == "bin")
                        {
                            key.SetValue(anahtar, deger, RegistryValueKind.Binary);
                        }
                        else if (tur == "exp_str")
                        {
                            key.SetValue(anahtar, deger, RegistryValueKind.ExpandString);
                        }
                        else if (tur == "none")
                        {
                            key.SetValue(anahtar, deger, RegistryValueKind.None);
                        }
                        else if (tur == "multi_str")
                        {
                            key.SetValue(anahtar, deger, RegistryValueKind.MultiString);
                        }
                        else if (tur == "dword")
                        {
                            key.SetValue(anahtar, deger, RegistryValueKind.DWord);
                        }
                        else if (tur == "qword")
                        {
                            key.SetValue(anahtar, deger, RegistryValueKind.QWord);
                        }
                        else if (tur == "unknow")
                        {
                            key.SetValue(anahtar, deger, RegistryValueKind.Unknown);
                        }
                        return(true);
                    }
                }
            }
            catch (Exception exception)
            {
                //MessageBox.Show("CurrentUser: " + exception.Message);
            }
            return(false);
        }
コード例 #18
0
        /// <summary>获取注册表项权限</summary>
        /// <remarks>将注册表项所有者改为当前管理员用户</remarks>
        /// <param name="regPath">要获取权限的注册表完整路径</param>
        public static void TakeRegKeyOwnerShip(string regPath)
        {
            if (regPath.IsNullOrWhiteSpace())
            {
                return;
            }
            RegistryKey     key = null;
            WindowsIdentity id  = null;

            //利用试错判断是否有写入权限
            try { key = RegistryEx.GetRegistryKey(regPath, true); }
            catch (Exception)
            {
                try
                {
                    //获取当前用户的ID
                    id = WindowsIdentity.GetCurrent();

                    //添加TakeOwnership特权
                    bool flag = NativeMethod.TrySetPrivilege(NativeMethod.TakeOwnership, true);
                    if (!flag)
                    {
                        throw new PrivilegeNotHeldException(NativeMethod.TakeOwnership);
                    }

                    //添加恢复特权(必须这样做才能更改所有者)
                    flag = NativeMethod.TrySetPrivilege(NativeMethod.Restore, true);
                    if (!flag)
                    {
                        throw new PrivilegeNotHeldException(NativeMethod.Restore);
                    }

                    //打开没有权限的注册表路径
                    key = RegistryEx.GetRegistryKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);

                    RegistrySecurity security = key.GetAccessControl(AccessControlSections.All);

                    //得到真正所有者
                    //IdentityReference oldId = security.GetOwner(typeof(SecurityIdentifier));
                    //SecurityIdentifier siTrustedInstaller = new SecurityIdentifier(oldId.ToString());

                    //使进程用户成为所有者
                    security.SetOwner(id.User);
                    key.SetAccessControl(security);

                    //添加完全控制
                    RegistryAccessRule fullAccess = new RegistryAccessRule(id.User, RegistryRights.FullControl,
                                                                           InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
                    security.AddAccessRule(fullAccess);
                    key.SetAccessControl(security);

                    //注册表操作(写入、删除)
                    //key.SetValue("temp", "");//示例

                    //恢复原有所有者
                    //security.SetOwner(siTrustedInstaller);
                    //key.SetAccessControl(security);

                    //收回原有权利
                    //security.RemoveAccessRule(fullAccess);
                    //key.SetAccessControl(security);

                    ///得到真正所有者、注册表操作、恢复原有所有者、收回原有权利,这四部分在原文中没有被注释掉
                    ///但是如果保留这四部分,会在恢复原有所有者这一步抛出异常,提示没有权限,
                    ///不过我发现经过上面的操作,虽然无法还原所有者权限,但是已经获取了注册表权限
                    ///即已经将TrustedInstaller权限更改为当前管理员用户权限,我要的目的已经达到了
                }
                catch (Exception) { }
            }
            finally { key?.Close(); id?.Dispose(); }
        }
コード例 #19
0
        public static bool WriteTrustedRegistry(int regType, string regPath, bool blAdd)
        {
            try
            {
                WindowsIdentity current = WindowsIdentity.GetCurrent();
                if (!Trust.MySetPrivilege("SeTakeOwnershipPrivilege", true))
                {
                    Logger.Info("Failed to take ownership privilege");
                    return(false);
                }
                if (!Trust.MySetPrivilege("SeRestorePrivilege", true))
                {
                    Logger.Info("Failed to restore ownership privilege");
                    return(false);
                }
                RegistryKey registryKey = (RegistryKey)null;
                switch (regType)
                {
                case 0:
                    registryKey = Registry.ClassesRoot.OpenSubKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
                    break;

                case 1:
                    registryKey = Registry.CurrentUser.OpenSubKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
                    break;

                case 2:
                    registryKey = Registry.LocalMachine.OpenSubKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership);
                    break;
                }
                if (registryKey == null)
                {
                    return(true);
                }
                RegistrySecurity   accessControl      = registryKey.GetAccessControl(AccessControlSections.All);
                SecurityIdentifier securityIdentifier = new SecurityIdentifier(accessControl.GetOwner(typeof(SecurityIdentifier)).ToString());
                accessControl.SetOwner((IdentityReference)current.User);
                registryKey.SetAccessControl(accessControl);
                RegistryAccessRule rule = new RegistryAccessRule((IdentityReference)current.User, RegistryRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);
                accessControl.AddAccessRule(rule);
                registryKey.SetAccessControl(accessControl);
                registryKey.Close();
                switch (regType)
                {
                case 0:
                    registryKey = Registry.ClassesRoot.OpenSubKey(regPath, true);
                    break;

                case 1:
                    registryKey = Registry.CurrentUser.OpenSubKey(regPath, true);
                    break;

                case 2:
                    registryKey = Registry.LocalMachine.OpenSubKey(regPath, true);
                    break;
                }
                if (blAdd)
                {
                    registryKey.SetValue((string)null, (object)FixUpOle.olePath);
                }
                else
                {
                    registryKey.SetValue((string)null, (object)"oleaut32.dll");
                }
                accessControl.SetOwner((IdentityReference)securityIdentifier);
                registryKey.SetAccessControl(accessControl);
                accessControl.RemoveAccessRule(rule);
                registryKey.SetAccessControl(accessControl);
                registryKey.Close();
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }