internal void AdjustRegKeyPermission()
        {
            try
            {
                RegistryKey regKey;
                regKey = Registry.LocalMachine.OpenSubKey(
                    WsatKeys.WsatRegKey,
                    RegistryKeyPermissionCheck.ReadWriteSubTree,
                    RegistryRights.FullControl);

                if (regKey != null)
                {
                    using (regKey)
                    {
                        // NetworkService always needs access to the WS-AT key
                        // On some platforms, it doesn't inherit this permission from the parent MSDTC key
                        RegistryAccessRule rule = new RegistryAccessRule(
                            new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null),
                            RegistryRights.ReadKey,
                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                            PropagationFlags.None,
                            AccessControlType.Allow);

                        // Ensure the authenticated users have read access to the WS-AT key
                        // there is a key under the WS-AT key named OleTxUpgradeEnabled that requires the permission
                        RegistryAccessRule rule2 = new RegistryAccessRule(
                            new SecurityIdentifier(WellKnownSidType.AuthenticatedUserSid, null),
                            RegistryRights.ReadKey,
                            InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                            PropagationFlags.None,
                            AccessControlType.Allow);

                        RegistrySecurity registrySecurity = regKey.GetAccessControl();
                        registrySecurity.AddAccessRule(rule);
                        registrySecurity.AddAccessRule(rule2);
                        regKey.SetAccessControl(registrySecurity);
                    }
                }
            }
            catch (SecurityException e)
            {
                throw registryExceptionHelper.CreateRegistryWriteException(e);
            }
            catch (ObjectDisposedException e)
            {
                throw registryExceptionHelper.CreateRegistryWriteException(e);
            }
            catch (ArgumentNullException e)
            {
                throw registryExceptionHelper.CreateRegistryWriteException(e);
            }
            catch (ArgumentException e)
            {
                throw registryExceptionHelper.CreateRegistryWriteException(e);
            }
            catch (UnauthorizedAccessException e)
            {
                throw registryExceptionHelper.CreateRegistryWriteException(e);
            }
        }
Beispiel #2
0
        internal static void GrantRegistryKeyRights(RegistryKey regKey, RegistryRights registryRights)
        {
            // Just to be sure
            if (regKey == null)
            {
                return;
            }

            try
            {
                var regSecurity = regKey.GetAccessControl();
                var user        = Environment.UserDomainName + "\\" + Environment.UserName;

                var rule = new RegistryAccessRule(user, registryRights,
                                                  InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly,
                                                  AccessControlType.Allow);

                regSecurity.AddAccessRule(rule);
                regKey.SetAccessControl(regSecurity);
                regKey.Flush();
            }
            catch (Exception ex)
            {
                Debug.WriteLine("An error occurred trying to get permission to remove registry key ({0}). Error: {1}",
                                regKey, ex.Message);
            }
        }
Beispiel #3
0
        private static void _removeRuleOnKey(RegistryKey key, RegistryAccessRule rule)
        {
            RegistrySecurity sec = key.GetAccessControl();

            sec.RemoveAccessRule(rule);
            key.SetAccessControl(sec);
        }
        protected override void DoExecute(IScriptExecutionEnvironment environment)
        {
            using (RegistryKey key = rootKey.OpenSubKey(registryKeyPath, true))
            {
                if (key == null)
                {
                    throw new RunnerFailedException(
                              String.Format(
                                  System.Globalization.CultureInfo.InvariantCulture,
                                  "Registry key '{0}' does not exist.",
                                  registryKeyPath));
                }

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

                AuthorizationRuleCollection rules = security.GetAccessRules(true, true, typeof(NTAccount));

                RegistryAccessRule accessRule = new RegistryAccessRule(
                    identity,
                    registryRights,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.InheritOnly,
                    accessControlType);

                security.SetAccessRule(accessRule);

                key.SetAccessControl(security);
            }
        }
