public void ctor_CreateFromSettingUrnWithoutNamespace()
        {
            var registryPath = new RegistryPath(new SettingPath(new[] { "Foo" }));

            registryPath.Namespace.Verify().IsNullOrEmpty();
            registryPath.WeakName.Verify().IsEqual(@"Foo");
        }
        public void Parse_Name()
        {
            var registryPath = RegistryPath.Parse("Foo");

            registryPath.Namespace.Verify().IsNullOrEmpty();
            registryPath.WeakName.Verify().IsEqual(@"Foo");
        }
        public void ctor_CreateFromSettingUrnWithNamespace()
        {
            var registryPath = new RegistryPath(new SettingPath(new[] { "qux", "Foo", "Bar", "Baz" }));

            registryPath.Namespace.Verify().IsEqual(@"qux\Foo\Bar");
            registryPath.WeakName.Verify().IsEqual(@"Baz");
        }
        public void Parse_NameWithNamespace()
        {
            var registryPath = RegistryPath.Parse(@"qux\Foo\Bar\Baz");

            registryPath.Namespace.Verify().IsEqual(@"qux\Foo\Bar");
            registryPath.WeakName.Verify().IsEqual(@"Baz");
        }
        public void StringValue_should_throw_an_InvalidCastExpression_if_the_value_is_not_a_string()
        {
            var    path   = RegistryPath.CreateValuePath(RegistryHive.Users, "Path", "Value", 123);
            Action action = () => { string unused = path.StringValue; };

            action.Should().ThrowExactly <InvalidCastException>();
        }
        public void IntValue_should_throw_an_InvalidCastExpression_if_the_value_is_not_an_integer()
        {
            var    path   = RegistryPath.CreateValuePath(RegistryHive.Users, "Path", "Value", "s");
            Action action = () => { int unused = path.IntValue; };

            action.Should().ThrowExactly <InvalidCastException>();
        }
 public void Parse_should_recognize_an_integer_value()
 {
     RegistryPath.Parse(@"HKEY_DYN_DATA\SubKey\IntValue=123")
     .Should()
     .BeEquivalentTo(
         RegistryPath.CreateValuePath(RegistryHive.DynData, "SubKey", "IntValue", 123),
         GetEquivalenceOptions);
 }
 public void Parse_should_recognize_just_a_hive()
 {
     RegistryPath.Parse("HKCU")
     .Should()
     .BeEquivalentTo(RegistryPath.CreatePath(RegistryHive.CurrentUser), GetEquivalenceOptions);
     RegistryPath.Parse("HKEY_CURRENT_USER")
     .Should()
     .BeEquivalentTo(RegistryPath.CreatePath(RegistryHive.CurrentUser), GetEquivalenceOptions);
 }
 private static void Write(RegistryPath path)
 {
     lock (writeLock)
     {
         pathToWrite = path;
         writeReady.Set();
         writeCompleted.WaitOne();
     }
 }
        //// ===========================================================================================================
        //// Methods
        //// ===========================================================================================================

        public IWin32RegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view)
        {
            if (view != RegistryView.Registry64)
            {
                throw new ArgumentException("View type not supported", nameof(view));
            }

            return(CreateSubKey(RegistryPath.HiveToWin32Name(hKey), false));
        }
 public void HiveToWin32Name_should_correctly_map_hives_to_long_names()
 {
     RegistryPath.HiveToWin32Name(RegistryHive.ClassesRoot).Should().Be("HKEY_CLASSES_ROOT");
     RegistryPath.HiveToWin32Name(RegistryHive.CurrentUser).Should().Be("HKEY_CURRENT_USER");
     RegistryPath.HiveToWin32Name(RegistryHive.LocalMachine).Should().Be("HKEY_LOCAL_MACHINE");
     RegistryPath.HiveToWin32Name(RegistryHive.Users).Should().Be("HKEY_USERS");
     RegistryPath.HiveToWin32Name(RegistryHive.CurrentConfig).Should().Be("HKEY_CURRENT_CONFIG");
     RegistryPath.HiveToWin32Name(RegistryHive.PerformanceData).Should().Be("HKEY_PERFORMANCE_DATA");
     RegistryPath.HiveToWin32Name(RegistryHive.DynData).Should().Be("HKEY_DYN_DATA");
 }
