Пример #1
0
    public static void Main(string[] args)
    {
        if (args.Length < 1)
        {
            Console.WriteLine("No Args");
            System.Environment.Exit(1);
        }
        else
        {
            Console.WriteLine(args[0]);
        }

        RegistryKey      key      = Registry.LocalMachine.OpenSubKey(args[0]);
        RegistrySecurity security = key.GetAccessControl();


        foreach (RegistryAccessRule rule in security.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
        {
            if (rule.InheritanceFlags.ToString() == "None")
            {
                Console.WriteLine("        User: {0}", rule.IdentityReference);
                Console.WriteLine("        Type: {0}", rule.AccessControlType);
                Console.WriteLine("      Rights: {0}", rule.RegistryRights);
                //Console.WriteLine(" Inheritance: {0}", rule.InheritanceFlags);
                //Console.WriteLine(" Propagation: {0}", rule.PropagationFlags);
                //Console.WriteLine("   Inherited? {0}", rule.IsInherited);
                Console.WriteLine();
            }
        }
    }
Пример #2
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();
            }
        }
Пример #3
0
 /// <summary>
 /// Class constructor. if extra = false, builds the base config. if extra = true, builds the extra certificate config.
 /// </summary>
 public RegistryConfig(bool extra = false)
 {
     try
     {
         if (Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes") == null)
         {
             Registry.LocalMachine.OpenSubKey("SOFTWARE", true).CreateSubKey("WinCertes", true);
         }
         if (extra)
         {
             if (Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes").OpenSubKey("extra") == null)
             {
                 _logger.Debug("Creating SubKey 'extra'");
                 Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes", true).CreateSubKey("extra", true);
             }
             _registryKey += @"\extra";
             _subKey      += @"\extra";
         }
         RegistryKey      regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes");
         RegistrySecurity regSec = regKey.GetAccessControl(AccessControlSections.All);
         foreach (RegistryAccessRule rule in regSec.GetAccessRules(true, true, typeof(NTAccount)))
         {
             if (rule.IdentityReference.Value == @"BUILTIN\Users")
             {
                 _logger.Debug("Users have rights on Registry entry: Need to fix rights");
                 fixRights();
                 break;
             }
         }
     }
     catch (Exception e)
     {
         _logger.Warn(e, $"Warning: Could not open/create registry subkey: {e.Message}. We'll try to continue anyway.");
     }
 }
        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);
            }
        }
        public void CanDiaplayDaclForRegistryKey()
        {
            RegistrySecurity            security = Registry.CurrentUser.GetAccessControl();
            AuthorizationRuleCollection rules    = security.GetAccessRules(true, true, typeof(NTAccount));

            PrintRegistryAccessRights(rules);
        }
Пример #6
0
        /// <summary>
        /// Class constructor. <code>certificateStore</code> specifies the name of the certificate being managed.
        /// </summary>
        /// <remarks>
        /// If <code>certificateStore</code> is provided a sub key is created to store all information about this specific
        /// certificate. <code>extra=true</code> provides legacy support for the "extra" certificate store sub key.
        /// Registry security is enforced from the parent HKLM\Software minus Users.
        /// No support is provided for any credentials like "MyDomain\Certificate Users" as it hits the *users* filter.
        /// </remarks>
        /// <param name="certificateStore">Name of subkey to store certificate information if more than one certificate
        /// is managed by WinCertes on this computer</param>
        private void Initialise(string certificateStore = null)
        {
            try
            {
                //
                // HKLM WinCertes key is for Administrative access only.
                // Manage access rights by using parent permissions from HKLM\Software and remove user permissions.
                //
                RegistryKey      keySoftware = Registry.LocalMachine.OpenSubKey("SOFTWARE", true);
                RegistrySecurity security    = keySoftware.GetAccessControl(AccessControlSections.Access);

                RegistryKey keyWinCertes = keySoftware.OpenSubKey(_keyBaseName, true);
                if (keyWinCertes == null)
                {
                    _logger.Info("Creating new Registry Key {0}", _keyBaseName);
                    keyWinCertes = keySoftware.CreateSubKey(_keyBaseName, RegistryKeyPermissionCheck.ReadWriteSubTree);
                }
                // Remove inheritance - also deletes all inherited rules
                RegistrySecurity securityWinCertes = keyWinCertes.GetAccessControl(AccessControlSections.All);
                securityWinCertes.SetAccessRuleProtection(true, false);
                // Copy rules from parent, except user access
                foreach (RegistryAccessRule rule in security.GetAccessRules(true, true, typeof(NTAccount)))
                {
                    try
                    {
                        // Copy all relevant rules except user
                        if (rule.IdentityReference.Value.IndexOf("Users", StringComparison.InvariantCultureIgnoreCase) < 0)
                        {
                            securityWinCertes.AddAccessRule(rule);
                        }
                    }
                    catch { }
                }
                keyWinCertes.SetAccessControl(securityWinCertes);
#if DEBUG
                //ShowSecurity(securityWinCertes);
#endif
                //
                // Now manage the certificate store
                //
                CertificateStore = certificateStore;
                if (certificateStore != null)
                {
                    if (keyWinCertes.OpenSubKey(certificateStore, true) == null)
                    {
                        _logger.Debug("Creating SubKey '{0}'", certificateStore);
                        keyWinCertes.CreateSubKey(certificateStore, true);
                        keyWinCertes.SetAccessControl(securityWinCertes);
                    }
                    FullRegistryKey       += @"\" + certificateStore;
                    HKLMRegistryKey       += @"\" + certificateStore;
                    HKLMCertificateParent += @"\" + _keyBaseName;
                }
                Initialised = true;
            }
            catch (Exception e)
            {
                _logger.Warn(e, $"Warning: Could not open/create registry subkey: {e.Message}. We'll try to continue anyway.");
            }
        }
Пример #7
0
        private void LoadSecurity(RegistryKey regKey)
        {
            RegistrySecurity security = regKey.GetAccessControl();

            this.Owner     = security.GetOwner(typeof(NTAccount)).Value;
            this.Access    = RegistryControl.AccessRulesToString(security.GetAccessRules(true, false, typeof(NTAccount)));
            this.Inherited = !security.AreAccessRulesProtected;
        }
Пример #8
0
        protected override void ProcessRecord()
        {
            using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, true))
            {
                bool             isChange = false;
                RegistrySecurity security = security = regKey.GetAccessControl();
                if (All)
                {
                    //  テスト自動生成
                    _generator.RegistryAccess(RegistryPath, "", false);

                    foreach (RegistryAccessRule rule in security.GetAccessRules(true, false, typeof(NTAccount)))
                    {
                        security.RemoveAccessRule(rule);
                        isChange = true;
                    }
                }
                else
                {
                    foreach (RegistryAccessRule rule in security.GetAccessRules(true, false, typeof(NTAccount)))
                    {
                        string account = rule.IdentityReference.Value;

                        //  テスト自動生成
                        _generator.RegistryAccount(RegistryPath, account);

                        if (Account.Contains("\\") && account.Equals(Account, StringComparison.OrdinalIgnoreCase) ||
                            !Account.Contains("\\") && account.EndsWith("\\" + Account, StringComparison.OrdinalIgnoreCase))
                        {
                            security.RemoveAccessRule(rule);
                            isChange = true;
                        }
                    }
                }

                if (isChange)
                {
                    regKey.SetAccessControl(security);
                }

                WriteObject(new RegistrySummary(regKey, true));
            }
        }
Пример #9
0
 private static void ShowSecurity(RegistrySecurity security)
 {
     foreach (RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(NTAccount)))
     {
         m_logger.DebugFormat("           User: {0}", ar.IdentityReference);
         m_logger.DebugFormat("           Type: {0}", ar.AccessControlType);
         m_logger.DebugFormat("         Rights: {0}", ar.RegistryRights);
         m_logger.DebugFormat("    Inheritance: {0}", ar.InheritanceFlags);
         m_logger.DebugFormat("    Propagation: {0}", ar.PropagationFlags);
         m_logger.DebugFormat("      Inherited? {0}", ar.IsInherited);
     }
 }