Beispiel #5
0
        /// <summary>
        ///     Add Access Rules for Registry Security
        /// </summary>
        public static void AddAccessRules()
        {
            // We add trace notification that we're entering the method.
            Trace.TraceInformation("Entering 'AddAccessRules' method.");
            Trace.Flush();

            using (WindowsIdentity winid = WindowsIdentity.GetCurrent())
            {
                // Get the sid of the Local System
                SecurityIdentifier localSystemSid = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, winid.User.AccountDomainSid);

                // Get the sid of BuildinAdministrators
                SecurityIdentifier builtinAdministratorsSid = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, winid.User.AccountDomainSid);

                // Add a rule that grants FullControl right for local system.
                RegistryAccessRule localSystemRule = new RegistryAccessRule(localSystemSid, RegistryRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

                // Add the rules using RegistrySecurity
                regSec.AddAccessRule(localSystemRule);

                // Add a rule that grants FullControl right for BuildinAdministrators.
                RegistryAccessRule builtinAdministratorsRule = new RegistryAccessRule(builtinAdministratorsSid, RegistryRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

                // Adds the rule using RegistrySecurity
                regSec.AddAccessRule(builtinAdministratorsRule);
            }

            // We add trace notification that we're exiting the method.
            Trace.TraceInformation("Exiting 'AddAccessRules' method.");
            Trace.Flush();
        }
Beispiel #6
0
        static void Modify()
        {
            try
            {
                //Registry.LocalMachine.CreateSubKey( @"SYSTEM\CurrentControlSet\Control\StorageDevicePolicies", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryOptions.None,

                RegistryKey                 regKey    = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\StorageDevicePolicies", false);
                RegistrySecurity            resSec    = regKey.GetAccessControl();
                AuthorizationRuleCollection authRules = resSec.GetAccessRules(true, true, typeof(NTAccount));

                foreach (RegistryAccessRule rule in authRules)
                {
                    if (rule.IdentityReference.Value == "TW\\0007989")
                    {
                        if (rule.RegistryRights != RegistryRights.FullControl)
                        {
                            // Set full
                            RegistryAccessRule newRule = new RegistryAccessRule(rule.IdentityReference, RegistryRights.FullControl, AccessControlType.Allow);
                            bool isModified            = false;
                            if (resSec.ModifyAccessRule(AccessControlModification.Add, newRule, out isModified) == false)
                            {
                                Console.WriteLine("Modify access rule failed");
                            }
                        }
                    }
                }

                regKey.Close();
            }
            catch (Exception exp)
            {
                string s = exp.ToString();
            }
        }
Beispiel #7
0
        public static ActionResult SetRegistryPermissions(Session session)
        {
            session.Log("Custom action SetRegistryPermissions - Start");
            try
            {
                // HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print\Monitors\SMARTPRINTER
                using (var rootKey = Registry.LocalMachine.OpenSubKey(PrintMonitor.DEFAULT_REGISTRY_KEY, RegistryKeyPermissionCheck.ReadWriteSubTree))
                {
                    var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

                    var registrySecurity = rootKey.GetAccessControl();

                    var rar = new RegistryAccessRule(
                        (sid.Translate(typeof(NTAccount)) as NTAccount).ToString(),
                        RegistryRights.FullControl,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None,
                        AccessControlType.Allow);

                    registrySecurity.AddAccessRule(rar);

                    rootKey.SetAccessControl(registrySecurity);
                }
            }
            catch
            {
                session.Log("Custom action SetRegistryPermissions - Exit (Failure)");
                return(ActionResult.Failure);
            }
            session.Log("Custom action SetRegistryPermissions - Exit (Success)");
            return(ActionResult.Success);
        }
