Exemple #1
0
        /// <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);
        }
Exemple #2
0
        /// <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(int pid, string path, string target, int protocol, int targetPort, int localPort)
        {
            try
            {
                string fileName = System.IO.Path.GetFileName(path);
                if (path != "System")
                {
                    path = Common.IO.Files.PathResolver.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         = Array.Empty <string>();
                    string[] svcdsc      = Array.Empty <string>();
                    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)
                        {
                            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 (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);
        }