Пример #10
0
 /// <summary>
 /// Class constructor. if extra = false, builds the base config. if extra = true, builds the extra certificate config.
 /// </summary>
 public RegistryConfig(int extra = -1)
 {
     try
     {
         // First we check if WinCertes key is there
         RegistryKey winCertesKey = Registry.LocalMachine.OpenSubKey("SOFTWARE", true).OpenSubKey("WinCertes", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
         if (winCertesKey == null)
         {
             // and if not, we create it
             Registry.LocalMachine.OpenSubKey("SOFTWARE", true).CreateSubKey("WinCertes", RegistryKeyPermissionCheck.ReadWriteSubTree);
             winCertesKey = Registry.LocalMachine.OpenSubKey("SOFTWARE", true).OpenSubKey("WinCertes", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
         }
         // Let's fix the permissions
         RegistrySecurity winCertesKeySec = winCertesKey.GetAccessControl(AccessControlSections.All);
         // First we remove the inheritence
         winCertesKeySec.SetAccessRuleProtection(true, false);
         RegistrySecurity security = Registry.LocalMachine.OpenSubKey("SOFTWARE", false).GetAccessControl(AccessControlSections.Access);
         // Copy rules from parent ("HKLM\Software"), except user access
         foreach (RegistryAccessRule rule in security.GetAccessRules(true, true, typeof(NTAccount)))
         {
             try
             {
                 // Copy all relevant rules except user
                 if (rule.IdentityReference.Value.IndexOf("Users", StringComparison.InvariantCultureIgnoreCase) < 0)
                 {
                     winCertesKeySec.AddAccessRule(rule);
                 }
             }
             catch { }
         }
         winCertesKey.SetAccessControl(winCertesKeySec);
         if (extra > -1)
         {
             string extraIndex = "";
             if (extra > 1)
             {
                 extraIndex = extra.ToString();
             }
             if (Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes").OpenSubKey("extra" + extraIndex) == null)
             {
                 _logger.Debug("Creating SubKey 'extra" + extraIndex + "'");
                 Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes", true).CreateSubKey("extra" + extraIndex, RegistryKeyPermissionCheck.ReadWriteSubTree);
             }
             _registryKey += @"\extra" + extraIndex;
             _subKey      += @"\extra" + extraIndex;
         }
     }
     catch (Exception e)
     {
         _logger.Warn(e, $"Warning: Could not open/create registry subkey: {e.Message}. We'll try to continue anyway.");
     }
 }
Пример #11
0
        // checkRegistryPermissions()
        // Args: None
        // Function: check if the registry keys associated with services are modifiable by the current user.
        // Return: None (will print out alert if anything is found).
        static void checkRegistryPermissions()
        {
            string             myUser   = Environment.UserName;
            NTAccount          account  = new NTAccount(myUser);
            List <RegistryKey> services = getServices();
            List <string>      groups   = getGroupIdentities();

            foreach (RegistryKey service in services)
            {
                Dictionary <string, object> config      = getServiceConfig(service);
                RegistrySecurity            regSecurity = service.GetAccessControl();
                AuthorizationRuleCollection rules       = regSecurity.GetAccessRules(true, true, (account).GetType());
                List <string> exploitablePerms          = new List <string> {
                };
                foreach (RegistryAccessRule rule in rules)
                {
                    // Some identities have the BUILTIN\ prefix; this get's rid out it if it is there,
                    // but also handles the situations in which it's not.
                    string identity = "";
                    try
                    {
                        identity = rule.IdentityReference.ToString().Split('\\')[1];
                    }
                    catch (Exception)
                    {
                        identity = rule.IdentityReference.ToString();
                    }

                    string right = rule.RegistryRights.ToString();

                    // Checks if the identity is a group; if so, check if our user is within that group.
                    if (groups.Contains(identity))
                    {
                        List <string> members = getGroupMembers(identity);
                        if (members.Contains(myUser))
                        {
                            exploitablePerms.AddRange(checkPermissions(right));
                        }
                    }
                    else if (identity.Equals(myUser))
                    {
                        exploitablePerms.AddRange(checkPermissions(right));
                    }
                }

                if (exploitablePerms.Count > 0)
                {
                    string permString = string.Join(",", exploitablePerms);
                    printServiceModifiableAlert(service.Name, config, permString, myUser);
                }
            }
        }
Пример #12
0
    private static void ShowSecurity(RegistrySecurity security)
    {
        Console.WriteLine("\r\nCurrent access rules:\r\n");

        foreach (RegistryAccessRule ar in
                 security.GetAccessRules(true, true, typeof(NTAccount)))
        {
            Console.WriteLine("        User: {0}", ar.IdentityReference);
            Console.WriteLine("        Type: {0}", ar.AccessControlType);
            Console.WriteLine("      Rights: {0}", ar.RegistryRights);
            Console.WriteLine();
        }
    }
Пример #13
0
        /// <summary>
        /// Remove Permissions on a Registry key
        /// </summary>
        /// <param name="userName">the user name to remove permissions for</param>
        /// <param name="root">the root hive</param>
        /// <param name="subKey">the key</param>
        public static void RemoveRegistryKeyPermission(string userName, Microsoft.Win32.RegistryKey root, string subKey)
        {
            RegistryKey                 registryKey      = root.OpenSubKey(subKey);
            RegistrySecurity            registrySecurity = registryKey.GetAccessControl();
            AuthorizationRuleCollection accessRules      = registrySecurity.GetAccessRules(true, true, typeof(NTAccount));

            foreach (RegistryAccessRule accessRule in accessRules)
            {
                if (userName.ToLowerInvariant().Equals(accessRule.IdentityReference.Value.ToLowerInvariant()))
                {
                    registrySecurity.RemoveAccessRule(accessRule);
                }
            }
        }
Пример #14
0
 /// <summary>
 /// Utility to display security rules
 /// </summary>
 /// <param name="security">RegistrySecurity object from the RegistryKey</param>
 private static void ShowSecurity(RegistrySecurity security)
 {
     _logger.Info("Current access rules:");
     foreach (RegistryAccessRule rule in security.GetAccessRules(true, true, typeof(NTAccount)))
     {
         _logger.Info("        User: {0}", rule.IdentityReference);
         _logger.Info("        Type: {0}", rule.AccessControlType);
         _logger.Info("      Rights: {0}", rule.RegistryRights);
         _logger.Info(" Inheritance: {0}", rule.InheritanceFlags);
         _logger.Info(" Propagation: {0}", rule.PropagationFlags);
         _logger.Info("   Inherited? {0}", rule.IsInherited);
         _logger.Info("");
     }
 }
Пример #15
0
        protected override void ProcessRecord()
        {
            bool isChange = false;

            using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, false, true))
            {
                RegistrySecurity            security = regKey.GetAccessControl();
                AuthorizationRuleCollection rules    = security.GetAccessRules(true, false, typeof(NTAccount));
                if (All)
                {
                    //  テスト自動生成
                    TestGenerator.RegistryAccess(Path, "", false);

                    foreach (RegistryAccessRule rule in rules)
                    {
                        security.RemoveAccessRule(rule);
                        isChange = true;
                    }
                }
                else
                {
                    foreach (RegistryAccessRule rule in rules)
                    {
                        if (Account.Contains("\\") &&
                            rule.IdentityReference.Value.Equals(Account, StringComparison.OrdinalIgnoreCase))
                        {
                            //  テスト自動生成
                            TestGenerator.RegistryAccess(Path, RegistryControl.AccessRuleToString(rule), true);

                            security.RemoveAccessRule(rule);
                            isChange = true;
                        }
                        else if (!Account.Contains("\\") &&
                                 rule.IdentityReference.Value.EndsWith("\\" + Account, StringComparison.OrdinalIgnoreCase))
                        {
                            //  テスト自動生成
                            TestGenerator.RegistryAccess(Path, RegistryControl.AccessRuleToString(rule), true);

                            security.RemoveAccessRule(rule);
                            isChange = true;
                        }
                    }
                }
                if (isChange)
                {
                    regKey.SetAccessControl(security);
                }
            }
            WriteObject(new RegistryKeyInfo(Path, true));
        }
Пример #16
0
        /// <summary>
        /// apply registry security settings to user profiles
        /// </summary>
        /// <param name="where"></param>
        /// <param name="keyname"></param>
        /// <param name="username"></param>
        /// <returns></returns>
        public static Boolean RegSec(pInvokes.structenums.RegistryLocation where, string keyname, string username)
        {
            try
            {
                IdentityReference  UserIRef = new NTAccount(String.Format("{0}\\{1}", Environment.MachineName, username));
                SecurityIdentifier UserSid  = (SecurityIdentifier)UserIRef.Translate(typeof(SecurityIdentifier));

                using (RegistryKey key = pInvokes.GetRegistryLocation(where).OpenSubKey(keyname, true))
                {
                    RegistrySecurity keySecurity = key.GetAccessControl(AccessControlSections.Access);
                    string           SDDL        = keySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);
                    //LibraryLogging.Info(SDDL);

                    foreach (RegistryAccessRule user in keySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)))
                    {
                        //LibraryLogging.Info("registry ACE user: {0} {1} {2}", key.Name, user.InheritanceFlags.ToString(), user.IdentityReference.Value);
                        if (user.IdentityReference.Value.StartsWith("S-1-5-21-") && !user.IdentityReference.Value.Equals(UserIRef.Value))
                        {
                            //LibraryLogging.Info("mod registry ACE:{0} from unknown user:{1} to {2} {3} {4}", key.Name, user.IdentityReference.Value, username, user.RegistryRights.ToString(), user.AccessControlType.ToString());

                            SDDL = SDDL.Replace(user.IdentityReference.Value, UserSid.Value);
                            //LibraryLogging.Info(SDDL);
                            keySecurity.SetSecurityDescriptorSddlForm(SDDL);
                            key.SetAccessControl(keySecurity);

                            break;
                        }
                    }
                    foreach (string subkey in key.GetSubKeyNames())
                    {
                        if (!RegSec(where, keyname + "\\" + subkey, username))
                        {
                            return(false);
                        }
                    }
                }
            }
            catch (SystemException ex)
            {
                LibraryLogging.Warn("RegSec:{0} Warning {1}", keyname, ex.Message);
            }
            catch (Exception ex)
            {
                LibraryLogging.Error("RegSec:{0} Error:{1}", keyname, ex.Message);
                return(false);
            }

            return(true);
        }