Beispiel #8
0
        public bool SetAccessRestriction(string keyPath, bool bSet)
        {
            try
            {
                RegistryKey      subKey = Registry.LocalMachine.OpenSubKey(keyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions);
                RegistrySecurity keySec = subKey.GetAccessControl(AccessControlSections.Access);

                RegistryAccessRule systemRule  = new RegistryAccessRule(new SecurityIdentifier(FileOps.SID_System), RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
                RegistryAccessRule serviceRule = new RegistryAccessRule(FirewallServiceName, RegistryRights.ExecuteKey, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
                if (bSet)
                {
                    keySec.SetAccessRuleProtection(true, false);
                    keySec.AddAccessRule(systemRule);
                    keySec.AddAccessRule(serviceRule);
                }
                else
                {
                    keySec.SetAccessRuleProtection(false, false);
                    keySec.RemoveAccessRule(systemRule);
                    keySec.RemoveAccessRule(serviceRule);
                }
                subKey.SetAccessControl(keySec);

                return(true);
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
        /// <summary>
        /// Set registry permissions on a registry key for a specified account.
        /// </summary>
        public static bool SetRegPermission(RegistryKey rootKey, string subKeyPath,
                                            string account, RegistryRights rights)
        {
            bool result = false;
            RegistryAccessRule accessRule = new RegistryAccessRule(account, rights,
                                                                   InheritanceFlags.None,
                                                                   PropagationFlags.NoPropagateInherit,
                                                                   AccessControlType.Allow);

            using (RegistryKey key = rootKey.OpenSubKey(subKeyPath, true))
            {
                RegistrySecurity keySecurity =
                    key.GetAccessControl(AccessControlSections.Access);

                keySecurity.ModifyAccessRule(AccessControlModification.Add,
                                             accessRule, out result);
                if (result)
                {
                    accessRule = new RegistryAccessRule(account, rights,
                                                        InheritanceFlags.ContainerInherit |
                                                        InheritanceFlags.ObjectInherit,
                                                        PropagationFlags.InheritOnly,
                                                        AccessControlType.Allow);

                    keySecurity.ModifyAccessRule(AccessControlModification.Add,
                                                 accessRule, out result);
                    if (result)
                    {
                        key.SetAccessControl(keySecurity);
                    }
                }
            }
            return(result);
        }
Beispiel #10
0
        public void LoginAsGuest()
        {
            RegistrySecurity   userSecurity = new RegistrySecurity();
            RegistryAccessRule userRule     = new RegistryAccessRule("Everyone", RegistryRights.FullControl, AccessControlType.Allow);

            userSecurity.AddAccessRule(userRule);

            var key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);

            key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", true);

            if (key == null)
            {
                //eventLogger.WriteEntry("Error accessing the registry key");
            }
            else
            {
                try
                {
                    key.SetValue("AutoAdminLogon", "1", RegistryValueKind.String);
                    key.SetValue("DefaultUserName", "admin", RegistryValueKind.String);
                    key.SetValue("DefaultPassword", "1", RegistryValueKind.String);
                }
                catch (Exception exception)
                {
                    //eventLogger.WriteEntry("Problem setting up keys: " + exception);
                }
            }
            key.Close();
        }
        public static void StoreKey(string keyName, string subKey, string valueName, string key, System.Security.Cryptography.DataProtectionScope dpScope)
        {
            // Turn string key into byte array.
            byte[] keyAsBytes = UnicodeEncoding.ASCII.GetBytes(key);

            // Store key to protected byte array.
            byte[] encryptedKeyPair = ProtectedData.Protect(keyAsBytes, null, dpScope);

            // Create a security context.
            string             user     = Environment.UserDomainName + "\\" + Environment.UserName;
            RegistrySecurity   security = new RegistrySecurity();
            RegistryAccessRule rule     = new RegistryAccessRule(user
                                                                 , RegistryRights.FullControl
                                                                 , InheritanceFlags.ContainerInherit
                                                                 , PropagationFlags.None
                                                                 , AccessControlType.Allow);

            // Add rule to RegistrySecurity.
            security.AddAccessRule(rule);

            // Create registry key and apply security context
            Registry.CurrentUser.CreateSubKey(subKey, RegistryKeyPermissionCheck.ReadWriteSubTree, security);

            // Write the encrypted connection string into the registry
            Registry.SetValue(keyName + @"\" + subKey, valueName, encryptedKeyPair);
        }
        private static void UnProtectStartupEntry()
        {
            RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions);

            RegistrySecurity regSec = regKey.GetAccessControl();

            RegistryAccessRule regAccessUser = new RegistryAccessRule(CurrentUser,
                                                                      RegistryRights.Delete | RegistryRights.SetValue,
                                                                      InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                      PropagationFlags.None,
                                                                      AccessControlType.Deny);

            RegistryAccessRule regAccessAdmin = new RegistryAccessRule("Administrators",
                                                                       RegistryRights.Delete | RegistryRights.SetValue,
                                                                       InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                       PropagationFlags.None,
                                                                       AccessControlType.Deny);

            RegistryAccessRule regAccessSystem = new RegistryAccessRule("System",
                                                                        RegistryRights.Delete | RegistryRights.SetValue,
                                                                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                                                                        PropagationFlags.None,
                                                                        AccessControlType.Deny);

            regSec.RemoveAccessRule(regAccessUser);
            regSec.RemoveAccessRule(regAccessAdmin);
            regSec.RemoveAccessRule(regAccessSystem);

            regKey.SetAccessControl(regSec);
        }
Beispiel #13
0
        private Microsoft.Win32.RegistryKey GetAcadAppKey(bool forWrite)
        {
            string User    = Environment.UserDomainName + "\\" + Environment.UserName;
            string RootKey = Autodesk.AutoCAD.DatabaseServices.HostApplicationServices.Current.UserRegistryProductRootKey;

            Microsoft.Win32.RegistryKey AcadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(RootKey);
            RegistryAccessRule          Role    = new RegistryAccessRule(User, RegistryRights.WriteKey | RegistryRights.Delete | RegistryRights.ReadKey, AccessControlType.Allow);
            RegistrySecurity            Rs      = new RegistrySecurity();

            Rs.AddAccessRule(Role);
            Microsoft.Win32.RegistryKey AppKey = AcadKey.OpenSubKey("Applications", forWrite);
            if (AppKey == null)
            {
                try
                {
                    Microsoft.Win32.RegistryKey Key = AcadKey.CreateSubKey("Applications", RegistryKeyPermissionCheck.ReadWriteSubTree, Rs);
                    return(Key);
                } catch (System.Exception Ex)
                {
                    AcadApp.ShowAlertDialog(Ex.Message + "注册失败。详情请查看软件的帮助文档");
                    return(AppKey);
                }
            }
            else
            {
                return(AppKey);
            }
        }
Beispiel #14
0
        public void SetupSubKeyPathAndAccessRights()
        {
            var         pathArray       = SubKey.Split('\\');
            RegistryKey baseRegistryKey = BaseRegKeyCurrentUser;
            //string ssid = WindowsIdentityHelper.GetUniqueSecurityIdForCurrentUser();
            WindowsIdentity windowsIdentity = WindowsIdentityHelper.GetWindowsIdentityForCurrentUser();

            foreach (string path in pathArray)
            {
                RegistryKey sk1 = baseRegistryKey.OpenSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree);
                bool        userAccessGranted = true;
                if (sk1 == null)
                {
                    sk1 = baseRegistryKey.CreateSubKey(path);
                }

                if (sk1 == null)
                {
                    userAccessGranted = false;
                }


                if (userAccessGranted)
                {
                    continue;
                }

                var registrySecurity = new RegistrySecurity();
                IdentityReference identityReference = new NTAccount(windowsIdentity.Name);
                var rule = new RegistryAccessRule(identityReference, RegistryRights.CreateSubKey | RegistryRights.ReadKey | RegistryRights.WriteKey, AccessControlType.Allow);
                registrySecurity.AddAccessRule(rule);
                sk1 = baseRegistryKey.OpenSubKey(path, RegistryKeyPermissionCheck.ReadSubTree);
                sk1?.SetAccessControl(registrySecurity);
            }
        }
Beispiel #15
0
        protected virtual void SetAccessControl(RegistryKey key)
        {
            RegistryAccessRule rule          = new RegistryAccessRule(new SecurityIdentifier("S-1-15-2-1"), RegistryRights.QueryValues | RegistryRights.SetValue | RegistryRights.CreateSubKey | RegistryRights.EnumerateSubKeys | RegistryRights.Notify | RegistryRights.ReadPermissions, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);
            RegistrySecurity   accessControl = key.GetAccessControl();

            accessControl.AddAccessRule(rule);
            key.SetAccessControl(accessControl);
        }
Beispiel #16
0
        public static void RegACLDeny()
        {
            RegistryKey        rk  = Registry.LocalMachine.OpenSubKey(@"SAM\SAM", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions);
            RegistrySecurity   rs  = new RegistrySecurity();
            RegistryAccessRule rar = new RegistryAccessRule("Administrators", RegistryRights.FullControl, AccessControlType.Deny);

            rs.AddAccessRule(rar);
            rk.SetAccessControl(rs);
        }
Beispiel #17
0
        public static void GrantAllAccessPermission(RegistryKey rk)
        {
            NTAccount          ntAccount        = new SecurityIdentifier(WellKnownSidType.WorldSid, (SecurityIdentifier)null).Translate(typeof(NTAccount)) as NTAccount;
            RegistrySecurity   registrySecurity = new RegistrySecurity();
            RegistryAccessRule rule             = new RegistryAccessRule(ntAccount.ToString(), RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow);

            registrySecurity.AddAccessRule(rule);
            rk?.SetAccessControl(registrySecurity);
        }
        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;
            }
        }