Example #12
0
        protected override void BeginProcessing()
        {
            Type      = Item.CheckCase(Type);
            Inherited = Item.CheckCase(Inherited);

            if (Chroot != null)
            {
                string keyName = RegistryPath.Substring(RegistryPath.IndexOf("\\") + 1);
                RegistryPath = System.IO.Path.Combine(Chroot, keyName);
            }

            _generator = new TestGenerator(Test);
        }
        static void AddEntry(SQLiteConnection connection, RegistryPath path)
        {
            SQLiteCommand command = new SQLiteCommand("INSERT INTO Snapshot (RegistryView, Path, IsKey, RegistryValueKind, ValueName, Value, HashValue) VALUES (@RegistryView, @Path, @IsKey, @RegistryValueKind, @ValueName, @Value, @HashValue)", connection);

            command.Parameters.Add("@RegistryView", DbType.Int32).Value      = path.View;
            command.Parameters.Add("@Path", DbType.String).Value             = path.Path;
            command.Parameters.Add("@IsKey", DbType.Boolean).Value           = path.IsKey;
            command.Parameters.Add("@RegistryValueKind", DbType.Int32).Value = path.ValueKind;
            command.Parameters.Add("@ValueName", DbType.String).Value        = path.ValueName;
            command.Parameters.Add("@Value", DbType.Object).Value            = path.Value;
            command.Parameters.Add("@HashValue", DbType.Int32).Value         = path.HashValue;
            command.ExecuteNonQuery();
        }
        public void Parse_should_recognize_a_string_value()
        {
            RegistryPath.Parse(@"HKCR\SubKey\StringValue=""s""")
            .Should()
            .BeEquivalentTo(
                RegistryPath.CreateValuePath(RegistryHive.ClassesRoot, "SubKey", "StringValue", "s"),
                GetEquivalenceOptions);

            RegistryPath.Parse(@"HKEY_PERFORMANCE_DATA\SubKey\StringValue='s'")
            .Should()
            .BeEquivalentTo(
                RegistryPath.CreateValuePath(RegistryHive.PerformanceData, "SubKey", "StringValue", "s"),
                GetEquivalenceOptions);
        }
Example #15
0
        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;
                }
            }
        }
