Пример #1
0
 public static bool DeleteRegistryKeyValue(RegistryHive hive, string path, string name) =>
     RegistryKey.OpenBaseKey(hive, RegistryView.Registry64).OpenWritableSubKeySafe(path,
         (key) =>
         {
             key.DeleteValue(name, true);
             return true;
         });
Пример #2
0
		public static RegistryKeyOptions CreateRegistryKey(this ProtoServer protoServer, RegistryHive hive, string name, Action<RegistryKeyOptions> options)
		{
			var proto = CreateRegistryKey(protoServer, hive, name);
			if (options != null)
				options(proto);
			return proto;
		}
Пример #3
0
        public static object ReadKey(RegistryHive hive, RegistryView view, string subkey, string name)
        {
            // open root
            RegistryKey rootKey = Microsoft.Win32.RegistryKey.OpenBaseKey(hive, view);
            if (rootKey == null)
            {
                return null;
            }

            // look for key
            RegistryKey key = rootKey.OpenSubKey(subkey);
            if (key == null)
            {
                return null;
            }

            // look for value
            object value = key.GetValue(name);
            if (value == null)
            {
                return null;
            }

            return value;
        }
Пример #4
0
 public IRegistryKey OpenBaseKey(
     RegistryHive hKey,
     RegistryView view
 )
 {
     return new RegistryKeyWrap(RegistryKey.OpenBaseKey(hKey, view));
 }
Пример #5
0
        /// <summary>
        /// Удалить ключ реестра
        /// </summary>
        /// <param name="root">Ветка реестра</param>
        /// <param name="key">Ключ для удаления</param>
        public static void RemoveRegistrySubKey(RegistryHive root, string key)
        {
            switch (root)
            {
                case RegistryHive.ClassesRoot:
                    Registry.ClassesRoot.DeleteSubKey(key);
                    break;

                case RegistryHive.CurrentUser:
                    Registry.CurrentUser.DeleteSubKey(key);
                    break;

                case RegistryHive.LocalMachine:
                    Registry.LocalMachine.DeleteSubKey(key);
                    break;

                case RegistryHive.Users:
                    Registry.Users.DeleteSubKey(key);
                    break;

                case RegistryHive.CurrentConfig:
                    Registry.CurrentConfig.DeleteSubKey(key);
                    break;
            }
        }
 public RegistrySettingsProvider
     (RegistryHive hKey, RegistryView view = RegistryView.Default, string baseKey = null)
 {
     this.hKey = hKey;
     this.view = view;
     this.baseKey = baseKey ?? ProductInfo.Company + "\\" + ProductInfo.Product;
 }
Пример #7
0
 public void SetValue(RegistryHive hive, string registryValueName, object value)
 {
     RegistryKey rootKey = RegistryKey.OpenBaseKey(hive, RegistryView.Default);
     RegistryKey testKey = rootKey.CreateSubKey(TestKeyPath);
     Assert.NotNull(testKey);
     testKey.SetValue(registryValueName, value);
 }
Пример #8
0
        public void HBinSizeShouldNotMatchReadSize()
        {
            var r = new RegistryHive(@"..\..\Hives\SAM_DUPENAME");
            //if you don't call parse, it wont match

            Check.That(r.Header.Length).IsNotEqualTo(r.HBinRecordTotalSize);
        }
Пример #9
0
        private static void CleanUpRegistry(RegistryHive hive)
        {
            var regValueNames = new[]{ Reg_LoggingEnabled,
									   Reg_DebugLogEnabled,
                                       Reg_FileLogEnabled,
                                       Reg_Severity,
                                       Reg_Path};

            using (RegistryKey rootKey = RegistryKey.OpenBaseKey(hive, RegistryView.Default))
            {
                using (RegistryKey key = rootKey.OpenSubKey(TestKeyPath, true))
                {
                    if (key != null)
                    {
                        foreach (var regValueName in regValueNames)
                        {
                            try
                            {
                                key.DeleteValue(regValueName);
                            }
                            catch (ArgumentException)
                            {
                                // Assumption: ArgumentExceptions caused by values that are not present
                            }
                        }
                    }
                }
            }

        }
Пример #10
0
        protected override void DoRun()
        {
            using (Stream fileStream = File.OpenRead(_bcdFile.Value))
            {
                using (RegistryHive hive = new RegistryHive(fileStream))
                {

                    Store bcdDb = new Store(hive.Root);
                    foreach (var obj in bcdDb.Objects)
                    {
                        Console.WriteLine(obj.FriendlyName + ":");
                        Console.WriteLine("               Id: " + obj.ToString());
                        Console.WriteLine("             Type: " + obj.ObjectType);
                        Console.WriteLine("   App Image Type: " + obj.ApplicationImageType);
                        Console.WriteLine("         App Type: " + obj.ApplicationType);
                        Console.WriteLine("  App can inherit: " + obj.IsInheritableBy(ObjectType.Application));
                        Console.WriteLine("  Dev can inherit: " + obj.IsInheritableBy(ObjectType.Device));
                        Console.WriteLine("  ELEMENTS");
                        foreach (var elem in obj.Elements)
                        {
                            Console.WriteLine("    " + elem.FriendlyName + ":");
                            Console.WriteLine("          Id: " + elem.ToString());
                            Console.WriteLine("       Class: " + elem.Class);
                            Console.WriteLine("      Format: " + elem.Format);
                            Console.WriteLine("       Value: " + elem.Value);
                        }

                        Console.WriteLine();
                    }
                }
            }
        }