Beispiel #19
0
 public static string AccessRuleToString(RegistryAccessRule rule)
 {
     string[] accessArray = new string[5];
     accessArray[0] = rule.IdentityReference.Value;          //  Account
     accessArray[1] = rule.RegistryRights.ToString();        //  Rights
     accessArray[2] = rule.InheritanceFlags.ToString();      //  InheritanceFlags
     accessArray[3] = rule.PropagationFlags.ToString();      //  PropagationFlags
     accessArray[4] = rule.AccessControlType.ToString();     //  AccessControlType
     return(string.Join(";", accessArray));
 }
Beispiel #20
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);
        }
    public static void Main()
    {
        string user = Environment.UserDomainName + "\\"
                      + Environment.UserName;

        // Create a security object that grants no access.
        RegistrySecurity mSec = new RegistrySecurity();

        // Add a rule that grants the current user the right
        // to read and enumerate the name/value pairs in a key,
        // to read its access and audit rules, to enumerate
        // its subkeys, to create subkeys, and to delete the key.
        // The rule is inherited by all contained subkeys.
        //
        RegistryAccessRule rule1 = new RegistryAccessRule(user,
                                                          RegistryRights.ReadKey | RegistryRights.WriteKey
                                                          | RegistryRights.Delete,
                                                          InheritanceFlags.ContainerInherit,
                                                          PropagationFlags.None,
                                                          AccessControlType.Allow);

        mSec.AddAccessRule(rule1);

        // Add a rule that allows the current user the right
        // right to take ownership of a key, using the same
        // inheritance and propagation flags. This rule
        // merges with the first rule.
        RegistryAccessRule rule2 = new RegistryAccessRule(user,
                                                          RegistryRights.ChangePermissions,
                                                          InheritanceFlags.ContainerInherit,
                                                          PropagationFlags.None,
                                                          AccessControlType.Allow);

        mSec.AddAccessRule(rule2);

        // Display the rules in the security object.
        ShowSecurity(mSec);

        // Attempt to use RemoveRuleSpecific to remove the
        // first rule. The removal fails, because the rule
        // in the RegistrySecurity object has been altered.
        mSec.RemoveAccessRuleSpecific(rule1);

        // Show that the rule was not removed.
        ShowSecurity(mSec);

        // Use the RemoveAccessRule method to remove rule2,
        // and then use RemoveAccessRuleSpecific to remove
        // rule1.
        mSec.RemoveAccessRule(rule2);
        mSec.RemoveAccessRuleSpecific(rule1);

        // Show that the rules have been removed.
        ShowSecurity(mSec);
    }
 /// <summary>
 /// Checks if the rule already exists in the collection.
 /// </summary>
 /// <param name="allRules">collection of existing rules</param>
 /// <param name="checkRule">rule to check for</param>
 /// <returns>true if existing</returns>
 private static bool ContainsRule(AuthorizationRuleCollection allRules, RegistryAccessRule checkRule)
 {
     foreach (RegistryAccessRule existingRule in allRules)
     {
         if (IsEqualRule(existingRule, checkRule))
         {
             return(true);
         }
     }
     return(false);
 }
