public static void Set(RegistryValue key, string val) { using (RegistryKey rk = Registry.CurrentUser.CreateSubKey(c_RegistryRoot)) { rk.SetValue(key.ToString(), val); } }
public static string GetString(RegistryValue key, string defaultVal) { using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(c_RegistryRoot, false)) { if (rk == null) return defaultVal; return (string)(rk.GetValue(key.ToString(), defaultVal)); } }
public static bool GetBoolean(RegistryValue key, bool defaultVal) { using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(c_RegistryRoot, false)) { if (rk == null) return defaultVal; bool ret; if (bool.TryParse((string)(rk.GetValue(key.ToString(), defaultVal)), out ret)) return ret; else return defaultVal; } }
/// <summary> /// Writes a registry value to registry. /// </summary> /// <param name="inKey">Target key</param> /// <param name="valueToWrite">Registry value to save</param> public void value_save(Microsoft.Win32.RegistryKey inKey, RegistryValue valueToWrite) { valueToWrite.writeValue(inKey); }
private void ResolveRegistryValue(SortedList <string, string> directoryIds, SortedList <string, string> fileIds, RegistryValue registryValue) { string value = registryValue.Value.ToLower(CultureInfo.InvariantCulture); // Replace file paths with ids. foreach (KeyValuePair <string, string> pair in fileIds) { int index; while ((index = value.IndexOf(pair.Key)) != -1) { // Replace the non-lower case value itself. registryValue.Value = registryValue.Value.Remove(index, (pair.Key).Length); registryValue.Value = registryValue.Value.Insert(index, pair.Value); value = registryValue.Value.ToLower(CultureInfo.InvariantCulture); } } // Replace directory paths with ids. foreach (KeyValuePair <string, string> pair in directoryIds) { int index; while ((index = value.IndexOf(pair.Key)) != -1) { // Replace the non-lower case value itself. registryValue.Value = registryValue.Value.Remove(index, (pair.Key).Length); registryValue.Value = registryValue.Value.Insert(index, pair.Value); value = registryValue.Value.ToLower(CultureInfo.InvariantCulture); } } }
public static void Set(RegistryValue key, bool val) { Set(key, val.ToString()); }
public override bool Process() { Dictionary <double, List <string> > dictionary = new Dictionary <double, List <string> >(); List <string> list; RegistryKey[] subkeys = Key.GetListOfSubkeys(); RegistryValue value = null; string data = string.Empty; if (null != subkeys && 0 < subkeys.Length) { foreach (RegistryKey subkey in subkeys) { value = subkey.GetValue("(Default)"); if (null != value) { data = value.GetDataAsObject().ToString(); } else { data = string.Empty; } data = subkey.Name + " [" + data + "]"; if (dictionary.ContainsKey(subkey.Timestamp)) { list = dictionary[subkey.Timestamp]; list.Add(data); dictionary[subkey.Timestamp] = list; } else { list = new List <string>(); list.Add(data); dictionary.Add(subkey.Timestamp, list); } } List <KeyValuePair <double, List <string> > > sorted = new List <KeyValuePair <double, List <string> > >(dictionary); sorted.Sort( delegate(KeyValuePair <double, List <string> > first, KeyValuePair <double, List <string> > next) { return(next.Key.CompareTo(first.Key)); } ); string precedent = string.Empty; string gmtdate = string.Empty; foreach (KeyValuePair <double, List <string> > pair in sorted) { gmtdate = Library.TransrateTimestamp(pair.Key, TimeZoneBias, OutputUtc); if (!precedent.Equals(gmtdate)) { Reporter.Write(gmtdate); precedent = gmtdate; } foreach (string item in pair.Value) { Reporter.Write(" " + item); } } } else { Reporter.Write(KeyPath + " にはサブキーがありませんでした。"); } return(true); }
private static void ParseRegFile(string sRegFile, List <RegistryKey> wixKeys, List <RegistryValue> wixValues) { using (var reader = new StreamReader(sRegFile, true)) { string line; RegistryRootType rootCurrent = RegistryRootType.HKMU; // The current registry Root to read the values into string sCurrentKey = ""; // The current key path under the current root to read the values into var regexJustRoot = new Regex(@"^HKEY_[^\\]+$", RegexOptions.IgnoreCase | RegexOptions.Singleline); var regexRootAndKey = new Regex(@"^(?<Root>HKEY_.+?)\\(?<Key>.*)$", RegexOptions.IgnoreCase | RegexOptions.Singleline); var regexValueQuotedQuoted = new Regex("^\"(?<Name>.+?)(?<!\\\\)\"\\s*=\\s*\"(?<Value>.+)\"$", RegexOptions.IgnoreCase | RegexOptions.Singleline); var regexDefaultValueQuoted = new Regex("^@=\"(?<Value>.+)\"$", RegexOptions.IgnoreCase | RegexOptions.Singleline); while ((line = reader.ReadLine()) != null) { line = line.Trim(); if (string.IsNullOrEmpty(line)) { continue; } // A key? Match match; if (line[0] == '[') { if (line[line.Length - 1] != ']') { throw new InvalidOperationException(string.Format("There's a key opening bracket, but no closing one.")); } string key = line.Substring(1, line.Length - 2); // Only HKEY_SMTH? Not interested if (regexJustRoot.IsMatch(key)) { continue; } // Break into the root and the key match = regexRootAndKey.Match(key); if (!match.Success) { throw new InvalidOperationException(string.Format("Failed to parse the key “{0}”.", key)); } string sKeyPrefix = ""; string sRootValue = match.Groups["Root"].Value.ToUpperInvariant(); switch (sRootValue) { case "HKEY_CLASSES_ROOT": rootCurrent = RegistryRootType.HKMU; sKeyPrefix = "Software\\Classes\\"; break; case "HKEY_LOCAL_MACHINE": rootCurrent = RegistryRootType.HKLM; break; case "HKEY_CURRENT_USER": rootCurrent = RegistryRootType.HKCU; break; case "HKEY_USERS": rootCurrent = RegistryRootType.HKU; break; default: throw new InvalidOperationException(string.Format("Unsupported registry root “{0}”.", sRootValue)); } sCurrentKey = sKeyPrefix + match.Groups["Key"].Value; // List the key var wixKey = new RegistryKey(); wixKey.Root = rootCurrent; wixKey.Key = sCurrentKey; wixKey.Action = RegistryKey.ActionType.createAndRemoveOnUninstall; if (wixKey.Root != RegistryRootType.HKU) { wixKeys.Add(wixKey); } continue; } // A value, otherwise // Parse the value string sValueName = null; object oValueValue = null; match = null; foreach (Regex regex in new[] { regexValueQuotedQuoted, regexDefaultValueQuoted, }) { match = regex.Match(line); if (!match.Success) { continue; } if (match.Groups["Name"] != null) { sValueName = match.Groups["Name"].Value; } if (match.Groups["Value"] != null) { oValueValue = match.Groups["Value"].Value; } break; } if ((match == null) || (!match.Success)) { throw new InvalidOperationException(string.Format("Could not parse the Registry value “{0}”.", line)); } // Create the value var wixValue = new RegistryValue(); wixValue.Root = rootCurrent; wixValue.Key = sCurrentKey; if (!string.IsNullOrEmpty(sValueName)) { wixValue.Name = sValueName; } wixValue.Value = oValueValue != null?oValueValue.ToString() : null; wixValue.Type = RegistryValue.TypeType.@string; wixValue.Action = RegistryValue.ActionType.write; if (wixValue.Root != RegistryRootType.HKU) { wixValues.Add(wixValue); } } } }
public override bool Process() { // 最初にXP固有のキーの取得を試みる RegistryKey key = Key.GetSubkey("AppCompatibility"); if (key == null) { // XP固有キーが存在しない場合、XP以外のキー名で検索 key = Key.GetSubkey("AppCompatCache"); } if (key == null) { Reporter.Write("Keyが見つかりませんでした。"); return(true); } RegistryValue value = key.GetValue("AppCompatCache"); uint sig = BitConverter.ToUInt32(Library.ExtractArrayElements(value.Data, 0, 4), 0); Reporter.Write("Signature: 0x" + Convert.ToString(sig, 16)); #region Debug #if DEBUG // データ部分として取得されたバイナリを見たいときshowHexをtrueにして表示させる bool showHex = false; if (showHex) { StringBuilder hex = new StringBuilder(); for (int i = 0; i < Math.Min(value.Data.Length, 2000); ++i) { byte b = value.Data[i]; hex.Append(b.ToString("X2")); hex.Append(" "); } string list = hex.ToString().TrimEnd(); System.Windows.Forms.MessageBox.Show(list, "DataViewer", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information, System.Windows.Forms.MessageBoxDefaultButton.Button1, System.Windows.Forms.MessageBoxOptions.DefaultDesktopOnly); } #endif #endregion // Dictionary<パス文字列, Dictionary<値の種類, 値>> Dictionary <string, Dictionary <string, string> > results; switch (sig) { // XP32Bit case 0xdeadbeef: results = this.ParseXp32(value.Data); break; // Win2003, Vista, Win2008 case 0xbadc0ffe: results = this.ParseWin2003(value.Data); break; // Win2008R2, Win7 case 0xbadc0fee: results = ParseWin7(value.Data); break; // Win10 case 0x30: case 0x34: results = ParseWin10(value.Data); break; // 本来は判定不能 = 対象外バージョンだが、暫定的に Win8 として扱う default: results = ParseWin8(value.Data); //Reporter.Write("未対応バージョンのOSです。"); //results = null; break; } if (results != null) { StringBuilder sb = new StringBuilder(); // "temp"を含むパスを最後に列挙する var tempList = new List <string>(); foreach (string s in results.Keys) { string path = s.Substring(0, s.IndexOf(DELIM)); sb.AppendLine(path); if (0 <= s.IndexOf("temp", StringComparison.OrdinalIgnoreCase)) { tempList.Add(path); } var values = results[s]; if (values.ContainsKey(MOD_TIME)) { sb.AppendLine("ModTime: " + values[MOD_TIME]); } if (values.ContainsKey(UPD_TIME)) { sb.AppendLine("UpdTime: " + values[UPD_TIME]); } if (values.ContainsKey(SIZE)) { sb.AppendLine("Size: " + values[SIZE]); } if (values.ContainsKey(EXEC)) { sb.AppendLine(values[EXEC]); } sb.AppendLine(); } if (0 < tempList.Count) { sb.AppendLine("Temp paths found:"); foreach (string path in tempList) { sb.AppendLine(path); } } Reporter.Write(sb.ToString()); } return(true); }
/// <summary> /// /// </summary> /// <param name="args"></param> static void Main(string[] args) { try { Assembly assembly = Assembly.GetExecutingAssembly(); AssemblyName assemblyName = assembly.GetName(); Console.WriteLine(Environment.NewLine + "shimcacheparser v" + assemblyName.Version.ToString(3) + Environment.NewLine); Options options = new Options(); if (CommandLineParser.Default.ParseArguments(args, options) == false) { return; } if (IsValidSortValue(options) == false) { Console.WriteLine("Invalid sort parameter value (-s)"); return; } if (File.Exists(options.File) == false) { Console.WriteLine("The registry file does not exist"); return; } Registry.Registry registry = new Registry.Registry(options.File); RegistryKey rootKey = registry.Root; foreach (RegistryKey subKey in rootKey.SubKeys()) { if (subKey.Name.IndexOf("ControlSet", StringComparison.InvariantCultureIgnoreCase) == -1) { continue; } try { List <Hit> hits = new List <Hit>(); RegistryKey regKeySessionManager = registry.Open(string.Format(@"{0}\Control\Session Manager", subKey.Name)); if (regKeySessionManager == null) { continue; } foreach (RegistryKey subKeySessionManager in regKeySessionManager.SubKeys()) { //@"ControlSet001\Control\Session Manager\AppCompatibility\AppCompatCache" //@"ControlSet001\Control\Session Manager\AppCompatCache\AppCompatCache" if (subKeySessionManager.Name.IndexOf("AppCompatibility", StringComparison.InvariantCultureIgnoreCase) == -1 & subKeySessionManager.Name.IndexOf("AppCompatCache", StringComparison.InvariantCultureIgnoreCase) == -1) { continue; } RegistryValue regVal = subKeySessionManager.Value("AppCompatCache"); if (regVal == null) { continue; } byte[] data = (byte[])regVal.Value; // Data size less than minimum header size. if (data.Length < 16) { continue; } UInt32 magic = BitConverter.ToUInt32(data.Slice(0, 4), 0); // Determine which version we are working with switch (magic) { case Global.WINXP_MAGIC32: // This is WinXP cache data Console.WriteLine("[+] Found 32bit Windows XP Shim Cache data..."); hits = ReadWinXpEntries(data); break; case Global.CACHE_MAGIC_NT5_2: // This is a Windows 2k3/Vista/2k8 Shim Cache format, // Shim Cache types can come in 32-bit or 64-bit formats. We can determine this because 64-bit entries are serialized with u_int64 pointers. // This means that in a 64-bit entry, valid UNICODE_STRING sizes are followed by a NULL DWORD. Check for this here. UInt16 testSizeNt5 = BitConverter.ToUInt16(data.Slice(8, 10), 0); UInt16 testMaxSizeNt5 = BitConverter.ToUInt16(data.Slice(10, 12), 0); UInt32 testTempNt5 = BitConverter.ToUInt32(data.Slice(12, 16), 0); if ((testMaxSizeNt5 - testSizeNt5 == 2) & (testTempNt5 == 0)) { Console.WriteLine("[+] Found 64bit Windows 2k3/Vista/2k8 Shim Cache data..."); hits = ReadNt5Entries(data, false); } else { Console.WriteLine("[+] Found 32bit Windows 2k3/Vista/2k8 Shim Cache data..."); hits = ReadNt5Entries(data, true); } break; case Global.CACHE_MAGIC_NT6_1: // This is a Windows 7/2k8-R2 Shim Cache. // Shim Cache types can come in 32-bit or 64-bit formats. We can determine this because 64-bit entries are serialized with u_int64 pointers. // This means that in a 64-bit entry, valid UNICODE_STRING sizes are followed by a NULL DWORD. Check for this here. UInt16 testSizeNt6 = BitConverter.ToUInt16(data.Slice(Global.CACHE_HEADER_SIZE_NT6_1, Global.CACHE_HEADER_SIZE_NT6_1 + 2), 0); UInt16 testMaxSizeNt6 = BitConverter.ToUInt16(data.Slice(Global.CACHE_HEADER_SIZE_NT6_1 + 2, Global.CACHE_HEADER_SIZE_NT6_1 + 4), 0); UInt32 testTempNt6 = BitConverter.ToUInt32(data.Slice(Global.CACHE_HEADER_SIZE_NT6_1 + 4, Global.CACHE_HEADER_SIZE_NT6_1 + 8), 0); if ((testMaxSizeNt6 - testSizeNt6 == 2) & (testTempNt6 == 0)) { Console.WriteLine("[+] Found 64bit Windows 7/2k8-R2 Shim Cache data..."); hits = ReadNt6Entries(data, false); } else { Console.WriteLine("[+] Found 32bit Windows 7/2k8-R2 Shim Cache data..."); hits = ReadNt6Entries(data, true); } break; default: Console.WriteLine(string.Format("[-] Got an unrecognized magic value of {0}... bailing... ", magic)); return; } } PrintHits(options, hits); } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); } } } catch (Exception ex) { Console.WriteLine("An error occurred: " + ex.Message); } }
private void Recursive(RegistryKey key, string path, string folderName) { // NodeSlotから実体のフォルダの内容を取得 RegistryValue slotValue = key.GetValue("NodeSlot"); if (null != slotValue) { string slotNumber = slotValue.GetDataAsObject().ToString(); // RegistryKey bagKey = RootKey.GetSubkey(pathBuilder.ToString() + @"\" + slotValue.GetData().ToString()); RegistryKey bagKey = RootKey.GetSubkey(path.Remove(path.Length - 3) + @"s\" + slotNumber + @"\Shell"); if (null != bagKey) { RegistryKey[] subkeys = bagKey.GetListOfSubkeys(); if (null != subkeys) { } RegistryValue[] bagValues = bagKey.GetListOfValues(); if (null != bagValues) { Reporter.Write(" FolderName : " + ((0 != folderName.Length) ? folderName : "デスクトップ?")); Reporter.Write(" [ValueList]"); string dataString = ""; byte[] bytes; StringBuilder dataBuilder = new StringBuilder(); foreach (RegistryValue bagValue in bagValues) { if (Constants.REG_BINARY != bagValue.Type) { dataString = bagValue.GetDataAsString(); } else { bytes = bagValue.Data; foreach (byte item in bytes) { if (0 < dataBuilder.Length) { dataBuilder.Append(" "); } dataBuilder.Append(item.ToString("X2")); } dataString = dataBuilder.ToString(); } Reporter.Write(" " + bagValue.Name + " : " + dataString); } Reporter.Write(""); } } } // まずMRUListExを取得 RegistryValue mruValue = key.GetValue("MRUListEx"); if (null != mruValue) { byte[] mruData = (byte[])mruValue.GetDataAsObject(); if (null != mruData) { uint mru = 0; RegistryValue value; List <byte> byteList = new List <byte>(); byte[] bytes = null; for (uint count = 0; count < mruData.Length; count += 4) { mru = BitConverter.ToUInt16(Library.ExtractArrayElements(mruData, count, 4), 0); value = key.GetValue(mru.ToString()); if (null != value) { bytes = (byte[])value.GetDataAsObject(); if (0x19 == bytes[0]) { if (0 < folderName.Length) { Logger.Write(LogLevel.WARNING, folderName + " / " + mru.ToString() + "は怪しげです。"); } folderName = Encoding.ASCII.GetString(Library.ExtractArrayElements(bytes, 3, 3)); } else { byteList = new List <byte>(); // Reporter.Write("\t" + value.Name + "WriteTime : " Library.ExtractArrayElements(bytes, 8, 4)); //hoge++; //System.IO.File.WriteAllBytes(@"C:\WORK\KaniReg\dummyFile\" + hoge.ToString() + ".txt" , (byte[])data); bool start = false; for (uint innerCount = 4; innerCount < bytes.Length; innerCount++) { if (!start && 0x14 == bytes[innerCount - 4] && 0x00 == bytes[innerCount - 3] && 0x00 == bytes[innerCount - 2] && 0x00 == bytes[innerCount - 1]) { start = true; } if (!start) { continue; } byteList.Add(bytes[innerCount]); if (0x00 == bytes[innerCount] && 0x00 == bytes[innerCount + 1]) { break; } } if (0 < folderName.Length) { folderName += @"\"; } folderName += Encoding.Unicode.GetString(byteList.ToArray()); } } RegistryKey subKey = key.GetSubkey(mru.ToString()); if (null != subKey) { Recursive(subKey, path, folderName); } } } } }