Пример #11
0
        private static bool ExistsInRemoteSubKey(string p_machineName, RegistryHive p_hive, string p_subKeyName, string p_attributeName, string p_name)
        {
            RegistryKey subkey;
            string displayName;

            using (RegistryKey regHive = RegistryKey.OpenRemoteBaseKey(p_hive, p_machineName))
            {
                using (RegistryKey regKey = regHive.OpenSubKey(p_subKeyName))
                {
                    if (regKey != null)
                    {
                        foreach (string kn in regKey.GetSubKeyNames())
                        {
                            using (subkey = regKey.OpenSubKey(kn))
                            {
                                displayName = subkey.GetValue(p_attributeName) as string;
                                if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true) // key found!
                                {
                                    return true;
                                }
                            }
                        }
                    }
                }
            }
            return false;
        }
Пример #12
0
        public Bin(RegistryHive hive, Stream stream)
        {
            _hive = hive;
            _fileStream = stream;
            _streamPos = stream.Position;

            stream.Position = _streamPos;
            byte[] buffer = Utilities.ReadFully(stream, 0x20);
            _header = new BinHeader();
            _header.ReadFrom(buffer, 0);

            _fileStream.Position = _streamPos;
            _buffer = Utilities.ReadFully(_fileStream, _header.BinSize);

            // Gather list of all free cells.
            _freeCells = new List<Range<int, int>>();
            int pos = 0x20;
            while (pos < _buffer.Length)
            {
                int size = Utilities.ToInt32LittleEndian(_buffer, pos);
                if (size > 0)
                {
                    _freeCells.Add(new Range<int, int>(pos, size));
                }

                pos += Math.Abs(size);
            }
        }
Пример #13
0
        public static bool GetRegistryLocation(MapLocation which, ref RegistryHive hive, ref string keyname, ref string valuename)
        {
            hive = RegistryHive.CurrentUser;

            switch (which)
            {
                case MapLocation.LocalMachineKeyboardLayout:
                    hive = RegistryHive.LocalMachine;
                    keyname = @"SYSTEM\CurrentControlSet\Control\Keyboard Layout";
                    valuename = "Scancode Map";
                    break;
              case MapLocation.KeyMapperLocalMachineKeyboardLayout:
                    keyname = AppController.ApplicationRegistryKeyName;
                    valuename = "BootMaps";
                    break;
              case MapLocation.KeyMapperVistaMappingsCache:
                    keyname = AppController.ApplicationRegistryKeyName;
                    valuename = "VistaBootCache";
                    break;
                default:
                    return false;
            }

            return true;
        }
Пример #14
0
        public RegistryKeyMonitor(
            RegistryHive hive,
            string key,
            RegistryNotifyFilter filter,
            RegistryKeyWatch watch,
            KeyChangedDelegate keyChanged,
            ExceptionRaisedDelegate exceptionRaised)
        {
            if (keyChanged == null)
            {
                throw new ArgumentNullException(nameof(keyChanged));
            }

            if (exceptionRaised == null)
            {
                throw new ArgumentNullException(nameof(exceptionRaised));
            }

            RegistryHive = hive;
            Key = key;
            Filter = filter;
            WatchSubTree = watch == RegistryKeyWatch.KeyAndSubKeys;
            this.keyChanged = keyChanged;
            this.exceptionRaised = exceptionRaised;

            StartMonitor();
        }
Пример #15
0
        private UIntPtr OpenKey(RegistryHive hive, string keyname, int requiredAccess)
        {
            UIntPtr hiveptr;
            UIntPtr hkey;

            switch (hive)
            {
                case RegistryHive.ClassesRoot:
                    hiveptr = (UIntPtr)0x80000000;
                    break;
                case RegistryHive.CurrentUser:
                    hiveptr = (UIntPtr)0x80000001;
                    break;
                case RegistryHive.LocalMachine:
                    hiveptr = (UIntPtr)0x80000002;
                    break;
                case RegistryHive.Users:
                    hiveptr = (UIntPtr)0x80000003;
                    break;
                case RegistryHive.CurrentConfig:
                    hiveptr = (UIntPtr)0x80000005;
                    break;
                default:
                    return UIntPtr.Zero;
            }

            int result = NativeMethods.RegOpenKeyEx(hiveptr, keyname, 0, requiredAccess, out hkey);

            if (result == 0)
                return hkey;

            return UIntPtr.Zero;
        }
Пример #16
0
 private void add_key(IList<RegistryKey> keys, RegistryHive hive, RegistryView view)
 {
     FaultTolerance.try_catch_with_logging_exception(
         () => keys.Add(RegistryKey.OpenBaseKey(hive, view)),
         "Could not open registry hive '{0}' for view '{1}'".format_with(hive.to_string(), view.to_string()),
         logWarningInsteadOfError: true);
 }
Пример #17
0
        private Int64 GetRawRegistryKeyTimestamp(RegistryHive hive, string keyname)
        {
            if (String.IsNullOrEmpty(keyname))
            {
                return 0; // Otherwise the function opens HKLM (or HKCU) again.
            }

            UIntPtr hkey = OpenKey(hive, keyname, KEY_QUERY_VALUE);

            if (hkey == UIntPtr.Zero)
            {
                return 0; // Didn't open key
            }

            Int64 timestamp;

            uint result2 = NativeMethods.RegQueryInfoKey(
                hkey, IntPtr.Zero,
                IntPtr.Zero, IntPtr.Zero,
                IntPtr.Zero, IntPtr.Zero,
                IntPtr.Zero, IntPtr.Zero,
                IntPtr.Zero, IntPtr.Zero,
                IntPtr.Zero, out timestamp);

            if (result2 != 0)
            {
                timestamp = 0; // Failed, don't return whatever value was supplied.
            }

            NativeMethods.RegCloseKey(hkey);

            return timestamp;
        }
        public static RegistryKey GetRegBaseKey(RegistryHive hive)
        {
#if NET4
            return RegistryKey.OpenBaseKey(hive, (Environment.Is64BitOperatingSystem ? RegistryView.Registry64 : RegistryView.Registry32));
#else
            RegistryKey result = null;

            switch (hive)
            {
                case RegistryHive.ClassesRoot:
                    break;
                case RegistryHive.CurrentConfig:
                    break;
                case RegistryHive.CurrentUser:
                    break;
                case RegistryHive.DynData:
                    break;
                case RegistryHive.PerformanceData:
                    break;
                case RegistryHive.Users:
                    break;
                default:
                    result = Microsoft.Win32.Registry.LocalMachine;
                    break;
            }

            return result;
#endif
        }