Example #16
0
        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));
                }
            }
        }
        //// ===========================================================================================================
        //// Constructors
        //// ===========================================================================================================

        /// <summary>
        /// Initializes a new instance of the <see cref="FakeRegistry"/> class with the specified keys and value.
        /// </summary>
        /// <param name="keysAndValues">
        /// The string needs to be in the form "BASE\SubKey[\Value=123]", where BASE is one of <c>HKEY_CLASSES_ROOT</c>
        /// (or <c>HKCR</c>), <c>HKEY_CURRENT_USER</c> (or <c>HKCU</c>), <c>HKEY_LOCAL_MACHINE</c> (or <c>HKLM</c>), or
        /// HKEY_USERS (or <c>HKU</c>). The value can either be an integer or a string with single or double quotes.
        /// </param>
        public FakeRegistry(params string[] keysAndValues)
        {
            foreach (string keyAndValue in keysAndValues)
            {
                var parsedPath = RegistryPath.Parse(keyAndValue);
                using (IWin32RegistryKey key = OpenBaseKey(parsedPath.Hive, RegistryView.Registry64)
                                               .CreateSubKey(parsedPath.Path, writable: true))
                {
                    if (!string.IsNullOrEmpty(parsedPath.ValueName))
                    {
                        RegistryValueKind kind = parsedPath.Value is string
                                                 ?RegistryValueKind.String
                                                 : RegistryValueKind.DWord;
                        key.SetValue(parsedPath.ValueName, parsedPath.Value, kind);
                    }
                }
            }
        }
        /// <summary>
        /// Cria uma instância da classe <see cref="DirectoryPrompAquiItem"/>
        /// </summary>
        /// <param name="path">Caminho do registro onde a chave se encontra</param>
        /// <param name="paramPattern">Padrão para recuperar o parâmetro. Ex: %1, %V</param>
        /// <param name="isAdm">Indica se o comando será executado com privilégios de administrador</param>
        public DirectoryPrompAquiItem(string path, string paramPattern, bool isAdm)
            : base(Registry.ClassesRoot, path + "\\Shell\\04PromptAqui")
        {
            MUIVerb = "Prompt aqui";
            Icon    = "%SystemRoot%\\system32\\cmd.exe";

            string exePath = Constantes.WinShellShortcutsFullPath;

            if (isAdm)
            {
                MUIVerb     += " (Adm)";
                exePath      = Constantes.WinShellShortcutsFullPath_Adm;
                RegistryPath = RegistryPath.Replace("04PromptAqui", "05PromptAquiAdm");
            }

            Command      = $"\"{exePath}\" /p={typeof(DirectoryPrompAquiItem).FullName} \"{paramPattern}\" ";
            HasLUAShield = isAdm;
        }
        private static void WalkKey(RegistryView view, RegistryKey key)
        {
            RegistryPath path = new RegistryPath(view, key.Name);

            Write(path);
            string[] valueNames = null;
            try
            {
                valueNames = key.GetValueNames();
            }
            catch { }
            if (valueNames != null)
            {
                foreach (string valueName in valueNames)
                {
                    RegistryValueKind valueKind = RegistryValueKind.Unknown;
                    try
                    {
                        valueKind = key.GetValueKind(valueName);
                    }
                    catch { }
                    object       value        = key.GetValue(valueName);
                    RegistryPath pathForValue = new RegistryPath(view, key.Name, valueKind, valueName, value);
                    Write(pathForValue);
                }
            }
            string[] subKeyNames = null;
            try
            {
                subKeyNames = key.GetSubKeyNames();
            }
            catch { }
            if (subKeyNames != null)
            {
                foreach (string subKeyName in subKeyNames)
                {
                    try
                    {
                        WalkKey(view, key.OpenSubKey(subKeyName));
                    }
                    catch { }
                }
            }
        }
Example #20
0
        private static void ResetData()
        {
            var baseKey = Microsoft.Win32.Registry.CurrentUser;

            using (var subKey = baseKey.OpenSubKey(@"Software\SmartConfig", writable: true))
            {
                if (subKey != null && subKey.GetSubKeyNames().Contains("Test", StringComparer.OrdinalIgnoreCase))
                {
                    subKey.DeleteSubKeyTree("Test");
                }
            }

            foreach (var testSetting in TestSettingFactory.CreateTestSettings1())
            {
                var settingPath  = SettingPath.Parse(testSetting.Name);
                var registryPath = new RegistryPath(settingPath);
                var subKeyName   = Path.Combine(@"Software\SmartConfig\Test", registryPath.Namespace);
                using (var subKey = baseKey.CreateSubKey(subKeyName, writable: true))
                {
                    subKey.SetValue(registryPath.StrongName, testSetting.Value);
                }
            }
        }