Пример #17
0
        public static void PrintRegistrySecurity(RegistrySecurity security)
        {
            Console.WriteLine("\r\nCurrent access rules:\r\n");

            foreach (RegistryAccessRule ar in security.GetAccessRules(true, true, typeof(NTAccount)))
            {
                Console.WriteLine("        User: {0}", ar.IdentityReference);
                Console.WriteLine("        Type: {0}", ar.AccessControlType);
                Console.WriteLine("      Rights: {0}", ar.RegistryRights);
                Console.WriteLine(" Inheritance: {0}", ar.InheritanceFlags);
                Console.WriteLine(" Propagation: {0}", ar.PropagationFlags);
                Console.WriteLine("   Inherited? {0}", ar.IsInherited);
                Console.WriteLine();
            }
        }
Пример #18
0
        /// <summary>
        /// Verify that a specific user has access rights to a specific Registry Key
        /// </summary>
        /// <param name="userName">Name of the user to check for</param>
        /// <param name="root">Root key for the registry key</param>
        /// <param name="subKey">Registry key to check for</param>
        /// <param name="rights">Expected access rights</param>
        public static void VerifyRegistryKeyPermission(string userName, Microsoft.Win32.RegistryKey root, string subKey, RegistryRights rights)
        {
            RegistryKey                 registryKey      = root.OpenSubKey(subKey);
            RegistrySecurity            registrySecurity = registryKey.GetAccessControl();
            AuthorizationRuleCollection accessRules      = registrySecurity.GetAccessRules(true, true, typeof(NTAccount));

            foreach (RegistryAccessRule accessRule in accessRules)
            {
                if (userName.ToLowerInvariant().Equals(accessRule.IdentityReference.Value.ToLowerInvariant()))
                {
                    if ((accessRule.RegistryRights & rights) == rights)
                    {
                        return;
                    }
                }
            }

            Assert.True(false, string.Format("User '{0}' do not have the correct permessions to RegistryKey '{1}/{2}'.", userName, root.ToString(), subKey));
        }
Пример #19
0
        public static bool DoesUserHaveAccess(RegistryKey registryKey, string userNameOrSID, RegistryRights accessType)
        {
            RegistrySecurity registrySecurity = registryKey.GetAccessControl();

            foreach (RegistryAccessRule registryAccessRule in registrySecurity.GetAccessRules(true, true, typeof(NTAccount)))
            {
                IdentityReference sidIdentityReference = registryAccessRule.IdentityReference.Translate(typeof(SecurityIdentifier));

                if (
                    (userNameOrSID.Equals(registryAccessRule.IdentityReference.Value, StringComparison.InvariantCultureIgnoreCase) == true ||
                     userNameOrSID.Equals(sidIdentityReference.Value, StringComparison.InvariantCultureIgnoreCase) == true) &&
                    (registryAccessRule.RegistryRights & accessType) == accessType)
                {
                    return(true);
                }
            }

            return(false);
        }
Пример #20
0
        /// <summary>
        /// apply registry security settings to user profiles
        /// </summary>
        public static bool RegSec(Abstractions.WindowsApi.pInvokes.structenums.RegistryLocation where, string keyname, SecurityIdentifier userSid)
        {
            try
            {
                using (RegistryKey key = Abstractions.WindowsApi.pInvokes.GetRegistryLocation(where).OpenSubKey(keyname, true))
                {
                    RegistrySecurity keySecurity = key.GetAccessControl(AccessControlSections.Access);
                    string           sddl        = keySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.All);

                    foreach (RegistryAccessRule user in keySecurity.GetAccessRules(true, true, typeof(SecurityIdentifier)))
                    {
                        if (user.IdentityReference.Value.StartsWith("S-1-5-21-") && !user.IdentityReference.Value.Equals(userSid.Value))
                        {
                            sddl = sddl.Replace(user.IdentityReference.Value, userSid.Value);
                            keySecurity.SetSecurityDescriptorSddlForm(sddl);
                            key.SetAccessControl(keySecurity);

                            break;
                        }
                    }
                    foreach (string subkey in key.GetSubKeyNames())
                    {
                        if (!RegSec(where, keyname + "\\" + subkey, userSid))
                        {
                            return(false);
                        }
                    }
                }
            }
            catch (SystemException ex)
            {
                Log.WarnFormat("RegSec:{0} Warning {1}", keyname, ex.Message);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("RegSec:{0} Error:{1}", keyname, ex.Message);
                return(false);
            }

            return(true);
        }
Пример #21
0
        public const string FirewallServiceName = @"NT SERVICE\MpsSvc"; // Windows Defender Firewall

        public bool GetAccessRestriction(string keyPath)
        {
            try
            {
                RegistryKey      subKey = Registry.LocalMachine.OpenSubKey(keyPath, false);
                RegistrySecurity keySec = subKey.GetAccessControl(AccessControlSections.Access);

                foreach (var rule in keySec.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount)).Cast <AuthorizationRule>())
                {
                    if (rule.IdentityReference.Value.Equals(FirewallServiceName, StringComparison.OrdinalIgnoreCase))
                    {
                        return(true);
                    }
                }
            }
            catch (Exception err)
            {
                AppLog.Exception(err);
            }
            return(false);
        }
