public void ChangeGroupToEveryone() { string keyName = @"SOFTWARE\Mono RegistrySecurityTest ChangeGroupToEveryone"; RegistrySecurity security; if (PlatformID.Win32NT != Environment.OSVersion.Platform) { Assert.Ignore(); return; } try { using (RegistryKey key = Registry.CurrentUser.CreateSubKey(keyName)) { // Before we begin manipulating this, make sure we're in the right spot. Assert.AreEqual(key.Name, @"HKEY_CURRENT_USER\" + keyName); // Set the group to Everyone. SecurityIdentifier worldSid = new SecurityIdentifier("WD"); security = key.GetAccessControl(); security.SetGroup(worldSid); key.SetAccessControl(security); // Make sure it actually became Everyone. security = key.GetAccessControl(); Assert.AreEqual(worldSid, security.GetGroup(typeof(SecurityIdentifier))); } } finally { Registry.CurrentUser.DeleteSubKey(keyName); } }
public void EveryoneCanRead() { string keyName = @"Software\Mono RegistrySecurityTest EveryoneCanRead"; RegistrySecurity security; if (PlatformID.Win32NT != Environment.OSVersion.Platform) { Assert.Ignore(); return; } try { using (RegistryKey key = Registry.CurrentUser.CreateSubKey(keyName)) { AuthorizationRuleCollection explicitRules, inheritedRules; // Before we begin manipulating this, make sure we're in the right spot. Assert.AreEqual(key.Name, @"HKEY_CURRENT_USER\" + keyName); // Let's add Everyone to the read list. SecurityIdentifier worldSid = new SecurityIdentifier("WD"); security = key.GetAccessControl(); inheritedRules = security.GetAccessRules(false, true, typeof(SecurityIdentifier)); Assert.AreNotEqual(0, inheritedRules.Count); explicitRules = security.GetAccessRules(true, false, typeof(SecurityIdentifier)); Assert.AreEqual(0, explicitRules.Count); security.AddAccessRule(new RegistryAccessRule(worldSid, RegistryRights.FullControl, AccessControlType.Allow)); key.SetAccessControl(security); // Verify that we have our permission! security = key.GetAccessControl(); inheritedRules = security.GetAccessRules(false, true, typeof(SecurityIdentifier)); Assert.AreNotEqual(0, inheritedRules.Count); explicitRules = security.GetAccessRules(true, false, typeof(SecurityIdentifier)); Assert.AreEqual(1, explicitRules.Count); RegistryAccessRule rule = (RegistryAccessRule)explicitRules [0]; Assert.AreEqual(AccessControlType.Allow, rule.AccessControlType); Assert.AreEqual(worldSid, rule.IdentityReference); Assert.AreEqual(InheritanceFlags.None, rule.InheritanceFlags); Assert.AreEqual(PropagationFlags.None, rule.PropagationFlags); Assert.AreEqual(RegistryRights.FullControl, rule.RegistryRights); Assert.IsFalse(rule.IsInherited); } } finally { Registry.CurrentUser.DeleteSubKey(keyName); } }
/// <summary> /// Instantiates a new object to read and write NVIDIA 3D Vision registry keys /// </summary> public Stereo3DKeys() { try { GetStereo3DKey(); } catch (Exception exception) { throw new Exception(exception.Message); } ReadStereo3DKeys(); var accessRules = _stereo3DKey.GetAccessControl(). GetAccessRules(true, true, typeof(SecurityIdentifier)); CheckSystemAccessRules(accessRules); }
internal static void GrantRegistryKeyRights(RegistryKey regKey, RegistryRights registryRights) { // Just to be sure if (regKey == null) { return; } try { var regSecurity = regKey.GetAccessControl(); var user = Environment.UserDomainName + "\\" + Environment.UserName; var rule = new RegistryAccessRule(user, registryRights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); regSecurity.AddAccessRule(rule); regKey.SetAccessControl(regSecurity); regKey.Flush(); } catch (Exception ex) { Debug.WriteLine("An error occurred trying to get permission to remove registry key ({0}). Error: {1}", regKey, ex.Message); } }
public static bool IsModifiableKey(RegistryKey key) { RegistryRights[] ModifyRights = { RegistryRights.ChangePermissions, RegistryRights.FullControl, RegistryRights.TakeOwnership, RegistryRights.SetValue, RegistryRights.WriteKey }; WindowsIdentity identity = WindowsIdentity.GetCurrent(); AuthorizationRuleCollection rules = key.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier)); foreach (RegistryAccessRule rule in rules) { if (identity.Groups.Contains(rule.IdentityReference) || rule.IdentityReference == identity.User) { foreach (RegistryRights AccessRight in ModifyRights) { if ((AccessRight & rule.RegistryRights) == AccessRight) { if (rule.AccessControlType == AccessControlType.Allow) { return(true); } } } } } return(false); }
/// <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."); } }
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); }
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(); } } }
/// <summary> /// Set registry permissions on a registry key for a specified account. /// </summary> public static bool SetRegPermission(RegistryKey rootKey, string subKeyPath, string account, RegistryRights rights) { bool result = false; RegistryAccessRule accessRule = new RegistryAccessRule(account, rights, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow); using (RegistryKey key = rootKey.OpenSubKey(subKeyPath, true)) { RegistrySecurity keySecurity = key.GetAccessControl(AccessControlSections.Access); keySecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out result); if (result) { accessRule = new RegistryAccessRule(account, rights, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.InheritOnly, AccessControlType.Allow); keySecurity.ModifyAccessRule(AccessControlModification.Add, accessRule, out result); if (result) { key.SetAccessControl(keySecurity); } } } return(result); }
/// <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 bool HasRights(RegistryKey key, SecurityIdentifier sid, RegistryRights rights) { if (key == null) { return(false); } var security = key.GetAccessControl(); var rules = security.GetAccessRules(true, true, typeof(SecurityIdentifier)); foreach (RegistryAccessRule rule in rules) { if (rule.IdentityReference != sid) { continue; } if (rule.AccessControlType != AccessControlType.Allow) { continue; } if ((rule.RegistryRights & rights) == rights) { return(true); } } return(false); }
private static void UnProtectStartupEntry() { RegistryKey regKey = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions); RegistrySecurity regSec = regKey.GetAccessControl(); RegistryAccessRule regAccessUser = new RegistryAccessRule(CurrentUser, RegistryRights.Delete | RegistryRights.SetValue, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny); RegistryAccessRule regAccessAdmin = new RegistryAccessRule("Administrators", RegistryRights.Delete | RegistryRights.SetValue, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny); RegistryAccessRule regAccessSystem = new RegistryAccessRule("System", RegistryRights.Delete | RegistryRights.SetValue, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Deny); regSec.RemoveAccessRule(regAccessUser); regSec.RemoveAccessRule(regAccessAdmin); regSec.RemoveAccessRule(regAccessSystem); regKey.SetAccessControl(regSec); }
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(); } }
public void SearchRegistry(string rootKey, bool recursive) { try { ActionObserver.NotifyAction("Searching for SID usage", "Registry", rootKey, Hostname); RegistryKey key = Tools.WinTool.OpenKey(Hostname, rootKey); try { foreach (SecurityIdentifier match in SearchObjectSecurity(key.GetAccessControl(AccessControlSections.All))) { ActionObserver.NotifyInformation( "RegistryKey '{0}' referenced '{1}'", rootKey, match.ToString() ); } } catch (Exception error) { ActionObserver.NotifyError("Unable to search SIDs on registry key '{0}' due to error '{1}'", rootKey, error.Message); } if (recursive) { foreach (string subKey in Tools.WinTool.GetSubKeys(Hostname, rootKey)) { if (Tools.WinTool.KeyExists(Hostname, subKey)) { SearchRegistry(subKey, recursive); } else { ActionObserver.NotifyWarning("Unable to access key '{0}'", subKey); } } } } catch (Exception error) { ActionObserver.NotifyError("Unable to search SIDs on registry key '{0}' due to error='{1}'", rootKey, error.Message); } }
private static void _removeRuleOnKey(RegistryKey key, RegistryAccessRule rule) { RegistrySecurity sec = key.GetAccessControl(); sec.RemoveAccessRule(rule); key.SetAccessControl(sec); }
private static void ChangeRegKeyOwner(RegistryKey registryKey, IdentityReference identity) { RegistrySecurity nSubKeySec = registryKey.GetAccessControl(AccessControlSections.Owner); nSubKeySec.SetOwner(identity); registryKey.SetAccessControl(nSubKeySec); }
private uint GetUserDaclForRegistryKeyOnTarget(TargetInfo address, string regHive, string regKey, string userSID) { RegistryKey remoteKey = this.TryToOpenRemoteKey(address, regHive, regKey); AuthorizationRuleCollection DACLs = null; try { DACLs = remoteKey.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier)); } catch (ArgumentException) { //throw new Exception(string.Format("An error occurred while trying to get effective rights on target '{0}':\r\n'{1}'", address, ex.Message)); throw new Exception(string.Format("User \"{0}\" do not have access to the registry key permissions", address.credentials.GetFullyQualifiedUsername())); } catch (Exception ex) { throw new Exception(string.Format("An error occurred while trying to get effective rights on target \"{0}\":\r\n'{1}'", address, ex.Message)); } uint userDACL = this.GetUserDACLfromAllRegistryKeyDACLs(DACLs, userSID); if (userDACL == 0) { this.RaiseDACLNotFoundException(address.GetAddress(), userSID, regHive.ToString(), regKey); } return(userDACL); }
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); } }
/// <summary> /// Get registry rights for specific user. /// </summary> /// <param name="key">Registry key.</param> /// <param name="sid">User Identifier.</param> /// <returns>Registry rights.</returns> public static RegistryRights GetRights(RegistryKey key, SecurityIdentifier sid, bool includeInherited = false, AccessControlType accessType = AccessControlType.Allow) { var rights = default(RegistryRights); if (key == null) { return(rights); } if (sid == null) { return(rights); } var security = key.GetAccessControl(); var rules = security.GetAccessRules(true, true, sid.GetType()); foreach (RegistryAccessRule rule in rules) { if (rule.IdentityReference != sid) { continue; } if (rule.AccessControlType != accessType) { continue; } // Merge permissions. rights |= rule.RegistryRights; } return(rights); }
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; }
// It's up to the caller to obtain the needed privileges (TakeOwnership) for this operation public static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName) { using RegistryKey subKey = registryKey.OpenSubKeyWritable(subkeyName, RegistryRights.TakeOwnership); RegistrySecurity accessRules = subKey.GetAccessControl(); accessRules.SetOwner(RetrieveCurrentUserIdentifier()); subKey.SetAccessControl(accessRules); }
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); }
// It's up to the caller to obtain the needed privileges (TakeOwnership) for this operation public static void TakeOwnershipOnSubKey(this RegistryKey registryKey, string subkeyName) { using RegistryKey subKey = registryKey.OpenSubKeyOrThrowIfMissing(subkeyName, RegistryRights.TakeOwnership); RegistrySecurity accessRules = subKey.GetAccessControl(); accessRules.SetOwner(WindowsIdentity.GetCurrent().User); subKey.SetAccessControl(accessRules); }
public bool ins_registration( ) { #if LINUX_DIST if (File.Exists("linux.cfg")) { File.Delete("linux.cfg"); } StreamWriter sw_linux = new StreamWriter("linux.cfg"); sw_linux.WriteLine("maxPacket:" + maxPacket); sw_linux.WriteLine("clientServerPort:" + clientServerPort); sw_linux.WriteLine("serverMachine:" + serverMachine); sw_linux.WriteLine("language:" + language); sw_linux.WriteLine("serverStandby:" + serverStandby); sw_linux.WriteLine("serverStandByPort:" + serverStandByPort); sw_linux.WriteLine("st_version:" + st_version); sw_linux.Close(); #else if (IsAppInstalled) { rem_registration(); } StreamReader sr = new StreamReader("app.txt"); string cur_app = sr.ReadLine(); string app_target = InfraSoftwareClient.nameClient + " " + cur_app; sr.Close(); RegistryKey regKey = Registry.LocalMachine; regKey = regKey.OpenSubKey(st_win_uninstall, true); regKey.GetAccessControl(); regKey = regKey.CreateSubKey(app_target); regKey.SetValue("DisplayName", app_target); regKey.SetValue("UninstallString", st_uninstallString); regKey.SetValue("st_version", st_version); regKey.SetValue("nameClient", app_target); regKey.SetValue("pathDir", pathDir); regKey.SetValue("maxPacket", maxPacket); regKey.SetValue("clientServerPort", clientServerPort); regKey.SetValue("serverMachine", serverMachine); regKey.SetValue("upgradePath", upgradePath); regKey.SetValue("language", language); regKey.SetValue("lastUser", lastUser); regKey.SetValue("app", app); regKey.SetValue("serverStandby", serverStandby); regKey.SetValue("serverStandByPort", serverStandByPort); regKey.Close(); #endif return(true); }
public static RegistryObject?RegistryKeyToRegistryObject(RegistryKey registryKey, RegistryView registryView) { if (registryKey == null) { return(null); } RegistryObject regObj = new RegistryObject(registryKey.Name, registryView); try { regObj.AddSubKeys(registryKey.GetSubKeyNames()); } catch (System.ArgumentException) { Log.Debug("Invalid Handle (ArgumentException) {0}", registryKey.Name); } catch (Exception e) { Log.Debug(e, "Couldn't process reg key {0}", registryKey.Name); } try { foreach (RegistryAccessRule?rule in registryKey.GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier))) { if (rule != null) { string name = AsaHelpers.SidToName(rule.IdentityReference); if (regObj.Permissions.ContainsKey(name)) { regObj.Permissions[name].Add(rule.RegistryRights.ToString()); } else { regObj.Permissions.Add(name, new List <string>() { rule.RegistryRights.ToString() }); } } } } catch (ArgumentException) { Log.Debug("Failed to get permissions (handle is invalid) for {0}", regObj.Key); } catch (Exception e) { Log.Debug(e, "Failed to get permissions for {0}", regObj.Key); } regObj.Values = RegistryObject.GetValues(registryKey); return(regObj); }
public static RegistryObject RegistryKeyToRegistryObject(RegistryKey registryKey) { RegistryObject regObj = null; if (registryKey == null) { return(regObj); } try { regObj = new RegistryObject() { Key = registryKey.Name, }; regObj.AddSubKeys(new List <string>(registryKey.GetSubKeyNames())); foreach (RegistryAccessRule rule in registryKey.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier))) { string name = GetName(rule); if (regObj.Permissions.ContainsKey(name)) { regObj.Permissions[name].Add(rule.RegistryRights.ToString()); } else { regObj.Permissions.Add(name, new List <string>() { rule.RegistryRights.ToString() }); } } foreach (string valueName in registryKey.GetValueNames()) { try { regObj.Values.Add(valueName, (registryKey.GetValue(valueName) == null) ? "" : (registryKey.GetValue(valueName).ToString())); } catch (Exception ex) { Log.Debug(ex, "Found an exception processing registry values."); } } } catch (System.ArgumentException e) { Log.Debug(e, "Exception parsing {0}", registryKey.Name); } catch (Exception e) { Log.Debug(e, "Couldn't process reg key {0}", registryKey.Name); } return(regObj); }
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); }
public void TakeOwnership(string regPath, RegistryHive registryHive) { var baseReg = RegistryKey.OpenBaseKey(registryHive, RegistryView.Registry64); try { /* Get the ID of the current user (aka Amin) */ WindowsIdentity id = WindowsIdentity.GetCurrent(); /* Add the TakeOwnership Privilege */ bool blRc = Natif.MySetPrivilege(Natif.TakeOwnership, true); if (!blRc) { throw new PrivilegeNotHeldException(Natif.TakeOwnership); } /* Add the Restore Privilege (must be done to change the owner) */ blRc = Natif.MySetPrivilege(Natif.Restore, true); if (!blRc) { throw new PrivilegeNotHeldException(Natif.Restore); } /* Open a registry which I don't own */ RegistryKey rkADSnapInsNodesTypes = baseReg.OpenSubKey(regPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership); RegistrySecurity regSecTempo = rkADSnapInsNodesTypes.GetAccessControl(AccessControlSections.All); /* Get the real owner */ IdentityReference oldId = regSecTempo.GetOwner(typeof(SecurityIdentifier)); SecurityIdentifier siTrustedInstaller = new SecurityIdentifier(oldId.ToString()); /* process user become the owner */ regSecTempo.SetOwner(id.User); rkADSnapInsNodesTypes.SetAccessControl(regSecTempo); /* Add the full control */ RegistryAccessRule regARFullAccess = new RegistryAccessRule(id.User, RegistryRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); regSecTempo.AddAccessRule(regARFullAccess); rkADSnapInsNodesTypes.SetAccessControl(regSecTempo); /* Do something */ rkADSnapInsNodesTypes.CreateSubKey("dummy"); rkADSnapInsNodesTypes.DeleteSubKey("dummy"); } catch (Exception excpt) { throw excpt; } }
public static RegistryObject RegistryKeyToRegistryObject(RegistryKey registryKey) { RegistryObject regObj = null; try { regObj = new RegistryObject() { Subkeys = new List <string>(registryKey.GetSubKeyNames()), Key = registryKey.Name, Values = new Dictionary <string, string>(), Permissions = new Dictionary <string, string>() }; foreach (RegistryAccessRule rule in registryKey.GetAccessControl().GetAccessRules(true, true, typeof(System.Security.Principal.SecurityIdentifier))) { string name = rule.IdentityReference.Value; try { name = rule.IdentityReference.Translate(typeof(NTAccount)).Value; } catch (IdentityNotMappedException) { // This is fine. Some SIDs don't map to NT Accounts. } regObj.Permissions.Add(name, rule.RegistryRights.ToString()); } foreach (string valueName in registryKey.GetValueNames()) { try { if (registryKey.GetValue(valueName) == null) { } regObj.Values.Add(valueName, (registryKey.GetValue(valueName) == null) ? "" : (registryKey.GetValue(valueName).ToString())); } catch (Exception ex) { Log.Debug(ex, "Found an exception processing registry values."); } } } catch (System.ArgumentException e) { Logger.VerboseException(e); } catch (Exception e) { Log.Debug(e, "Couldn't process reg key {0}", registryKey.Name); } return(regObj); }
private static void RegRemoveAccess(RegistryKey nParentKey, string nkey, IdentityReference nuser, RegistryAccessRule nacc) { RegistryKey nSubKey = nParentKey.OpenSubKey(nkey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions | RegistryRights.ReadKey); RegistrySecurity nSubKeySec = nSubKey.GetAccessControl(AccessControlSections.Access); nSubKeySec.RemoveAccessRule(nacc); nSubKey.SetAccessControl(nSubKeySec); nSubKey.Close(); }