Example #21
0
        private PaloAltoUserIdUpdater()
        {
            var configKey = RegistryPath.Open(@"HKEY_LOCAL_MACHINE\SOFTWARE\AHA-NET\PaloAltoUserId");

            wifi_reauth_plus_padding         = Int32.Parse((string)configKey.GetValue("wifi_reauth_plus_padding"));
            dhcp_lease_duration_plus_padding = Int32.Parse((string)configKey.GetValue("dhcp_lease_duration_plus_padding"));
            dhcp_lease_timespan_plus_padding = TimeSpan.FromMinutes(dhcp_lease_duration_plus_padding);
            summertime_start = DateTime.Parse((string)configKey.GetValue("summertime_start"));
            summertime_end   = DateTime.Parse((string)configKey.GetValue("summertime_end"));
            public_abuse_session_length_timespan       = TimeSpan.FromDays(Double.Parse((string)configKey.GetValue("public_abuse_session_length_timespan")));
            public_abuse_session_count_threshold       = Int32.Parse((string)configKey.GetValue("public_abuse_session_count_threshold"));
            public_abuse_retain_session_count_timespan = TimeSpan.FromDays(Double.Parse((string)configKey.GetValue("public_abuse_retain_session_count_timespan")));

            rateLimitedMacs = new RateLimitedMacs(@"HKEY_LOCAL_MACHINE\SOFTWARE\AHA-NET\PaloAltoUserId\RateLimitedMacs", true);
            publicCache     = new DhcpRecordsByMac(rateLimitedMacs, dhcp_lease_duration_plus_padding);
            dhcpCache       = new DhcpRecordsByMac(rateLimitedMacs, dhcp_lease_duration_plus_padding);
            iasCache        = new IasRecordsByMac(wifi_reauth_plus_padding);
            uidCache        = new UidRecordsByIp();
            registeredMacs  = new RegSzRawDictionary(@"HKEY_LOCAL_MACHINE\SOFTWARE\AHA-NET\PaloAltoUserId\RegisteredMacs", true);
            ahanetMacs      = new RegSzDictionary(@"HKEY_LOCAL_MACHINE\SOFTWARE\AHA-NET\PaloAltoUserId\AhanetMacs", true);
            publicMacs      = new PublicRecordsByMac(@"HKEY_LOCAL_MACHINE\SOFTWARE\AHA-NET\PaloAltoUserId\PublicMacs", dhcp_lease_timespan_plus_padding, public_abuse_retain_session_count_timespan, true);
            debugTable      = new RegSzRawDictionary(@"HKEY_LOCAL_MACHINE\SOFTWARE\AHA-NET\PaloAltoUserId\Debug", true);
            mapper          = MapUserIp.Instance;
        }
 public void BaseKeyToHive_should_correctly_map_keys_to_Win32_hives()
 {
     RegistryPath.BaseKeyToHive(RegistryBaseKey.ClassesRoot)
     .Should()
     .Be(RegistryHive.ClassesRoot);
     RegistryPath.BaseKeyToHive(RegistryBaseKey.CurrentUser)
     .Should()
     .Be(RegistryHive.CurrentUser);
     RegistryPath.BaseKeyToHive(RegistryBaseKey.LocalMachine)
     .Should()
     .Be(RegistryHive.LocalMachine);
     RegistryPath.BaseKeyToHive(RegistryBaseKey.Users)
     .Should()
     .Be(RegistryHive.Users);
     RegistryPath.BaseKeyToHive(RegistryBaseKey.PerformanceData)
     .Should()
     .Be(RegistryHive.PerformanceData);
     RegistryPath.BaseKeyToHive(RegistryBaseKey.CurrentConfig)
     .Should()
     .Be(RegistryHive.CurrentConfig);
     RegistryPath.BaseKeyToHive(RegistryBaseKey.DynData)
     .Should()
     .Be(RegistryHive.DynData);
 }
        private void ThreadInitialize()
        {
            var configKey = RegistryPath.Open(@"HKEY_LOCAL_MACHINE\SOFTWARE\AHA-NET\PaloAltoUserId");

            var log_path = (string)configKey.GetValue("log_path");
            var log      = new LogTagged(new LogFileWeekly(log_path, true), 1);

            log.TagWithDateTime = true;
            Log.Replace(log);

            Log.Inform(">>>>> STARTING <<<<<");

            var firewall_address  = (string)configKey.GetValue("firewall_address");
            var firewall_username = (string)configKey.GetValue("firewall_username");
            var firewall_api_key  = (string)configKey.GetValue("firewall_api_key");

            MapUserIp.New(new PanXmlApi(firewall_address, firewall_username, firewall_api_key));

            var dhcpFileFilter        = new FileFilterRecent(new FileFilterChanged());
            var dhcpWatcher           = new FolderWatchers(dhcpFileFilter);
            var dhcp_logfile_wildcard = (string)configKey.GetValue("dhcp_logfile_wildcard");

            foreach (var dhcp_log_paths in ((string)configKey.GetValue("dhcp_log_paths")).Split(';'))
            {
                dhcpWatcher.AddWatcher(dhcp_log_paths, dhcp_logfile_wildcard);
            }
            var dhcpHandler     = AssembleDhcpRecordHandler(new DsvLineConfig());
            var dhcpFileManager = new FileFollowerManager(dhcpHandler, token);
            var dhcpLogs        = new FolderWatcherManager(dhcpWatcher, dhcpFileManager, token);

            var iasFileFilter        = new FileFilterRecent(new FileFilterChanged());
            var iasWatcher           = new FolderWatchers(iasFileFilter);
            var ias_logfile_wildcard = (string)configKey.GetValue("ias_logfile_wildcard");

            foreach (var ias_log_paths in ((string)configKey.GetValue("ias_log_paths")).Split(';'))
            {
                iasWatcher.AddWatcher(ias_log_paths, ias_logfile_wildcard);
            }
            var iasHandler     = AssembleIasRecordHandler(new DsvLineConfig());
            var iasFileManager = new FileFollowerManager(iasHandler, token);
            var iasLogs        = new FolderWatcherManager(iasWatcher, iasFileManager, token);

            var dhcpTask = dhcpLogs.ProcessAsync();
            var IasTask  = iasLogs.ProcessAsync();

            Func <bool> checkIfAllOldLogsRead = () => {
                return(!(dhcpFileManager.AreAllFollowing && iasFileManager.AreAllFollowing));
            };
            Func <bool> wait15msecs = () => {
                const int _15_msecs = 15;
                Task      taskDelay = null;
                try     { taskDelay = Task.Delay(_15_msecs, token); taskDelay.Wait(); return(true); }
                catch   { return(false); }
                finally { if (taskDelay != null)
                          {
                              taskDelay.Dispose();
                          }
                }
            };
            var blockUntilAllOldLogsRead = new RepeatedTask(checkIfAllOldLogsRead, wait15msecs);

            blockUntilAllOldLogsRead.Process();

            if (token.IsCancellationRequested)
            {
                return;
            }

            Log.Inform(">>>>> FOLLOWING <<<<<");
            var updater = PaloAltoUserIdUpdater.Instance;

            updater.LoginCached();

            if (token.IsCancellationRequested)
            {
                return;
            }

            Func <bool> maintainDatabases = () => {
                Log.Inform(">>>>> MAINTAIN DATABASES <<<<<");
                updater.RemoveStaleEntries();
                return(true);
            };
            Func <bool> wait1day = () => {
                TimeSpan _1_day    = TimeSpan.FromDays(1);
                Task     taskDelay = null;
                try     { taskDelay = Task.Delay(_1_day, token); taskDelay.Wait(); return(true); }
                catch   { return(false); }
                finally { if (taskDelay != null)
                          {
                              taskDelay.Dispose();
                          }
                }
            };
            var maintainDatabasesEveryDay = new RepeatedTask(maintainDatabases, wait1day);

            maintainDatabasesEveryDay.Process();
        }
 public void Parse_should_recognize_a_nested_path()
 {
     RegistryPath.Parse(@"HKU\Level1\Level2\Level3")
     .Should()
     .BeEquivalentTo(RegistryPath.CreatePath(RegistryHive.Users, @"Level1\Level2\Level3"), GetEquivalenceOptions);
 }
        public void Parse_should_throw_a_FormatException_when_the_value_is_not_a_string_or_integer()
        {
            Action action = () => RegistryPath.Parse(@"HKEY_CURRENT_CONFIG\SubKey\Value=$123");

            action.Should().ThrowExactly <FormatException>();
        }
 public void HasValue_should_be_true_if_there_is_a_value()
 {
     RegistryPath.CreateValuePath(RegistryHive.Users, "Path", "Value", 123).HasValue.Should().BeTrue();
 }
 public void Parse_should_recognize_a_single_sub_level_in_the_path()
 {
     RegistryPath.Parse(@"HKLM\SubKey")
     .Should()
     .BeEquivalentTo(RegistryPath.CreatePath(RegistryHive.LocalMachine, "SubKey"), GetEquivalenceOptions);
 }
 public void HasValue_should_be_false_if_there_is_no_value()
 {
     RegistryPath.CreatePath(RegistryHive.Users, "Path").HasValue.Should().BeFalse();
 }
 public void IntValue_should_return_an_integer_if_originally_specified()
 {
     RegistryPath.CreateValuePath(RegistryHive.Users, "Path", "Value", 123).IntValue.Should().Be(123);
 }
 public void StringValue_should_return_an_integer_if_originally_specified()
 {
     RegistryPath.CreateValuePath(RegistryHive.Users, "Path", "Value", "s").StringValue.Should().Be("s");
 }