Пример #22
0
        /// <summary>
        /// Grants full control on the given registry key under RegistryKey for everyone
        /// </summary>
        /// <param name="subKey">subkey name</param>
        public static void GrantFullControlRegKey(RegistryKey baseKey, string subKey)
        {
            RegistryKey rKey = baseKey.OpenSubKey(subKey, true);

            if (rKey == null)
            {
                return;
            }
            Console.WriteLine("Granting full control to: {0}\\{1}", baseKey, subKey);
            try
            {
                // Create a SecurityIdentifier object for "everyone".
                SecurityIdentifier everyoneSid =
                    new SecurityIdentifier(WellKnownSidType.WorldSid, null);

                RegistrySecurity   security = rKey.GetAccessControl();
                RegistryAccessRule newRule  =
                    new RegistryAccessRule(
                        everyoneSid,
                        RegistryRights.FullControl,                                         // modify is enough for reading/writing/deleting
                        InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, // all subfolders and files
                        PropagationFlags.None,
                        AccessControlType.Allow);

                // Check if such a rule already exists, if so skip the modifications
                if (ContainsRule(security.GetAccessRules(true, true, typeof(SecurityIdentifier)), newRule))
                {
                    Console.WriteLine("Permissions already set.");
                    return;
                }

                security.AddAccessRule(newRule);
                rKey.SetAccessControl(security);
                rKey.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while setting full write access to everyone for file: {0} : {1}", subKey, ex);
            }
        }
Пример #23
0
 static void Query(string Computer, string KeyName, string ValueName, string SearchTeam)
 {
     try
     {
         RegistryKey hive;
         if (Computer.ToUpper() != "LOCAL")
         {
             hive = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, Computer, RegistryView.Default);
         }
         else
         {
             hive = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default);
         }
         var key = hive.OpenSubKey(KeyName);
         if (ValueName.ToUpper() == "COUNT")
         {
             try
             {
                 Console.WriteLine("\nThere are {0} subkeys under {1}.", key.SubKeyCount.ToString(), key.Name);
                 hive.Close();
                 return;
             }
             catch { }                     // Used to ignore exceptions
         }
         else if (ValueName.ToUpper() == "PERMS")
         {
             try
             {
                 RegistrySecurity registrySecurity = key.GetAccessControl();
                 Console.WriteLine("\n{0}\n", key.Name);
                 Console.WriteLine("[*] None:\n{0}\n", registrySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.None));
                 Console.WriteLine("[*] Audit:\n{0}\n", registrySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.Audit));
                 Console.WriteLine("[*] Access:\n{0}\n", registrySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.Access));
                 Console.WriteLine("[*] Group:\n{0}\n", registrySecurity.GetSecurityDescriptorSddlForm(AccessControlSections.Group));
                 var rules = registrySecurity.GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
                 foreach (var rule in rules.Cast <AuthorizationRule>())
                 {
                     Console.WriteLine("{0}", rule.IdentityReference.Value);
                 }
                 hive.Close();
                 return;
             }
             catch { }                     // Used to ignore exceptions
         }
         else if (ValueName.ToUpper() == "ALL")
         {
             Console.WriteLine();
             foreach (string oVal in key.GetValueNames())
             {
                 Console.WriteLine("    {0}    REG_{1}    {2}", oVal, key.GetValueKind(oVal).ToString().ToUpper(), key.GetValue(oVal).ToString());
             }
             Console.WriteLine();
             foreach (string oSubKey in key.GetSubKeyNames())
             {
                 Console.WriteLine("{0}\\{1}", KeyName, oSubKey);
             }
             hive.Close();
             return;
         }
         else if (ValueName.ToUpper() == "RECURSE")
         {
             Console.WriteLine();
             foreach (string oVal in key.GetValueNames())
             {
                 Console.WriteLine("    {0}    REG_{1}    {2}", oVal, key.GetValueKind(oVal).ToString().ToUpper(), key.GetValue(oVal).ToString());
             }
             Console.WriteLine();
             foreach (string oSubKey in key.GetSubKeyNames())
             {
                 Console.WriteLine("{0}\\{1}", KeyName, oSubKey);
                 Console.WriteLine();
                 var skey = hive.OpenSubKey(KeyName + "\\" + oSubKey);
                 foreach (string osVal in skey.GetValueNames())
                 {
                     Console.WriteLine("    {0}    REG_{1}    {2}", osVal, skey.GetValueKind(osVal).ToString().ToUpper(), skey.GetValue(osVal).ToString());
                 }
                 Console.WriteLine();
             }
             hive.Close();
             return;
         }
         else if (ValueName.ToUpper() == "GREP")
         {
             Console.WriteLine();
             foreach (string oVal in key.GetValueNames())
             {
                 if (oVal.Contains(SearchTeam))
                 {
                     try
                     {
                         Console.WriteLine("    {0}    REG_{1}    {2}", oVal, key.GetValueKind(oVal).ToString().ToUpper(), key.GetValue(oVal).ToString());
                     }
                     catch { }                             // Used to ignore exceptions
                 }
             }
             Console.WriteLine();
             foreach (string oSubKey in key.GetSubKeyNames())
             {
                 if (oSubKey.Contains(SearchTeam))
                 {
                     Console.WriteLine("{0}\\{1}", KeyName, oSubKey);
                 }
                 try
                 {
                     var skey = hive.OpenSubKey(KeyName + "\\" + oSubKey);
                     foreach (string osVal in skey.GetValueNames())
                     {
                         try
                         {
                             if (osVal.Contains(SearchTeam) || skey.GetValue(osVal).ToString().Contains(SearchTeam))
                             {
                                 Console.WriteLine("\n{0}\\{1}", KeyName, oSubKey);
                                 Console.WriteLine("\n    {0}    REG_{1}    {2}", osVal, skey.GetValueKind(osVal).ToString().ToUpper(), skey.GetValue(osVal).ToString());
                             }
                         }
                         catch { }                                 // Used to ignore exceptions
                     }
                 }
                 catch { }                         // Used to ignore exceptions
             }
             Console.WriteLine();
             hive.Close();
             return;
         }
         else
         {
             if (key.GetValueKind(ValueName).ToString().ToUpper() == "BINARY")
             {
                 byte[] BinData   = (byte[])key.GetValue(ValueName);
                 string BinString = BitConverter.ToString(BinData).Replace("-", "");;
                 Console.WriteLine("\n    {0}    REG_{1}    {2}", ValueName, key.GetValueKind(ValueName).ToString().ToUpper(), BinString.ToString());
             }
             else if (key.GetValueKind(ValueName).ToString().ToUpper() == "MULTISTRING")
             {
                 Console.WriteLine();
                 string[] tArray = (string[])key.GetValue(ValueName);
                 for (int i = 0; i < tArray.Length; i++)
                 {
                     Console.WriteLine("    {0}    REG_{1}    {2}", ValueName, key.GetValueKind(ValueName).ToString().ToUpper(), tArray[i]);
                 }
             }
             else
             {
                 Console.WriteLine("\n    {0}    REG_{1}    {2}", ValueName, key.GetValueKind(ValueName).ToString().ToUpper(), key.GetValue(ValueName).ToString());
             }
             hive.Close();
             return;
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("\n [!] {0}: {1}", e.GetType().Name, e.Message);
         return;
     }
 }