Пример #19
0
		private void deleteRegistryKey(RegistryHive hive, string key)
		{
			using (var reg = RegistryKey.OpenBaseKey(hive, RegistryView.Default))
			{
				reg.DeleteSubKey(key);
			}
		}
 static Register()
 {
     ClassesRoot = new RegistryHive(Registry.ClassesRoot);
     CurrentUser = new RegistryHive(Registry.CurrentUser);
     LocalMachine = new RegistryHive(Registry.LocalMachine);
     Users = new RegistryHive(Registry.Users);
     CurrentConfig = new RegistryHive(Registry.CurrentConfig);
 }
Пример #21
0
		public static string GetString( string computerName, RegistryHive rh, string registryPath, string valueName ) {
			using( var reg = RegistryKey.OpenRemoteBaseKey( rh, computerName ) ) {
				using( var regFolder = reg.OpenSubKey( registryPath ) ) {
					var result = GetString( regFolder, valueName );
					return result;
				}
			}
		}
Пример #22
0
		static void DeleteKey(RegistryHive hive, RegistryView view, string guid)
		{
			using (RegistryKey key = RegistryKey.OpenBaseKey(hive, view)) {
				key.DeleteSubKey("Software\\Classes\\CLSID\\" + guid + "\\ProgId", false);
				key.DeleteSubKey("Software\\Classes\\CLSID\\" + guid + "\\InProcServer32", false);
				key.DeleteSubKey("Software\\Classes\\CLSID\\" + guid, false);
			}
		}
Пример #23
0
		public static void KeyExists(RegistryHive hive, string key)
		{
			using (var reg = RegistryKey.OpenBaseKey(hive, RegistryView.Default))
				using (var subKey = reg.OpenSubKey(key))
				{
					Assert.IsNotNull(subKey);
				}
		}
Пример #24
0
 /// <summary>
 /// Returns the names of the subkeys under the provided key.
 /// </summary>
 /// <param name="hive">The hive where <paramref name="key"/> is located.</param>
 /// <param name="key">The key to search.</param>
 /// <returns>A list of subkeys.</returns>
 public string[] GetSubKeys(RegistryHive hive, string key)
 {
     RegistryKey hiveKey = getHiveKey(hive);
     using (RegistryKey openKey = hiveKey.OpenSubKey(key))
     {
         return openKey.GetSubKeyNames();
     }
 }
Пример #25
0
		/// <summary>
		///	Construct an instance of a root registry key entry.
		/// </summary>
		internal RegistryKey (RegistryHive hiveId, IntPtr keyHandle, bool remoteRoot)
		{
			hive = hiveId;
			handle = keyHandle;
			qname = GetHiveName (hiveId);
			isRemoteRoot = remoteRoot;
			isWritable = true; // always consider root writable
		}
Пример #26
0
        private object GetRegistryValue(RegistryHive hive, string registryValueName)
        {
            RegistryKey rootKey = RegistryKey.OpenBaseKey(hive, RegistryView.Default);
            RegistryKey testKey = rootKey.OpenSubKey(TestKeyPath);
            Assert.NotNull(testKey);

            return testKey.GetValue(registryValueName);
        }
Пример #27
0
 public RegistryKeyMonitor(
     RegistryHive hive,
     string key,
     KeyChangedDelegate keyChanged,
     ExceptionRaisedDelegate exceptionRaised)
     : this(hive, key, ALL_FILTERS, keyChanged, exceptionRaised)
 {
 }
 internal void Close()
 {
     if (_hive != null)
     {
         _hive.Dispose();
         _hive = null;
     }
 }
Пример #29
0
        public DateTime GetRegistryKeyTimestamp(RegistryHive hive, string keyName)
        {
            Int64 ts = GetRawRegistryKeyTimestamp(hive, keyName);

            DateTime dt = (ts != 0 ? DateTime.FromFileTimeUtc(ts) : DateTime.MinValue);

            return dt.ToLocalTime();
        }
Пример #30
0
        public IRegistryKey OpenRemoteBaseKey(
	RegistryHive hKey,
	string machineName,
	RegistryView view
)
        {
            return new RegistryKeyWrap(RegistryKey.OpenRemoteBaseKey(hKey, machineName, view));
        }
Пример #31
0
        public void ShouldFindAdbRecordWhileParsing()
        {
            var usrclass = new RegistryHive(@"..\..\..\Hives\SYSTEM");

            usrclass.ParseHive();
        }