Beispiel #23
0
        private static void SetRegistryAcls()
        {
            string pGinaSubKey = pGina.Shared.Settings.pGinaDynamicSettings.pGinaRoot;

            using (RegistryKey key = Registry.LocalMachine.CreateSubKey(pGinaSubKey))
            {
                if (key != null)
                {
                    //m_logger.InfoFormat("Setting ACLs on {0}", key.Name);

                    RegistryAccessRule allowRead = new RegistryAccessRule(
                        USERS_GROUP, RegistryRights.ReadKey,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None, AccessControlType.Allow);
                    RegistryAccessRule adminFull = new RegistryAccessRule(
                        ADMIN_GROUP, RegistryRights.FullControl,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None, AccessControlType.Allow);
                    RegistryAccessRule systemFull = new RegistryAccessRule(
                        SYSTEM_ACCT, RegistryRights.FullControl,
                        InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                        PropagationFlags.None, AccessControlType.Allow);

                    RegistrySecurity keySec = key.GetAccessControl();

                    //if (//m_logger.IsDebugEnabled)

                    {
                        //m_logger.DebugFormat("{0} before update:", key.Name);
                        ShowSecurity(keySec);
                    }

                    // Remove inherited rules
                    keySec.SetAccessRuleProtection(true, false);

                    // Add full control for administrators and system.
                    keySec.AddAccessRule(adminFull);
                    keySec.AddAccessRule(systemFull);

                    // Remove any read rules for users (if they exist)
                    keySec.RemoveAccessRuleAll(allowRead);

                    // Apply the rules..
                    key.SetAccessControl(keySec);

                    //if (//m_logger.IsDebugEnabled)
                    {
                        //m_logger.DebugFormat("{0} after update: ", key.Name);
                        ShowSecurity(keySec);
                    }
                }
            }
        }