Пример #24
0
        /// <summary>
        /// Check and if required, fix permissions on HKEY_CLASSES_ROOT
        /// </summary>
        /// <param name="FixPermissions">True to fix missing permissions, false just to check and report permission state</param>
        protected static void CheckHKCRPermissions(bool FixPermissions)
        {
            try
            {
                LogMessage("CheckHKCRPermissions", "Starting HKCR permission check, FixPermissions: " + FixPermissions.ToString());

                bool         FoundCreatorOwnerGenericAccess   = false;
                bool         FoundSystemGenericAccess         = false;
                bool         FoundSystemSpecificAccess        = false;
                bool         FoundAdministratorGenericAccess  = false;
                bool         FoundAdministratorSpecificAccess = false;
                bool         FoundUserGenericAccess           = false;
                bool         FoundUserSpecificAccess          = false;
                AccessRights Rights;

                RegistrySecurity HKCRAccessControl = Registry.ClassesRoot.GetAccessControl();

                //Iterate over the rule set and list them for Built in users
                foreach (RegistryAccessRule RegRule in HKCRAccessControl.GetAccessRules(true, true, typeof(NTAccount)))
                {
                    Rights = (AccessRights)RegRule.RegistryRights;

                    LogMessage("CheckHKCRPermissions", "Found rule: " + RegRule.AccessControlType.ToString() + " " + RegRule.IdentityReference.ToString() + " " + Rights.ToString() + " / " + (RegRule.IsInherited ? "Inherited" : "NotInherited") + " / " + RegRule.InheritanceFlags.ToString() + " / " + RegRule.PropagationFlags.ToString());

                    // Allow CREATOR OWNER GenericAll / NotInherited / ContainerInherit / InheritOnly
                    if ((RegRule.IdentityReference.ToString().Equals(GetLocalAccountName(CreatorOwnerSID), StringComparison.OrdinalIgnoreCase)) &
                        Rights == AccessRights.GenericAll &
                        RegRule.InheritanceFlags == InheritanceFlags.ContainerInherit &
                        RegRule.PropagationFlags == PropagationFlags.InheritOnly)
                    {
                        FoundCreatorOwnerGenericAccess = true;
                    }

                    // Allow NT AUTHORITY\SYSTEM GenericAll / NotInherited / ContainerInherit / InheritOnly
                    if ((RegRule.IdentityReference.ToString().Equals(GetLocalAccountName(NTAuthoritySystemSID), StringComparison.OrdinalIgnoreCase)) &
                        Rights == AccessRights.GenericAll &
                        RegRule.InheritanceFlags == InheritanceFlags.ContainerInherit &
                        RegRule.PropagationFlags == PropagationFlags.InheritOnly)
                    {
                        FoundSystemGenericAccess = true;
                    }

                    // Allow NT AUTHORITY\SYSTEM Query, SetKey, CreateSubKey, EnumSubkey, Notify, CreateLink, StandardDelete, StandardReadControl, StandardWriteDAC, StandardWriteOwner / NotInherited / None / None
                    if ((RegRule.IdentityReference.ToString().Equals(GetLocalAccountName(NTAuthoritySystemSID), StringComparison.OrdinalIgnoreCase)) &
                        Rights == FullRights &
                        RegRule.InheritanceFlags == InheritanceFlags.None &
                        RegRule.PropagationFlags == PropagationFlags.None)
                    {
                        FoundSystemSpecificAccess = true;
                    }

                    // Allow BUILTIN\Administrators GenericAll / NotInherited / ContainerInherit / InheritOnly
                    if ((RegRule.IdentityReference.ToString().Equals(GetLocalAccountName(BuiltInAdministratorsSID), StringComparison.OrdinalIgnoreCase)) &
                        Rights == AccessRights.GenericAll &
                        RegRule.InheritanceFlags == InheritanceFlags.ContainerInherit &
                        RegRule.PropagationFlags == PropagationFlags.InheritOnly)
                    {
                        FoundAdministratorGenericAccess = true;
                    }

                    // Allow BUILTIN\Administrators Query, SetKey, CreateSubKey, EnumSubkey, Notify, CreateLink, StandardDelete, StandardReadControl, StandardWriteDAC, StandardWriteOwner / NotInherited / None / None
                    if ((RegRule.IdentityReference.ToString().Equals(GetLocalAccountName(BuiltInAdministratorsSID), StringComparison.OrdinalIgnoreCase)) &
                        Rights == FullRights &
                        RegRule.InheritanceFlags == InheritanceFlags.None &
                        RegRule.PropagationFlags == PropagationFlags.None)
                    {
                        FoundAdministratorSpecificAccess = true;
                    }

                    // Allow BUILTIN\Users GenericRead / NotInherited / ContainerInherit / InheritOnly
                    if ((RegRule.IdentityReference.ToString().Equals(GetLocalAccountName(BuiltInUsersSID), StringComparison.OrdinalIgnoreCase)) &
                        Rights == AccessRights.GenericRead &
                        RegRule.InheritanceFlags == InheritanceFlags.ContainerInherit &
                        RegRule.PropagationFlags == PropagationFlags.InheritOnly)
                    {
                        FoundUserGenericAccess = true;
                    }

                    // Allow BUILTIN\Users Query, EnumSubkey, Notify, StandardReadControl / NotInherited / None / None
                    if ((RegRule.IdentityReference.ToString().Equals(GetLocalAccountName(BuiltInUsersSID), StringComparison.OrdinalIgnoreCase)) &
                        Rights == ReadRights &
                        RegRule.InheritanceFlags == InheritanceFlags.None &
                        RegRule.PropagationFlags == PropagationFlags.None)
                    {
                        FoundUserSpecificAccess = true;
                    }
                }
                LogMessage("CheckHKCRPermissions", " ");

                if (FoundCreatorOwnerGenericAccess)
                {
                    LogMessage("CheckHKCRPermissions", "OK - HKCR\\ does have CreatorOwnerGenericAccess");
                }
                else
                {
                    LogError("CheckHKCRPermissions", "HKCR\\ does not have CreatorOwnerGenericAccess!");
                }

                if (FoundSystemGenericAccess)
                {
                    LogMessage("CheckHKCRPermissions", "OK - HKCR\\ does have SystemGenericAccess");
                }
                else
                {
                    LogError("CheckHKCRPermissions", "HKCR\\ does not have SystemGenericAccess!");
                }
                if (FoundSystemSpecificAccess)
                {
                    LogMessage("CheckHKCRPermissions", "OK - HKCR\\ does have SystemSpecificAccess");
                }
                else
                {
                    LogError("CheckHKCRPermissions", "HKCR\\ does not have SystemSpecificAccess!");
                }

                if (FoundAdministratorGenericAccess)
                {
                    LogMessage("CheckHKCRPermissions", "OK - HKCR\\ does have AdministratorGenericAccess");
                }
                else
                {
                    LogError("CheckHKCRPermissions", "HKCR\\ does not have AdministratorGenericAccess!");
                }
                if (FoundAdministratorSpecificAccess)
                {
                    LogMessage("CheckHKCRPermissions", "OK - HKCR\\ does have AdministratorSpecificAccess");
                }
                else
                {
                    LogError("CheckHKCRPermissions", "HKCR\\ does not have AdministratorSpecificAccess!");
                }

                if (FoundUserGenericAccess)
                {
                    LogMessage("CheckHKCRPermissions", "OK - HKCR\\ does have UserGenericAccess");
                }
                else
                {
                    LogError("CheckHKCRPermissions", "HKCR\\ does not have UserGenericAccess!");
                }
                if (FoundUserSpecificAccess)
                {
                    LogMessage("CheckHKCRPermissions", "OK - HKCR\\ does have UserSpecificAccess");
                }
                else
                {
                    LogError("CheckHKCRPermissions", "HKCR\\ does not have UserSpecificAccess!");
                }

                LogMessage("CheckHKCRPermissions", " ");

                if (FixPermissions)
                {
                    Stopwatch swLocal = null;

                    try
                    {
                        swLocal = Stopwatch.StartNew();
                        LogMessage("SetRegistryACL", "Fixing registry permissions");

                        //Set a security ACL on the ASCOM Profile key giving the Users group Full Control of the key
                        LogMessage("SetRegistryACL", "Creating security identifiers");
                        SecurityIdentifier DomainSid = new SecurityIdentifier("S-1-0-0"); //Create a starting point domain SID

                        //Create security identifiers for the various accounts to be passed to the new access rule
                        SecurityIdentifier BuiltinUsersIdentifier   = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, DomainSid);
                        SecurityIdentifier AdministratorsIdentifier = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, DomainSid);
                        SecurityIdentifier CreatorOwnerIdentifier   = new SecurityIdentifier(WellKnownSidType.CreatorOwnerSid, DomainSid);
                        SecurityIdentifier SystemIdentifier         = new SecurityIdentifier(WellKnownSidType.LocalSystemSid, DomainSid);

                        LogMessage("SetRegistryACL", "Creating new ACL rules"); // Create the new access permission rules
                        RegistryAccessRule CreatorOwnerGenericAccessRule = new RegistryAccessRule(CreatorOwnerIdentifier,
                                                                                                  (RegistryRights)AccessRights.GenericAll,
                                                                                                  InheritanceFlags.ContainerInherit,
                                                                                                  PropagationFlags.InheritOnly,
                                                                                                  AccessControlType.Allow);

                        RegistryAccessRule SystemGenericAccessRule = new RegistryAccessRule(SystemIdentifier,
                                                                                            (RegistryRights)AccessRights.GenericAll,
                                                                                            InheritanceFlags.ContainerInherit,
                                                                                            PropagationFlags.InheritOnly,
                                                                                            AccessControlType.Allow);

                        RegistryAccessRule SystemFullAccessRule = new RegistryAccessRule(SystemIdentifier,
                                                                                         (RegistryRights)FullRights,
                                                                                         InheritanceFlags.None,
                                                                                         PropagationFlags.None,
                                                                                         AccessControlType.Allow);

                        RegistryAccessRule AdministratorsGenericAccessRule = new RegistryAccessRule(AdministratorsIdentifier,
                                                                                                    (RegistryRights)AccessRights.GenericAll,
                                                                                                    InheritanceFlags.ContainerInherit,
                                                                                                    PropagationFlags.InheritOnly,
                                                                                                    AccessControlType.Allow);

                        RegistryAccessRule AdministratorsFullAccessRule = new RegistryAccessRule(AdministratorsIdentifier,
                                                                                                 (RegistryRights)FullRights,
                                                                                                 InheritanceFlags.None,
                                                                                                 PropagationFlags.None,
                                                                                                 AccessControlType.Allow);

                        RegistryAccessRule BuiltinUsersGenericAccessRule = new RegistryAccessRule(BuiltinUsersIdentifier,
                                                                                                  unchecked ((RegistryRights)AccessRights.GenericRead),
                                                                                                  InheritanceFlags.ContainerInherit,
                                                                                                  PropagationFlags.InheritOnly,
                                                                                                  AccessControlType.Allow);

                        RegistryAccessRule BuiltinUsersReadAccessRule = new RegistryAccessRule(BuiltinUsersIdentifier,
                                                                                               (RegistryRights)ReadRights,
                                                                                               InheritanceFlags.None,
                                                                                               PropagationFlags.None,
                                                                                               AccessControlType.Allow);

                        LogMessage("SetRegistryACL", "Retrieving current ACL rule");
                        LogMessage("SetRegistryACL", " ");
                        RegistrySecurity KeySec = Registry.ClassesRoot.GetAccessControl(); // Get existing ACL rules on the key

                        //Iterate over the rule set and list them
                        foreach (RegistryAccessRule RegRule in KeySec.GetAccessRules(true, true, typeof(NTAccount)))
                        {
                            LogMessage("SetRegistryACL Before", RegRule.AccessControlType.ToString() + " " +
                                       RegRule.IdentityReference.ToString() + " " +
                                       ((AccessRights)RegRule.RegistryRights).ToString() + " " +
                                       RegRule.IsInherited.ToString() + " " +
                                       RegRule.InheritanceFlags.ToString() + " " +
                                       RegRule.PropagationFlags.ToString());
                        }

                        LogMessage("SetRegistryACL", "Adding new ACL rules");
                        LogMessage("SetRegistryACL", " ");

                        // Remove old rules
                        KeySec.PurgeAccessRules(CreatorOwnerIdentifier);
                        KeySec.PurgeAccessRules(AdministratorsIdentifier);
                        KeySec.PurgeAccessRules(BuiltinUsersIdentifier);
                        KeySec.PurgeAccessRules(SystemIdentifier);

                        //Add the new rules to the existing rules
                        KeySec.AddAccessRule(CreatorOwnerGenericAccessRule);
                        KeySec.AddAccessRule(SystemGenericAccessRule);
                        KeySec.AddAccessRule(SystemFullAccessRule);
                        KeySec.AddAccessRule(AdministratorsGenericAccessRule);
                        KeySec.AddAccessRule(AdministratorsFullAccessRule);
                        KeySec.AddAccessRule(BuiltinUsersGenericAccessRule);
                        KeySec.AddAccessRule(BuiltinUsersReadAccessRule);

                        //Iterate over the new rule set and list them
                        foreach (RegistryAccessRule RegRule in KeySec.GetAccessRules(true, true, typeof(NTAccount)))
                        {
                            LogMessage("SetRegistryACL After", RegRule.AccessControlType.ToString() + " " +
                                       RegRule.IdentityReference.ToString() + " " +
                                       ((AccessRights)RegRule.RegistryRights).ToString() + " " +
                                       RegRule.IsInherited.ToString() + " " +
                                       RegRule.InheritanceFlags.ToString() + " " +
                                       RegRule.PropagationFlags.ToString());
                        }

                        LogMessage("SetRegistryACL", "Setting new ACL rule");
                        Registry.ClassesRoot.SetAccessControl(KeySec); //Apply the new rules to the Profile key

                        LogMessage("SetRegistryACL", "Retrieving new rule set from key");

                        // Retrieve the new rule set and list them
                        foreach (RegistryAccessRule RegRule in Registry.ClassesRoot.GetAccessControl().GetAccessRules(true, true, typeof(NTAccount)))
                        {
                            LogMessage("SetRegistryACL New", RegRule.AccessControlType.ToString() + " " +
                                       RegRule.IdentityReference.ToString() + " " +
                                       ((AccessRights)RegRule.RegistryRights).ToString() + " " +
                                       RegRule.IsInherited.ToString() + " " +
                                       RegRule.InheritanceFlags.ToString() + " " +
                                       RegRule.PropagationFlags.ToString());
                        }

                        swLocal.Stop();
                        LogMessage("SetRegistryACL", "ElapsedTime " + swLocal.ElapsedMilliseconds + " milliseconds");
                        swLocal = null;
                    }
                    catch (Exception ex)
                    {
                        LogMessage("SetRegistryACLException", ex.ToString());
                    }
                }
            }
            catch (NullReferenceException ex)
            {
                SetReturnCode(5);
                LogError("CheckHKCRPermissions", "HKCR\\ does not exist. " + ex.ToString()); // Should never happen!
            }
            catch (SecurityException ex)
            {
                SetReturnCode(5);
                LogError("CheckHKCRPermissions", "Security exception when accessing HKCR\\ " + ex.ToString()); // Should never happen!
            }
            catch (Exception ex)
            {
                SetReturnCode(5);
                LogError("CheckHKCRPermissions", "Unexpected exception: " + ex.ToString());
            }
        }
