public bool SetAccessRestriction(string keyPath, bool bSet) { try { RegistryKey subKey = Registry.LocalMachine.OpenSubKey(keyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions); RegistrySecurity keySec = subKey.GetAccessControl(AccessControlSections.Access); RegistryAccessRule systemRule = new RegistryAccessRule(new SecurityIdentifier(FileOps.SID_System), RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); RegistryAccessRule serviceRule = new RegistryAccessRule(FirewallServiceName, RegistryRights.ExecuteKey, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow); if (bSet) { keySec.SetAccessRuleProtection(true, false); keySec.AddAccessRule(systemRule); keySec.AddAccessRule(serviceRule); } else { keySec.SetAccessRuleProtection(false, false); keySec.RemoveAccessRule(systemRule); keySec.RemoveAccessRule(serviceRule); } subKey.SetAccessControl(keySec); return(true); } catch (Exception err) { AppLog.Exception(err); } return(false); }
/// <summary> /// 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 void Elevate() { using var key = Registry.CurrentUser.CreateSubKey("_test_sec_0"); var security = new RegistrySecurity(); security.SetAccessRuleProtection(true, false); key.SetAccessControl(security);
private void disableButton_Click(object sender, EventArgs e) { int disable = 1; if (sender == enableButton) { disable = 0; } #if !DEBUG try #endif { var hklm = Environment.Is64BitOperatingSystem ? RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64) : Registry.LocalMachine; Privileges.EnablePrivilege(SecurityEntity.SE_TAKE_OWNERSHIP_NAME); using (RegistryKey regKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.TakeOwnership)) { RegistrySecurity rs = regKey.GetAccessControl(AccessControlSections.None); //rs.SetGroup(new NTAccount("Administrators")); rs.SetOwner(WindowsIdentity.GetCurrent().User); rs.SetAccessRuleProtection(false, false); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.FullControl, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.WriteKey, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.ChangePermissions, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.CreateLink, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.CreateSubKey, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.Delete, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.EnumerateSubKeys, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.ExecuteKey, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.Notify, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.QueryValues, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.ReadKey, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.ReadPermissions, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.SetValue, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.TakeOwnership, AccessControlType.Allow)); rs.AddAccessRule(new RegistryAccessRule(WindowsIdentity.GetCurrent().User, RegistryRights.WriteKey, AccessControlType.Allow)); regKey.SetAccessControl(rs); } using (RegistryKey regKey = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Windows Defender\", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.SetValue)) { regKey.SetValue("DisableAntiSpyware", disable); regKey.SetValue("DisableAntiVirus", disable); } if (MessageBox.Show(this, "Done! For changes to take effect, the system needs to be restarted.\n\nWould you like to restart now?", "Done.", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { Process.Start("shutdown", "/r /t 0"); } } #if !DEBUG catch (Exception ex) { MessageBox.Show(this, "Please post this to the XDA thread (link in the app):\n" + ex.Message + "\n" + ex.Source + "\n" + ex.HelpLink + "\n" + ex.StackTrace, "Operation Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } #endif }
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); } } } }
/// <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."); } }
private RegistryKey OpenExplorerPoliciesKey() { RegistrySecurity RegistrySecurity = new RegistrySecurity(); WindowsIdentity WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); RegistryAccessRule AccessRule = new RegistryAccessRule(WindowsIdentity.Name, RegistryRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); RegistrySecurity.AddAccessRule(AccessRule); RegistrySecurity.SetAccessRuleProtection(false, true); RegistryKey RegistryKey = Registry.LocalMachine.OpenSubKey(ExplorerPolitiesRegistryPath, true); RegistryKey.SetAccessControl(RegistrySecurity); return(RegistryKey); }
static void Main(string[] args) { // Reload Registry Hive Trick CommonUtilities.ExecuteCommand("REG SAVE HKLM\\SYSTEM " + CommonUtilities.EscapePath(Environment.GetEnvironmentVariable("TEMP") + "\\SYSTEM.hiv"), true); CommonUtilities.ExecuteCommand("REG RESTORE HKLM\\SYSTEM " + CommonUtilities.EscapePath(Environment.GetEnvironmentVariable("TEMP") + "\\SYSTEM.hiv"), true); CommonUtilities.FileDelete(Environment.GetEnvironmentVariable("TEMP") + "\\SYSTEM.hiv"); // Rename and Delete WPA Key using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM", true)) { if (key != null) { // TODO : Powershell Bundled Vista+ ??? CommonUtilities.ExecuteCommand(@"POWERSHELL -command rename-item HKLM:\SYSTEM\WPA -NewName WPA_Delete", true); key.DeleteSubKeyTree("WPA_DELETE"); key.CreateSubKey("WPA"); // Create Default Values CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\478C035F-04BC-48C7-B324-2462D786DAD7-5P-9 /t REG_BINARY /ve /d 20c0c44b5d68c7085f442818128270ea642e5b5dba2d8885a7831a85c3d1ece262b36911a0d5bdb5e55106656d12578af73f942ffe1562ba665b18ce8969bbf74ff8ceacf3c424de22cf36560c8633b92173d5f38abbe0fbe3f408ca314725a94d599a4587daea29aa207b5cefbfcf2361b7a9beeaacc754513fdce82c16828d", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\478C035F-04BC-48C7-B324-2462D786DAD7-5P-9 /t REG_BINARY /v Time /d e318ad15241c695f751c6b19fe1ba41cebfb91bf29367de3146d79a76ace067c", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\478C035F-04BC-48C7-B324-2462D786DAD7-5P-9 /t REG_DWORD /v Type /d 2111353691", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\8DEC0AF1-0341-4b93-85CD-72606C2DF94C-7P-1 /t REG_BINARY /ve /d 6979d03b99a73c736882ceadf1a96320c15405927dc0b721f83cad674fb340496d75f608189d84dcd18fdaff8ea3866a3f37edc3d1eb5c0647e97bb7bea79f5dd05a66062fabb480d137cd3623563962e200b1bd42531cc3e6e4c1ffff693a208e9937f7a4d48b7463e68faf0df08811", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\8DEC0AF1-0341-4b93-85CD-72606C2DF94C-7P-2 /t REG_BINARY /ve /d 79e3ad3e68302e43bc97f4aceb98f3e328155f42df9684935abbc4f3c1652637a70f81fdf5f469d8586bf1d1a8ff96af9ead400b1c9d5621f4b4c57ad44fc2b129ca20a19a64bcfc481c52738b876b64", true); CommonUtilities.ExecuteCommand("REG ADD HKLM\\SYSTEM\\WPA\\8DEC0AF1-0341-4b93-85CD-72606C2DF94C-7P-3 /t REG_BINARY /ve /d 65a7778c965816a2df869e044edf4671f2ac716502d74d5b30c531c1469dc758dc25c2b480393d6fb7336d3d915668a7f05ff3847468228168833bed8947b4bc", true); } } // Set WPA Key Permissions using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\\WPA", true)) { if (key != null) { RegistrySecurity acl = new RegistrySecurity(); acl.SetAccessRuleProtection(true, false); acl.SetAccessRule(new RegistryAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), RegistryRights.FullControl, InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); key.SetAccessControl(acl); } } }
public static void SetKeyPermissions(RegistryKey key, string subKey, bool reset) { bool isProtected = !reset; string text = "SYSTEM"; string text2 = reset ? text : GetNewOwnerName(); SetKeyOwnerWithPrivileges(key, subKey, text); using (RegistryKey registryKey = key.OpenSubKey(subKey, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.ChangePermissions)) { RegistrySecurity registrySecurity = new RegistrySecurity(); if (!reset) { RegistryAccessRule rule = new RegistryAccessRule(text2, RegistryRights.FullControl, InheritanceFlags.None, PropagationFlags.NoPropagateInherit, AccessControlType.Allow); registrySecurity.AddAccessRule(rule); } registrySecurity.SetAccessRuleProtection(isProtected, false); registryKey.SetAccessControl(registrySecurity); } if (!reset) { SetKeyOwnerWithPrivileges(key, subKey, text2); } }
private static void SetRegistryAcls() { string ToopherSubKey = Abstractions.Settings.DynamicSettings.ROOT_KEY; using (RegistryKey key = Registry.LocalMachine.CreateSubKey(ToopherSubKey)) { if (key != null) { 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(); // 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); } } }
private void fixRights() { // We have a private key inside the registry, therefore we should ensure only admins have access to it RegistryKey regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE").OpenSubKey("WinCertes", RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl); RegistrySecurity regSec = regKey.GetAccessControl(AccessControlSections.All); regSec.SetOwner(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null)); regSec.SetAccessRuleProtection(true, false); regKey.SetAccessControl(regSec); RegistryAccessRule adminFull = new RegistryAccessRule(new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null), RegistryRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); regSec.AddAccessRule(adminFull); adminFull = new RegistryAccessRule(new SecurityIdentifier(WellKnownSidType.LocalSystemSid, null), RegistryRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); regSec.AddAccessRule(adminFull); string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName; // If we're joined to a domain, we probably need to give access to domain admins as well if ((domain != null) && (domain.Length > 0)) { adminFull = new RegistryAccessRule(new SecurityIdentifier(WellKnownSidType.AccountDomainAdminsSid, null), RegistryRights.FullControl, InheritanceFlags.ObjectInherit | InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow); regSec.AddAccessRule(adminFull); } regKey.SetAccessControl(regSec); }
protected override void ProcessRecord() { using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, true)) { if (regKey == null) { return; } RegistrySecurity security = null; // Account, Rights, AccessControlから追加 if (!string.IsNullOrEmpty(Account)) { if (security == null) { security = regKey.GetAccessControl(); } string accessString = string.Format("{0};{1};{2};{3};{4}", Account, _Rights, Recursive ? Item.CONTAINERINHERIT + ", " + Item.OBJECTINHERIT : Item.NONE, Item.NONE, AccessControl); // テスト自動生成 _generator.RegistryAccess(RegistryPath, accessString, true); foreach (RegistryAccessRule addRule in RegistryControl.StringToAccessRules(accessString)) { security.AddAccessRule(addRule); } } // Access文字列からの設定 if (!string.IsNullOrEmpty(Access)) { if (security == null) { security = regKey.GetAccessControl(); } // テスト自動生成 _generator.RegistryAccess(RegistryPath, Access, true); foreach (RegistryAccessRule rule in RegistryControl.StringToAccessRules(Access)) { security.AddAccessRule(rule); } } // 上位からのアクセス権継承の設定変更 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); } WriteObject(new RegistrySummary(regKey, true)); } }
protected override void ProcessRecord() { using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { if (regKey != null) { return; } } // テスト自動生成 _generator.RegistryPath(RegistryPath); using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, true, true)) { RegistrySecurity security = null; // Access文字列からの設定 if (!string.IsNullOrEmpty(Access)) { if (security == null) { security = regKey.GetAccessControl(); } // テスト自動生成 _generator.RegistryAccess(RegistryPath, Access, false); foreach (RegistryAccessRule rule in RegistryControl.StringToAccessRules(Access)) { security.AddAccessRule(rule); } } // 上位からのアクセス権継承の設定変更 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) { // 埋め込みのsubinacl.exeを展開 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(); } } using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { WriteObject(new RegistrySummary(regKey, true)); } }
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)); * } */ }
protected override void ProcessRecord() { if (Inherit != Item.NONE || !string.IsNullOrEmpty(Access)) { using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, true, true)) { RegistrySecurity security = regKey.GetAccessControl(); // 上位からのアクセス権継承の設定変更 switch (Inherit) { case Item.ENABLE: TestGenerator.RegistryInherit(Path, true); security.SetAccessRuleProtection(false, false); break; case Item.DISABLE: TestGenerator.RegistryInherit(Path, false); security.SetAccessRuleProtection(true, true); break; case Item.REMOVE: TestGenerator.RegistryInherit(Path, false); security.SetAccessRuleProtection(true, false); break; } // Access文字列からのアクセス権設定 if (!string.IsNullOrEmpty(Access)) { foreach (string ruleString in Access.Contains("/") ? Access.Split('/') : new string[1] { Access }) { // テスト自動生成 TestGenerator.RegistryAccess(Path, ruleString, true); security.SetAccessRule(RegistryControl.StringToAccessRule(ruleString)); } } /* * foreach (RegistryAccessRule accessRule in RegistryControl.StringToAccess(Access)) * { * security.SetAccessRule(accessRule); * } */ regKey.SetAccessControl(security); } } // 所有者変更 if (Owner != null) { // テスト自動生成 TestGenerator.RegistryOwner(Path, Owner); // 埋め込みのsubinacl.exeを展開 string tempDir = System.IO.Path.Combine( Environment.ExpandEnvironmentVariables("%TEMP%"), "PowerReg"); string subinacl = System.IO.Path.Combine(tempDir, "subinacl.exe"); if (!File.Exists(subinacl)) { EmbeddedResource.Expand(tempDir); } // 管理者実行確認 Message.CheckAdmin(); using (Process proc = new Process()) { proc.StartInfo.FileName = subinacl; proc.StartInfo.Arguments = $"/subkeyreg \"{Path}\" /owner=\"{Owner}\""; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.Start(); proc.WaitForExit(); } } // レジストリ値の設定 if (Name != null) { // テスト自動生成 TestGenerator.RegistryName(Path, Name); TestGenerator.RegistryType(Path, Name, Type); TestGenerator.RegistryValue(Path, Name, Value); switch (Type) { case Item.REG_SZ: Registry.SetValue(Path, Name, Value, RegistryValueKind.String); break; case Item.REG_BINARY: Registry.SetValue(Path, Name, RegistryControl.RegBinaryStringToBytes(Value), RegistryValueKind.Binary); break; case Item.REG_DWORD: Registry.SetValue(Path, Name, int.Parse(Value), RegistryValueKind.DWord); break; case Item.REG_QWORD: Registry.SetValue(Path, Name, long.Parse(Value), RegistryValueKind.QWord); break; case Item.REG_MULTI_SZ: Registry.SetValue(Path, Name, Regex.Split(Value, "\\\\0"), RegistryValueKind.MultiString); break; case Item.REG_EXPAND_SZ: Registry.SetValue(Path, Name, Value, RegistryValueKind.ExpandString); break; case Item.REG_NONE: Registry.SetValue(Path, Name, new byte[2] { 0, 0 }, RegistryValueKind.None); break; } } }
protected override void ProcessRecord() { bool isChange = false; using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, false, true)) { if (regKey == null) { return; } RegistrySecurity security = regKey.GetAccessControl(); // アクセス権設定 if (!string.IsNullOrEmpty(Account)) { RegistryAccessRule rule = new RegistryAccessRule( new NTAccount(Account), (RegistryRights)Enum.Parse(typeof(RegistryRights), _Rights), Recursive ? InheritanceFlags.ContainerInherit : InheritanceFlags.None, PropagationFlags.None, (AccessControlType)Enum.Parse(typeof(AccessControlType), AccessControl)); // テスト自動生成 TestGenerator.RegistryAccess(Path, RegistryControl.AccessRuleToString(rule), true); security.SetAccessRule(rule); isChange = true; } // Access文字列からの設定 if (!string.IsNullOrEmpty(Access)) { /* * foreach (RegistryAccessRule accessRule in RegistryControl.StringToAccess(Access)) * { * security.SetAccessRule(accessRule); * isChange = true; * } */ foreach (string ruleString in Access.Contains("/") ? Access.Split('/') : new string[1] { Access }) { // テスト自動生成 TestGenerator.RegistryAccess(Path, ruleString, true); security.SetAccessRule(RegistryControl.StringToAccessRule(ruleString)); isChange = true; } } // 上位からのアクセス権継承の設定変更 switch (Inherit) { case Item.ENABLE: TestGenerator.RegistryInherit(Path, true); security.SetAccessRuleProtection(false, false); isChange = true; break; case Item.DISABLE: TestGenerator.RegistryInherit(Path, false); security.SetAccessRuleProtection(true, true); isChange = true; break; case Item.REMOVE: TestGenerator.RegistryInherit(Path, false); security.SetAccessRuleProtection(true, false); isChange = true; break; } if (isChange) { regKey.SetAccessControl(security); } } WriteObject(new RegistryKeyInfo(Path, true)); }