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 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)); }
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 ServicesForm(CurrentConn activeConn) { this.activeConn = activeConn; this._services = activeConn.PossibleServices.Select((s, i) => new ServiceView { Name = s, Description = activeConn.PossibleServicesDesc[i], IsSelected = true }).ToList(); InitializeComponent(); }
/// <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 async void ResolveHostForConnection(CurrentConn conn) { try { DnsResolver.ResolveIpAddress(conn.Target, entry => conn.ResolvedHost = conn.Target != entry.HostEntry.HostName ? entry.HostEntry.HostName : "..."); } catch (Exception e) { LogHelper.Warning($"Cannot resolve host name for {conn.Target} - Exception: {e.Message}"); } }
private async void resolveHostForConnection(CurrentConn conn) { try { var host = (await Dns.GetHostEntryAsync(conn.Target)).HostName; if (conn.Target != host) { conn.ResolvedHost = host; } } catch { } }
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); }
private bool createAllowRule(CurrentConn activeConn, string[] services, bool isTemp) { int Profiles = OptionsView.IsCurrentProfileChecked ? FirewallHelper.GetCurrentProfile() : FirewallHelper.GetGlobalProfile(); string ruleName = isTemp ? Messages.RULE_TEMP_PREFIX + activeConn.RuleName : activeConn.RuleName; CustomRule newRule = new CustomRule(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 , CustomRule.CustomRuleAction.A); bool success = FirewallHelper.AddRule(newRule.GetPreparedRule(isTemp)); // does not use RuleManager if (success && isTemp) { CreateTempRuleNotifyIcon(newRule); } return(success); }
/// <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="threadid"></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(int pid, int threadid, string path, string target, int protocol, int targetPort, int localPort) { try { string fileName = System.IO.Path.GetFileName(path); if (path != "System") { path = FileHelper.GetFriendlyPath(path); } //FIXME: Do a proper path compare...? CASE! var existing = this.Connections.FirstOrDefault(c => c.CurrentPath == path && c.Target == target && c.TargetPort == targetPort.ToString() && (localPort >= IPHelper.GetMaxUserPort() || c.LocalPort == localPort.ToString()) && c.Protocol == protocol); if (existing != null) { LogHelper.Debug("Connection matches an already existing connection request."); if (!existing.LocalPortArray.Contains(localPort)) { existing.LocalPortArray.Add(localPort); existing.LocalPortArray.Sort(); //Note: Unfortunately, C# doesn't have a simple List that automatically sorts... :( existing.LocalPort = IPHelper.MergePorts(existing.LocalPortArray); } existing.TentativesCounter++; } else { string[] svc = new string[0]; string[] svcdsc = new string[0]; bool unsure = false; string description = null; if (path == "System") { description = "System"; } else { try { if (File.Exists(path)) { description = FileVersionInfo.GetVersionInfo(path).FileDescription; if (String.IsNullOrWhiteSpace(description)) { description = path.Substring(path.LastIndexOf('\\') + 1); } } else { // TODO: this happens when accessing system32 files from a x86 application i.e. File.Exists always returns false; solution would be to target AnyCPU description = path; } } catch (Exception exc) { LogHelper.Error("Unable to check the file description.", exc); description = path + " (not found)"; } if (Settings.Default.EnableServiceDetection) { ProcessHelper.ServiceInfoResult svcInfo = AsyncTaskRunner.GetServiceInfo(pid, fileName); if (svcInfo != null) { svc = new string[] { svcInfo.Name }; svcdsc = new string[] { svcInfo.DisplayName }; unsure = false; } } } // Check whether this connection has been excluded - exclusion means ignore i.e do not notify if (exclusions != null) { // WARNING: check for regressions LogHelper.Debug("Checking exclusions..."); var exclusion = exclusions.FirstOrDefault(e => e.StartsWith(/*svc ??*/ path, StringComparison.InvariantCulture) || svc != null && svc.All(s => e.StartsWith(s, StringComparison.InvariantCulture))); if (exclusion != null) { string[] esplit = exclusion.Split(';'); if (esplit.Length == 1 || (String.IsNullOrEmpty(esplit[1]) || esplit[1] == localPort.ToString()) && (String.IsNullOrEmpty(esplit[2]) || esplit[2] == target) && (String.IsNullOrEmpty(esplit[3]) || esplit[3] == targetPort.ToString()) ) { LogHelper.Info($"Connection is excluded: {exclusion}"); return(false); } } } // Check whether this connection is blocked by a rule. var blockingRules = FirewallHelper.GetMatchingRules(path, ProcessHelper.getAppPkgId(pid), protocol, target, targetPort.ToString(), localPort.ToString(), unsure ? svc : svc.Take(1), ProcessHelper.getLocalUserOwner(pid), blockOnly: true, outgoingOnly: true); if (blockingRules.Any()) { LogHelper.Info("Connection matches a block-rule!"); StringBuilder sb = new StringBuilder(); sb.Append("Blocked by: "); foreach (FirewallHelper.Rule s in blockingRules) { sb.Append(s.Name + ": " + s.ApplicationName + ", " + s.Description + ", " + s.ActionStr + ", " + s.ServiceName + ", " + s.Enabled); } LogHelper.Debug("pid: " + Process.GetCurrentProcess().Id + " GetMatchingRules: " + path + ", " + protocol + ", " + target + ", " + targetPort + ", " + localPort + ", " + String.Join(",", svc)); return(false); } FileVersionInfo fileinfo = null; try { fileinfo = FileVersionInfo.GetVersionInfo(path); } catch (FileNotFoundException) { } var conn = new CurrentConn { Description = description, CurrentAppPkgId = ProcessHelper.getAppPkgId(pid), CurrentLocalUserOwner = ProcessHelper.getLocalUserOwner(pid), ProductName = fileinfo != null ? fileinfo.ProductName : String.Empty, Company = fileinfo != null ? fileinfo.CompanyName : String.Empty, CurrentPath = path, Protocol = protocol, TargetPort = targetPort.ToString(), RuleName = String.Format(Common.Properties.Resources.RULE_NAME_FORMAT, unsure || String.IsNullOrEmpty(svcdsc.FirstOrDefault()) ? description : svcdsc.FirstOrDefault()), Target = target, LocalPort = localPort.ToString() }; conn.LocalPortArray.Add(localPort); if (unsure) { //LogHelper.Debug("Adding services (unsure): " + String.Join(",", svc)); conn.PossibleServices = svc; conn.PossibleServicesDesc = svcdsc; } else { //LogHelper.Debug("Adding services: " + svc.FirstOrDefault()); conn.CurrentService = svc.FirstOrDefault(); conn.CurrentServiceDesc = svcdsc.FirstOrDefault(); } ResolveHostForConnection(conn); this.Connections.Add(conn); return(true); } } catch (Exception e) { LogHelper.Error("Unable to add the connection to the pool.", e); } return(false); }
private async void retrieveIcon(CurrentConn conn) { var icon = await IconHelper.GetIconAsync(conn.CurrentPath, true); conn.Icon = icon; }
public ActivityEventArgs(ActivityEnum activity, CurrentConn currentConnection) { Activity = activity; CurrentConnection = currentConnection; }
public static void Publish(IActivitySender sender, ActivityEventArgs.ActivityEnum activity, CurrentConn currentConnection) { ActivityEventArgs args = new ActivityEventArgs(activity, currentConnection); OnRaiseActivityEvent(sender, args); }