Пример #25
0
        static private bool UserhasFullProfileAccessRights(RegistryKey key, string subKey)
        {
            RegistryKey sKey;
            bool        foundFullAccess = false;
            string      builtInUsers;

            try
            {
                builtInUsers = GetBuiltInUsers().ToUpperInvariant();
                TL.LogMessage("RegistryRights", (subKey == "") ? key.Name.ToString() : key.Name.ToString() + @"\" + subKey);

                if (subKey == "")
                {
                    sKey = key;
                }
                else
                {
                    sKey = key.OpenSubKey(subKey);
                }

                RegistrySecurity sec = sKey.GetAccessControl();                                           // System.Security.AccessControl.AccessControlSections.All)

                foreach (RegistryAccessRule RegRule in sec.GetAccessRules(true, true, typeof(NTAccount))) // Iterate over the rule set and list them
                {
                    try
                    {
                        TL.LogMessage("RegistryRights", RegRule.AccessControlType.ToString() + " " + RegRule.IdentityReference.ToString() + " " + RegRule.RegistryRights.ToString() + " / " + (RegRule.IsInherited ? "Inherited" : "NotInherited") + " / " + RegRule.InheritanceFlags.ToString() + " / " + RegRule.PropagationFlags.ToString());
                    }
                    catch (Exception ex1)
                    {
                        TL.LogMessageCrLf("RegistryRights", "Issue formatting registry rights: " + ex1.ToString());
                    }

                    if ((RegRule.IdentityReference.ToString().ToUpperInvariant() == builtInUsers) & (RegRule.RegistryRights == global::System.Security.AccessControl.RegistryRights.FullControl))
                    {
                        foundFullAccess = true;
                    }
                }

                if (foundFullAccess)
                {
                    TL.BlankLine();
                    TL.LogMessage("RegistryRights", "OK - SubKey " + subKey + @" does have full registry access rights for BUILTIN\Users");
                }
                else
                {
                    LogError("RegistryRights", "Subkey " + subKey + @" does not have full access rights for BUILTIN\Users!");
                }
            }
            catch (NullReferenceException)
            {
                TL.LogMessageCrLf("RegistryRights", "The subkey: " + key.Name + @"\" + subKey + " does not exist.");
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("RegistryRights", "Issue reading registry rights: " + ex.ToString());
            }

            TL.BlankLine();

            return(foundFullAccess);
        }
Пример #26
0
        protected override void ProcessRecord()
        {
            using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, true, true))
            {
                if (regKey == null)
                {
                    return;
                }

                RegistrySecurity security = null;

                //  Access文字列からの設定
                //  ""で全アクセス権設定を削除
                if (Access != null)
                {
                    if (security == null)
                    {
                        security = regKey.GetAccessControl();
                    }
                    foreach (RegistryAccessRule removeRule in security.GetAccessRules(true, false, typeof(NTAccount)))
                    {
                        security.RemoveAccessRule(removeRule);
                    }

                    //  テスト自動生成
                    _generator.RegistryAccess(RegistryPath, Access, false);

                    if (Access != string.Empty)     //  このif文分岐が無くても同じ挙動するけれど、一応記述
                    {
                        foreach (RegistryAccessRule addRule in RegistryControl.StringToAccessRules(Access))
                        {
                            security.AddAccessRule(addRule);
                        }
                    }
                }

                //  上位からのアクセス権継承の設定変更
                if (Inherited != Item.NONE)
                {
                    if (security == null)
                    {
                        security = regKey.GetAccessControl();
                    }

                    //  テスト自動生成
                    _generator.RegistryInherited(RegistryPath, Inherited == Item.ENABLE);

                    switch (Inherited)
                    {
                    case Item.ENABLE:
                        security.SetAccessRuleProtection(false, false);
                        break;

                    case Item.DISABLE:
                        security.SetAccessRuleProtection(true, true);
                        break;

                    case Item.REMOVE:
                        security.SetAccessRuleProtection(true, false);
                        break;
                    }
                }

                if (security != null)
                {
                    regKey.SetAccessControl(security);
                }
            }

            //  所有者変更
            if (Owner != null)
            {
                string subinacl = EmbeddedResource.GetSubinacl(Item.APPLICATION_NAME);

                //  管理者実行確認
                Functions.CheckAdmin();

                //  テスト自動生成
                _generator.RegistryOwner(RegistryPath, Owner);

                using (Process proc = new Process())
                {
                    proc.StartInfo.FileName    = subinacl;
                    proc.StartInfo.Arguments   = $"/subkeyreg \"{RegistryPath}\" /owner=\"{Owner}\"";
                    proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    proc.Start();
                    proc.WaitForExit();
                }
            }

            //  レジストリ値の設定
            if (Name != null)
            {
                //  テスト自動生成
                _generator.RegistryType(RegistryPath, Name, Type);
                _generator.RegistryValue(RegistryPath, Name, Value);

                switch (Type)
                {
                case Item.REG_SZ:
                    Registry.SetValue(RegistryPath, Name, Value, RegistryValueKind.String);
                    break;

                case Item.REG_BINARY:
                    Registry.SetValue(RegistryPath, Name, RegistryControl.StringToRegBinary(Value), RegistryValueKind.Binary);
                    break;

                case Item.REG_DWORD:
                    Registry.SetValue(RegistryPath, Name, int.Parse(Value), RegistryValueKind.DWord);
                    break;

                case Item.REG_QWORD:
                    Registry.SetValue(RegistryPath, Name, long.Parse(Value), RegistryValueKind.QWord);
                    break;

                case Item.REG_MULTI_SZ:
                    Registry.SetValue(RegistryPath, Name, Functions.SplitBQt0(Value), RegistryValueKind.MultiString);
                    break;

                case Item.REG_EXPAND_SZ:
                    Registry.SetValue(RegistryPath, Name, Value, RegistryValueKind.ExpandString);
                    break;

                case Item.REG_NONE:
                    Registry.SetValue(RegistryPath, Name, new byte[2] {
                        0, 0
                    }, RegistryValueKind.None);
                    break;
                }
            }

            /*  実行していて結構うっとおしいので、出力しないことにします。
             * using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, false, false))
             * {
             *  WriteObject(new RegistrySummary(regKey, true));
             * }
             */
        }