Пример #32
0
        public static bool CheckRegistry(string path, string name = null, string value = null, RegistryHive root = RegistryHive.CurrentUser)
        {
            string registryValue = GetRegistryValue(path, name, root);

            return(registryValue != null && (value == null || registryValue.Equals(value, StringComparison.InvariantCultureIgnoreCase)));
        }
        public static IEnumerable <RegistryObject> WalkHive(RegistryHive Hive, string startingKey = null)
        {
            Stack <RegistryKey> keys = new Stack <RegistryKey>();

            RegistryKey x86_View = RegistryKey.OpenBaseKey(Hive, RegistryView.Registry32);

            if (startingKey != null)
            {
                x86_View = x86_View.OpenSubKey(startingKey);
            }

            keys.Push(x86_View);

            RegistryKey x64_View = RegistryKey.OpenBaseKey(Hive, RegistryView.Registry64);

            if (startingKey != null)
            {
                x64_View = x64_View.OpenSubKey(startingKey);
            }

            keys.Push(x64_View);

            while (keys.Count > 0)
            {
                RegistryKey currentKey = keys.Pop();

                if (currentKey == null)
                {
                    continue;
                }
                if (Filter.IsFiltered(Helpers.GetPlatformString(), "Scan", "Registry", "Key", currentKey.Name))
                {
                    continue;
                }

                // First push all the new subkeys onto our stack.
                foreach (string key in currentKey.GetSubKeyNames())
                {
                    try
                    {
                        var next = currentKey.OpenSubKey(name: key, writable: false);
                        keys.Push(next);
                    }
                    // These are expected as we are running as administrator, not System.
                    catch (System.Security.SecurityException e)
                    {
                        Log.Verbose(e, "Permission Denied: {0}", currentKey.Name);
                    }
                    // There seem to be some keys which are listed as existing by the APIs but don't actually exist.
                    // Unclear if these are just super transient keys or what the other cause might be.
                    // Since this isn't user actionable, also just supress these to the verbose stream.
                    catch (System.IO.IOException e)
                    {
                        Log.Verbose(e, "Error Reading: {0}", currentKey.Name);
                    }
                    catch (Exception e)
                    {
                        Log.Information(e, "Unexpected error when parsing {0}:", currentKey.Name);
                        Telemetry.TrackTrace(Microsoft.ApplicationInsights.DataContracts.SeverityLevel.Error, e);
                    }
                }

                var regObj = RegistryKeyToRegistryObject(currentKey);

                if (regObj != null)
                {
                    yield return(regObj);
                }
            }
        }
Пример #34
0
 public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view)
 {
     ValidateKeyView(view);
     return(OpenBaseKeyCore(hKey, view));
 }
Пример #35
0
        public void BlahGetInstalledComponents()
        {
            // TODO: Does this make a difference, or does it depend just on the provider?
            const string softwareNode = @"Software";
            //const string softwareNodeWow = @"Software\Wow6432Node";

            //const string swUninstallSubnode = @"\Microsoft\Windows\CurrentVersion\Uninstall";
            const string swUninstallSubnode = @"\Asus";

            //ManagementClass reg = new ManagementClass(@"\\" + m_facade.Provider.Host + @"\root\Default", _REGISTRY_PROVIDER, null);

            RegistryHive hklm   = RegistryHive.LocalMachine;
            const string subKey = softwareNode + swUninstallSubnode;


            // Set up in+out params and call EnumKey
            //
            string method = "EnumKey";
            ManagementBaseObject inParams = m_registry.GetMethodParameters(method);

            inParams["hDefKey"]     = (uint)hklm;
            inParams["sSubKeyName"] = subKey;
            ManagementBaseObject outParams = m_registry.InvokeMethod(method, inParams, null);

            if (null == outParams)
            {
                return;
            }

            string[] props = outParams.Properties["sNames"].Value as string[];
            if (null == props)
            {
                return;
            }


            foreach (string pkgID in props)
            {
                string pkgKeyPath = subKey + "\\" + pkgID;

                // Set up in+out params and call GetStringValue
                //
                //string method = "GetExpandedStringValue";
                const string method2 = "GetStringValue";
                //const string field = "DisplayName";
                const string         field     = "Version";
                ManagementBaseObject inParams2 = m_registry.GetMethodParameters(method2);
                inParams2["hDefKey"]     = (uint)hklm;
                inParams2["sSubKeyName"] = pkgKeyPath;
                inParams2["sValueName"]  = field;
                ManagementBaseObject outParams2 = m_registry.InvokeMethod(method2, inParams2, null);

                string pkgName = (null == outParams2)
                                     ? string.Empty
                                     : (string)outParams2.Properties["sValue"].Value;

                // Other StringValue fields: DisplayVersion, InstallDate
                // Other ExpandedStringValue fields: InstallSource, UninstallString, QuietUninstallString
            }

            Console.WriteLine("Done.");
        }
Пример #36
0
 internal async Task RegScan(RegistryHive RegHive, RegistryView RegView, List <AddSoftware> lScanList)
 {
     await Task.Run(() => _RegScan(RegHive, RegView, lScanList));
 }
Пример #37
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="p_folder_type"></param>
 /// <param name="p_registry_hive"></param>
 public CRegistry(RegistryFolderType p_folder_type = RegistryFolderType.shared, RegistryHive p_registry_hive = RegistryHive.LocalMachine)
     : this("ODINSOFT", "SDK", "V5.2.2017.01", p_folder_type, p_registry_hive)
 {
 }
Пример #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RegistryMonitor"/> class.
 /// </summary>
 /// <param name="registryHive">The registry hive.</param>
 /// <param name="subkey">The subkey.</param>
 public RegistryMonitor(RegistryHive registryHive, string subkey)
 {
     this.InitRegistryKey(registryHive, subkey);
 }