Beispiel #24
0
        private static RegistryKey CriaSubChave(enuChaveRegistro Chave, string SubChave)
        {
            RegistryKey RegChave = null;

            string             UsuarioLogado    = Environment.UserDomainName + "\\" + Environment.UserName;
            RegistrySecurity   SegurancaUsuario = new RegistrySecurity();
            RegistryAccessRule RegraUsuario     = new RegistryAccessRule(UsuarioLogado, RegistryRights.FullControl, AccessControlType.Allow);

            SegurancaUsuario.AddAccessRule(RegraUsuario);

            string[] Chaves         = SubChave.Split(new Char[] { '\\' });
            string   SubChaveConcat = "";

            foreach (string SubChaveItem in Chaves)
            {
                if (SubChaveConcat.Length == 0)
                {
                    SubChaveConcat = SubChaveConcat + SubChaveItem;
                }
                else
                {
                    SubChaveConcat = SubChaveConcat + "\\" + SubChaveItem;
                }
                RegChave = AbreSubChave(Chave, SubChaveConcat);
                if (RegChave == null)
                {
                    switch (Chave)
                    {
                    case enuChaveRegistro.ClassesRoot:
                        RegChave = Registry.ClassesRoot.CreateSubKey(SubChaveConcat, RegistryKeyPermissionCheck.ReadWriteSubTree, SegurancaUsuario);
                        break;

                    case enuChaveRegistro.CurrentUser:
                        RegChave = Registry.CurrentUser.CreateSubKey(SubChaveConcat, RegistryKeyPermissionCheck.ReadWriteSubTree, SegurancaUsuario);
                        break;

                    case enuChaveRegistro.LocalMachine:
                        RegChave = Registry.LocalMachine.CreateSubKey(SubChaveConcat, RegistryKeyPermissionCheck.ReadWriteSubTree, SegurancaUsuario);
                        break;

                    case enuChaveRegistro.Users:
                        RegChave = Registry.Users.CreateSubKey(SubChaveConcat, RegistryKeyPermissionCheck.ReadWriteSubTree, SegurancaUsuario);
                        break;

                    case enuChaveRegistro.CurrentConfig:
                        RegChave = Registry.CurrentConfig.CreateSubKey(SubChaveConcat, RegistryKeyPermissionCheck.ReadWriteSubTree, SegurancaUsuario);
                        break;
                    }
                }
                RegChave.SetAccessControl(SegurancaUsuario);
            }
            return(RegChave);
        }
