private bool createAllowRule(CurrentConn activeConn, string[] services, bool createWithAdvancedOptions, bool createTempRule, string ruleName) { int Profiles = OptionsView.IsCurrentProfileChecked ? FirewallHelper.GetCurrentProfile() : FirewallHelper.GetGlobalProfile(); string finalRuleName = createTempRule ? Messages.RULE_TEMP_PREFIX + ruleName : ruleName; var newRule = new CustomRule(finalRuleName, createWithAdvancedOptions || OptionsView.IsPathChecked ? activeConn.Path : null, !createWithAdvancedOptions && OptionsView.IsAppChecked ? activeConn.CurrentAppPkgId : null, activeConn.CurrentLocalUserOwner, services, !createWithAdvancedOptions && OptionsView.IsProtocolChecked ? activeConn.RawProtocol : -1, !createWithAdvancedOptions && OptionsView.IsTargetIPChecked ? activeConn.TargetIP : null, !createWithAdvancedOptions && OptionsView.IsTargetPortChecked ? activeConn.TargetPort : null, !createWithAdvancedOptions && OptionsView.IsLocalPortChecked ? activeConn.SourcePort : null, Profiles, CustomRule.CustomRuleAction.Allow); bool success = FirewallHelper.AddRule(newRule.GetPreparedRule(createTempRule)); // does not use RuleManager if (success && createTempRule) { CreateTempRuleNotifyIcon(newRule); } return(success); }
public SetRuleResponse NewRule(SetRuleRequest dtoRule) { ToastHelper.PopToast("New rule"); Rule domainRule; if (dtoRule.WindowsRequst != null) { domainRule = dtoRule.WindowsRequst; } else if (dtoRule.GenericRequest != null) { domainRule = (Rule)(new WindowsRuleAdapter(dtoRule.GenericRequest).NativeType); } else { return(new SetRuleResponse() { Success = false }); } FirewallHelper.NewRule(domainRule); return(new SetRuleResponse() { Success = true }); }
private bool createBlockRule(CurrentConn activeConn, string[] services, bool isTemp) { bool success = false; if (!isTemp) { if (Settings.Default.UseBlockRules) { int Profiles = _optionsView.IsCurrentProfileChecked ? FirewallHelper.GetCurrentProfile() : FirewallHelper.GetGlobalProfile(); FirewallHelper.CustomRule newRule = new FirewallHelper.CustomRule(activeConn.RuleName, activeConn.CurrentPath, _optionsView.IsAppChecked ? activeConn.CurrentAppPkgId : null, activeConn.CurrentLocalUserOwner, services, _optionsView.IsProtocolChecked ? activeConn.Protocol : -1, _optionsView.IsTargetIPChecked ? activeConn.Target : null, _optionsView.IsTargetPortChecked ? activeConn.TargetPort : null, _optionsView.IsLocalPortChecked ? activeConn.LocalPort : null, Profiles, "B"); success = newRule.ApplyIndirect(isTemp); if (!success) { MessageBox.Show(Common.Properties.Resources.MSG_RULE_FAILED, Common.Properties.Resources.MSG_DLG_ERR_TITLE, MessageBoxButton.OK, MessageBoxImage.Error); } } else { string entry = (!_optionsView.IsServiceRuleChecked || String.IsNullOrEmpty(activeConn.CurrentService) ? activeConn.CurrentPath : activeConn.CurrentService) + (_optionsView.IsLocalPortChecked ? ";" + activeConn.LocalPort : ";") + (_optionsView.IsTargetIPChecked ? ";" + activeConn.Target : ";") + (_optionsView.IsTargetPortChecked ? ";" + activeConn.TargetPort : ";"); //FIXME: Need to add more? using (StreamWriter sw = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "exclusions.set"), true)) { sw.WriteLine(entry); } success = true; } } return(success); }
private void LauncherOpenBtn_Click(object sender, RoutedEventArgs e) { IsEnabled = false; try { var launcherPath = Assembly.GetEntryAssembly().Location; if (!File.Exists(launcherPath)) { GenericMessageDialog.Show(Celeste_Launcher_Gui.Properties.Resources.WindowsFirewallHelperLauncherNotFound, DialogIcon.Error, DialogOptions.Ok); Close(); return; } //outbound_tcp var rule = FirewallHelper.RuleExist("celeste_launcher_outbound_tcp"); if (rule) { FirewallHelper.RemoveRules("celeste_launcher_outbound_tcp"); } FirewallHelper.AddApplicationRule("celeste_launcher_outbound_tcp", launcherPath, FirewallDirection.Outbound, FirewallProtocol.TCP); } catch (Exception ex) { Logger.Error(ex, ex.Message); GenericMessageDialog.Show(Celeste_Launcher_Gui.Properties.Resources.GenericUnexpectedErrorMessage, DialogIcon.Error, DialogOptions.Ok); } LoadFirewallRules(); IsEnabled = true; }
private bool createAllowRule(CurrentConn activeConn, string[] services, bool isTemp) { int Profiles = _optionsView.IsCurrentProfileChecked ? FirewallHelper.GetCurrentProfile() : FirewallHelper.GetGlobalProfile(); FirewallHelper.CustomRule newRule = new FirewallHelper.CustomRule(activeConn.RuleName, activeConn.CurrentPath, _optionsView.IsAppChecked? activeConn.CurrentAppPkgId : null, activeConn.CurrentLocalUserOwner, services, _optionsView.IsProtocolChecked? activeConn.Protocol : -1, _optionsView.IsTargetIPChecked? activeConn.Target: null, _optionsView.IsTargetPortChecked? activeConn.TargetPort: null, _optionsView.IsLocalPortChecked? activeConn.LocalPort: null, Profiles, "A"); return(newRule.ApplyIndirect(isTemp)); }
static void SetFirewall() { FirewallHelper.AllowApplication(Application.ExecutablePath); FirewallHelper.AllowTcpPort(50457, "50457-测试规则"); FirewallHelper.AllowUdpPort(50458, "50458-测试规则"); }
private void MultiplayerOpenBtn_Click(object sender, RoutedEventArgs e) { IsEnabled = false; try { //inbound_udp var rule = FirewallHelper.RuleExist("celeste_port1000_inbound_udp"); if (rule) { FirewallHelper.RemoveRules("celeste_port1000_inbound_udp"); } FirewallHelper.AddPortRule("celeste_port1000_inbound_udp", 1000, FirewallDirection.Inbound, FirewallProtocol.UDP); //outbound_udp rule = FirewallHelper.RuleExist("celeste_port1000_outbound_udp"); if (rule) { FirewallHelper.RemoveRules("celeste_port1000_outbound_udp"); } FirewallHelper.AddPortRule("celeste_port1000_outbound_udp", 1000, FirewallDirection.Outbound, FirewallProtocol.UDP); } catch (Exception ex) { Logger.Error(ex, ex.Message); GenericMessageDialog.Show(Celeste_Launcher_Gui.Properties.Resources.GenericUnexpectedErrorMessage, DialogIcon.Error, DialogOptions.Ok); } LoadFirewallRules(); IsEnabled = true; }
/// <summary> /// Sets a value for the given key and value name /// </summary> /// <param name="value"></param> /// <param name="action">Action to perform when setting the value</param> public override bool SetValue(FirewallRule value, object action) { switch (value) { case FirewallRule.None: { FirewallHelper.EnableFirewallForExecutingApplication(programName, true); break; } case FirewallRule.Exist: { FirewallHelper.EnableFirewallForExecutingApplication(programName, false); break; } case FirewallRule.Enabled: { FirewallHelper.DisableFirewallForExecutingApplication(programName); break; } default: { throw new ArgumentException("Value is not a valid enum value.", "value"); } } return(true); }
public SetRulesResponse UpdateRules(SetRulesRequest rules) { ToastHelper.PopToast("Update rules"); var rulesToApply = rules.GenericRequest; if (rulesToApply.Count <= 0) { return(new SetRulesResponse() { Success = false }); } List <Rule> domainRules = rulesToApply.Select(x => (Rule)(new WindowsRuleAdapter(x).NativeType)).ToList(); foreach (var rule in domainRules) { FirewallHelper.NewRule(rule); } return(new SetRulesResponse() { Success = true }); }
private static void AddException(string[] args, FirewallHelper fwHelper) { string appName; if (args.Length == 2) { string appPath = args[1] == "-g" ? PickAFile() : Path.GetFullPath(args[1]); if (appPath != null) { appName = Path.GetFileNameWithoutExtension(appPath); fwHelper.GrantRule(Path.GetFullPath(appPath), appName, Resources.description); } else { return; } } else if (args.Length == 3) { string appPath = args[1]; appName = args[2]; fwHelper.GrantRule(Path.GetFullPath(appPath), appName, Resources.description); } else { throw new ArgumentOutOfRangeException("-a just has 1 or 2 options."); } Console.WriteLine("Added {0} to exceptions list.", appName); }
public async Task SubmitsTraces() { var agentPort = TcpPortProvider.GetOpenPort(); var webPort = TcpPortProvider.GetOpenPort(); using (var fwPort = FirewallHelper.OpenWinPort(agentPort, Output)) using (var agent = new MockZipkinCollector(Output, agentPort)) using (var container = await StartContainerAsync(agentPort, webPort)) { var client = new HttpClient(); var response = await client.GetAsync($"http://localhost:{webPort}"); var content = await response.Content.ReadAsStringAsync(); Output.WriteLine("Sample response:"); Output.WriteLine(content); agent.SpanFilters.Add(x => x.Name != "healthz"); var spans = agent.WaitForSpans(1); Assert.True(spans.Count >= 1, $"Expecting at least 1 span, only received {spans.Count}"); } }
public GetConfigurationResponse GetConfiguration() { ToastHelper.PopToast("Get configuration"); var response = new GetConfigurationResponse(); response.FirewallEnabled = FirewallHelper.IsEnabled(); return(response); }
/// <summary> /// Add item to internal query list (asking user whether to allow this connection request), if there is no block rule available. /// </summary> /// <param name="pid"></param> /// <param name="path"></param> /// <param name="target"></param> /// <param name="protocol"></param> /// <param name="targetPort"></param> /// <param name="localPort"></param> /// /// <returns>false if item is blocked and was thus not added to internal query list</returns> internal bool AddItem(CurrentConn conn) { try { var sourcePortAsInt = int.Parse(conn.SourcePort); var existing = Dispatcher.Invoke(() => this.Connections.FirstOrDefault(c => StringComparer.InvariantCultureIgnoreCase.Equals(c.Path, conn.Path) && c.TargetIP == conn.TargetIP && c.TargetPort == conn.TargetPort && (sourcePortAsInt >= IPHelper.GetMaxUserPort() || c.SourcePort == conn.SourcePort) && c.RawProtocol == conn.RawProtocol)); if (existing != null) { LogHelper.Debug("Connection matches an already existing connection request."); if (!existing.LocalPortArray.Contains(sourcePortAsInt)) { existing.LocalPortArray.Add(sourcePortAsInt); //Note: Unfortunately, C# doesn't have a simple List that automatically sorts... :( // TODO: it does with SortedSet. Don't get this comment... // existing.LocalPortArray.Sort(); existing.SourcePort = IPHelper.MergePorts(existing.LocalPortArray); } existing.TentativesCounter++; } else { ServiceInfoResult svcInfo = null; if (Settings.Default.EnableServiceDetection) { svcInfo = ServiceNameResolver.GetServiceInfo(conn.Pid, conn.FileName); } conn.CurrentAppPkgId = ProcessHelper.GetAppPkgId(conn.Pid); conn.CurrentLocalUserOwner = ProcessHelper.GetLocalUserOwner(conn.Pid); conn.CurrentService = svcInfo?.DisplayName; conn.CurrentServiceDesc = svcInfo?.Name; // Check whether this connection is blocked by a rule. var blockingRules = FirewallHelper.GetMatchingRules(conn.Path, conn.CurrentAppPkgId, conn.RawProtocol, conn.TargetIP, conn.TargetPort, conn.SourcePort, conn.CurrentServiceDesc, conn.CurrentLocalUserOwner, blockOnly: true, outgoingOnly: true); if (blockingRules.Any()) { LogHelper.Info("Connection matches a block-rule!"); LogHelper.Debug($"pid: {Process.GetCurrentProcess().Id} GetMatchingRules: {conn.FileName}, {conn.Protocol}, {conn.TargetIP}, {conn.TargetPort}, {conn.SourcePort}, {svcInfo?.Name}"); return(false); } conn.LocalPortArray.Add(sourcePortAsInt); Dispatcher.Invoke(() => this.Connections.Add(conn)); return(true); } } catch (Exception e) { LogHelper.Error("Unable to add the connection to the pool.", e); } return(false); }
private static void ni_Click(object sender, EventArgs e) { if (!tmpnames.All(kv => FirewallHelper.RemoveRule(kv.Value))) { MessageBox.Show(Resources.MSG_RULE_RM_FAILED, Resources.MSG_DLG_ERR_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); } Environment.Exit(0); }
public GetRulesResponse GetRules() { ToastHelper.PopToast("Get rules"); var rules = FirewallHelper.GetRules2(); var response = new GetRulesResponse(); response.WindowsResult = rules; return(response); }
private void btnRemoveRule_Click(object sender, RoutedEventArgs e) { if (MessageBox.Show(Common.Properties.Resources.MSG_RULE_DELETE, Common.Properties.Resources.MSG_DLG_TITLE, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { FirewallHelper.RemoveRule(((FirewallHelper.Rule)gridRules.SelectedItem).Name); initAllRules(); initRules(); } }
private static bool CreateDefaultRules() { bool ret = true; var rules = FirewallHelper.GetRules(); using (ServiceController sc = new ServiceController()) { string rname; // Windows 8 or higher if (Environment.OSVersion.Version >= new System.Version(6, 2)) { rname = String.Format(Resources.RULE_NAME_FORMAT, "Windows Applications (auto)"); if (rules.All(r => r.Name != rname)) { CustomRule newRule = new CustomRule(rname, Environment.SystemDirectory + "\\wwahost.exe", null, null, (string)null, Protocol.ANY, null, null, null, FirewallHelper.GetGlobalProfile(), CustomRule.CustomRuleAction.Allow); ret = ret && FirewallHelper.AddRule(newRule.GetPreparedRule(false)); } } sc.ServiceName = "wuauserv"; rname = String.Format(Resources.RULE_NAME_FORMAT, sc.DisplayName + " (auto)"); if (rules.All(r => r.Name != rname + " [R:80,443]")) { CustomRule newRule = new CustomRule(rname, Environment.SystemDirectory + "\\svchost.exe", null, null, "wuauserv", Protocol.TCP, null, "80,443", null, FirewallHelper.GetGlobalProfile(), CustomRule.CustomRuleAction.Allow); ret = ret && FirewallHelper.AddRule(newRule.GetPreparedRule(false)); } sc.ServiceName = "bits"; rname = String.Format(Resources.RULE_NAME_FORMAT, sc.DisplayName + "(auto)"); if (rules.All(r => r.Name != rname + " [R:80,443]")) { CustomRule newRule = new CustomRule(rname, Environment.SystemDirectory + "\\svchost.exe", null, null, "bits", Protocol.TCP, null, "80,443", null, FirewallHelper.GetGlobalProfile(), CustomRule.CustomRuleAction.Allow); ret = ret && FirewallHelper.AddRule(newRule.GetPreparedRule(false)); } sc.ServiceName = "cryptsvc"; rname = String.Format(Resources.RULE_NAME_FORMAT, sc.DisplayName + "(auto)"); if (rules.All(r => r.Name != rname + " [R:80]")) { CustomRule newRule = new CustomRule(rname, Environment.SystemDirectory + "\\svchost.exe", null, null, "cryptsvc", Protocol.TCP, null, "80", null, FirewallHelper.GetGlobalProfile(), CustomRule.CustomRuleAction.Allow); ret = ret && FirewallHelper.AddRule(newRule.GetPreparedRule(false)); } //sc.ServiceName = "aelookupsvc"; //rname = String.Format(Resources.RULE_NAME_FORMAT, sc.DisplayName + "(auto)"); //if (rules.All(r => r.Name != rname + " [R:80]")) //{ // CustomRule newRule = new CustomRule(rname, Environment.SystemDirectory + "\\svchost.exe", null, null,"aelookupsvc", (int)NET_FW_IP_PROTOCOL_.NET_FW_IP_PROTOCOL_TCP, null, "80", null, FirewallHelper.GetGlobalProfile(), "A"); // ret = ret && FirewallHelper.AddRule(newRule.GetPreparedRule(false)); //} } return(ret); }
/// <summary> /// Install and setup. /// </summary> /// <param name="checkResult"></param> /// <returns></returns> public static bool Install([param: NotNull] Func <Func <bool>, string, string, bool> checkResult) { if (checkResult is null) { throw new ArgumentNullException(nameof(checkResult)); } LogHelper.Debug("EnableProgram"); if (IsNotifierTaskInstalled()) { RemoveNotifierTask(); // will be re-created below } if (Settings.Default.StartNotifierAfterLogin) { if (!checkResult(() => CreateNotifierTask(), "Notifier will start after next windows login", Resources.MSG_INST_TASK_ERR)) { return(false); } } if (!checkResult(() => (ProcessHelper.GetProcessFeedback( Environment.SystemDirectory + "\\reg.exe", @"ADD HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v SCENoApplyLegacyAuditPolicy /t REG_DWORD /d 1 /f")) , "Registry enable SCENoApplyLegacyAuditPolicy." , Resources.MSG_INST_ENABLE_LOG_ERR)) { return(false); } if (!checkResult(() => SetAuditPolConnection(enableSuccess: Settings.Default.AuditPolEnableSuccessEvent, enableFailure: true) , "Audit policy enabled." , Resources.MSG_INST_ENABLE_LOG_ERR)) { return(false); } if (!checkResult(() => FirewallHelper.EnableWindowsFirewall() , "Windows firewall enabled." , Resources.MSG_INST_ENABLE_FW_ERR)) { return(false); } if (!checkResult(() => CreateDefaultRules() , Resources.MSG_INST_OK , "Unable to create the default windows firewall rules.")) { return(false); } Settings.Default.IsInstalled = true; Settings.Default.Save(); return(true); }
} // 保留一个静态引用,以免被GC回收 private static void Init() { string exePath = System.Reflection.Assembly.GetEntryAssembly().Location; // 将当前进程添加到防火墙的允许列表中 FirewallHelper.AllowApplication(exePath); // 强制指定【当前目录】,因为程序有可能是从计划任务中启动的,当前目录是Windows系统目录 Environment.CurrentDirectory = Path.GetDirectoryName(exePath); }
private void initAllRules() { try { allrules = FirewallHelper.GetRules().OrderBy(r => r.Name); } catch (Exception e) { LogHelper.Error("Unable to load all FW rules", e); } }
private static void ni_Click(object sender, EventArgs e) { LogHelper.Info("Now going to remove temporary rule(s)..."); if (!tmpnames.All(kv => FirewallHelper.RemoveRule(kv))) { MessageBox.Show(Resources.MSG_RULE_RM_FAILED, Resources.MSG_DLG_ERR_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Error); } Environment.Exit(0); }
private static void SkipAllEntriesFromRules() { for (int i = ((App)Application.Current).Connections.Count - 1; i >= 0; i--) { var c = ((App)Application.Current).Connections[i]; if (FirewallHelper.GetMatchingRules(c.Path, c.CurrentAppPkgId, c.RawProtocol, c.TargetIP, c.TargetPort, c.SourcePort, c.CurrentService, c.CurrentLocalUserOwner, false).Any()) //FIXME: LocalPort may have multiple!) { LogHelper.Debug("Auto-removing a similar connection..."); ((App)Application.Current).Connections.Remove(c); } } }
public void TestGetMatchingRulesForEvent() { string exePath = @"C:\Windows\System32\svchost.exe"; IEnumerable <FirewallHelper.Rule> results = FirewallHelper.GetMatchingRulesForEvent(pid: 0, path: exePath, target: "*", targetPort: "*", blockOnly: false); Assert.NotNull(results); Assert.True(results.ToList().Count >= 1, "Has no results or number of results does not match"); foreach (FirewallHelper.Rule rule in results) { Console.WriteLine($"{rule.Name}, {rule.RemoteAddresses}"); } }
private void initRules() { LogHelper.Debug("Retrieving all rules..."); try { allRules = FirewallHelper.GetRules(AlsoGetInactive: true).ToList(); } catch (Exception e) { LogHelper.Error("Unable to load all FW rules", e); } }
private void WindowsDefenderGameFilesDirctoryChange() { //Check if New Game! Files is not in Banned Folder Locations CheckGameFilesDirectoryPrevention(); try { //Remove current Exclusion and Add new location for Exclusion using (PowerShell ps = PowerShell.Create()) { Log.Warning("WINDOWS DEFENDER: Removing OLD Game Files Directory: " + FileSettingsSave.GameInstallation); ps.AddScript($"Remove-MpPreference -ExclusionPath \"{FileSettingsSave.GameInstallation}\""); Log.Core("WINDOWS DEFENDER: Excluding NEW Game Files Directory: " + _newGameFilesPath); ps.AddScript($"Add-MpPreference -ExclusionPath \"{_newGameFilesPath}\""); var result = ps.Invoke(); } } catch (Exception ex) { Log.Error("WINDOWS DEFENDER: " + ex.Message); } //Remove current Firewall for the Game Files string CurrentGameFilesExePath = Path.Combine(FileSettingsSave.GameInstallation + "\\nfsw.exe"); if (File.Exists(CurrentGameFilesExePath) && FirewallHelper.FirewallStatus() == true) { if (FirewallHelper.RuleExist("SBRW - Game") == true) { bool removeFirewallRule = true; bool firstTimeRun = true; string nameOfGame = "SBRW - Game"; string localOfGame = CurrentGameFilesExePath; string groupKeyGame = "Need for Speed: World"; string descriptionGame = groupKeyGame; //Inbound & Outbound FirewallHelper.DoesRulesExist(removeFirewallRule, firstTimeRun, nameOfGame, localOfGame, groupKeyGame, descriptionGame, FirewallProtocol.Any); } } FileSettingsSave.GameInstallation = _newGameFilesPath; //Clean Mods Files from New Dirctory (If it has .links in directory) var linksPath = Path.Combine(_newGameFilesPath, "\\.links"); ModNetLinksCleanup.CleanLinks(linksPath); _restartRequired = true; }
private static void RemoveExceptionByName(string[] args, FirewallHelper fwHelper) { if (args.Length == 2) { string appName = args[1]; fwHelper.RemoveRule(appName); Console.WriteLine("Removed {0} to exceptions list.", args[1]); } else { throw new ArgumentOutOfRangeException("-rN just has option."); } }
/// <summary> /// Updates all controls contents according to the currently selected blocked connection /// </summary> private void showConn() { var activeConn = (CurrentConn)lstConnections.SelectedItem; if (FirewallHelper.getProtocolAsString(activeConn.Protocol) == "Unknown") //FIXME: No string comparison, please! { OptionsView.IsProtocolChecked = false; } else { //On by default. Also: needed to be able to specify port! OptionsView.IsProtocolChecked = true; } OptionsView.IsTargetPortEnabled = FirewallHelper.IsIPProtocol(activeConn.Protocol); OptionsView.IsTargetPortChecked = FirewallHelper.IsIPProtocol(activeConn.Protocol); OptionsView.IsLocalPortChecked = (activeConn.LocalPortArray.Count == 1 && activeConn.LocalPortArray[0] != 0 && activeConn.LocalPortArray[0] < IPHelper.GetMaxUserPort()); if (!String.IsNullOrEmpty(activeConn.CurrentService)) { OptionsView.IsService = true; OptionsView.IsServiceMultiple = false; OptionsView.IsServiceRuleChecked = true; OptionsView.SingleServiceName = activeConn.CurrentServiceDesc; } else if (activeConn.PossibleServices != null && activeConn.PossibleServices.Length > 0) { OptionsView.IsService = true; if (activeConn.PossibleServices.Length > 1) { OptionsView.IsServiceMultiple = true; OptionsView.SingleServiceName = ""; } else { OptionsView.IsServiceMultiple = false; OptionsView.SingleServiceName = activeConn.PossibleServicesDesc.FirstOrDefault(); } OptionsView.IsServiceRuleChecked = false; //If we're unsure, let's choose the safe option. There are executables out there that run services but also open connections outside of those services. A false positive in such a case would create a rule that doesn't work. } else { OptionsView.IsService = false; OptionsView.IsServiceMultiple = false; OptionsView.IsServiceRuleChecked = false; OptionsView.SingleServiceName = ""; } OptionsView.IsAppEnabled = !String.IsNullOrEmpty(activeConn.CurrentAppPkgId); NotifyPropertyChanged("OptionsView"); }
private void btnRemoveRule_Click(object sender, RoutedEventArgs e) { if (MessageBox.Show(Common.Properties.Resources.MSG_RULE_DELETE, Common.Properties.Resources.MSG_DLG_TITLE, MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) { FirewallHelper.Rule selectedRule = (FirewallHelper.Rule)gridRules.SelectedItem; if (!FirewallHelper.RemoveRule(selectedRule.Name)) { MessageBox.Show(Common.Properties.Resources.MSG_RULE_DELETE_FAILED, Common.Properties.Resources.MSG_DLG_ERR_TITLE, MessageBoxButton.OK, MessageBoxImage.Error); return; } allRules.Remove(selectedRule); filterRules(); } }
public void UpdateRule(string id, SetRuleRequest rule) { Linux.Models.Rule newEntry = null; if (rule.GenericRequest != null) { newEntry = (Linux.Models.Rule)(new LinuxRuleAdapter(rule.GenericRequest).NativeType); } else if (rule.UfwRequest != null) { newEntry = rule.UfwRequest; } FirewallHelper.UpdateRule(newEntry); }
private bool createBlockRule(CurrentConn activeConn, string[] services, bool createWithAdvancedOptions, bool createTempRule, string ruleName) { bool success; if (Settings.Default.UseBlockRules) { int Profiles = OptionsView.IsCurrentProfileChecked ? FirewallHelper.GetCurrentProfile() : FirewallHelper.GetGlobalProfile(); string finalRuleName = (createTempRule) ? Messages.RULE_TEMP_PREFIX + ruleName : ruleName; var newRule = new CustomRule(finalRuleName, createWithAdvancedOptions || OptionsView.IsPathChecked ? activeConn.Path : null, !createWithAdvancedOptions && OptionsView.IsAppChecked ? activeConn.CurrentAppPkgId : null, activeConn.CurrentLocalUserOwner, services, !createWithAdvancedOptions && OptionsView.IsProtocolChecked ? activeConn.RawProtocol : -1, !createWithAdvancedOptions && OptionsView.IsTargetIPChecked ? activeConn.TargetIP : null, !createWithAdvancedOptions && OptionsView.IsTargetPortChecked ? activeConn.TargetPort : null, !createWithAdvancedOptions && OptionsView.IsLocalPortChecked ? activeConn.SourcePort : null, Profiles, CustomRule.CustomRuleAction.Block); success = FirewallHelper.AddRule(newRule.GetPreparedRule(createTempRule)); // does not use RuleManager if (success && createTempRule) { CreateTempRuleNotifyIcon(newRule); } if (!success) { MessageBox.Show(Messages.MSG_RULE_FAILED, Messages.MSG_DLG_ERR_TITLE, MessageBoxButton.OK, MessageBoxImage.Error); } } else { // FIXME: Remove and always use Global Rules? throw new ArgumentException("Only global block rules can be used - check options"); string entry = (!OptionsView.IsServiceRuleChecked || String.IsNullOrEmpty(activeConn.CurrentService) ? activeConn.Path : activeConn.CurrentService) + (OptionsView.IsLocalPortChecked ? ";" + activeConn.SourcePort : ";") + (OptionsView.IsTargetIPChecked ? ";" + activeConn.TargetIP : ";") + (OptionsView.IsTargetPortChecked ? ";" + activeConn.TargetPort : ";"); //FIXME: Need to add more? using (StreamWriter sw = new StreamWriter(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "exclusions.set"), true)) { sw.WriteLine(entry); } success = true; } return(success); }