Пример #39
0
        public static RegistryKey GetRegistryKey(string computerName, string keyPath)
        {
            int          firstPeriodPos = keyPath.IndexOf("\\");
            string       hKeyName       = keyPath.Substring(0, firstPeriodPos);
            RegistryHive hKey           = RegistryHive.LocalMachine;

            switch (hKeyName.ToUpperInvariant())
            {
            case "HKLM:":
            case "HKLM":
            case "HKEY_LOCAL_MACHINE":
                hKey = RegistryHive.LocalMachine;
                break;

            case "HKCR:":
            case "HKCR":
            case "HKEY_CLASSES_ROOT":
                hKey = RegistryHive.ClassesRoot;
                break;

            case "HKCC:":
            case "HKCC":
            case "HKEY_CURRENT_CONFIG":
                hKey = RegistryHive.CurrentConfig;
                break;

            case "HKCU:":
            case "HKCU":
            case "HKEY_CURRENT_USER":
                hKey = RegistryHive.CurrentUser;
                break;

            case "HKDD:":
            case "HKDD":
            case "HKEY_DYN_DATA":
                hKey = RegistryHive.DynData;
                break;

            case "HKPD:":
            case "HKPD":
            case "HKEY_PERFROMANCE_DATA":
                hKey = RegistryHive.PerformanceData;
                break;

            case "HKU:":
            case "HKU":
            case "HKEY_USERS":
                hKey = RegistryHive.Users;
                break;
            }
            RegistryKey remoteRegistry = RegistryKey.OpenRemoteBaseKey(hKey, LocalizeName(computerName));
            string      pathName       = keyPath.Substring(firstPeriodPos + 1);

            if (string.IsNullOrEmpty(pathName))
            {
                return(remoteRegistry);
            }
            else
            {
                return(remoteRegistry.OpenSubKey(pathName));
            }
        }
Пример #40
0
 public static string GetValueString(string path, string name = null, RegistryHive root = RegistryHive.CurrentUser, RegistryView view = RegistryView.Default)
 {
     return GetValue(path, name, root, view) as string;
 }
Пример #41
0
 public static int GetValueDWord(string path, string name = null, RegistryHive root = RegistryHive.CurrentUser, RegistryView view = RegistryView.Default)
 {
     return (int)GetValue(path, name, root, view);
 }
Пример #42
0
 private static RegistryKey GetKeyFromHive(RegistryHive hive, string path) =>
 RegistryKey.OpenBaseKey(hive, RegistryView.Registry64).OpenSubKey(path);
Пример #43
0
 private static RegistryKey OpenRemoteBaseKeyCore(RegistryHive hKey, string machineName, RegistryView view)
 {
     throw new PlatformNotSupportedException(SR.Security_RegistryPermission); // remote stores not supported on Unix
 }
Пример #44
0
 private static RegistryKey OpenBaseKeyCore(RegistryHive hKey, RegistryView view)
 {
     throw new PlatformNotSupportedException(SR.PlatformNotSupported_Registry);
 }
Пример #45
0
 public SECURITYHive(string filename) : base(filename)
 {
     _hive = this;
 }
Пример #46
0
        public static bool IsNewFormat(string file, bool noLog)
        {
            RegistryKey  fileKey = null;
            RegistryHive reg;

            var dirname  = Path.GetDirectoryName(file);
            var hiveBase = Path.GetFileName(file);

            List <RawCopy.RawCopyReturn> rawFiles = null;

            try
            {
                try
                {
                    reg = new RegistryHive(file)
                    {
                        RecoverDeleted = true
                    };
                }
                catch (IOException)
                {
                    //file is in use

                    if (RawCopy.Helper.IsAdministrator() == false)
                    {
                        throw new UnauthorizedAccessException("Administrator privileges not found!");
                    }

                    var files = new List <string>();
                    files.Add(file);

                    var logFiles = Directory.GetFiles(dirname, $"{hiveBase}.LOG?");

                    foreach (var logFile in logFiles)
                    {
                        files.Add(logFile);
                    }

                    rawFiles = RawCopy.Helper.GetFiles(files);

                    reg = new RegistryHive(rawFiles.First().FileBytes, rawFiles.First().InputFilename);
                }

                LogManager.DisableLogging();

                if (reg.Header.PrimarySequenceNumber != reg.Header.SecondarySequenceNumber)
                {
                    if (string.IsNullOrEmpty(dirname))
                    {
                        dirname = ".";
                    }

                    var logFiles = Directory.GetFiles(dirname, $"{hiveBase}.LOG?");

                    if (logFiles.Length == 0)
                    {
                        var log = LogManager.GetCurrentClassLogger();

                        if (noLog == false)
                        {
                            log.Warn("Registry hive is dirty and no transaction logs were found in the same directory! LOGs should have same base name as the hive. Aborting!!");
                            throw new Exception("Sequence numbers do not match and transaction logs were not found in the same directory as the hive. Aborting");
                        }

                        log.Warn("Registry hive is dirty and no transaction logs were found in the same directory. Data may be missing! Continuing anyways...");
                    }
                    else
                    {
                        if (rawFiles != null)
                        {
                            var lt = new List <TransactionLogFileInfo>();
                            foreach (var rawCopyReturn in rawFiles.Skip(1).ToList())
                            {
                                var tt = new TransactionLogFileInfo(rawCopyReturn.InputFilename, rawCopyReturn.FileBytes);
                                lt.Add(tt);
                            }

                            reg.ProcessTransactionLogs(lt, true);
                        }
                        else
                        {
                            reg.ProcessTransactionLogs(logFiles.ToList(), true);
                        }
                    }
                }


                reg.ParseHive();

                fileKey = reg.GetKey(@"Root\InventoryApplicationFile");

                LogManager.EnableLogging();
            }
            catch (Exception)
            {
                LogManager.EnableLogging();
            }

            return(fileKey != null);
        }
Пример #47
0
 /// <summary>Retrieves a new RegistryKey that represents the requested key on a foreign machine.</summary>
 /// <param name="hKey">hKey HKEY_* to open.</param>
 /// <param name="machineName">Name the machine to connect to.</param>
 /// <returns>The RegistryKey requested.</returns>
 public static RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName)
 {
     return(OpenRemoteBaseKey(hKey, machineName, RegistryView.Default));
 }