Пример #27
0
        static void Main(string[] args)
        {
            //Authnetication = Who are you?
            //Authorization = What can you do?

            //Get current Identity
            WindowsIdentity curr = WindowsIdentity.GetCurrent();

            //Get anonymous identity
            curr = WindowsIdentity.GetAnonymous();
            //curr = WindowsIdentity.Impersonate();
            curr = WindowsIdentity.GetCurrent();
            Console.WriteLine("Name:" + curr.Name);
            Console.WriteLine("Token:" + curr.Token.ToString());
            Console.WriteLine("Authentication Type:" + curr.AuthenticationType);
            Console.WriteLine("Is anonymous? {0}", curr.IsAnonymous);
            Console.WriteLine("Is authenticated? {0}", curr.IsAuthenticated);
            Console.WriteLine("Is a guest? {0}", curr.IsGuest);
            Console.WriteLine("Is System? {0}", curr.IsSystem);

            //WindowsPrincipal = group info.  You can retrieve this by using an identity
            WindowsPrincipal wingroup = new WindowsPrincipal(curr);

            //or by pulling the group info from the current thread.
            AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
            wingroup = (WindowsPrincipal)Thread.CurrentPrincipal;
            Console.WriteLine("Current user is a member of the following roles:");
            Console.WriteLine("In role Administrator? {0}", wingroup.IsInRole(WindowsBuiltInRole.Administrator));
            Console.WriteLine("In role AccountOperator? {0}", wingroup.IsInRole(WindowsBuiltInRole.AccountOperator));
            Console.WriteLine("In role Guest? {0}", wingroup.IsInRole(WindowsBuiltInRole.Guest));
            Console.WriteLine("In role PowerUser? {0}", wingroup.IsInRole(WindowsBuiltInRole.PowerUser));
            Console.WriteLine(@"In  role Atlas\Admin? {0}", wingroup.IsInRole(@"Atlas\Admin"));

            //AdminOnly();
            AlsoAdminOnly();

            string r = System.Environment.MachineName + @"\VS Developers";

            try
            {
                PrincipalPermission p = new PrincipalPermission(null, r, true);
                p.Demand();
                Console.WriteLine("You are in " + r);
            }
            catch (SecurityException ex)
            {
                Console.WriteLine("You are not in " + r);
            }

            //DACL = Restricts or grants control
            //SACL = Used for logging accesses to a resource...

            DirectorySecurity ds = new DirectorySecurity(@"C:\Program Files\", AccessControlSections.All);
            //FileSystemRights.AppendData
            //FileSystemRights.ChangePermissions
            //FileSystemRights.CreateDirectories
            //FileSystemRights.CreateFiles
            //FileSystemRights.Delete
            //FileSystemRights.DeleteSubdirectoriesAndFiles
            //FileSystemRights.ExecuteFile
            //FileSystemRights.FullControl
            //FileSystemRights.ListDirectory
            //FileSystemRights.Modify
            //FileSystemRights.Read
            //FileSystemRights.ReadAndExecute
            //FileSystemRights.ReadAttributes
            //FileSystemRights.ReadData
            //FileSystemRights.ReadExtendedAttributes
            //  FileSystemRights.ReadPermissions
            //FileSystemRights.Synchronize
            //FileSystemRights.TakeOwnership
            //FileSystemRights.Traverse
            //FileSystemRights.Write
            //  FileSystemRights.WriteAttributes
            //FileSystemRights.WriteData
            //FileSystemRights.WriteExtendedAttributes
            AuthorizationRuleCollection arc = ds.GetAccessRules(true, true, typeof(NTAccount));

            foreach (FileSystemAccessRule ar in arc)
            {
                Console.WriteLine(ar.IdentityReference + " : " + ar.AccessControlType + " " + ar.FileSystemRights);
            }

            RegistrySecurity rs = Registry.LocalMachine.GetAccessControl();

            arc = rs.GetAccessRules(true, true, typeof(NTAccount));
            foreach (RegistryAccessRule rar in arc)
            {
                Console.WriteLine(rar.IdentityReference + ":" + rar.AccessControlType + " " + rar.RegistryRights);
            }
            //RegistryRights.ChangePermissions
            //RegistryRights.CreateLink
            //RegistryRights.CreateSubKey
            //RegistryRights.Delete
            //RegistryRights.EnumerateSubKeys;
            //RegistryRights.ExecuteKey;
            //RegistryRights.FullControl;
            //RegistryRights.Notify;
            //RegistryRights.QueryValues;
            //RegistryRights.ReadKey;
            //RegistryRights.ReadPermissions;
            //RegistryRights.SetValue;
            //RegistryRights.TakeOwnership;
            //RegistryRights.WriteKey;
            string dir = @"C:\logs";

            ds = Directory.GetAccessControl(dir);
            ds.AddAccessRule(new FileSystemAccessRule("Guest", FileSystemRights.Read, AccessControlType.Allow));
            Directory.SetAccessControl(dir, ds);
            //THE ABOVE IS 20X easier than anything before .net 2.0

            //SYMETRIC ENCRYPTION = Encryption & decryption is done w/ the same key
            string          ss = "p@ssw0rd";
            RijndaelManaged rj = new RijndaelManaged();

            byte[]             salt = Encoding.ASCII.GetBytes("This is my salt!");
            Rfc2898DeriveBytes key  = new Rfc2898DeriveBytes(ss, salt);

            rj.Key = key.GetBytes(rj.KeySize / 8);
            rj.IV  = key.GetBytes(rj.BlockSize / 8);
            string     inFile  = @"C:\boot.ini";
            string     outFile = @"C:\boot.ini.enc";
            FileStream inFS    = new FileStream(inFile, FileMode.Open, FileAccess.Read);
            FileStream outFS   = new FileStream(outFile, FileMode.OpenOrCreate, FileAccess.Write);

            byte[] fileData = new byte[inFS.Length];
            inFS.Read(fileData, 0, (int)inFS.Length);
            ICryptoTransform enc       = rj.CreateEncryptor();
            CryptoStream     encStream = new CryptoStream(outFS, enc, CryptoStreamMode.Write);

            encStream.Write(fileData, 0, fileData.Length);
            encStream.Close();
            inFS.Close();
            outFS.Close();
            RSACryptoServiceProvider myRSA    = new RSACryptoServiceProvider();
            RSAParameters            rsaParam = myRSA.ExportParameters(true);

            Console.WriteLine(myRSA.ToXmlString(true));

            //How to put the keys in the key store!
            CspParameters persistantCsp = new CspParameters();

            persistantCsp.KeyContainerName = "AsymetricExample";
            myRSA = new RSACryptoServiceProvider(persistantCsp);
            myRSA.PersistKeyInCsp = true;
            rsaParam = myRSA.ExportParameters(true);
            foreach (byte thisbyte in rsaParam.D)
            {
                Console.Write(thisbyte.ToString("X2") + " ");
            }
            string Message = "Hello, world!";

            byte[] messByte = Encoding.Unicode.GetBytes(Message);
            byte[] encMess  = myRSA.Encrypt(messByte, false);
            byte[] decMess  = myRSA.Decrypt(encMess, false);
            Console.WriteLine(Encoding.Unicode.GetString(decMess));

            //HASHING -non keyed
            MD5          myHash = new MD5CryptoServiceProvider();
            FileStream   file   = new FileStream(outFile, FileMode.Open, FileAccess.Read);
            BinaryReader br     = new BinaryReader(file);

            myHash.ComputeHash(br.ReadBytes((int)file.Length));
            Console.WriteLine(Convert.ToBase64String(myHash.Hash));
            br.Close();
            file.Close();
            //HASHING keyed
            byte[]             saltValue   = Encoding.ASCII.GetBytes("This is some good salt!");
            Rfc2898DeriveBytes passwordkey = new Rfc2898DeriveBytes("p@55w0r6", saltValue);

            byte[] secretkey = passwordkey.GetBytes(16);

            HMACSHA1 keyhash = new HMACSHA1(secretkey);

            file = new FileStream(outFile, FileMode.Open, FileAccess.Read);
            br   = new BinaryReader(file);
            keyhash.ComputeHash(br.ReadBytes((int)file.Length));
            Console.WriteLine(Convert.ToBase64String(keyhash.Hash));
        }
Пример #28
0
        private void button1_Click(object sender, EventArgs e)
        {
            bool   flag  = false;
            string name1 = Convert.ToString(listBox1.SelectedItem);

            if (textBox1.Text == "")
            {
                MessageBox.Show(" Субъект не выбран. Будет показан список объектов доступных для каждого субъекта.");
            }
            else
            {
                if (textBox1.Text != name1)
                {
                    string[] s;
                    s = new string[listBox1.Items.Count - 1];
                    for (int i = 0; i < listBox1.Items.Count - 1; i++)
                    {
                        if (listBox1.Items.ToString() != "")
                        {
                            s[i] = listBox1.Items[i].ToString();
                        }
                        if (textBox1.Text == s[i])
                        {
                            flag = true;
                        }
                    }
                    if (flag != true || textBox1.Text != "Список групп" || textBox1.Text != "Список пользователей" || textBox1.Text != "____________")
                    {
                        MessageBox.Show(" Такого субъекта не существует.");
                    }
                }
            }


            listBox2.DataSource = null;
            RegistryRights     WriteAndRead = RegistryRights.ReadKey | RegistryRights.SetValue | RegistryRights.CreateSubKey; //== writekey and readkey
            List <RegistryKey> RKMas        = new List <RegistryKey>();
            List <string>      list         = new List <string>();


            foreach (string name in RK.GetSubKeyNames())
            {
                try
                {
                    RKMas.Add(RK.OpenSubKey(name));
                }
                catch { }
            }
            foreach (RegistryKey rk in RKMas)
            {
                RegistrySecurity rs = rk.GetAccessControl();
                foreach (RegistryAccessRule ar in rs.GetAccessRules(true, true, typeof(NTAccount)))
                {
                    string buf = ar.IdentityReference.ToString();
                    if (radioButton1.Checked == true)
                    {
                        if (ar.RegistryRights == RegistryRights.ReadKey | ar.RegistryRights == RegistryRights.FullControl | ar.RegistryRights == WriteAndRead && buf.Contains(textBox1.Text))
                        {
                            //listBox2.Items.Add(rk + " доступен на чтение для " + ar.IdentityReference);
                            list.Add(rk + " доступен для чтения  " + ar.IdentityReference);
                        }
                        listBox2.DataSource = list.Distinct().ToList();
                    }
                    if (radioButton2.Checked == true)
                    {
                        if (ar.RegistryRights == RegistryRights.WriteKey | ar.RegistryRights == RegistryRights.FullControl | ar.RegistryRights == WriteAndRead && buf.Contains(textBox1.Text))
                        {
                            //listBox2.Items.Add(rk +  " доступен на запись для "  + ar.IdentityReference);
                            list.Add(rk + " доступен на запись для " + ar.IdentityReference);
                        }
                        listBox2.DataSource = list.Distinct().ToList();
                    }
                    if (radioButton3.Checked == true)
                    {
                        if (ar.RegistryRights == WriteAndRead | ar.RegistryRights == RegistryRights.FullControl && buf.Contains(textBox1.Text))
                        {
                            //listBox2.Items.Add(rk + " доступен на чтение и запись для " + ar.IdentityReference);
                            list.Add(rk + " доступен на чтение и запись для  " + ar.IdentityReference);
                        }
                        listBox2.DataSource = list.Distinct().ToList();
                    }
                }
            }
        }