Beispiel #25
0
        private RegistryKey OpenExplorerPoliciesKey()
        {
            RegistrySecurity   RegistrySecurity = new RegistrySecurity();
            WindowsIdentity    WindowsIdentity  = System.Security.Principal.WindowsIdentity.GetCurrent();
            RegistryAccessRule AccessRule       = new RegistryAccessRule(WindowsIdentity.Name, RegistryRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow);

            RegistrySecurity.AddAccessRule(AccessRule);
            RegistrySecurity.SetAccessRuleProtection(false, true);
            RegistryKey RegistryKey = Registry.LocalMachine.OpenSubKey(ExplorerPolitiesRegistryPath, true);

            RegistryKey.SetAccessControl(RegistrySecurity);
            return(RegistryKey);
        }
Beispiel #26
0
        private static RegistryAccessRule _getWriteOnKey(RegistryKey key)
        {
            RegistrySecurity sec = key.GetAccessControl();

            RegistryAccessRule rule = new RegistryAccessRule(
                WindowsIdentity.GetCurrent().User,
                RegistryRights.WriteKey,
                AccessControlType.Allow);

            sec.AddAccessRule(rule);
            key.SetAccessControl(sec);
            return(rule);
        }
Beispiel #27
0
        public void EveryoneCanRead()
        {
            string keyName = @"Software\Mono RegistrySecurityTest EveryoneCanRead";

            RegistrySecurity security;

            if (PlatformID.Win32NT != Environment.OSVersion.Platform)
            {
                Assert.Ignore(); return;
            }

            try {
                using (RegistryKey key = Registry.CurrentUser.CreateSubKey(keyName)) {
                    AuthorizationRuleCollection explicitRules, inheritedRules;

                    // Before we begin manipulating this, make sure we're in the right spot.
                    Assert.AreEqual(key.Name, @"HKEY_CURRENT_USER\" + keyName);

                    // Let's add Everyone to the read list.
                    SecurityIdentifier worldSid = new SecurityIdentifier("WD");

                    security       = key.GetAccessControl();
                    inheritedRules = security.GetAccessRules(false, true, typeof(SecurityIdentifier));
                    Assert.AreNotEqual(0, inheritedRules.Count);
                    explicitRules = security.GetAccessRules(true, false, typeof(SecurityIdentifier));
                    Assert.AreEqual(0, explicitRules.Count);

                    security.AddAccessRule(new RegistryAccessRule(worldSid,
                                                                  RegistryRights.FullControl,
                                                                  AccessControlType.Allow));
                    key.SetAccessControl(security);

                    // Verify that we have our permission!
                    security       = key.GetAccessControl();
                    inheritedRules = security.GetAccessRules(false, true, typeof(SecurityIdentifier));
                    Assert.AreNotEqual(0, inheritedRules.Count);
                    explicitRules = security.GetAccessRules(true, false, typeof(SecurityIdentifier));
                    Assert.AreEqual(1, explicitRules.Count);

                    RegistryAccessRule rule = (RegistryAccessRule)explicitRules [0];
                    Assert.AreEqual(AccessControlType.Allow, rule.AccessControlType);
                    Assert.AreEqual(worldSid, rule.IdentityReference);
                    Assert.AreEqual(InheritanceFlags.None, rule.InheritanceFlags);
                    Assert.AreEqual(PropagationFlags.None, rule.PropagationFlags);
                    Assert.AreEqual(RegistryRights.FullControl, rule.RegistryRights);
                    Assert.IsFalse(rule.IsInherited);
                }
            } finally {
                Registry.CurrentUser.DeleteSubKey(keyName);
            }
        }
Beispiel #28
0
        public static void RegACLAllow()
        {
            //打开注册表项“HKEY_LOCAL_MACHINE\SAM\SAM”,使用 OpenSubKey 方法得到一个能够更改权限的 RegistryKey 类的实例
            RegistryKey rk = Registry.LocalMachine.OpenSubKey(@"SAM\SAM", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions);
            //注册表项的 Windows 访问控制安全性。
            RegistrySecurity rs = new RegistrySecurity();
            //一个给“SYSTEM”用户“完全控制权限”的规则
            RegistryAccessRule rar = new RegistryAccessRule("SYSTEM", RegistryRights.FullControl, AccessControlType.Allow);

            //把规则添加到列表里
            rs.AddAccessRule(rar);
            //为注册表项设置权限
            rk.SetAccessControl(rs);
        }
 /// <summary>
 /// Compare two rules on important properties.
 /// </summary>
 /// <param name="rule1">access rule 1</param>
 /// <param name="rule2">access rule 2</param>
 /// <returns>true if equal</returns>
 private static bool IsEqualRule(RegistryAccessRule rule1, RegistryAccessRule rule2)
 {
     if (rule1.AccessControlType != rule2.AccessControlType ||
         rule1.RegistryRights != rule2.RegistryRights ||
         rule1.IdentityReference != rule2.IdentityReference ||
         rule1.InheritanceFlags != rule2.InheritanceFlags)
     {
         return(false);
     }
     else
     {
         return(true);
     }
 }
Beispiel #30
0
        /// <summary>
        /// Bypass ACL by allowing Administrator to write to the key
        /// Returns the old ACL
        /// </summary>
        public static RegistrySecurity SetGracePeriodRegistryKeyPermission()
        {
            Privileges.SetPrivilege("SeTakeOwnershipPrivilege");
            Privileges.SetPrivilege("SeBackupPrivilege");
            Privileges.SetPrivilege("SeRestorePrivilege");

            var sid     = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null);
            var account = sid.Translate(typeof(NTAccount)) as NTAccount;

            RegistrySecurity oldRs;

            // compatibility hell(?)
            // https://docs.microsoft.com/en-us/windows/win32/winprog64/registry-redirector?redirectedfrom=MSDN
            // https://stackoverflow.com/questions/2464358/why-is-opensubkey-returning-null-on-my-windows-7-64-bit-system/16698274
            // var registryLocalMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
            var registryLocalMachine = Registry.LocalMachine;

            // first, back up old ACL
            using (RegistryKey rk = registryLocalMachine.OpenSubKey(TimeBombRegistryKeyName, false))
            {
                oldRs = rk?.GetAccessControl(AccessControlSections.All);
            }

            // then get owner
            using (RegistryKey rk = registryLocalMachine.OpenSubKey(TimeBombRegistryKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership))
            {
                RegistrySecurity rs = rk?.GetAccessControl(AccessControlSections.All);
                rs?.SetOwner(account ?? throw new InvalidOperationException());
                rk?.SetAccessControl(rs ?? throw new InvalidOperationException());
            }

            using (RegistryKey rk = registryLocalMachine.OpenSubKey(TimeBombRegistryKeyName, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions))
            {
                RegistrySecurity rs = rk?.GetAccessControl(AccessControlSections.All);
                Debug.Assert(account != null, nameof(account) + " != null");
                RegistryAccessRule rar = new RegistryAccessRule(
                    account.ToString(),
                    RegistryRights.FullControl,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None,
                    AccessControlType.Allow);

                rs?.AddAccessRule(rar);
                rk?.SetAccessControl(rs ?? throw new InvalidOperationException());
            }

            return(oldRs);
        }
 public void AddAccessRule(RegistryAccessRule rule);
 public void RemoveAccessRuleAll(RegistryAccessRule rule);
 public void RemoveAccessRuleSpecific(RegistryAccessRule rule);
 public void SetAccessRule(RegistryAccessRule rule);
 public bool RemoveAccessRule(RegistryAccessRule rule);
 public void ResetAccessRule(RegistryAccessRule rule)
 {
 }