Пример #48
0
 public DynamicRegistryKey(RegistryHive hive, RegistryView view, RegistrySecurity rs, bool writable = false)
 {
     this.writable = writable;
     this.key      = RegistryKey.OpenBaseKey(hive, view);
 }
Пример #49
0
 public RegistryKey OpenRemoteBaseKey(RegistryHive hKey, string machineName)
 {
     throw new NotImplementedException();
 }
Пример #50
0
 public DynamicRegistryKey(RegistryHive hive, RegistrySecurity rs, bool writable = false)
     : this(hive, RegistryView.Default, rs, writable)
 {
 }
Пример #51
0
 static RegistryKey getBaseKey64(RegistryHive hive) => RegistryKey.OpenBaseKey(hive, RegistryView.Registry64);
 /// <summary>
 /// Initializes a new instance of the <see cref="RegistryMonitor"/> class.
 /// </summary>
 /// <param name="registryHive">The registry hive.</param>
 /// <param name="subKey">The sub key.</param>
 public RegistryMonitor(RegistryHive registryHive, string subKey)
 {
     InitRegistryKey(registryHive, subKey);
 }
Пример #53
0
        public AmcacheOld(string hive, bool recoverDeleted, bool noLogs)
        {
            _logger = LogManager.GetCurrentClassLogger();

            var reg = new RegistryHive(hive)
            {
                RecoverDeleted = recoverDeleted
            };

            if (reg.Header.PrimarySequenceNumber != reg.Header.SecondarySequenceNumber)
            {
                var hiveBase = Path.GetFileName(hive);

                var dirname = Path.GetDirectoryName(hive);

                if (string.IsNullOrEmpty(dirname))
                {
                    dirname = ".";
                }

                var logFiles = Directory.GetFiles(dirname, $"{hiveBase}.LOG?");

                if (logFiles.Length == 0)
                {
                    var log = LogManager.GetCurrentClassLogger();

                    if (noLogs == false)
                    {
                        log.Warn("Registry hive is dirty and no transaction logs were found in the same directory! LOGs should have same base name as the hive. Aborting!!");
                        throw new Exception("Sequence numbers do not match and transaction logs were not found in the same directory as the hive. Aborting");
                    }
                    else
                    {
                        log.Warn("Registry hive is dirty and no transaction logs were found in the same directory. Data may be missing! Continuing anyways...");
                    }
                }
                else
                {
                    reg.ProcessTransactionLogs(logFiles.ToList(), true);
                }
            }


            reg.ParseHive();

            var fileKey     = reg.GetKey(@"Root\File");
            var programsKey = reg.GetKey(@"Root\Programs");


            UnassociatedFileEntries = new List <FileEntryOld>();
            ProgramsEntries         = new List <ProgramsEntryOld>();

            if (fileKey == null || programsKey == null)
            {
                _logger.Error("Hive does not contain a File and/or Programs key. Processing cannot continue");
                return;
            }

            //First, we get data for all the Program entries under Programs key

            foreach (var registryKey in programsKey.SubKeys)
            {
                var            ProgramName0    = "";
                var            ProgramVersion1 = "";
                var            Guid10          = "";
                var            UninstallGuid11 = "";
                var            Guid12          = "";
                var            Dword13         = 0;
                var            Dword14         = 0;
                var            Dword15         = 0;
                var            UnknownBytes    = new byte[0];
                long           Qword17         = 0;
                var            Dword18         = 0;
                var            VenderName2     = "";
                var            LocaleID3       = "";
                var            Dword5          = 0;
                var            InstallSource6  = "";
                var            UninstallKey7   = "";
                DateTimeOffset?EpochA          = null;
                DateTimeOffset?EpochB          = null;
                var            PathListd       = "";
                var            Guidf           = "";
                var            RawFiles        = "";

                try
                {
                    foreach (var value in registryKey.Values)
                    {
                        switch (value.ValueName)
                        {
                        case "0":
                            ProgramName0 = value.ValueData;
                            break;

                        case "1":
                            ProgramVersion1 = value.ValueData;
                            break;

                        case "2":
                            VenderName2 = value.ValueData;
                            break;

                        case "3":
                            LocaleID3 = value.ValueData;
                            break;

                        case "5":
                            Dword5 = int.Parse(value.ValueData);
                            break;

                        case "6":
                            InstallSource6 = value.ValueData;
                            break;

                        case "7":
                            UninstallKey7 = value.ValueData;
                            break;

                        case "a":
                            try
                            {
                                var seca = long.Parse(value.ValueData);
                                if (seca > 0)
                                {
                                    EpochA = DateTimeOffset.FromUnixTimeSeconds(seca).ToUniversalTime();
                                }
                            }
                            catch (Exception)
                            {
                                //sometimes the number is way too big
                            }

                            break;

                        case "b":
                            var seconds = long.Parse(value.ValueData);
                            if (seconds > 0)
                            {
                                EpochB =
                                    DateTimeOffset.FromUnixTimeSeconds(seconds).ToUniversalTime();
                            }

                            break;

                        case "d":
                            PathListd = value.ValueData;
                            break;

                        case "f":
                            Guidf = value.ValueData;
                            break;

                        case "10":
                            Guid10 = value.ValueData;
                            break;

                        case "11":
                            UninstallGuid11 = value.ValueData;
                            break;

                        case "12":
                            Guid12 = value.ValueData;
                            break;

                        case "13":
                            Dword13 = int.Parse(value.ValueData);
                            break;

                        case "14":
                            Dword13 = int.Parse(value.ValueData);
                            break;

                        case "15":
                            Dword13 = int.Parse(value.ValueData);
                            break;

                        case "16":
                            UnknownBytes = value.ValueDataRaw;
                            break;

                        case "17":
                            Qword17 = long.Parse(value.ValueData);
                            break;

                        case "18":
                            Dword18 = int.Parse(value.ValueData);
                            break;

                        case "Files":
                            RawFiles = value.ValueData;
                            break;

                        default:
                            _logger.Warn(
                                $"Unknown value name in Program at path {registryKey.KeyPath}: {value.ValueName}");
                            break;
                        }
                    }

                    var pe = new ProgramsEntryOld(ProgramName0, ProgramVersion1, VenderName2, LocaleID3, InstallSource6,
                                                  UninstallKey7, Guid10, Guid12, UninstallGuid11, Dword5, Dword13, Dword14, Dword15, UnknownBytes,
                                                  Qword17, Dword18, EpochA, EpochB, PathListd, Guidf, RawFiles, registryKey.KeyName,
                                                  registryKey.LastWriteTime.Value);

                    ProgramsEntries.Add(pe);
                }
                catch (Exception ex)
                {
                    _logger.Error($"Error parsing ProgramsEntry at {registryKey.KeyPath}. Error: {ex.Message}");
                    _logger.Error(
                        $"Please send the following text to [email protected]. \r\n\r\nKey data: {registryKey}");
                }
            }

            //For each Programs entry, add the related Files entries from Files\Volume subkey, put the rest in unassociated


            foreach (var registryKey in fileKey.SubKeys)
            {
                //These are the guids for volumes
                foreach (var subKey in registryKey.SubKeys)
                {
                    var prodName      = "";
                    int?langId        = null;
                    var fileVerString = "";
                    var fileVerNum    = "";
                    var fileDesc      = "";
                    var compName      = "";
                    var fullPath      = "";
                    var switchBack    = "";
                    var peHash        = "";
                    var progID        = "";
                    var sha           = "";

                    long  binProdVersion   = 0;
                    ulong binFileVersion   = 0;
                    var   linkerVersion    = 0;
                    var   binType          = 0;
                    var   isLocal          = 0;
                    var   gProgramID       = 0;
                    int?  fileSize         = null;
                    int?  sizeOfImage      = null;
                    uint? peHeaderChecksum = null;

                    DateTimeOffset?created  = null;
                    DateTimeOffset?lm       = null;
                    DateTimeOffset?lmStore  = null;
                    DateTimeOffset?linkDate = null;

                    var hasLinkedProgram = false;

                    try
                    {
                        //these are the files executed from the volume
                        foreach (var keyValue in subKey.Values)
                        {
                            var keyVal = int.Parse(keyValue.ValueName, NumberStyles.HexNumber);

                            switch (keyVal)
                            {
                            case ProductName:
                                prodName = keyValue.ValueData;
                                break;

                            case CompanyName:
                                compName = keyValue.ValueData;
                                break;

                            case FileVersionNumber:
                                fileVerNum = keyValue.ValueData;
                                break;

                            case LanguageCode:
                                langId = int.Parse(keyValue.ValueData);
                                break;

                            case SwitchBackContext:
                                switchBack = keyValue.ValueData;
                                break;

                            case FileVersionString:
                                fileVerString = keyValue.ValueData;
                                break;

                            case FileSize:
                                fileSize = int.Parse(keyValue.ValueData);
                                break;

                            case SizeOfImage:
                                sizeOfImage = int.Parse(keyValue.ValueData);
                                break;

                            case PEHeaderHash:
                                peHash = keyValue.ValueData;
                                break;

                            case PEHeaderChecksum:
                                peHeaderChecksum = uint.Parse(keyValue.ValueData);
                                break;

                            case BinProductVersion:
                                binProdVersion = long.Parse(keyValue.ValueData);
                                break;

                            case BinFileVersion:
                                binFileVersion = ulong.Parse(keyValue.ValueData);
                                break;

                            case FileDescription:
                                fileDesc = keyValue.ValueData;
                                break;

                            case LinkerVersion:
                                linkerVersion = int.Parse(keyValue.ValueData);
                                break;

                            case LinkDate:
                                linkDate =
                                    DateTimeOffset.FromUnixTimeSeconds(long.Parse(keyValue.ValueData))
                                    .ToUniversalTime();
                                break;

                            case BinaryType:
                                binType = int.Parse(keyValue.ValueData);
                                break;

                            case LastModified:
                                lm = DateTimeOffset.FromFileTime(long.Parse(keyValue.ValueData)).ToUniversalTime();
                                break;

                            case Created:
                                created =
                                    DateTimeOffset.FromFileTime(long.Parse(keyValue.ValueData)).ToUniversalTime();
                                break;

                            case FullPath:
                                fullPath = keyValue.ValueData;
                                break;

                            case IsLocal:
                                isLocal = int.Parse(keyValue.ValueData);
                                break;

                            case GuessProgramID:
                                gProgramID = int.Parse(keyValue.ValueData);
                                break;

                            case LastModifiedStore:
                                lmStore = DateTimeOffset.FromFileTime(long.Parse(keyValue.ValueData))
                                          .ToUniversalTime();
                                break;

                            case ProgramID:
                                progID = keyValue.ValueData;

                                var program = ProgramsEntries.SingleOrDefault(t => t.ProgramID == progID);
                                if (program != null)
                                {
                                    hasLinkedProgram = true;
                                }

                                break;

                            case SHA1:
                                sha = keyValue.ValueData;
                                break;

                            default:
                                _logger.Warn(
                                    $"Unknown value name when processing FileEntry at path '{subKey.KeyPath}': 0x{keyVal:X}");
                                break;
                            }
                        }

                        if (fullPath.Length == 0)
                        {
                            continue;
                        }

                        TotalFileEntries += 1;

                        var fe = new FileEntryOld(prodName, progID, sha, fullPath, lmStore, registryKey.KeyName,
                                                  registryKey.LastWriteTime.Value, subKey.KeyName, subKey.LastWriteTime.Value,
                                                  isLocal, compName, langId, fileVerString, peHash, fileVerNum, fileDesc, binProdVersion,
                                                  binFileVersion,
                                                  linkerVersion, binType, switchBack, fileSize, linkDate, sizeOfImage,
                                                  lm, created, peHeaderChecksum, gProgramID, subKey.KeyName);

                        if (hasLinkedProgram)
                        {
                            var program = ProgramsEntries.SingleOrDefault(t => t.ProgramID == fe.ProgramID);
                            fe.ProgramName = program.ProgramName_0;
                            program.FileEntries.Add(fe);
                        }
                        else
                        {
                            fe.ProgramName = "Unassociated";
                            UnassociatedFileEntries.Add(fe);
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.Error($"Error parsing FileEntry at {subKey.KeyPath}. Error: {ex.Message}");
                        _logger.Error(
                            $"Please send the following text to [email protected]. \r\n\r\nKey data: {subKey}");
                    }
                }
            }
        }
Пример #54
0
 public static RegistryKey OpenBaseKey(RegistryHive hKey)
 {
     return(OpenBaseKey(hKey, RegistryView.Default));
 }
Пример #55
0
 internal RegistryKey(RegistryHive hiveId)
 {
     throw new PlatformNotSupportedException();
 }
Пример #56
0
 public static void CreateRegistry(string path, int value, RegistryHive root = RegistryHive.CurrentUser)
 {
     CreateRegistry(path, null, value, root);
 }
Пример #57
0
 public static RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view)
 {
     throw new PlatformNotSupportedException();
 }
Пример #58
0
        public void ExportToRegFormatSingleKey()
        {
            var samOnDemand = new RegistryHiveOnDemand(@"..\..\..\Hives\SAM");
            var key         = samOnDemand.GetKey(@"SAM\Domains\Account");

            var exported = Helpers.ExportToReg(@"exportSamTest.reg", key, HiveTypeEnum.Sam, false);

            Check.That(exported).IsTrue();

            var ntUser1OnDemand = new RegistryHiveOnDemand(@"..\..\..\Hives\NTUSER1.DAT");

            key = ntUser1OnDemand.GetKey(@"CsiTool-CreateHive-{00000000-0000-0000-0000-000000000000}\Console");

            exported = Helpers.ExportToReg(@"exportntuser1Test.reg", key, HiveTypeEnum.NtUser, false);

            Check.That(exported).IsTrue();

            var security = new RegistryHiveOnDemand(@"..\..\..\Hives\SECURITY");

            key =
                security.GetKey(
                    @"CsiTool-CreateHive-{00000000-0000-0000-0000-000000000000}\Policy\Accounts\S-1-5-9");

            exported = Helpers.ExportToReg(@"exportsecTest.reg", key, HiveTypeEnum.Security, false);

            Check.That(exported).IsTrue();

            var systemOnDemand = new RegistryHiveOnDemand(@"..\..\..\Hives\SYSTEM");

            key =
                systemOnDemand.GetKey(
                    @"CsiTool-CreateHive-{00000000-0000-0000-0000-000000000000}\ControlSet001\Enum\ACPI\PNP0C02\1");

            exported = Helpers.ExportToReg(@"exportsysTest.reg", key, HiveTypeEnum.System, false);

            Check.That(exported).IsTrue();

            var usrClassFtp = new RegistryHiveOnDemand(@"..\..\..\Hives\UsrClass FTP.dat");

            key = usrClassFtp.GetKey(@"S-1-5-21-2417227394-2575385136-2411922467-1105_Classes\.3g2");

            exported = Helpers.ExportToReg(@"exportusrTest.reg", key, HiveTypeEnum.UsrClass, false);

            Check.That(exported).IsTrue();

            var samDupeNameOnDemand = new RegistryHiveOnDemand(@"..\..\..\Hives\SAM_DUPENAME");

            key = samDupeNameOnDemand.GetKey(@"SAM\SAM\Domains\Account\Aliases\000003E9");

            exported = Helpers.ExportToReg(@"exportotherTest.reg", key, HiveTypeEnum.Other, false);

            Check.That(exported).IsTrue();

            var usrclassDeleted = new RegistryHive(@"..\..\..\Hives\UsrClassDeletedBags.dat");

            usrclassDeleted.RecoverDeleted             = true;
            usrclassDeleted.FlushRecordListsAfterParse = false;
            usrclassDeleted.ParseHive();
            key =
                usrclassDeleted.GetKey(
                    @"S-1-5-21-146151751-63468248-1215037915-1000_Classes\Local Settings\Software\Microsoft\Windows\Shell\BagMRU\1");

            exported = Helpers.ExportToReg(@"exportDeletedTest.reg", key, HiveTypeEnum.UsrClass, false);

            Check.That(exported).IsTrue();
        }
Пример #59
0
 public void ShouldThrowExceptionWithBadHbinHeader()
 {
     Check.ThatCode(() => { var r = new RegistryHive(@"..\..\Hives\SAMBadHBinHeader"); r.ParseHive(); }).Throws <Exception>();
 }
Пример #60
0
        public static bool CheckStringValue(string path, string name = null, string value = null, RegistryHive root = RegistryHive.CurrentUser, RegistryView view = RegistryView.Default)
        {
            string registryValue = GetValueString(path, name, root, view);

            return registryValue != null && (value == null || registryValue.Equals(value, StringComparison.OrdinalIgnoreCase));
        }