From e0d9c8ba87c8bea85cee7ed3767998c6e66cbe55 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:11:44 +0000 Subject: [PATCH 01/62] feat: configurable DNS routing (Direct and Proxy modes) Add a global DNS policy for conventional DNS (UDP and TCP port 53): - Direct (default, also for configurations without a dns section): port-53 traffic bypasses every proxy for IPv4 and IPv6. TCP/53 is now unconditionally direct as well (previously only UDP/53 was). - Proxy: all captured port-53 traffic, whatever process sends it (including the Windows DNS Client service), goes through one selected SOCKS5 proxy via the existing UDP ASSOCIATE and TCP CONNECT paths. The policy fails closed: DNS the proxy cannot carry is dropped, never sent direct, and takes precedence over LAN bypass through front-of-table driver REDIRECT filters. - Optional serverOverride (IPv4/IPv6 literal): only the SOCKS5 destination changes; UDP answers are restored to the server the resolver queried (tracked by client port and DNS message ID). Queries to servers of the other family are blocked. - The DNS proxy is referenced by a new stable per-rule "id", which survives reordering, editing and reload; invalid or dangling references and proxies without TCP+UDP are rejected by validation. Native: dns_routing_policy.h holds the platform-independent decisions, override syntax, reply classification and origin tracker; the router applies them before process attribution. socks5_udp_local_redirect gains optional SOCKS destination / source-restore parameters. ProxiFyre's own upstream traffic is never captured. Managed: DnsSettings model, DnsConfiguration helpers, validator and normalizer rules, service wiring (fail closed when the selected proxy could not be created), and a DNS routing group in the GUI settings tab. Tests: GoogleTest policy suite (also in netlib-tests), a portable packet round-trip suite that runs the real redirect headers and the product checksum routines on Linux (new CI job), and NUnit DNS configuration tests. Docs: configuration reference, GUI guide, README, sample configuration. --- .gitattributes | 1 + .github/workflows/native-tests.yml | 26 +- .../ConfigurationNormalizer.cs | 29 + .../ConfigurationValidator.cs | 162 ++++ ProxiFyre.Configuration/DnsConfiguration.cs | 269 +++++++ ProxiFyre.Configuration/Models.cs | 48 ++ .../ProxiFyre.Configuration.csproj | 1 + ProxiFyre.Tests/DnsConfigurationTests.cs | 400 ++++++++++ ProxiFyre.Tests/ProxiFyre.Tests.csproj | 1 + ProxiFyre/Program.cs | 58 ++ ProxiFyreUI/Forms/MainForm.Designer.cs | 36 +- ProxiFyreUI/Forms/MainForm.cs | 132 ++++ README.md | 12 +- app-config.sample.json | 8 +- docs/configuration.md | 83 +- docs/gui.md | 15 + netlib-tests/netlib-tests.vcxproj | 1 + netlib-tests/pch.h | 1 + netlib/README.md | 24 + .../src/ndisapi/socks5_udp_local_redirect.h | 61 +- netlib/src/proxy/dns_routing_policy.h | 477 ++++++++++++ netlib/src/proxy/socks_local_router.h | 720 +++++++++++++++++- .../portable/dns_packet_redirect_test.cpp | 439 +++++++++++ netlib/test/portable/pch.h | 18 + netlib/test/portable/run-portable-tests.sh | 50 ++ netlib/test/portable/winshim/WinIoctl.h | 1 + netlib/test/portable/winshim/in6addr.h | 1 + netlib/test/portable/winshim/ip2string.h | 1 + netlib/test/portable/winshim/packet_env.h | 24 + netlib/test/portable/winshim/winshim.h | 142 ++++ netlib/test/proxy/dns_routing_policy_test.cpp | 404 ++++++++++ socksify/Socksifier.cpp | 26 + socksify/Socksifier.h | 22 + socksify/mixed_types.h | 11 + socksify/socksify.vcxproj | 1 + socksify/socksify.vcxproj.filters | 3 + socksify/socksify_unmanaged.cpp | 17 + socksify/socksify_unmanaged.h | 12 + 38 files changed, 3704 insertions(+), 33 deletions(-) create mode 100644 ProxiFyre.Configuration/DnsConfiguration.cs create mode 100644 ProxiFyre.Tests/DnsConfigurationTests.cs create mode 100644 netlib/src/proxy/dns_routing_policy.h create mode 100644 netlib/test/portable/dns_packet_redirect_test.cpp create mode 100644 netlib/test/portable/pch.h create mode 100755 netlib/test/portable/run-portable-tests.sh create mode 100644 netlib/test/portable/winshim/WinIoctl.h create mode 100644 netlib/test/portable/winshim/in6addr.h create mode 100644 netlib/test/portable/winshim/ip2string.h create mode 100644 netlib/test/portable/winshim/packet_env.h create mode 100644 netlib/test/portable/winshim/winshim.h create mode 100644 netlib/test/proxy/dns_routing_policy_test.cpp diff --git a/.gitattributes b/.gitattributes index ddcd7fd..9835b74 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ ProxiFyre/App.config text eol=lf ProxiFyre/NLog.config text eol=lf ProxiFyreUI/ProxiFyreUI.exe.config text eol=lf +netlib/test/portable/run-portable-tests.sh text eol=lf diff --git a/.github/workflows/native-tests.yml b/.github/workflows/native-tests.yml index 6e092a9..e557ea7 100644 --- a/.github/workflows/native-tests.yml +++ b/.github/workflows/native-tests.yml @@ -1,6 +1,7 @@ name: 'Native tests' -# Builds and runs the native x64 GoogleTest executable (netlib-tests). This workflow is +# Builds and runs the native x64 GoogleTest executable (netlib-tests) on Windows and the portable +# native tests on Linux. This workflow is # independent of release packaging and signing: it produces no release artifacts and needs no # secrets. The commands mirror the local instructions in netlib/README.md. @@ -9,6 +10,29 @@ on: workflow_dispatch: jobs: + portable-native-tests: + # Platform-independent native tests (DNS routing policy and the real packet-rewriting + # headers it drives); see netlib/README.md#portable-native-tests. + runs-on: ubuntu-24.04 + permissions: + contents: read + steps: + - name: Checkout from GitHub + uses: actions/checkout@v7 + with: + persist-credentials: false + + - name: Install compiler and test dependencies + run: | + sudo apt-get update + sudo apt-get install -y --no-install-recommends g++ libgtest-dev libmsgsl-dev + + - name: Run portable native tests + run: netlib/test/portable/run-portable-tests.sh + + - name: Run portable native tests with sanitizers + run: SANITIZE=1 netlib/test/portable/run-portable-tests.sh + netlib-tests: strategy: fail-fast: false diff --git a/ProxiFyre.Configuration/ConfigurationNormalizer.cs b/ProxiFyre.Configuration/ConfigurationNormalizer.cs index 512ea68..2578ea1 100644 --- a/ProxiFyre.Configuration/ConfigurationNormalizer.cs +++ b/ProxiFyre.Configuration/ConfigurationNormalizer.cs @@ -28,12 +28,40 @@ public ProxiFyreConfiguration Normalize(ProxiFyreConfiguration configuration) Excludes = configuration.Excludes == null ? new List() : configuration.Excludes.Where(value => !string.IsNullOrWhiteSpace(value)).ToList(), + Dns = configuration.Dns == null ? null : NormalizeDns(configuration.Dns), ExtensionData = CloneExtensionData(configuration.ExtensionData) }; return result; } + public DnsSettings NormalizeDns(DnsSettings dns) + { + if (dns == null) + throw new ArgumentNullException(nameof(dns)); + + var mode = dns.Mode == null ? null : dns.Mode.Trim(); + DnsRoutingMode parsed; + if (DnsConfiguration.TryGetMode(mode, out parsed)) + mode = parsed == DnsRoutingMode.Proxy ? DnsConfiguration.ProxyMode : DnsConfiguration.DirectMode; + + return new DnsSettings + { + Mode = mode, + ProxyId = EmptyToNull(dns.ProxyId), + ServerOverride = EmptyToNull(dns.ServerOverride), + ExtensionData = CloneExtensionData(dns.ExtensionData) + }; + } + + private static string EmptyToNull(string value) + { + if (value == null) + return null; + var trimmed = value.Trim(); + return trimmed.Length == 0 ? null : trimmed; + } + public ProxyRule NormalizeRule(ProxyRule rule) { if (rule == null) @@ -64,6 +92,7 @@ public ProxyRule NormalizeRule(ProxyRule rule) var hasCanonicalTransport = TryGetCanonicalTransport(rule.Socks5Transport, out transport); return new ProxyRule { + Id = rule.Id == null ? null : rule.Id.Trim(), AppNames = appNames, Socks5ProxyEndpoint = rule.Socks5ProxyEndpoint == null ? null : rule.Socks5ProxyEndpoint.Trim(), Username = rule.Username, diff --git a/ProxiFyre.Configuration/ConfigurationValidator.cs b/ProxiFyre.Configuration/ConfigurationValidator.cs index f980a9e..52ee118 100644 --- a/ProxiFyre.Configuration/ConfigurationValidator.cs +++ b/ProxiFyre.Configuration/ConfigurationValidator.cs @@ -62,6 +62,8 @@ public ValidationResult Validate(ProxiFyreConfiguration configuration) ValidateCatchAllOrdering(configuration.Proxies, issues); ValidateApplicationOverlap(configuration.Proxies, issues); + ValidateProxyIds(configuration.Proxies, issues); + ValidateDns(configuration.Dns, configuration.Proxies, issues); return new ValidationResult(issues); } @@ -507,6 +509,166 @@ private static string GetPathTail(string value) : lastSlash < 0 ? value : string.Empty; } + private static void ValidateProxyIds(IList rules, ICollection issues) + { + var seen = new Dictionary(StringComparer.OrdinalIgnoreCase); + for (var index = 0; index < rules.Count; index++) + { + var id = rules[index] == null ? null : rules[index].Id; + if (id == null) + continue; + + var trimmed = id.Trim(); + if (!DnsConfiguration.IsValidProxyId(trimmed)) + { + issues.Add(Error( + "PROXY_ID_INVALID", + "A proxy id must contain 1 to " + DnsConfiguration.MaximumProxyIdLength + + " letters, digits, '-', '_', or '.' characters. Remove the id or give it a valid value.", + RulePath(index) + ".id", + index)); + continue; + } + + int firstIndex; + if (seen.TryGetValue(trimmed, out firstIndex)) + { + issues.Add(Error( + "PROXY_ID_DUPLICATE", + "The proxy id '" + trimmed + "' is already used by rule " + (firstIndex + 1) + + "; proxy ids must be unique (case-insensitive).", + RulePath(index) + ".id", + index)); + continue; + } + + seen.Add(trimmed, index); + } + } + + private static void ValidateDns(DnsSettings dns, IList rules, ICollection issues) + { + if (dns == null) + return; // Omitted means Direct. + + DnsRoutingMode mode; + if (!DnsConfiguration.TryGetMode(dns.Mode, out mode)) + { + issues.Add(Error( + "DNS_MODE_UNKNOWN", + "The DNS mode must be Direct or Proxy.", + "dns.mode")); + return; + } + + if (mode == DnsRoutingMode.Direct) + { + if (!string.IsNullOrWhiteSpace(dns.ServerOverride)) + { + issues.Add(Warning( + "DNS_SERVER_OVERRIDE_IGNORED", + "The DNS server override is used only in Proxy mode; in Direct mode DNS keeps its original destination.", + "dns.serverOverride")); + } + return; + } + + if (string.IsNullOrWhiteSpace(dns.ProxyId)) + { + issues.Add(Error( + "DNS_PROXY_ID_MISSING", + "DNS Proxy mode requires dns.proxyId to name the id of the proxy rule that carries DNS.", + "dns.proxyId")); + return; + } + + var ruleIndex = DnsConfiguration.FindProxyRuleIndex(rules, dns.ProxyId); + if (ruleIndex < 0) + { + issues.Add(Error( + "DNS_PROXY_NOT_FOUND", + "No proxy rule has the id '" + dns.ProxyId.Trim() + "'. Set dns.proxyId to the id of an existing proxy rule; " + + "DNS is never switched to another proxy automatically.", + "dns.proxyId")); + return; + } + + var rule = rules[ruleIndex]; + ProxyProtocolSelection protocols; + try + { + protocols = ConfigurationValueParser.GetProtocols(rule.SupportedProtocols); + } + catch (InvalidOperationException) + { + return; // PROTOCOL_UNKNOWN is already reported for the rule. + } + + if (protocols != ProxyProtocolSelection.Both) + { + issues.Add(Error( + "DNS_PROXY_PROTOCOLS_UNSUPPORTED", + "The DNS proxy (rule " + (ruleIndex + 1) + ") must support both TCP and UDP: DNS uses UDP and falls back to TCP " + + "for truncated answers. Enable both protocols on that rule or select another proxy.", + "dns.proxyId")); + } + + ProxyAddressFamilySelection families; + try + { + families = ConfigurationValueParser.GetAddressFamilies(rule.SupportedAddressFamilies); + } + catch (InvalidOperationException) + { + return; // ADDRESS_FAMILIES_EMPTY or ADDRESS_FAMILY_UNKNOWN is already reported. + } + + DnsServerOverride serverOverride = null; + if (!string.IsNullOrWhiteSpace(dns.ServerOverride)) + { + DnsServerOverrideParseError error; + if (!DnsConfiguration.TryParseServerOverride(dns.ServerOverride, out serverOverride, out error)) + { + issues.Add(Error( + error == DnsServerOverrideParseError.InvalidPort ? "DNS_SERVER_OVERRIDE_PORT_INVALID" : "DNS_SERVER_OVERRIDE_INVALID", + error == DnsServerOverrideParseError.InvalidPort + ? "The DNS server override port must be an integer from 1 to 65535." + : error == DnsServerOverrideParseError.UnusableAddress + ? "The DNS server override must be a unicast address (not unspecified, broadcast, multicast, or IPv4-mapped)." + : "The DNS server override must be an IPv4 or IPv6 address literal such as 1.1.1.1 or " + + "[2606:4700:4700::1111]:53. Host names are not accepted because resolving them would itself require DNS.", + "dns.serverOverride")); + return; + } + + var overrideFamily = serverOverride.IsIpv6 ? ProxyAddressFamilySelection.Ipv6 : ProxyAddressFamilySelection.Ipv4; + if ((families & overrideFamily) == 0) + { + issues.Add(Error( + "DNS_SERVER_OVERRIDE_FAMILY_UNSUPPORTED", + "The DNS server override is " + (serverOverride.IsIpv6 ? "IPv6" : "IPv4") + " but the DNS proxy (rule " + + (ruleIndex + 1) + ") does not accept " + (serverOverride.IsIpv6 ? "IPv6" : "IPv4") + " destinations.", + "dns.serverOverride")); + return; + } + + issues.Add(Warning( + "DNS_SERVER_OVERRIDE_OTHER_FAMILY_BLOCKED", + "DNS queries addressed to " + (serverOverride.IsIpv6 ? "IPv4" : "IPv6") + " servers are blocked because the " + + "server override is " + (serverOverride.IsIpv6 ? "IPv6" : "IPv4") + ". Windows falls back to its other configured DNS servers.", + "dns.serverOverride")); + } + else if (families != ProxyAddressFamilySelection.Both) + { + var unsupported = (families & ProxyAddressFamilySelection.Ipv6) == 0 ? "IPv6" : "IPv4"; + issues.Add(Warning( + "DNS_PROXY_FAMILY_BLOCKED", + "The DNS proxy (rule " + (ruleIndex + 1) + ") does not accept " + unsupported + " destinations, so DNS queries " + + "addressed to " + unsupported + " servers are blocked rather than sent directly.", + "dns.proxyId")); + } + } + private static string RulePath(int index) { return "proxies[" + index + "]"; diff --git a/ProxiFyre.Configuration/DnsConfiguration.cs b/ProxiFyre.Configuration/DnsConfiguration.cs new file mode 100644 index 0000000..fa67abb --- /dev/null +++ b/ProxiFyre.Configuration/DnsConfiguration.cs @@ -0,0 +1,269 @@ +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Net; +using System.Net.Sockets; + +namespace ProxiFyre.Configuration +{ + /// + /// Global routing mode for conventional DNS (UDP and TCP port 53). + /// + public enum DnsRoutingMode + { + /// DNS bypasses every SOCKS5 proxy (default). + Direct, + + /// DNS is sent through one selected SOCKS5 proxy, or dropped; it never leaks direct. + Proxy + } + + /// + /// A parsed DNS server override. + /// + public sealed class DnsServerOverride + { + public const int DefaultPort = 53; + + internal DnsServerOverride(IPAddress address, int port) + { + Address = address; + Port = port; + } + + public IPAddress Address { get; } + + public int Port { get; } + + public bool IsIpv6 => Address.AddressFamily == AddressFamily.InterNetworkV6; + + public override string ToString() + { + var port = Port.ToString(CultureInfo.InvariantCulture); + return IsIpv6 ? "[" + Address + "]:" + port : Address + ":" + port; + } + } + + public enum DnsServerOverrideParseError + { + None, + Missing, + InvalidPort, + NotAnIpLiteral, + UnusableAddress + } + + /// + /// DNS configuration helpers shared by the service, validator, and GUI. They never perform + /// DNS resolution. + /// + public static class DnsConfiguration + { + public const string DirectMode = "Direct"; + public const string ProxyMode = "Proxy"; + + /// Maximum length of a proxy rule identifier. + public const int MaximumProxyIdLength = 64; + + /// + /// Returns the effective mode. A missing DNS section or mode means Direct. + /// + public static DnsRoutingMode GetMode(DnsSettings settings) + { + DnsRoutingMode mode; + return TryGetMode(settings == null ? null : settings.Mode, out mode) ? mode : DnsRoutingMode.Direct; + } + + /// + /// Parses a mode token case-insensitively. Null or whitespace is Direct. + /// + public static bool TryGetMode(string value, out DnsRoutingMode mode) + { + var candidate = value == null ? null : value.Trim(); + if (string.IsNullOrEmpty(candidate) || string.Equals(candidate, DirectMode, StringComparison.OrdinalIgnoreCase)) + { + mode = DnsRoutingMode.Direct; + return true; + } + + if (string.Equals(candidate, ProxyMode, StringComparison.OrdinalIgnoreCase)) + { + mode = DnsRoutingMode.Proxy; + return true; + } + + mode = DnsRoutingMode.Direct; + return false; + } + + /// + /// Proxy identifiers contain 1 to 64 letters, digits, '-', '_', or '.' characters. + /// + public static bool IsValidProxyId(string value) + { + if (string.IsNullOrEmpty(value) || value.Length > MaximumProxyIdLength) + return false; + return value.All(c => (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || + c == '-' || c == '_' || c == '.'); + } + + /// + /// Creates an identifier ("proxy-1", "proxy-2", ...) that does not collide, + /// case-insensitively, with . + /// + public static string CreateUniqueProxyId(IEnumerable existingIds) + { + var existing = new HashSet( + (existingIds ?? Enumerable.Empty()).Where(id => id != null).Select(id => id.Trim()), + StringComparer.OrdinalIgnoreCase); + for (var index = 1; ; index++) + { + var candidate = "proxy-" + index.ToString(CultureInfo.InvariantCulture); + if (!existing.Contains(candidate)) + return candidate; + } + } + + /// + /// Returns the index of the rule whose identifier equals + /// (case-insensitively, ignoring surrounding whitespace), or -1. + /// + public static int FindProxyRuleIndex(IList rules, string proxyId) + { + if (rules == null || string.IsNullOrWhiteSpace(proxyId)) + return -1; + var wanted = proxyId.Trim(); + for (var index = 0; index < rules.Count; index++) + { + var id = rules[index] == null ? null : rules[index].Id; + if (id != null && string.Equals(id.Trim(), wanted, StringComparison.OrdinalIgnoreCase)) + return index; + } + return -1; + } + + /// + /// Parses a DNS server override: "1.1.1.1", "1.1.1.1:5353", "2606:4700:4700::1111", + /// "[2606:4700:4700::1111]" or "[2606:4700:4700::1111]:5353". Host names are rejected so + /// the override can never require DNS resolution itself. The syntax matches the native + /// engine's split_dns_server_override(). + /// + public static bool TryParseServerOverride(string value, out DnsServerOverride result, out DnsServerOverrideParseError error) + { + result = null; + error = DnsServerOverrideParseError.None; + + if (string.IsNullOrWhiteSpace(value)) + { + error = DnsServerOverrideParseError.Missing; + return false; + } + + var candidate = value.Trim(); + string addressText; + var port = DnsServerOverride.DefaultPort; + bool expectIpv6; + + if (candidate.StartsWith("[", StringComparison.Ordinal)) + { + var closing = candidate.IndexOf(']'); + if (closing <= 1) + { + error = DnsServerOverrideParseError.NotAnIpLiteral; + return false; + } + + addressText = candidate.Substring(1, closing - 1); + var rest = candidate.Substring(closing + 1); + if (rest.Length > 0) + { + if (rest[0] != ':' || !TryParsePort(rest.Substring(1), out port)) + { + error = rest[0] == ':' ? DnsServerOverrideParseError.InvalidPort : DnsServerOverrideParseError.NotAnIpLiteral; + return false; + } + } + expectIpv6 = true; + } + else + { + var firstColon = candidate.IndexOf(':'); + if (firstColon < 0) + { + addressText = candidate; + expectIpv6 = false; + } + else if (candidate.IndexOf(':', firstColon + 1) < 0) + { + addressText = candidate.Substring(0, firstColon); + if (!TryParsePort(candidate.Substring(firstColon + 1), out port)) + { + error = DnsServerOverrideParseError.InvalidPort; + return false; + } + expectIpv6 = false; + } + else + { + addressText = candidate; + expectIpv6 = true; + } + } + + if (addressText.Length == 0 || addressText.Any(c => char.IsWhiteSpace(c) || c == '%' || c == '/' || c == '\\' || c == '[' || c == ']')) + { + error = DnsServerOverrideParseError.NotAnIpLiteral; + return false; + } + + IPAddress address; + if (!expectIpv6) + { + // IPAddress.TryParse accepts shorthand such as "1" or "1.1"; the native engine + // (inet_pton) accepts only four dotted-decimal parts, and .NET Framework reads a leading + // zero as octal, so require four plain decimal parts here. + var parts = addressText.Split('.'); + if (parts.Length != 4 || parts.Any(part => part.Length == 0 || part.Length > 3 || !part.All(c => c >= '0' && c <= '9') || + (part.Length > 1 && part[0] == '0')) || + !IPAddress.TryParse(addressText, out address) || address.AddressFamily != AddressFamily.InterNetwork) + { + error = DnsServerOverrideParseError.NotAnIpLiteral; + return false; + } + + var bytes = address.GetAddressBytes(); + if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.Broadcast) || (bytes[0] >= 224 && bytes[0] <= 239)) + { + error = DnsServerOverrideParseError.UnusableAddress; + return false; + } + } + else + { + if (!IPAddress.TryParse(addressText, out address) || address.AddressFamily != AddressFamily.InterNetworkV6) + { + error = DnsServerOverrideParseError.NotAnIpLiteral; + return false; + } + + if (address.Equals(IPAddress.IPv6Any) || address.IsIPv6Multicast || address.IsIPv4MappedToIPv6) + { + error = DnsServerOverrideParseError.UnusableAddress; + return false; + } + } + + result = new DnsServerOverride(address, port); + return true; + } + + private static bool TryParsePort(string text, out int port) + { + port = 0; + return text.Length > 0 && text.Length <= 5 && + int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out port) && + port >= 1 && port <= 65535; + } + } +} diff --git a/ProxiFyre.Configuration/Models.cs b/ProxiFyre.Configuration/Models.cs index 607bd0e..2a156ba 100644 --- a/ProxiFyre.Configuration/Models.cs +++ b/ProxiFyre.Configuration/Models.cs @@ -30,6 +30,13 @@ public ProxiFyreConfiguration() [JsonProperty("excludes")] public List Excludes { get; set; } + /// + /// Global DNS routing. Omitted (null) means Direct, which keeps configurations written + /// before DNS routing existed unchanged when they are loaded and saved again. + /// + [JsonProperty("dns", NullValueHandling = NullValueHandling.Ignore)] + public DnsSettings Dns { get; set; } + [JsonExtensionData] public IDictionary ExtensionData { get; set; } @@ -53,6 +60,14 @@ public ProxyRule() ExtensionData = new Dictionary(StringComparer.Ordinal); } + /// + /// Optional stable identifier used to reference this rule's SOCKS5 proxy from other + /// settings (for example ). Unlike the rule position it + /// survives reordering. Compared case-insensitively. + /// + [JsonProperty("id", NullValueHandling = NullValueHandling.Ignore, Order = -2)] + public string Id { get; set; } + [JsonProperty("appNames")] public List AppNames { get; set; } @@ -100,4 +115,37 @@ public string EffectiveTlsServerName } } } + + /// + /// Global DNS routing for conventional DNS (UDP and TCP port 53). + /// + public sealed class DnsSettings + { + public DnsSettings() + { + ExtensionData = new Dictionary(StringComparer.Ordinal); + } + + /// + /// "Direct" (default when omitted) or "Proxy". + /// + [JsonProperty("mode", NullValueHandling = NullValueHandling.Ignore)] + public string Mode { get; set; } + + /// + /// The of the rule whose SOCKS5 proxy carries DNS in Proxy mode. + /// + [JsonProperty("proxyId")] + public string ProxyId { get; set; } + + /// + /// Optional IPv4 or IPv6 literal, with an optional port, of the DNS server the SOCKS5 + /// proxy should query instead of the server the application addressed. + /// + [JsonProperty("serverOverride")] + public string ServerOverride { get; set; } + + [JsonExtensionData] + public IDictionary ExtensionData { get; set; } + } } diff --git a/ProxiFyre.Configuration/ProxiFyre.Configuration.csproj b/ProxiFyre.Configuration/ProxiFyre.Configuration.csproj index 8f6549f..9ab3463 100644 --- a/ProxiFyre.Configuration/ProxiFyre.Configuration.csproj +++ b/ProxiFyre.Configuration/ProxiFyre.Configuration.csproj @@ -73,6 +73,7 @@ + diff --git a/ProxiFyre.Tests/DnsConfigurationTests.cs b/ProxiFyre.Tests/DnsConfigurationTests.cs new file mode 100644 index 0000000..5706eb1 --- /dev/null +++ b/ProxiFyre.Tests/DnsConfigurationTests.cs @@ -0,0 +1,400 @@ +using Newtonsoft.Json.Linq; +using NUnit.Framework; +using ProxiFyre.Configuration; +using System.Collections.Generic; +using System.Linq; + +namespace ProxiFyre.Tests +{ + /// + /// DNS routing configuration: the JSON schema, stable proxy references, validation of the two + /// modes and the server override, and normalization. The engine-side packet routing is + /// covered by netlib/test/proxy/dns_routing_policy_test.cpp and + /// netlib/test/portable/dns_packet_redirect_test.cpp. + /// + [TestFixture] + public sealed class DnsConfigurationTests + { + private readonly ConfigurationSerializer _serializer = new ConfigurationSerializer(); + private readonly ConfigurationValidator _validator = new ConfigurationValidator(); + private readonly ConfigurationNormalizer _normalizer = new ConfigurationNormalizer(); + + private static ProxiFyreConfiguration TwoProxyConfiguration() + { + var first = TestModels.ValidRule(); + first.Id = "office"; + first.AppNames = new List { "browser" }; + first.Socks5ProxyEndpoint = "office.example.com:1080"; + + var second = TestModels.ValidRule(); + second.Id = "vpn"; + second.AppNames = new List { string.Empty }; + second.Socks5ProxyEndpoint = "vpn.example.com:1080"; + + var configuration = TestModels.ValidConfiguration(); + configuration.Proxies = new List { first, second }; + configuration.Dns = new DnsSettings { Mode = "Proxy", ProxyId = "vpn" }; + return configuration; + } + + // ---------------------------------------------------------------- 12. compatibility + + [Test] + public void ConfigurationWithoutDnsSettingsDefaultsToDirectAndStaysUnchanged() + { + const string json = "{ \"logLevel\": \"Info\", \"bypassLan\": true, \"proxies\": [ { \"appNames\": [\"chrome\"], " + + "\"socks5ProxyEndpoint\": \"proxy.example.com:1080\" } ], \"excludes\": [] }"; + + var configuration = _serializer.Deserialize(json); + + Assert.That(configuration.Dns, Is.Null); + Assert.That(configuration.Proxies[0].Id, Is.Null); + Assert.That(DnsConfiguration.GetMode(configuration.Dns), Is.EqualTo(DnsRoutingMode.Direct)); + Assert.That(_validator.Validate(configuration).HasErrors, Is.False); + + var saved = JObject.Parse(_serializer.Serialize(_normalizer.Normalize(configuration))); + Assert.That(saved.Property("dns"), Is.Null, "A legacy configuration must not gain a dns section."); + Assert.That(((JObject)saved["proxies"][0]).Property("id"), Is.Null, "Rules must not gain ids on load/save."); + } + + [TestCase(null)] + [TestCase("")] + [TestCase(" ")] + [TestCase("direct")] + [TestCase("DIRECT")] + public void MissingOrDirectModeIsDirect(string mode) + { + Assert.That(DnsConfiguration.GetMode(new DnsSettings { Mode = mode }), Is.EqualTo(DnsRoutingMode.Direct)); + } + + [Test] + public void ProxyModeIsCaseInsensitive() + { + Assert.That(DnsConfiguration.GetMode(new DnsSettings { Mode = " proxy " }), Is.EqualTo(DnsRoutingMode.Proxy)); + } + + // ---------------------------------------------------------------- serialization + + [Test] + public void DnsSettingsAndProxyIdsRoundTrip() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.ServerOverride = "1.1.1.1"; + + var json = _serializer.Serialize(configuration); + var copy = _serializer.Deserialize(json); + + Assert.That(copy.Dns.Mode, Is.EqualTo("Proxy")); + Assert.That(copy.Dns.ProxyId, Is.EqualTo("vpn")); + Assert.That(copy.Dns.ServerOverride, Is.EqualTo("1.1.1.1")); + CollectionAssert.AreEqual(new[] { "office", "vpn" }, copy.Proxies.Select(rule => rule.Id)); + + var root = JObject.Parse(json); + Assert.That(root["dns"]["mode"].Value(), Is.EqualTo("Proxy")); + Assert.That(root["dns"]["proxyId"].Value(), Is.EqualTo("vpn")); + Assert.That(root["dns"]["serverOverride"].Value(), Is.EqualTo("1.1.1.1")); + Assert.That(((JObject)root["proxies"][0]).Properties().First().Name, Is.EqualTo("id")); + } + + [Test] + public void UnknownDnsPropertiesSurviveRoundTrip() + { + const string json = "{ \"proxies\": [ { \"id\": \"p\", \"appNames\": [\"a\"], \"socks5ProxyEndpoint\": \"p.example.com:1080\" } ], " + + "\"dns\": { \"mode\": \"Proxy\", \"proxyId\": \"p\", \"futureSetting\": { \"x\": 1 } } }"; + + var copy = JObject.Parse(_serializer.Serialize(_normalizer.Normalize(_serializer.Deserialize(json)))); + + Assert.That(copy["dns"]["futureSetting"]["x"].Value(), Is.EqualTo(1)); + } + + [Test] + public void CloningARulePreservesItsId() + { + var rule = TestModels.ValidRule(); + rule.Id = "office"; + + Assert.That(_serializer.CloneRule(rule).Id, Is.EqualTo("office")); + } + + // ---------------------------------------------------------------- 5. explicit selection + + [Test] + public void ProxySelectionUsesTheStableIdAndSurvivesReordering() + { + var configuration = TwoProxyConfiguration(); + Assert.That(DnsConfiguration.FindProxyRuleIndex(configuration.Proxies, "vpn"), Is.EqualTo(1)); + + configuration.Proxies.Reverse(); + Assert.That(DnsConfiguration.FindProxyRuleIndex(configuration.Proxies, "vpn"), Is.EqualTo(0)); + Assert.That(configuration.Proxies[DnsConfiguration.FindProxyRuleIndex(configuration.Proxies, " VPN ")].Socks5ProxyEndpoint, + Is.EqualTo("vpn.example.com:1080")); + Assert.That(_validator.Validate(configuration).HasErrors, Is.False); + + var reloaded = _serializer.Deserialize(_serializer.Serialize(configuration)); + Assert.That(reloaded.Proxies[DnsConfiguration.FindProxyRuleIndex(reloaded.Proxies, reloaded.Dns.ProxyId)].Socks5ProxyEndpoint, + Is.EqualTo("vpn.example.com:1080")); + } + + [Test] + public void GeneratedIdsAreUniqueAndValid() + { + var id = DnsConfiguration.CreateUniqueProxyId(new[] { "proxy-1", "PROXY-2", null, "office" }); + + Assert.That(id, Is.EqualTo("proxy-3")); + Assert.That(DnsConfiguration.IsValidProxyId(id), Is.True); + Assert.That(DnsConfiguration.CreateUniqueProxyId(null), Is.EqualTo("proxy-1")); + } + + // ---------------------------------------------------------------- 13. invalid references + + [Test] + public void ValidProxyModeConfigurationHasNoErrors() + { + var result = _validator.Validate(TwoProxyConfiguration()); + + Assert.That(result.HasErrors, Is.False, string.Join("; ", result.Errors.Select(issue => issue.Code))); + Assert.That(result.Issues.Any(issue => issue.Code.StartsWith("DNS_")), Is.False); + } + + [Test] + public void ProxyModeRequiresAProxyId() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.ProxyId = " "; + + HasError(_validator.Validate(configuration), "DNS_PROXY_ID_MISSING", "dns.proxyId"); + } + + [Test] + public void UnknownProxyReferenceIsRejectedInsteadOfSwitchingProxies() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.ProxyId = "removed-proxy"; + + var issue = HasError(_validator.Validate(configuration), "DNS_PROXY_NOT_FOUND", "dns.proxyId"); + StringAssert.Contains("removed-proxy", issue.Message); + } + + [Test] + public void RemovingTheSelectedRuleLeavesADanglingReferenceThatIsReported() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies.RemoveAt(1); + + HasError(_validator.Validate(configuration), "DNS_PROXY_NOT_FOUND", "dns.proxyId"); + } + + [Test] + public void UnknownModeIsRejected() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.Mode = "Tunnel"; + + HasError(_validator.Validate(configuration), "DNS_MODE_UNKNOWN", "dns.mode"); + } + + [TestCase("TCP")] + [TestCase("UDP")] + public void SelectedProxyMustSupportTcpAndUdp(string onlyProtocol) + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[1].SupportedProtocols = new List { onlyProtocol }; + + HasError(_validator.Validate(configuration), "DNS_PROXY_PROTOCOLS_UNSUPPORTED", "dns.proxyId"); + } + + [Test] + public void LegacyOmittedProtocolsMeanBothAndAreAccepted() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[1].SupportedProtocols = null; + + Assert.That(_validator.Validate(configuration).Issues.Any(issue => issue.Code == "DNS_PROXY_PROTOCOLS_UNSUPPORTED"), Is.False); + } + + [TestCase("")] + [TestCase(" ")] + [TestCase("has space")] + [TestCase("slash/id")] + [TestCase("ünicode")] + public void InvalidProxyIdsAreRejected(string id) + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[0].Id = id; + + HasError(_validator.Validate(configuration), "PROXY_ID_INVALID", "proxies[0].id"); + } + + [Test] + public void TooLongProxyIdIsRejected() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[0].Id = new string('a', DnsConfiguration.MaximumProxyIdLength + 1); + + HasError(_validator.Validate(configuration), "PROXY_ID_INVALID", "proxies[0].id"); + } + + [Test] + public void DuplicateProxyIdsAreRejectedCaseInsensitively() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[1].Id = "OFFICE"; + configuration.Dns.ProxyId = "office"; + + var issue = HasError(_validator.Validate(configuration), "PROXY_ID_DUPLICATE", "proxies[1].id"); + Assert.That(issue.ProxyRuleIndex, Is.EqualTo(1)); + } + + [Test] + public void ProxyIdsAreValidatedInDirectModeToo() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns = null; + configuration.Proxies[1].Id = "office"; + + HasError(_validator.Validate(configuration), "PROXY_ID_DUPLICATE", "proxies[1].id"); + } + + // ---------------------------------------------------------------- 6. server override + + [TestCase("1.1.1.1", "1.1.1.1", 53, false)] + [TestCase(" 9.9.9.9:5353 ", "9.9.9.9", 5353, false)] + [TestCase("192.168.1.1", "192.168.1.1", 53, false)] + [TestCase("127.0.0.1", "127.0.0.1", 53, false)] + [TestCase("2606:4700:4700::1111", "2606:4700:4700::1111", 53, true)] + [TestCase("[2606:4700:4700::1111]", "2606:4700:4700::1111", 53, true)] + [TestCase("[2001:4860:4860::8888]:853", "2001:4860:4860::8888", 853, true)] + public void ServerOverrideLiteralsAreAccepted(string value, string address, int port, bool ipv6) + { + DnsServerOverride parsed; + DnsServerOverrideParseError error; + + Assert.That(DnsConfiguration.TryParseServerOverride(value, out parsed, out error), Is.True, error.ToString()); + Assert.That(parsed.Address.ToString(), Is.EqualTo(address)); + Assert.That(parsed.Port, Is.EqualTo(port)); + Assert.That(parsed.IsIpv6, Is.EqualTo(ipv6)); + } + + [TestCase("dns.example.com", DnsServerOverrideParseError.NotAnIpLiteral)] + [TestCase("dns.example.com:53", DnsServerOverrideParseError.NotAnIpLiteral)] + [TestCase("1", DnsServerOverrideParseError.NotAnIpLiteral)] + [TestCase("1.1", DnsServerOverrideParseError.NotAnIpLiteral)] + [TestCase("010.1.1.1", DnsServerOverrideParseError.NotAnIpLiteral)] + [TestCase("1.1.1.256", DnsServerOverrideParseError.NotAnIpLiteral)] + [TestCase("1.1.1.1:0", DnsServerOverrideParseError.InvalidPort)] + [TestCase("1.1.1.1:65536", DnsServerOverrideParseError.InvalidPort)] + [TestCase("1.1.1.1:abc", DnsServerOverrideParseError.InvalidPort)] + [TestCase("[::1]:0", DnsServerOverrideParseError.InvalidPort)] + [TestCase("[::1", DnsServerOverrideParseError.NotAnIpLiteral)] + [TestCase("[1.1.1.1]", DnsServerOverrideParseError.NotAnIpLiteral)] + [TestCase("fe80::1%12", DnsServerOverrideParseError.NotAnIpLiteral)] + [TestCase("0.0.0.0", DnsServerOverrideParseError.UnusableAddress)] + [TestCase("255.255.255.255", DnsServerOverrideParseError.UnusableAddress)] + [TestCase("224.0.0.251", DnsServerOverrideParseError.UnusableAddress)] + [TestCase("::", DnsServerOverrideParseError.UnusableAddress)] + [TestCase("ff02::fb", DnsServerOverrideParseError.UnusableAddress)] + [TestCase("::ffff:1.1.1.1", DnsServerOverrideParseError.UnusableAddress)] + public void InvalidServerOverridesAreRejected(string value, DnsServerOverrideParseError expected) + { + DnsServerOverride parsed; + DnsServerOverrideParseError error; + + Assert.That(DnsConfiguration.TryParseServerOverride(value, out parsed, out error), Is.False); + Assert.That(error, Is.EqualTo(expected)); + } + + [TestCase("dns.example.com", "DNS_SERVER_OVERRIDE_INVALID")] + [TestCase("1.1.1.1:0", "DNS_SERVER_OVERRIDE_PORT_INVALID")] + [TestCase("224.0.0.1", "DNS_SERVER_OVERRIDE_INVALID")] + public void InvalidServerOverrideIsAnError(string value, string code) + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.ServerOverride = value; + + HasError(_validator.Validate(configuration), code, "dns.serverOverride"); + } + + [Test] + public void ServerOverrideFamilyMustBeSupportedByTheSelectedProxy() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[1].SupportedAddressFamilies = new List { "IPv4" }; + configuration.Dns.ServerOverride = "2606:4700:4700::1111"; + + HasError(_validator.Validate(configuration), "DNS_SERVER_OVERRIDE_FAMILY_UNSUPPORTED", "dns.serverOverride"); + } + + [Test] + public void ServerOverrideWarnsThatTheOtherFamilyIsBlocked() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.ServerOverride = "1.1.1.1"; + + var result = _validator.Validate(configuration); + Assert.That(result.HasErrors, Is.False); + var warning = result.Warnings.Single(issue => issue.Code == "DNS_SERVER_OVERRIDE_OTHER_FAMILY_BLOCKED"); + StringAssert.Contains("IPv6", warning.Message); + } + + [Test] + public void ProxyWithoutIpv6WarnsThatIpv6DnsIsBlocked() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[1].SupportedAddressFamilies = new List { "IPv4" }; + + var result = _validator.Validate(configuration); + Assert.That(result.HasErrors, Is.False); + Assert.That(result.Warnings.Any(issue => issue.Code == "DNS_PROXY_FAMILY_BLOCKED"), Is.True); + } + + [Test] + public void ServerOverrideInDirectModeIsIgnoredWithAWarning() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.Mode = "Direct"; + configuration.Dns.ProxyId = "does-not-exist"; + configuration.Dns.ServerOverride = "1.1.1.1"; + + var result = _validator.Validate(configuration); + Assert.That(result.HasErrors, Is.False, "Proxy-only settings are not validated against rules in Direct mode."); + Assert.That(result.Warnings.Any(issue => issue.Code == "DNS_SERVER_OVERRIDE_IGNORED"), Is.True); + } + + // ---------------------------------------------------------------- normalization + + [Test] + public void NormalizationCanonicalizesDnsSettingsWithoutChangingMeaning() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[0].Id = " office "; + configuration.Dns = new DnsSettings { Mode = " proxy ", ProxyId = " vpn ", ServerOverride = " " }; + + var normalized = _normalizer.Normalize(configuration); + + Assert.That(normalized.Proxies[0].Id, Is.EqualTo("office")); + Assert.That(normalized.Dns.Mode, Is.EqualTo("Proxy")); + Assert.That(normalized.Dns.ProxyId, Is.EqualTo("vpn")); + Assert.That(normalized.Dns.ServerOverride, Is.Null); + Assert.That(_normalizer.Normalize(TestModels.ValidConfiguration()).Dns, Is.Null); + } + + [Test] + public void NormalizationKeepsAnUnknownModeVisibleForValidation() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.Mode = "Tunnel"; + + Assert.That(_normalizer.Normalize(configuration).Dns.Mode, Is.EqualTo("Tunnel")); + } + + private static ValidationIssue HasError(ValidationResult result, string code, string path) + { + var issue = result.Issues.FirstOrDefault(item => item.Code == code); + Assert.That(issue, Is.Not.Null, + "Expected " + code + "; found: " + string.Join(", ", result.Issues.Select(item => item.Code))); + Assert.That(issue.Severity, Is.EqualTo(ValidationSeverity.Error)); + Assert.That(issue.Path, Is.EqualTo(path)); + return issue; + } + } +} diff --git a/ProxiFyre.Tests/ProxiFyre.Tests.csproj b/ProxiFyre.Tests/ProxiFyre.Tests.csproj index df3a5b3..a2f36fa 100644 --- a/ProxiFyre.Tests/ProxiFyre.Tests.csproj +++ b/ProxiFyre.Tests/ProxiFyre.Tests.csproj @@ -84,6 +84,7 @@ + diff --git a/ProxiFyre/Program.cs b/ProxiFyre/Program.cs index 8e37fcc..7745837 100644 --- a/ProxiFyre/Program.cs +++ b/ProxiFyre/Program.cs @@ -116,8 +116,16 @@ public void Start() LoggerInstance.Info("LAN bypass enabled - local network traffic will not be proxied."); } + // Native proxy handle of each rule, index-aligned with serviceSettings.Proxies + // (-1 when the proxy could not be created). The DNS policy resolves its stable + // proxy id to a rule here, never by position in the native proxy list. + var proxyHandles = new IntPtr[serviceSettings.Proxies.Count]; + var ruleIndex = -1; + foreach (var appSettings in serviceSettings.Proxies) { + ruleIndex++; + proxyHandles[ruleIndex] = new IntPtr(-1); var protocolSelection = ConfigurationValueParser.GetProtocols(appSettings.SupportedProtocols); var addressFamilySelection = ConfigurationValueParser.GetAddressFamilies(appSettings.SupportedAddressFamilies); @@ -140,6 +148,8 @@ public void Start() continue; } + proxyHandles[ruleIndex] = proxy; + var protocols = appSettings.SupportedProtocols != null && appSettings.SupportedProtocols.Count > 0 ? string.Join(", ", appSettings.SupportedProtocols) : "TCP, UDP"; @@ -166,6 +176,8 @@ public void Start() } } + ConfigureDnsRouting(serviceSettings, proxyHandles); + // Start() propagates failure from the whole native chain (e.g. the Windows Packet // Filter driver is not installed or failed to load). Do NOT ignore it: swallowing // the failure leaves the Windows service in the RUNNING state while proxying nothing, @@ -189,6 +201,52 @@ public void Start() LoggerInstance.Info("ProxiFyre Service is running..."); } + /// + /// Applies the global DNS policy. In Proxy mode the selected proxy is resolved by its + /// stable id; when that proxy could not be created the engine is still put into Proxy + /// mode without a usable proxy so DNS is blocked rather than leaked or silently moved + /// to another proxy. + /// + private void ConfigureDnsRouting(ProxiFyreConfiguration settings, IntPtr[] proxyHandles) + { + if (DnsConfiguration.GetMode(settings.Dns) == DnsRoutingMode.Direct) + { + if (!_socksify.SetDnsRouting(DnsRoutingModeEnum.Direct, new IntPtr(-1), null)) + LoggerInstance.Warn("Failed to apply Direct DNS routing."); + else if (_logLevel >= LogLevel.Info) + LoggerInstance.Info("DNS routing: Direct - DNS (UDP/TCP port 53) bypasses the SOCKS5 proxies."); + return; + } + + var dns = settings.Dns; + var ruleIndex = DnsConfiguration.FindProxyRuleIndex(settings.Proxies, dns.ProxyId); + var handle = ruleIndex >= 0 && ruleIndex < proxyHandles.Length ? proxyHandles[ruleIndex] : new IntPtr(-1); + + if (handle.ToInt64() == -1) + { + LoggerInstance.Error( + $"DNS routing: the selected DNS proxy '{dns.ProxyId}' is not available because its SOCKS5 proxy could not be created. " + + "All DNS queries will be blocked instead of being sent directly or through another proxy."); + } + + if (!_socksify.SetDnsRouting(DnsRoutingModeEnum.Proxy, handle, dns.ServerOverride)) + { + LoggerInstance.Error( + "DNS routing: the engine rejected the Proxy mode configuration; DNS queries will be blocked. " + + "See the preceding engine log entries for the reason."); + return; + } + + if (_logLevel >= LogLevel.Info) + { + var serverOverride = string.IsNullOrWhiteSpace(dns.ServerOverride) + ? "original destinations" + : dns.ServerOverride; + LoggerInstance.Info( + $"DNS routing: Proxy via '{dns.ProxyId}' ({settings.Proxies[ruleIndex].Socks5ProxyEndpoint}), upstream DNS: {serverOverride}."); + } + } + /// /// Loads, validates, and normalizes app-config.json through the shared managed layer. /// Validation is dependency-free: this service owns logging and native enum mapping. diff --git a/ProxiFyreUI/Forms/MainForm.Designer.cs b/ProxiFyreUI/Forms/MainForm.Designer.cs index f94a77a..16fee7c 100644 --- a/ProxiFyreUI/Forms/MainForm.Designer.cs +++ b/ProxiFyreUI/Forms/MainForm.Designer.cs @@ -76,6 +76,15 @@ partial class MainForm private System.Windows.Forms.CheckBox bypassLanCheckBox; private System.Windows.Forms.Label bypassLanExplanationLabel; private System.Windows.Forms.CheckBox minimizeToTrayCheckBox; + private System.Windows.Forms.GroupBox dnsGroupBox; + private System.Windows.Forms.Label dnsModeLabel; + private System.Windows.Forms.ComboBox dnsModeComboBox; + private System.Windows.Forms.Label dnsProxyLabel; + private System.Windows.Forms.ComboBox dnsProxyComboBox; + private System.Windows.Forms.Label dnsServerOverrideLabel; + private System.Windows.Forms.TextBox dnsServerOverrideTextBox; + private System.Windows.Forms.Label dnsServerOverrideHintLabel; + private System.Windows.Forms.Label dnsExplanationLabel; private System.Windows.Forms.GroupBox diagnosticsGroupBox; private System.Windows.Forms.Label serviceNameLabel; private System.Windows.Forms.Label serviceNameValueLabel; @@ -189,6 +198,15 @@ private void InitializeComponent() this.configurationSettingsGroupBox = new System.Windows.Forms.GroupBox(); this.bypassLanExplanationLabel = new System.Windows.Forms.Label(); this.minimizeToTrayCheckBox = new System.Windows.Forms.CheckBox(); + this.dnsGroupBox = new System.Windows.Forms.GroupBox(); + this.dnsModeLabel = new System.Windows.Forms.Label(); + this.dnsModeComboBox = new System.Windows.Forms.ComboBox(); + this.dnsProxyLabel = new System.Windows.Forms.Label(); + this.dnsProxyComboBox = new System.Windows.Forms.ComboBox(); + this.dnsServerOverrideLabel = new System.Windows.Forms.Label(); + this.dnsServerOverrideTextBox = new System.Windows.Forms.TextBox(); + this.dnsServerOverrideHintLabel = new System.Windows.Forms.Label(); + this.dnsExplanationLabel = new System.Windows.Forms.Label(); this.bypassLanCheckBox = new System.Windows.Forms.CheckBox(); this.logLevelComboBox = new System.Windows.Forms.ComboBox(); this.logLevelLabel = new System.Windows.Forms.Label(); @@ -235,6 +253,7 @@ private void InitializeComponent() this.settingsTabPage.SuspendLayout(); this.diagnosticsGroupBox.SuspendLayout(); this.configurationSettingsGroupBox.SuspendLayout(); + this.dnsGroupBox.SuspendLayout(); this.engineSettingsGroupBox.SuspendLayout(); this.actionPanel.SuspendLayout(); this.statusStrip.SuspendLayout(); @@ -511,6 +530,7 @@ private void InitializeComponent() this.settingsTabPage.AutoScroll = true; this.settingsTabPage.Controls.Add(this.uninstallNoteLabel); this.settingsTabPage.Controls.Add(this.uninstallServiceButton); + this.settingsTabPage.Controls.Add(this.dnsGroupBox); this.settingsTabPage.Controls.Add(this.diagnosticsGroupBox); this.settingsTabPage.Controls.Add(this.configurationSettingsGroupBox); this.settingsTabPage.Controls.Add(this.engineSettingsGroupBox); @@ -552,8 +572,19 @@ private void InitializeComponent() this.architectureLabel.AutoSize = true; this.architectureLabel.Location = new System.Drawing.Point(14, 103); this.architectureLabel.Text = "Architecture:"; this.architectureValueLabel.AutoSize = true; this.architectureValueLabel.Location = new System.Drawing.Point(112, 103); this.architectureValueLabel.Text = "Unknown"; this.copyDiagnosticsButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.copyDiagnosticsButton.Location = new System.Drawing.Point(473, 25); this.copyDiagnosticsButton.Size = new System.Drawing.Size(151, 29); this.copyDiagnosticsButton.Text = "Copy diagnostics"; this.copyDiagnosticsButton.UseVisualStyleBackColor = true; this.copyDiagnosticsButton.Click += new System.EventHandler(this.CopyDiagnosticsButton_Click); - this.uninstallServiceButton.Location = new System.Drawing.Point(10, 362); this.uninstallServiceButton.Size = new System.Drawing.Size(125, 29); this.uninstallServiceButton.Text = "Uninstall service…"; this.uninstallServiceButton.UseVisualStyleBackColor = true; this.uninstallServiceButton.Click += new System.EventHandler(this.UninstallServiceButton_Click); - this.uninstallNoteLabel.AutoSize = true; this.uninstallNoteLabel.Location = new System.Drawing.Point(145, 369); this.uninstallNoteLabel.Text = "Uninstalling preserves " + ProxiFyre.Configuration.ProxiFyrePaths.ConfigurationFileName + ", its backup, and all log files."; + // DNS routing + this.dnsGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsGroupBox.Location = new System.Drawing.Point(10, 358); this.dnsGroupBox.Name = "dnsGroupBox"; this.dnsGroupBox.Size = new System.Drawing.Size(1078, 154); this.dnsGroupBox.TabIndex = 3; this.dnsGroupBox.TabStop = false; this.dnsGroupBox.Text = "DNS routing (UDP/TCP port 53)"; + this.dnsGroupBox.Controls.Add(this.dnsExplanationLabel); this.dnsGroupBox.Controls.Add(this.dnsServerOverrideHintLabel); this.dnsGroupBox.Controls.Add(this.dnsServerOverrideTextBox); this.dnsGroupBox.Controls.Add(this.dnsServerOverrideLabel); this.dnsGroupBox.Controls.Add(this.dnsProxyComboBox); this.dnsGroupBox.Controls.Add(this.dnsProxyLabel); this.dnsGroupBox.Controls.Add(this.dnsModeComboBox); this.dnsGroupBox.Controls.Add(this.dnsModeLabel); + this.dnsModeLabel.AutoSize = true; this.dnsModeLabel.Location = new System.Drawing.Point(13, 31); this.dnsModeLabel.Text = "DNS &mode:"; + this.dnsModeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.dnsModeComboBox.Items.AddRange(new object[] { "Direct", "Proxy" }); this.dnsModeComboBox.Location = new System.Drawing.Point(122, 27); this.dnsModeComboBox.Size = new System.Drawing.Size(108, 23); this.dnsModeComboBox.TabIndex = 1; this.dnsModeComboBox.SelectedIndexChanged += new System.EventHandler(this.DnsControlChanged); + this.dnsProxyLabel.AutoSize = true; this.dnsProxyLabel.Location = new System.Drawing.Point(250, 31); this.dnsProxyLabel.Text = "DNS &proxy:"; + this.dnsProxyComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsProxyComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.dnsProxyComboBox.Location = new System.Drawing.Point(340, 27); this.dnsProxyComboBox.Size = new System.Drawing.Size(723, 23); this.dnsProxyComboBox.TabIndex = 3; this.dnsProxyComboBox.SelectedIndexChanged += new System.EventHandler(this.DnsControlChanged); + this.dnsServerOverrideLabel.AutoSize = true; this.dnsServerOverrideLabel.Location = new System.Drawing.Point(13, 66); this.dnsServerOverrideLabel.Text = "&Server override:"; + this.dnsServerOverrideTextBox.Location = new System.Drawing.Point(122, 62); this.dnsServerOverrideTextBox.Size = new System.Drawing.Size(210, 23); this.dnsServerOverrideTextBox.TabIndex = 5; this.dnsServerOverrideTextBox.TextChanged += new System.EventHandler(this.DnsControlChanged); + this.dnsServerOverrideHintLabel.AutoSize = true; this.dnsServerOverrideHintLabel.ForeColor = System.Drawing.SystemColors.GrayText; this.dnsServerOverrideHintLabel.Location = new System.Drawing.Point(340, 66); this.dnsServerOverrideHintLabel.Text = "Optional IP literal, e.g. 1.1.1.1 or [2606:4700:4700::1111]:53. Empty keeps the server Windows queried."; + this.dnsExplanationLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsExplanationLabel.ForeColor = System.Drawing.SystemColors.GrayText; this.dnsExplanationLabel.Location = new System.Drawing.Point(13, 96); this.dnsExplanationLabel.Size = new System.Drawing.Size(1050, 50); this.dnsExplanationLabel.Text = "Direct: DNS bypasses the proxies. Proxy: DNS from every application, including the Windows DNS Client service, uses the selected proxy (which must support TCP and UDP), takes precedence over LAN bypass, and is blocked rather than sent directly if that proxy cannot carry it. Encrypted DNS (DoH/DoT) is not affected. Takes effect after service restart."; + this.uninstallServiceButton.Location = new System.Drawing.Point(10, 522); this.uninstallServiceButton.Size = new System.Drawing.Size(125, 29); this.uninstallServiceButton.Text = "Uninstall service…"; this.uninstallServiceButton.UseVisualStyleBackColor = true; this.uninstallServiceButton.Click += new System.EventHandler(this.UninstallServiceButton_Click); + this.uninstallNoteLabel.AutoSize = true; this.uninstallNoteLabel.Location = new System.Drawing.Point(145, 529); this.uninstallNoteLabel.Text = "Uninstalling preserves " + ProxiFyre.Configuration.ProxiFyrePaths.ConfigurationFileName + ", its backup, and all log files."; // action/status this.actionPanel.Controls.Add(this.operationProgressBar); this.actionPanel.Controls.Add(this.applyRestartButton); this.actionPanel.Controls.Add(this.saveButton); this.actionPanel.Controls.Add(this.validateButton); this.actionPanel.Controls.Add(this.reloadButton); this.actionPanel.Dock = System.Windows.Forms.DockStyle.Bottom; this.actionPanel.Location = new System.Drawing.Point(0, 617); this.actionPanel.Name = "actionPanel"; this.actionPanel.Size = new System.Drawing.Size(1114, 51); this.actionPanel.TabIndex = 2; this.reloadButton.Location = new System.Drawing.Point(12, 11); this.reloadButton.Size = new System.Drawing.Size(80, 29); this.reloadButton.Text = "Reload"; this.reloadButton.UseVisualStyleBackColor = true; this.reloadButton.Click += new System.EventHandler(this.ReloadButton_Click); @@ -601,6 +632,7 @@ private void InitializeComponent() this.settingsTabPage.ResumeLayout(false); this.settingsTabPage.PerformLayout(); this.diagnosticsGroupBox.ResumeLayout(false); this.diagnosticsGroupBox.PerformLayout(); this.configurationSettingsGroupBox.ResumeLayout(false); this.configurationSettingsGroupBox.PerformLayout(); + this.dnsGroupBox.ResumeLayout(false); this.dnsGroupBox.PerformLayout(); this.engineSettingsGroupBox.ResumeLayout(false); this.engineSettingsGroupBox.PerformLayout(); this.actionPanel.ResumeLayout(false); this.statusStrip.ResumeLayout(false); this.statusStrip.PerformLayout(); diff --git a/ProxiFyreUI/Forms/MainForm.cs b/ProxiFyreUI/Forms/MainForm.cs index cf309c9..f715a45 100644 --- a/ProxiFyreUI/Forms/MainForm.cs +++ b/ProxiFyreUI/Forms/MainForm.cs @@ -160,6 +160,7 @@ private void BindConfiguration() bypassLanCheckBox.Checked = configuration.BypassLan; RefreshRoutingGrid(); RefreshExclusionsList(); + BindDnsControls(); } finally { @@ -213,6 +214,134 @@ private void RefreshRoutingGrid(int selectIndex = -1) routingGrid.CurrentCell = routingGrid.Rows[selectIndex].Cells[0]; } UpdateRoutingButtons(); + RefreshDnsProxyChoices(); + } + + /// + /// One entry of the DNS proxy selector. The selection is stored as the rule's stable id, + /// so it survives reordering, editing, saving, and reloading. + /// + private sealed class DnsProxyChoice + { + public DnsProxyChoice(ProxyRule rule, string text) + { + Rule = rule; + Text = text; + } + + public ProxyRule Rule { get; } + + public string Text { get; } + + public override string ToString() => Text; + } + + private void BindDnsControls() + { + var dns = _workspace.Configuration?.Dns; + var previous = _suppressChanges; + _suppressChanges = true; + try + { + DnsRoutingMode mode; + DnsConfiguration.TryGetMode(dns?.Mode, out mode); + dnsModeComboBox.SelectedIndex = mode == DnsRoutingMode.Proxy ? 1 : 0; + dnsServerOverrideTextBox.Text = dns?.ServerOverride ?? string.Empty; + RefreshDnsProxyChoices(); + } + finally + { + _suppressChanges = previous; + } + UpdateDnsControlStates(); + } + + private void RefreshDnsProxyChoices() + { + var configuration = _workspace.Configuration; + var previous = _suppressChanges; + _suppressChanges = true; + try + { + dnsProxyComboBox.BeginUpdate(); + dnsProxyComboBox.Items.Clear(); + if (configuration?.Proxies == null) + return; + + var selectedId = configuration.Dns?.ProxyId; + var selectedIndex = -1; + for (var index = 0; index < configuration.Proxies.Count; index++) + { + var rule = configuration.Proxies[index]; + if (rule == null) + continue; + var text = "Rule " + (index + 1) + ": " + (rule.Socks5ProxyEndpoint ?? "(no endpoint)") + + " — " + FormatApplications(rule.AppNames) + + (string.IsNullOrWhiteSpace(rule.Id) ? string.Empty : " [id: " + rule.Id.Trim() + "]"); + var itemIndex = dnsProxyComboBox.Items.Add(new DnsProxyChoice(rule, text)); + if (!string.IsNullOrWhiteSpace(selectedId) && rule.Id != null && + string.Equals(rule.Id.Trim(), selectedId.Trim(), StringComparison.OrdinalIgnoreCase)) + selectedIndex = itemIndex; + } + + if (selectedIndex < 0 && !string.IsNullOrWhiteSpace(selectedId)) + { + // Keep a dangling reference visible instead of silently selecting another proxy. + selectedIndex = dnsProxyComboBox.Items.Add(new DnsProxyChoice(null, + "Missing proxy id '" + selectedId.Trim() + "' — select an existing rule")); + } + + dnsProxyComboBox.SelectedIndex = selectedIndex; + } + finally + { + dnsProxyComboBox.EndUpdate(); + _suppressChanges = previous; + } + } + + private void DnsControlChanged(object sender, EventArgs e) + { + UpdateDnsControlStates(); + var configuration = _workspace.Configuration; + if (_suppressChanges || ConfigurationMutationBlocked || configuration == null) + return; + + var dns = configuration.Dns ?? new DnsSettings(); + dns.Mode = dnsModeComboBox.SelectedIndex == 1 ? DnsConfiguration.ProxyMode : DnsConfiguration.DirectMode; + + if (ReferenceEquals(sender, dnsProxyComboBox) && + dnsProxyComboBox.SelectedItem is DnsProxyChoice choice && choice.Rule != null) + { + // Reference the rule by a stable id; assign one when the rule has none yet. + if (!DnsConfiguration.IsValidProxyId(choice.Rule.Id?.Trim())) + { + choice.Rule.Id = DnsConfiguration.CreateUniqueProxyId( + configuration.Proxies.Where(rule => rule != null).Select(rule => rule.Id)); + } + dns.ProxyId = choice.Rule.Id.Trim(); + } + + var serverOverride = dnsServerOverrideTextBox.Text.Trim(); + dns.ServerOverride = serverOverride.Length == 0 ? null : serverOverride; + configuration.Dns = dns; + MarkConfigurationChanged(); + + if (ReferenceEquals(sender, dnsProxyComboBox)) + BeginInvoke(new Action(RefreshDnsProxyChoices)); + } + + private void UpdateDnsControlStates() + { + var editable = !ConfigurationMutationBlocked && _workspace.Configuration != null; + var proxyMode = dnsModeComboBox.SelectedIndex == 1; + dnsModeComboBox.Enabled = editable; + // Settings that apply only to Proxy mode are disabled, not cleared, in Direct mode. + dnsProxyComboBox.Enabled = editable && proxyMode; + dnsServerOverrideTextBox.Enabled = editable && proxyMode; + dnsProxyLabel.Enabled = proxyMode; + dnsServerOverrideLabel.Enabled = proxyMode; + dnsServerOverrideHintLabel.Enabled = proxyMode; } private void RefreshExclusionsList(int selectIndex = -1) @@ -348,6 +477,8 @@ private void DuplicateRuleButton_Click(object sender, EventArgs e) return; var clone = new ConfigurationSerializer().CloneRule( _workspace.Configuration.Proxies[index]); + // Proxy ids are unique; the copy is a different proxy rule that DNS does not reference. + clone.Id = null; _workspace.Configuration.Proxies.Insert(index + 1, clone); MarkConfigurationChanged(); RefreshRoutingGrid(index + 1); @@ -1759,6 +1890,7 @@ private void UpdateAllStates() validateButton.Enabled = !_operationInProgress && _workspace.Configuration != null; logLevelComboBox.Enabled = !ConfigurationMutationBlocked && _workspace.Configuration != null; bypassLanCheckBox.Enabled = !ConfigurationMutationBlocked && _workspace.Configuration != null; + UpdateDnsControlStates(); trayExitMenuItem.Enabled = !_exitRequested && _configurationDialogDepth == 0; UpdateRoutingButtons(); UpdateExclusionButtons(); diff --git a/README.md b/README.md index ffe2a02..6e4f3f9 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ ProxiFyre transparently routes selected Windows applications—or all unmatched - Proxy IPv4 and IPv6 destinations over TCP, UDP, or both. - Choose normal SOCKS5 or TLS transport, with certificate validation and optional pinning. - Keep local network traffic direct with LAN bypass. +- Optionally send all conventional DNS (UDP/TCP port 53), including the Windows DNS Client's, through one selected proxy to prevent DNS leaks, without changing Windows DNS settings. - Configure, validate, apply, monitor, and troubleshoot through the Windows GUI. - Run unattended as `ProxiFyreService` with notification-area controls. @@ -86,7 +87,15 @@ The GUI edits `app-config.json` beside `ProxiFyre.exe`. A minimal configuration Rules are evaluated from top to bottom and the first match wins. Put the catch-all rule (`"appNames": [""]`) last; exclusions take priority over every routing rule. Unsupported destination address families are blocked rather than allowed to leak directly. -See the [configuration reference](docs/configuration.md) for matching rules, authentication, LAN bypass, logging, TLS options, and complete examples. The repository also includes a ready-to-edit [sample configuration](app-config.sample.json). +DNS (UDP/TCP port 53) bypasses the proxies by default. To prevent DNS leaks, give a rule an `id` and add a global DNS policy that sends all DNS through that proxy, optionally to a resolver the proxy can reach: + +```json +"dns": { "mode": "Proxy", "proxyId": "office", "serverOverride": "1.1.1.1" } +``` + +In `Proxy` mode DNS is never sent directly: if the selected proxy cannot carry a query, the query is dropped. See [DNS routing](docs/configuration.md#dns-routing) for the behavior, the TCP port 53 change in `Direct` mode, and limitations. + +See the [configuration reference](docs/configuration.md) for matching rules, authentication, LAN bypass, DNS routing, logging, TLS options, and complete examples. The repository also includes a ready-to-edit [sample configuration](app-config.sample.json). ## Windows GUI @@ -109,6 +118,7 @@ Set `socks5Transport` to `"TLS"` to protect the SOCKS5 TCP connection and UDP `A - The SOCKS5 server endpoint must be reachable over IPv4: use an IPv4 literal or a hostname with an A record. Destination traffic may still be IPv4, IPv6, or both. - IPv6 proxying requires working IPv6 connectivity on the client and a SOCKS5 server that accepts IPv6 targets (`ATYP=4`). ProxiFyre redirects packets the application emits; it does not create IPv6 connectivity. - Fragmented IPv6 datagrams are passed through directly to avoid corrupting partial packets. Applications that emit oversized fragmented UDP datagrams can therefore bypass the proxy. +- DNS routing covers conventional DNS on port 53 only. DNS over HTTPS/TLS/QUIC used internally by applications, mDNS, LLMNR, and loopback resolvers are not affected, and answers already in the Windows DNS cache are reused. - SOCKS5 usernames and passwords are stored in plaintext in `app-config.json`, although the GUI masks and redacts them from its diagnostics. - The MSI creates program-specific inbound TCP and UDP firewall rules for `ProxiFyre.exe` because redirect listener ports are allocated dynamically. diff --git a/app-config.sample.json b/app-config.sample.json index a97477c..9fe4220 100644 --- a/app-config.sample.json +++ b/app-config.sample.json @@ -3,6 +3,7 @@ "bypassLan": false, "proxies": [ { + "id": "primary", "appNames": ["chrome", "firefox"], "socks5ProxyEndpoint": "proxy.example.com:1080", "username": "REPLACE_WITH_USERNAME_OR_LEAVE_EMPTY", @@ -15,5 +16,10 @@ "supportedAddressFamilies": ["IPv4", "IPv6"] } ], - "excludes": [] + "excludes": [], + "dns": { + "mode": "Direct", + "proxyId": "primary", + "serverOverride": null + } } diff --git a/docs/configuration.md b/docs/configuration.md index 25d15d4..8f0d8b3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -24,6 +24,7 @@ Process ownership lookup is best effort for a standard user. ProxiFyre can route "bypassLan": true, "proxies": [ { + "id": "office", "appNames": ["chrome", "firefox"], "socks5ProxyEndpoint": "proxy.example.com:1080", "username": "example-user", @@ -46,7 +47,12 @@ Process ownership lookup is best effort for a standard user. ProxiFyre can route "excludes": [ "vpn-client.exe", "C:\\Program Files\\Local App\\NotProxied.exe" - ] + ], + "dns": { + "mode": "Proxy", + "proxyId": "office", + "serverOverride": "1.1.1.1" + } } ``` @@ -58,11 +64,13 @@ Process ownership lookup is best effort for a standard user. ProxiFyre can route | `bypassLan` | When `true`, supported local IPv4 ranges remain direct. Default: `false`. | | `proxies` | One or more ordered routing rules. The first matching rule wins. | | `excludes` | Process names or paths that always bypass proxy routing. | +| `dns` | Optional global DNS routing. Omitted means `Direct`. See [DNS routing](#dns-routing). | ## Routing rule properties | Property | Description | | --- | --- | +| `id` | Optional stable identifier used to reference this rule's proxy, for example from `dns.proxyId`. 1–64 letters, digits, `-`, `_`, or `.`; unique, case-insensitive. Unlike the rule position it survives reordering. | | `appNames` | Application names or paths matched by this rule. An explicit empty string is the catch-all. | | `socks5ProxyEndpoint` | SOCKS5 hostname or IPv4 address plus port, for example `proxy.example.com:1080`. | | `username`, `password` | Optional SOCKS5 authentication. Configure both or neither. | @@ -120,6 +128,79 @@ Set `bypassLan` to `true` to keep these local IPv4 destinations direct while mat Changing this setting requires a service restart. +In DNS `Proxy` mode, DNS takes precedence over LAN bypass: a query addressed to a LAN resolver such as `192.168.1.1:53` is still sent through the DNS proxy, while all other LAN traffic stays direct. See [DNS routing](#dns-routing). + +## DNS routing + +The optional `dns` object controls conventional DNS: UDP and TCP traffic to destination port 53, for IPv4 and IPv6. It is a global policy that applies to every process, independently of `appNames` rules and `excludes`. Windows normally resolves names in the DNS Client service (`Dnscache`, hosted by `svchost.exe`) rather than in the requesting application, so a per-application DNS rule could not be attributed reliably; ProxiFyre therefore does not try to. + +| Property | Description | +| --- | --- | +| `mode` | `Direct` (default when `dns` or `mode` is omitted) or `Proxy`, case-insensitive. | +| `proxyId` | Required in `Proxy` mode: the `id` of the proxy rule whose SOCKS5 proxy carries DNS. That rule must support both `TCP` and `UDP` (omitting `supportedProtocols` means both). | +| `serverOverride` | Optional, `Proxy` mode only: an IPv4 or IPv6 literal with an optional port that the SOCKS5 proxy queries instead of the server Windows addressed, for example `1.1.1.1`, `1.1.1.1:53`, `2606:4700:4700::1111`, or `[2606:4700:4700::1111]:53`. Host names are rejected so the override never needs DNS itself. | + +### Direct mode + +UDP and TCP DNS to port 53 bypass every SOCKS5 proxy for both address families, whatever process sends it. This is the behavior of configurations without a `dns` section. + +> **Behavior change:** earlier releases bypassed only UDP port 53. TCP port 53 was routed like any other TCP traffic of the owning process, so a catch-all rule could send it through a proxy. In `Direct` mode TCP/53 is now also always direct, so DNS uses one consistent path whether or not an answer was truncated. + +### Proxy mode + +All captured UDP and TCP DNS is sent through the selected proxy: UDP through a SOCKS5 `UDP ASSOCIATE`, TCP through a SOCKS5 `CONNECT`, reusing the same engine paths as application traffic. Queries from the Windows DNS Client service and from applications with their own resolvers are treated the same. + +ProxiFyre never falls back to sending DNS directly. DNS is dropped, and a warning is logged once per cause with a throttled count of dropped packets, when: + +- the selected proxy could not be created at startup, or the configuration is rejected by the engine; +- the SOCKS5 connection, authentication, TLS handshake, or `UDP ASSOCIATE` fails, or the proxy disconnects; +- the proxy does not accept the destination's address family (for example IPv6 DNS with an IPv4-only rule); +- a `serverOverride` is configured and the query is addressed to a server of the other address family (an IPv4 override blocks queries to IPv6 servers and vice versa; Windows then uses its other configured DNS servers); or +- the packet cannot be redirected, such as a fragmented datagram or a TCP connection to port 53 that was opened before ProxiFyre started. + +Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. + +The selection is made by `proxyId`, never by position, so reordering rules does not change the DNS proxy. If the referenced rule is removed or renamed, validation fails with `DNS_PROXY_NOT_FOUND`; ProxiFyre never silently switches to another proxy. The GUI assigns an id such as `proxy-1` to a rule when it is selected as the DNS proxy, and clears the id on a duplicated copy. + +### Server override + +Without `serverOverride`, each query keeps its original destination: the SOCKS5 server is asked to reach the DNS server Windows queried. That fails when Windows uses a local resolver, such as a home router at `192.168.1.1`, which the remote SOCKS5 server cannot reach. Set `serverOverride` to a resolver that is reachable from the SOCKS5 server, such as `1.1.1.1`. + +With an override, only the SOCKS5 destination changes: the `UDP ASSOCIATE` datagram header or the `CONNECT` target names the override, while the packets the application sees keep the original server address. For UDP, ProxiFyre remembers the original server for each query (by client port and DNS message ID, for 30 seconds) and presents the answer as coming from that server, because a resolver discards answers from an address it did not query. Answers relayed from the override that match no outstanding query are dropped. Checksums are recalculated on every rewritten packet. + +### Examples + +Direct (default; equivalent to omitting `dns`): + +```json +"dns": { "mode": "Direct" } +``` + +Proxy through the rule with `"id": "office"`, keeping the original DNS servers: + +```json +"dns": { "mode": "Proxy", "proxyId": "office" } +``` + +Proxy with an IPv4 override for a configuration that uses a router-provided resolver: + +```json +"dns": { "mode": "Proxy", "proxyId": "office", "serverOverride": "1.1.1.1" } +``` + +### Recursion and ProxiFyre's own traffic + +SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. Traffic addressed to a configured SOCKS5 server itself (TCP to its address and port, UDP to its address) is never redirected, even if the server listens on port 53. A consequence is that a DNS query addressed to the SOCKS5 server's own IP address is sent directly to that server. + +### Limitations + +- Only conventional DNS on port 53 is affected. DNS over HTTPS, DNS over TLS, DNS over QUIC, mDNS (5353), and LLMNR (5355) are outside the scope of this feature; applications that resolve names internally over encrypted transports (for example browsers with secure DNS enabled) are routed according to their ordinary application rules. +- ProxiFyre does not change Windows DNS adapter settings, does not disable or reconfigure the DNS Client service, and does not run its own resolver or cache. Answers already cached by Windows before the service started or before `Proxy` mode was enabled are still served from that cache; run `ipconfig /flushdns` after switching modes for an immediate effect. +- Only traffic visible to the Windows Packet Filter layer is captured. Loopback and local resolvers (for example a resolver on `127.0.0.1` or `::1`, or a resolver inside a local VM or container reached through a virtual adapter that is not filtered) are not routed, and their own upstream queries are subject to the same policy only if they leave through a filtered adapter. +- Each new UDP source port needs its own SOCKS5 control connection and `UDP ASSOCIATE`, as for application UDP traffic. The Windows DNS Client uses a fresh source port for most queries, so the first answer through the proxy is delayed by the SOCKS5 (and, for `TLS`, the TLS) handshake. +- When the service is stopped, packet filtering stops and all traffic, including DNS, is direct. +- Changing DNS settings requires a service restart. + ## Authentication Omit `username` and `password` when the SOCKS5 server does not require authentication. When authentication is enabled, both properties are required and each value must encode to no more than 255 bytes for the native SOCKS5 protocol. diff --git a/docs/gui.md b/docs/gui.md index a03b639..038fb41 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -58,6 +58,10 @@ The current engine reaches its upstream SOCKS5 server over IPv4, so an IPv6-lite SOCKS5-over-TLS protects the TCP control connection (including the UDP `ASSOCIATE` negotiation); it does not mean the SOCKS5 UDP relay payload is wrapped in that TLS stream. `tlsServerName` defaults to the endpoint host. Certificate fingerprints are normalized by removing whitespace, colons, and hyphens and must contain exactly 64 hexadecimal characters. A pinned leaf certificate can authenticate a self-signed lab endpoint. **Allow invalid certificate** disables normal certificate validation, requires an explicit confirmation, and is particularly dangerous without a pin. +### DNS routing + +The **DNS routing** group on the **Settings / Diagnostics** tab edits the global `dns` section described in the [configuration reference](configuration.md#dns-routing). **DNS mode** selects `Direct` (default) or `Proxy`. In `Direct` mode the **DNS proxy** and **Server override** fields are disabled but keep their values, so switching modes does not lose them. **DNS proxy** lists the routing rules by position, endpoint, and applications; selecting one stores that rule's stable `id` in `dns.proxyId`, assigning an id such as `proxy-1` to the rule if it has none. The reference therefore survives **Move Up**/**Move Down**, editing, saving, and reloading. **Duplicate** clears the id on the copy. If the referenced rule is removed, the selector shows the missing id and validation fails until another rule is chosen; the GUI never substitutes a different proxy. Validation also requires the selected rule to support both TCP and UDP and checks that the server override is an IP literal whose address family the rule accepts. Like other engine settings, DNS changes take effect after **Apply & Restart**. + ## Save, apply, conflicts, and recovery **Save** validates the complete model and refuses to write when errors exist. It writes a temporary file in the configuration directory, flushes it, preserves the prior live file as `app-config.json.bak`, and replaces the live file atomically. If the service is running, the UI reports that a restart is still required. @@ -151,3 +155,14 @@ On a Windows test machine with the appropriate driver and administrator access: 10. Hide the GUI to the notification area, launch `ProxiFyreUI.exe` again, and confirm the existing window is restored without creating a second tray icon. 11. Exit the GUI and confirm the service continues running. 12. On Windows 7 SP1 x64, launch the installed UI and confirm the main window is constructed without a managed startup failure before repeating the basic service-state checks. + +### DNS routing manual validation + +The routing policy and the packet rewriting are covered by automated tests (`netlib-tests` and `netlib/test/portable/run-portable-tests.sh`); the end-to-end path through the driver and a live SOCKS5 server needs a Windows test machine. Capture with Wireshark on the physical adapter and use `Resolve-DnsName -Server -DnsOnly` (UDP) and `Resolve-DnsName -TcpOnly` (TCP), running `ipconfig /flushdns` before each step: + +1. With no `dns` section (or `Direct`), confirm UDP and TCP queries to the system resolver and to `8.8.8.8` leave the adapter directly for IPv4 and IPv6, including with a catch-all rule. +2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). +3. Enable `bypassLan` with a router resolver (`192.168.x.1`): without an override the SOCKS5 server is asked for the router address; with `serverOverride: "1.1.1.1"` it is asked for `1.1.1.1` and `Resolve-DnsName` still reports answers from the router address. +4. Reorder the rules, Apply & Restart, and confirm DNS still uses the selected proxy. +5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; confirm the engine log shows one warning per cause and throttled drop counts. +6. Configure an IPv4 override with an IPv6 resolver and confirm IPv6 queries are dropped while IPv4 queries succeed. diff --git a/netlib-tests/netlib-tests.vcxproj b/netlib-tests/netlib-tests.vcxproj index 6b4fd3e..390b9cb 100644 --- a/netlib-tests/netlib-tests.vcxproj +++ b/netlib-tests/netlib-tests.vcxproj @@ -111,6 +111,7 @@ + diff --git a/netlib-tests/pch.h b/netlib-tests/pch.h index bcb3fa0..515be95 100644 --- a/netlib-tests/pch.h +++ b/netlib-tests/pch.h @@ -57,5 +57,6 @@ #include "../netlib/src/net/ip_endpoint.h" #include "../netlib/src/iphelper/process_lookup.h" #include "../netlib/src/proxy/process_routing_policy.h" +#include "../netlib/src/proxy/dns_routing_policy.h" #endif // PCH_H diff --git a/netlib/README.md b/netlib/README.md index af56c13..8a12320 100644 --- a/netlib/README.md +++ b/netlib/README.md @@ -87,3 +87,27 @@ Device-path conversion (`QueryDosDeviceW` in production) also goes through the ` completeness rule (`owner_identity::has_complete_device_path`) still decides what is memoized. No test depends on which drive letters exist on the host; `OwnerMemoMetadataTest` checks that the production source keeps the Windows conversion. + +## Portable native tests + +`netlib/test/portable/run-portable-tests.sh` builds and runs the platform-independent part of the +native tests with the host C++20 compiler, GoogleTest, and the Microsoft GSL headers (on Ubuntu: +`apt-get install g++ libgtest-dev libmsgsl-dev`). It runs on Linux and other non-Windows hosts and +in the `portable-native-tests` job of `.github/workflows/native-tests.yml`: + +```console +netlib/test/portable/run-portable-tests.sh +SANITIZE=1 netlib/test/portable/run-portable-tests.sh # AddressSanitizer + UndefinedBehaviorSanitizer +CXX=clang++ netlib/test/portable/run-portable-tests.sh +``` + +- `netlib/test/proxy/dns_routing_policy_test.cpp` covers the global DNS routing decisions, + DNS server override syntax, and the override answer bookkeeping (`dns_routing_policy.h`). It is + also part of `netlib-tests` on Windows. +- `netlib/test/portable/dns_packet_redirect_test.cpp` drives real Ethernet/IP/UDP/TCP frames + through the production `socks5_udp_local_redirect.h` and `tcp_local_redirect.h` exactly as the + router's DNS handlers do, and checks every rewritten field, the SOCKS5 UDP header sent to the + relay, the restored answer source, and independently verified checksums. `winshim/` supplies + the few Windows SDK declarations those headers need, and the script extracts the product + `CNdisApi` checksum routines verbatim from `ndisapi/ndisapi.cpp`. The Windows Packet Filter + driver, sockets, and the router class itself are not involved. diff --git a/netlib/src/ndisapi/socks5_udp_local_redirect.h b/netlib/src/ndisapi/socks5_udp_local_redirect.h index 039a3b9..ae7cb77 100644 --- a/netlib/src/ndisapi/socks5_udp_local_redirect.h +++ b/netlib/src/ndisapi/socks5_udp_local_redirect.h @@ -262,9 +262,14 @@ namespace ndisapi * * @param packet C2S network packet. * @param port Destination port to forward the packet to (network byte order). If 0, uses proxy_port_. + * @param socks_destination Optional destination (port in host byte order) written to the + * SOCKS5 UDP header instead of the packet's own destination. The IP header still + * records the original destination, so the response can be restored to it. Used + * for the DNS server override. * @return True if the packet was translated, false otherwise. */ - bool process_client_to_server_packet(INTERMEDIATE_BUFFER& packet, uint16_t port = 0) + bool process_client_to_server_packet(INTERMEDIATE_BUFFER& packet, uint16_t port = 0, + const std::optional>& socks_destination = std::nullopt) { if (port == 0) port = proxy_port_; @@ -339,8 +344,16 @@ namespace ndisapi socks5_udp_header_ptr->reserved = 0; socks5_udp_header_ptr->fragment = 0; socks5_udp_header_ptr->address_type = 1; - socks5_udp_header_ptr->dest_address = ip_header->ip_dst; - socks5_udp_header_ptr->dest_port = udp_header->th_dport; + if (socks_destination) + { + socks5_udp_header_ptr->dest_address = socks_destination->ip; + socks5_udp_header_ptr->dest_port = htons(socks_destination->port); + } + else + { + socks5_udp_header_ptr->dest_address = ip_header->ip_dst; + socks5_udp_header_ptr->dest_port = udp_header->th_dport; + } // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -425,8 +438,16 @@ namespace ndisapi socks5_udp_header_ptr->reserved = 0; socks5_udp_header_ptr->fragment = 0; socks5_udp_header_ptr->address_type = 4; // For IPv6 address type is 4 - socks5_udp_header_ptr->dest_address = ip_header->ip6_dst; - socks5_udp_header_ptr->dest_port = udp_header->th_dport; + if (socks_destination) + { + socks5_udp_header_ptr->dest_address = socks_destination->ip; + socks5_udp_header_ptr->dest_port = htons(socks_destination->port); + } + else + { + socks5_udp_header_ptr->dest_address = ip_header->ip6_dst; + socks5_udp_header_ptr->dest_port = udp_header->th_dport; + } // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -461,9 +482,13 @@ namespace ndisapi * addresses and ports as needed. * * @param packet S2C network packet. + * @param source_override Optional source endpoint (port in host byte order) presented to + * the client instead of the one in the relay's SOCKS5 UDP header. Used to restore + * the server the client originally queried when a DNS server override is active. * @return True if the packet was translated, false otherwise. */ - bool process_server_to_client_packet(INTERMEDIATE_BUFFER& packet) + bool process_server_to_client_packet(INTERMEDIATE_BUFFER& packet, + const std::optional>& source_override = std::nullopt) { if constexpr (auto* const eth_header = reinterpret_cast(packet.m_IBuffer); std::is_same_v< net::ip_address_v4, std::decay_t>) @@ -532,8 +557,16 @@ namespace ndisapi auto* udp_payload = reinterpret_cast(udp_header + 1); auto* socks5_udp_header_ptr = reinterpret_cast*>(udp_payload); - ip_header->ip_src = socks5_udp_header_ptr->dest_address; - udp_header->th_sport = socks5_udp_header_ptr->dest_port; + if (source_override) + { + ip_header->ip_src = source_override->ip; + udp_header->th_sport = htons(source_override->port); + } + else + { + ip_header->ip_src = socks5_udp_header_ptr->dest_address; + udp_header->th_sport = socks5_udp_header_ptr->dest_port; + } const auto udp_payload_size = static_cast(udp_length - sizeof(udphdr)); memmove(udp_payload, udp_payload + socks5_header_size, @@ -620,8 +653,16 @@ namespace ndisapi // Swap IP addresses std::swap(ip_header->ip6_dst, ip_header->ip6_src); - ip_header->ip6_src = socks5_udp_header_ptr->dest_address; - udp_header->th_sport = socks5_udp_header_ptr->dest_port; + if (source_override) + { + ip_header->ip6_src = source_override->ip; + udp_header->th_sport = htons(source_override->port); + } + else + { + ip_header->ip6_src = socks5_udp_header_ptr->dest_address; + udp_header->th_sport = socks5_udp_header_ptr->dest_port; + } const auto udp_payload_size = static_cast(udp_length - sizeof(udphdr)); memmove(udp_payload, udp_payload + socks5_header_size, diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h new file mode 100644 index 0000000..e94c90b --- /dev/null +++ b/netlib/src/proxy/dns_routing_policy.h @@ -0,0 +1,477 @@ +#pragma once + +// Global DNS routing policy used by socks_local_router's packet handlers. +// +// Everything in this header is deliberately free of Windows, driver, and socket types so the +// routing decisions, the DNS server override syntax, and the UDP response-origin bookkeeping +// can be unit tested on any platform without the Windows Packet Filter driver. The router +// supplies already-parsed packet fields and the state of the selected proxy; these helpers +// return what to do with the packet. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace proxy +{ + /// Conventional DNS destination port. Only this port is classified as DNS; payloads are + /// never inspected to classify traffic. + inline constexpr uint16_t dns_port = 53; + + /// Global DNS routing mode. + enum class dns_routing_mode : uint8_t + { + /// UDP/TCP traffic to port 53 bypasses every SOCKS5 proxy (default). + direct, + /// UDP/TCP traffic to port 53 is sent through one selected SOCKS5 proxy, or dropped. + proxy + }; + + /// What a packet handler does with a packet addressed to a destination port. + enum class dns_route_action : uint8_t + { + not_dns, ///< not conventional DNS: continue with the ordinary application routing + pass, ///< DNS that stays direct + proxy, ///< redirect to the selected proxy's local listener (dns_route_decision::listener_port) + block ///< DNS that must use the proxy but cannot: drop it, never send it direct + }; + + /// Why Proxy mode blocked a DNS packet; used for throttled diagnostics. + enum class dns_block_reason : uint8_t + { + none, + proxy_unavailable, ///< no usable proxy was selected (invalid reference or creation failure) + transport_unsupported, ///< the selected proxy does not carry this transport (TCP or UDP) + family_unsupported, ///< the selected proxy does not accept destinations of this family + listener_unavailable, ///< the local listener for this transport and family is not running + override_family_mismatch, ///< a server override of the other address family is configured + redirect_failed, ///< the packet could not be redirected (e.g. fragmented, oversized, + ///< or a TCP segment of a connection opened before ProxiFyre started) + count + }; + + /// Transport of the packet being classified. + enum class dns_transport : uint8_t { tcp, udp }; + + /// Address family of the packet being classified. + enum class dns_family : uint8_t { ipv4, ipv6 }; + + struct dns_route_decision + { + dns_route_action action{ dns_route_action::not_dns }; + dns_block_reason reason{ dns_block_reason::none }; + uint16_t listener_port{}; ///< local listener (host byte order) when action == proxy + }; + + /// What the selected DNS proxy offers to the transport and family being routed. + struct dns_proxy_target + { + bool selected{}; ///< a valid proxy is selected for DNS + bool transport_supported{}; ///< it carries this transport + bool family_supported{}; ///< it accepts destinations of this family + std::optional listener_port; ///< its local listener for this transport and family + bool override_configured{}; ///< a DNS server override is configured + bool override_family_matches{}; ///< the override has the family of this packet + }; + + /** + * @brief Decides how a captured outbound packet addressed to @p destination_port is routed. + * + * The decision depends only on the destination port, the global mode, and the selected + * proxy. It never depends on the process that sent the packet, so traffic from the Windows + * DNS Client service (svchost.exe) and from applications with their own resolvers is + * treated identically, independently of application rules and exclusions. + * + * @param destination_is_upstream The packet is addressed to one of ProxiFyre's own SOCKS5 + * upstream servers (recursion guard: ProxiFyre's own proxy traffic is never captured). + */ + [[nodiscard]] constexpr dns_route_decision decide_dns_route( + const dns_routing_mode mode, + const uint16_t destination_port, + const bool destination_is_upstream, + const dns_proxy_target& target) noexcept + { + if (destination_port != dns_port) + return { dns_route_action::not_dns, dns_block_reason::none, 0 }; + + if (mode == dns_routing_mode::direct || destination_is_upstream) + return { dns_route_action::pass, dns_block_reason::none, 0 }; + + const auto block = [](const dns_block_reason reason) constexpr + { + return dns_route_decision{ dns_route_action::block, reason, 0 }; + }; + + if (!target.selected) + return block(dns_block_reason::proxy_unavailable); + if (!target.transport_supported) + return block(dns_block_reason::transport_unsupported); + if (target.override_configured && !target.override_family_matches) + return block(dns_block_reason::override_family_mismatch); + if (!target.family_supported) + return block(dns_block_reason::family_unsupported); + if (!target.listener_port || *target.listener_port == 0) + return block(dns_block_reason::listener_unavailable); + + return { dns_route_action::proxy, dns_block_reason::none, *target.listener_port }; + } + + /// Human-readable text for a block reason (diagnostics only). + [[nodiscard]] constexpr const char* to_string(const dns_block_reason reason) noexcept + { + switch (reason) + { + case dns_block_reason::proxy_unavailable: + return "no usable SOCKS5 proxy is selected for DNS"; + case dns_block_reason::transport_unsupported: + return "the DNS proxy does not support this transport"; + case dns_block_reason::family_unsupported: + return "the DNS proxy does not support this destination address family"; + case dns_block_reason::listener_unavailable: + return "the DNS proxy's local listener for this transport and address family is not available"; + case dns_block_reason::override_family_mismatch: + return "the DNS server override belongs to the other address family"; + case dns_block_reason::redirect_failed: + return "the packet could not be redirected to the DNS proxy (fragmented, oversized, " + "not a DNS message, or part of a TCP connection opened before ProxiFyre started)"; + default: + return "unknown"; + } + } + + /// A DNS server override split into its literal address text and port. + struct dns_server_override_text + { + std::string address; ///< IPv4 or IPv6 literal text (brackets removed), not yet validated + uint16_t port{ dns_port }; + bool bracketed{}; ///< written as [address] or [address]:port + }; + + /** + * @brief Splits a DNS server override into address text and port without resolving names. + * + * Accepted forms: "1.1.1.1", "1.1.1.1:5353", "2606:4700:4700::1111", + * "[2606:4700:4700::1111]" and "[2606:4700:4700::1111]:5353". An unbracketed value + * containing more than one ':' is an IPv6 literal without a port. Whether the address + * text is a valid literal of the expected family is checked by the caller. + */ + [[nodiscard]] inline std::optional split_dns_server_override(std::string_view value) + { + const auto is_space = [](const char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; }; + while (!value.empty() && is_space(value.front())) + value.remove_prefix(1); + while (!value.empty() && is_space(value.back())) + value.remove_suffix(1); + + if (value.empty()) + return std::nullopt; + + const auto parse_port = [](const std::string_view text) -> std::optional + { + if (text.empty() || text.size() > 5) + return std::nullopt; + uint32_t port = 0; + for (const auto c : text) + { + if (c < '0' || c > '9') + return std::nullopt; + port = port * 10 + static_cast(c - '0'); + } + if (port == 0 || port > 65535) + return std::nullopt; + return static_cast(port); + }; + + dns_server_override_text result; + + if (value.front() == '[') + { + const auto closing = value.find(']'); + if (closing == std::string_view::npos || closing == 1) + return std::nullopt; + + result.address = std::string{ value.substr(1, closing - 1) }; + result.bracketed = true; + + const auto rest = value.substr(closing + 1); + if (!rest.empty()) + { + if (rest.front() != ':') + return std::nullopt; + const auto port = parse_port(rest.substr(1)); + if (!port) + return std::nullopt; + result.port = *port; + } + } + else + { + const auto first_colon = value.find(':'); + if (first_colon == std::string_view::npos) + { + result.address = std::string{ value }; + } + else if (value.find(':', first_colon + 1) == std::string_view::npos) + { + // Exactly one colon: IPv4 literal with a port. + const auto port = parse_port(value.substr(first_colon + 1)); + if (!port || first_colon == 0) + return std::nullopt; + result.address = std::string{ value.substr(0, first_colon) }; + result.port = *port; + } + else + { + // Several colons and no brackets: an IPv6 literal without a port. + result.address = std::string{ value }; + } + } + + if (result.address.empty() || + std::any_of(result.address.begin(), result.address.end(), + [&](const char c) { return is_space(c) || c == '[' || c == ']' || c == '/' || c == '\\' || c == '%'; })) + return std::nullopt; + + return result; + } + + /// Minimum size of a DNS message header (RFC 1035 section 4.1.1). + inline constexpr std::size_t dns_header_size = 12; + + /// Reads the DNS message ID used to map override responses back to their original server. + /// The payload is not used to classify traffic: classification is by port 53 only. + [[nodiscard]] constexpr std::optional dns_message_id(const uint8_t* payload, const std::size_t size) noexcept + { + if (payload == nullptr || size < dns_header_size) + return std::nullopt; + return static_cast((static_cast(payload[0]) << 8) | payload[1]); + } + + /** + * @brief Remembers, for UDP DNS queries rewritten to a server override, which server the + * application originally addressed. + * + * When a server override is configured, the SOCKS5 relay answers from the override server + * while the requesting resolver only accepts an answer from the server it queried. Each + * rewritten query records (client source port, DNS message ID) -> original server endpoint; + * the response carrying the same client port and message ID is restored to that endpoint + * before it is delivered. Entries expire after @p ttl and the table is bounded, so it cannot + * grow without limit under a flood of queries. Entries are not consumed by a lookup so that + * duplicate answers to a retransmitted query are restored consistently. + * + * Thread-safe. + * + * @tparam Endpoint Original server endpoint type (copyable). + */ + template + class dns_udp_origin_tracker + { + public: + using clock = std::chrono::steady_clock; + + explicit dns_udp_origin_tracker(const std::chrono::seconds ttl = std::chrono::seconds{ 30 }, + const std::size_t capacity = 8192) noexcept + : ttl_(ttl), capacity_(std::max(capacity, 1)) + { + } + + /// Records the original server of a query sent from @p client_port with @p message_id. + void remember(const uint16_t client_port, const uint16_t message_id, const Endpoint& original, + const clock::time_point now = clock::now()) + { + std::scoped_lock lock(lock_); + const auto key = make_key(client_port, message_id); + + if (const auto it = entries_.find(key); it != entries_.end()) + { + it->second = entry{ now, original }; + return; + } + + if (entries_.size() >= capacity_) + { + sweep_locked(now); + if (entries_.size() >= capacity_) + { + // Still full of live entries: evict the oldest one. Linear, but only reached + // when more than `capacity_` queries are outstanding within one TTL. + const auto oldest = std::min_element(entries_.begin(), entries_.end(), + [](const auto& left, const auto& right) { return left.second.created_at < right.second.created_at; }); + entries_.erase(oldest); + } + } + + entries_.emplace(key, entry{ now, original }); + } + + /// Returns the original server for a response to @p client_port with @p message_id. + [[nodiscard]] std::optional resolve(const uint16_t client_port, const uint16_t message_id, + const clock::time_point now = clock::now()) + { + std::scoped_lock lock(lock_); + const auto it = entries_.find(make_key(client_port, message_id)); + if (it == entries_.end()) + return std::nullopt; + + if (now - it->second.created_at > ttl_) + { + entries_.erase(it); + return std::nullopt; + } + + return it->second.original; + } + + /// Removes expired entries. + void sweep(const clock::time_point now = clock::now()) + { + std::scoped_lock lock(lock_); + sweep_locked(now); + } + + /// Removes every entry (router stop). + void clear() + { + std::scoped_lock lock(lock_); + entries_.clear(); + } + + [[nodiscard]] std::size_t size() const + { + std::scoped_lock lock(lock_); + return entries_.size(); + } + + private: + struct entry + { + clock::time_point created_at; + Endpoint original; + }; + + static constexpr uint32_t make_key(const uint16_t client_port, const uint16_t message_id) noexcept + { + return (static_cast(client_port) << 16) | message_id; + } + + void sweep_locked(const clock::time_point now) + { + for (auto it = entries_.begin(); it != entries_.end();) + { + if (now - it->second.created_at > ttl_) + it = entries_.erase(it); + else + ++it; + } + } + + mutable std::mutex lock_; + std::unordered_map entries_; + std::chrono::seconds ttl_; + std::size_t capacity_; + }; + + /// SOCKS5 UDP request/reply header fields (RFC 1928 section 7) of a relayed datagram. + struct socks5_udp_datagram_view + { + uint8_t address_type{}; ///< ATYP: 1 = IPv4, 4 = IPv6 + const uint8_t* address{}; ///< DST.ADDR (network byte order) + std::size_t address_size{}; ///< 4 or 16 + uint16_t port{}; ///< DST.PORT (host byte order) + const uint8_t* data{}; ///< DATA following the header + std::size_t data_size{}; + }; + + /** + * @brief Parses the SOCKS5 UDP header of a datagram relayed by a SOCKS5 server. + * @return std::nullopt for a short buffer, a non-zero RSV or FRAG field, or an address type + * other than IPv4/IPv6 literals. + */ + [[nodiscard]] constexpr std::optional parse_socks5_udp_datagram( + const uint8_t* datagram, const std::size_t size) noexcept + { + if (datagram == nullptr || size < 4 || datagram[0] != 0 || datagram[1] != 0 || datagram[2] != 0) + return std::nullopt; + + socks5_udp_datagram_view view; + view.address_type = datagram[3]; + if (view.address_type == 1) + view.address_size = 4; + else if (view.address_type == 4) + view.address_size = 16; + else + return std::nullopt; + + const auto header_size = 4 + view.address_size + 2; + if (size < header_size) + return std::nullopt; + + view.address = datagram + 4; + view.port = static_cast((static_cast(datagram[4 + view.address_size]) << 8) | + datagram[4 + view.address_size + 1]); + view.data = datagram + header_size; + view.data_size = size - header_size; + return view; + } + + /// How a datagram leaving a local UDP proxy listener is presented to the client. + enum class dns_reply_restore : uint8_t + { + unchanged, ///< not a DNS override answer: present the relay's SOCKS5 header source + restore, ///< DNS override answer: present it as coming from the original server + drop ///< DNS override answer to no known query: drop it + }; + + /** + * @brief Classifies a datagram relayed back by the DNS proxy while a server override is + * configured, and finds the server the resolver originally queried. + * + * Only an answer whose SOCKS5 header names the override server (address and port) is + * treated as a DNS override answer; anything else relayed through the same proxy is left + * unchanged. An override answer is restored to the original server recorded for + * (@p client_port, DNS message ID), or dropped when there is no such query: delivering it + * from the override address would only be rejected by the resolver. + * + * @param socks_datagram The UDP payload as relayed: SOCKS5 UDP header followed by the DNS message. + * @param expected_address_type 1 for the IPv4 path, 4 for the IPv6 path. + * @param override_address The override address bytes (network byte order). + */ + template + [[nodiscard]] std::pair> classify_dns_override_reply( + const uint8_t* socks_datagram, const std::size_t size, const uint8_t expected_address_type, + const uint8_t* override_address, const std::size_t override_address_size, const uint16_t override_port, + const uint16_t client_port, dns_udp_origin_tracker& origins) + { + const auto view = parse_socks5_udp_datagram(socks_datagram, size); + if (!view || view->address_type != expected_address_type || view->address_size != override_address_size || + view->port != override_port || + !std::equal(view->address, view->address + view->address_size, override_address)) + return { dns_reply_restore::unchanged, std::nullopt }; + + const auto message_id = dns_message_id(view->data, view->data_size); + if (!message_id) + return { dns_reply_restore::drop, std::nullopt }; + + if (auto original = origins.resolve(client_port, *message_id)) + return { dns_reply_restore::restore, std::move(original) }; + + return { dns_reply_restore::drop, std::nullopt }; + } + + // Compile-time checks of the decision table's key invariants. + static_assert(decide_dns_route(dns_routing_mode::direct, 443, false, {}).action == dns_route_action::not_dns, + "Non-DNS traffic must keep its ordinary routing."); + static_assert(decide_dns_route(dns_routing_mode::direct, dns_port, false, {}).action == dns_route_action::pass, + "Direct mode must pass DNS without consulting a proxy."); + static_assert(decide_dns_route(dns_routing_mode::proxy, dns_port, false, {}).action == dns_route_action::block, + "Proxy mode without a usable proxy must fail closed."); + static_assert(decide_dns_route(dns_routing_mode::proxy, dns_port, true, {}).action == dns_route_action::pass, + "ProxiFyre's own upstream traffic must never be captured recursively."); +} diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index c8a2392..00a6b6a 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -1,6 +1,7 @@ #pragma once #include "process_routing_policy.h" +#include "dns_routing_policy.h" namespace proxy { @@ -74,6 +75,26 @@ namespace proxy std::string host; }; + /** + * @brief Global DNS routing configuration (see set_dns_routing()). + */ + struct dns_routing_settings + { + /// Direct (default) keeps UDP/TCP port 53 traffic off every proxy; Proxy sends it + /// through proxy_id or drops it. + dns_routing_mode mode{ dns_routing_mode::direct }; + + /// Index returned by add_socks5_proxy() of the proxy that carries DNS in Proxy mode. + /// std::nullopt in Proxy mode means no proxy is usable: every DNS packet is dropped. + std::optional proxy_id; + + /// Optional upstream DNS server used instead of the destination the application + /// queried: an IPv4 or IPv6 literal with an optional port ("1.1.1.1", + /// "1.1.1.1:53", "2606:4700:4700::1111", "[2606:4700:4700::1111]:53"). Empty keeps + /// the original destination. Host names are rejected to avoid recursive resolution. + std::string server_override; + }; + private: static bool protocol_supports_tcp(const supported_protocols protocols) noexcept { @@ -227,6 +248,48 @@ namespace proxy */ std::vector proxy_address_families_; + /** + * @brief Upstream SOCKS5 server endpoint of each proxy, index-aligned with proxy_servers_. + * Used by the DNS policy so ProxiFyre's own upstream traffic is never captured. + */ + std::vector> proxy_upstreams_; + + /** + * @brief Global DNS routing state. Written only by set_dns_routing() while the router is + * inactive (under lifecycle_mutex_ and lock_); read by the packet handlers under + * lock_. + */ + dns_routing_mode dns_mode_{ dns_routing_mode::direct }; + std::optional dns_proxy_id_; + std::optional> dns_server_override_v4_; + std::optional> dns_server_override_v6_; + + /** + * @brief Original server of each UDP DNS query rewritten to the server override, so the + * answer can be restored to the server the resolver actually queried. + */ + dns_udp_origin_tracker> dns_udp_origins_v4_; + dns_udp_origin_tracker> dns_udp_origins_v6_; + + /** + * @brief True once the static driver filters that keep port-53 traffic (and the DNS + * proxy's own local replies) in user mode, ahead of the LAN-bypass PASS filters, + * have been installed. + */ + bool dns_filters_installed_{ false }; + + /** + * @brief Count of DNS packets dropped by the Proxy-mode policy since the last + * throttled report from the resolver thread. + */ + std::atomic dns_blocked_packets_{ 0 }; + + /** + * @brief One-shot flags so that each (family, transport, reason) block cause is + * described once in the log instead of once per packet. + */ + std::array(dns_block_reason::count) * 4> dns_block_reason_logged_{}; + /** * @brief Maps proxy indexes to their corresponding process names (sorted by proxy ID). */ @@ -505,6 +568,42 @@ namespace proxy return udp_mapper_v6_lock_; } + template + auto& tcp_redirect_for() noexcept + { + if constexpr (std::is_same_v) + return *tcp_redirect_; + else + return *tcp_redirect_v6_; + } + + template + auto& udp_redirect_for() noexcept + { + if constexpr (std::is_same_v) + return *udp_redirect_; + else + return *udp_redirect_v6_; + } + + template + auto& dns_udp_origins_for() noexcept + { + if constexpr (std::is_same_v) + return dns_udp_origins_v4_; + else + return dns_udp_origins_v6_; + } + + template + const std::optional>& dns_server_override_for() const noexcept + { + if constexpr (std::is_same_v) + return dns_server_override_v4_; + else + return dns_server_override_v6_; + } + public: /** * The socks_local_router class constructor, used to set up a local router to handle SOCKS traffic. @@ -857,6 +956,15 @@ namespace proxy if (udp) udp->stop(); + // Proxy-mode DNS must take precedence over the LAN-bypass PASS filters; install the + // front-of-table REDIRECT filters once the DNS proxy's listener ports are known. + dns_udp_origins_v4_.clear(); + dns_udp_origins_v6_.clear(); + dns_blocked_packets_.store(0, std::memory_order_relaxed); + for (auto& flag : dns_block_reason_logged_) + flag.clear(std::memory_order_relaxed); + install_dns_filters(); + process_resolve_thread_ = std::thread(&socks_local_router::process_resolve_thread_proc, this); // Update network configuration and start filter @@ -1064,6 +1172,8 @@ namespace proxy { add_lan_passover_filters_v4(); add_lan_passover_filters_v6(); + // In DNS Proxy mode, start() inserts port-53 REDIRECT filters ahead of these PASS + // filters, so DNS addressed to LAN resolvers is still proxied. } /** @@ -1420,6 +1530,7 @@ namespace proxy proxy_servers_v6_.reserve(proxy_servers_v6_.size() + 1); proxy_protocols_.reserve(proxy_protocols_.size() + 1); proxy_address_families_.reserve(proxy_address_families_.size() + 1); + proxy_upstreams_.reserve(proxy_upstreams_.size() + 1); } // Install PASS filters only for upstream addresses selected by @@ -1536,6 +1647,7 @@ namespace proxy std::move(socks_tcp_proxy_server_v6), std::move(socks_udp_proxy_server_v6)); proxy_protocols_.push_back(protocols); proxy_address_families_.push_back(address_families); + proxy_upstreams_.push_back(*proxy_endpoint->ipv4); return proxy_servers_.size() - 1; // Return the index of the added proxy server } @@ -1637,6 +1749,151 @@ namespace proxy return true; } + /** + * @brief Configures the global DNS routing policy. Must be called before start(). + * + * Direct mode lets UDP and TCP traffic to port 53 bypass every proxy, for both address + * families and independently of application rules. + * + * Proxy mode sends all captured UDP and TCP traffic to port 53, whatever process sent + * it (including the Windows DNS Client service), through the proxy @p settings.proxy_id + * using the existing SOCKS5 UDP ASSOCIATE and TCP CONNECT paths. The policy fails + * closed: when the selected proxy cannot carry a query (invalid reference, missing + * transport, unsupported address family, listener unavailable, or SOCKS5 failure) the + * query is dropped and never sent direct. Port-53 traffic takes precedence over LAN + * bypass in this mode. + * + * An invalid configuration is rejected with a logged reason, and the router is left in + * Proxy mode with no usable proxy so DNS is blocked rather than leaked. + * + * @return true when the configuration was applied as requested; false when it was + * rejected (Proxy mode then blocks DNS) or the router is already running. + */ + bool set_dns_routing(const dns_routing_settings& settings) + { + std::scoped_lock lifecycle_lock(lifecycle_mutex_); + + if (is_active_.load(std::memory_order_acquire)) + { + NETLIB_LOG(log_level::error, "DNS routing cannot be changed while the router is running."); + return false; + } + + std::scoped_lock lock(lock_); + + dns_mode_ = settings.mode; + dns_proxy_id_.reset(); + dns_server_override_v4_.reset(); + dns_server_override_v6_.reset(); + + if (settings.mode == dns_routing_mode::direct) + { + NETLIB_LOG(log_level::info, "DNS routing: Direct (UDP/TCP port 53 bypasses the SOCKS5 proxies)."); + return true; + } + + // From here on dns_proxy_id_ stays empty (fail closed: all DNS is dropped) unless the + // whole configuration is valid. + const auto reject = [this](const std::string& reason) + { + NETLIB_LOG(log_level::error, + "DNS routing: Proxy mode configuration rejected: {} All DNS queries will be blocked " + "instead of being sent directly.", reason); + return false; + }; + + if (!settings.proxy_id) + return reject("no SOCKS5 proxy is available for DNS (the selected proxy was not created)."); + + const auto proxy_id = *settings.proxy_id; + if (proxy_id >= proxy_servers_.size() || proxy_id >= proxy_protocols_.size()) + return reject("proxy index " + std::to_string(proxy_id) + " does not refer to a configured proxy."); + + if (proxy_protocols_[proxy_id] != supported_protocols::both) + return reject("the selected proxy must support both TCP and UDP (DNS uses UDP and falls back to TCP)."); + + const auto families = proxy_id < proxy_address_families_.size() + ? proxy_address_families_[proxy_id] + : supported_address_families::all; + + if (!settings.server_override.empty()) + { + const auto parsed = parse_dns_server_override(settings.server_override); + if (!parsed) + { + return reject("the DNS server override '" + settings.server_override + + "' is not an IPv4 or IPv6 literal with an optional port."); + } + + if (std::holds_alternative>(*parsed)) + { + if (!family_supports_ipv4(families)) + return reject("the DNS server override is IPv4 but the selected proxy does not accept IPv4 destinations."); + dns_server_override_v4_ = std::get>(*parsed); + } + else + { + if (!family_supports_ipv6(families)) + return reject("the DNS server override is IPv6 but the selected proxy does not accept IPv6 destinations."); + dns_server_override_v6_ = std::get>(*parsed); + } + } + + dns_proxy_id_ = proxy_id; + + const auto upstream = proxy_id < proxy_upstreams_.size() + ? proxy_upstreams_[proxy_id].to_string() + : std::string{ "unknown" }; + const auto override_text = dns_server_override_v4_ + ? dns_server_override_v4_->to_string() + : dns_server_override_v6_ + ? "[" + dns_server_override_v6_->ip_to_string() + "]:" + dns_server_override_v6_->port_to_string() + : std::string{ "none (original destinations are kept)" }; + + NETLIB_LOG(log_level::info, + "DNS routing: Proxy via SOCKS5 proxy #{} ({}); server override: {}.", + proxy_id, upstream, override_text); + + if (dns_server_override_v4_ || dns_server_override_v6_) + { + NETLIB_LOG(log_level::info, + "DNS routing: queries addressed to {} servers are blocked because the server override is {}.", + dns_server_override_v4_ ? "IPv6" : "IPv4", dns_server_override_v4_ ? "IPv4" : "IPv6"); + } + + return true; + } + + /** + * @brief Parses a DNS server override literal without resolving host names. + * @return the IPv4 or IPv6 endpoint, or std::nullopt when @p value is not a literal. + */ + static std::optional, net::ip_endpoint>> + parse_dns_server_override(const std::string& value) + { + const auto text = split_dns_server_override(value); + if (!text) + return std::nullopt; + + if (!text->bracketed && text->address.find(':') == std::string::npos) + { + in_addr address{}; + if (inet_pton(AF_INET, text->address.c_str(), &address) != 1) + return std::nullopt; + const auto host_order = ntohl(address.S_un.S_addr); + if (host_order == 0 || host_order == 0xffffffffu || (host_order & 0xf0000000u) == 0xe0000000u) + return std::nullopt; + return net::ip_endpoint{ net::ip_address_v4{ address }, text->port }; + } + + in6_addr address{}; + if (inet_pton(AF_INET6, text->address.c_str(), &address) != 1) + return std::nullopt; + if (IN6_IS_ADDR_UNSPECIFIED(&address) || IN6_IS_ADDR_MULTICAST(&address) || IN6_IS_ADDR_V4MAPPED(&address)) + return std::nullopt; + return net::ip_endpoint{ net::ip_address_v6{ address }, text->port }; + } + /** * Resolves a proxy endpoint into the first usable address of each family. * Hostnames use AF_UNSPEC so an A record can be found even when DNS returns @@ -1899,6 +2156,370 @@ namespace proxy }); } + // --------------------------------------------------------------------------------- + // Global DNS policy (see set_dns_routing() and dns_routing_policy.h) + // --------------------------------------------------------------------------------- + + /** + * @brief Local listener port of the DNS proxy for @p Transport and family @p AddrT. + * The caller holds lock_. + */ + template + std::optional dns_listener_port_locked() const + { + if (!dns_proxy_id_) + return std::nullopt; + + const auto listener = [id = *dns_proxy_id_](const auto& servers) -> std::optional + { + if (id >= servers.size()) + return std::nullopt; + if constexpr (Transport == dns_transport::tcp) + return servers[id].first ? std::optional{ servers[id].first->proxy_port() } : std::nullopt; + else + return servers[id].second ? std::optional{ servers[id].second->proxy_port() } : std::nullopt; + }; + + if constexpr (std::is_same_v) + return listener(proxy_servers_); + else + return listener(proxy_servers_v6_); + } + + /** + * @brief True when @p destination (and, for TCP, @p port) is one of ProxiFyre's own + * SOCKS5 upstream servers. Such traffic is never captured by the DNS policy so a + * SOCKS5 server listening on port 53 cannot cause a redirect loop. UDP is matched by + * address only because a UDP ASSOCIATE relay port is unrelated to the configured + * port; this mirrors the upstream PASS filters installed by add_socks5_proxy(). + * The caller holds lock_. + */ + template + bool is_upstream_destination_locked(const AddrT& destination, const uint16_t port) const + { + return std::ranges::any_of(proxy_upstreams_, [&](const net::ip_endpoint& upstream) + { + if (Transport == dns_transport::tcp && upstream.port != port) + return false; + + if constexpr (std::is_same_v) + { + return destination == upstream.ip; + } + else + { + // Dual-stack IPv6 listeners reach the IPv4 upstream through its IPv4-mapped form. + in6_addr mapped{}; + mapped.u.Byte[10] = 0xff; + mapped.u.Byte[11] = 0xff; + const in_addr v4 = upstream.ip; + memcpy(&mapped.u.Byte[12], &v4, sizeof(v4)); + return destination == net::ip_address_v6{ mapped }; + } + }); + } + + /// Routing decision plus the effective upstream destination of a DNS packet. + template + struct dns_route + { + dns_route_decision decision; + std::optional> server_override; ///< set when the destination is rewritten + }; + + /** + * @brief Applies the global DNS policy to an outbound packet addressed to + * @p destination : @p destination_port. Non-DNS packets return not_dns without + * taking any lock. + */ + template + dns_route decide_dns(const AddrT& destination, const uint16_t destination_port) + { + if (destination_port != dns_port) + return {}; + + std::shared_lock lock(lock_); + + if (dns_mode_ == dns_routing_mode::direct) + return { decide_dns_route(dns_mode_, destination_port, false, {}), std::nullopt }; + + constexpr auto v4 = std::is_same_v; + + dns_proxy_target target; + target.selected = dns_proxy_id_.has_value() && *dns_proxy_id_ < proxy_protocols_.size(); + if (target.selected) + { + const auto id = *dns_proxy_id_; + target.transport_supported = Transport == dns_transport::tcp + ? protocol_supports_tcp(proxy_protocols_[id]) + : protocol_supports_udp(proxy_protocols_[id]); + target.family_supported = id >= proxy_address_families_.size() || + (v4 ? family_supports_ipv4(proxy_address_families_[id]) : family_supports_ipv6(proxy_address_families_[id])); + target.listener_port = dns_listener_port_locked(); + } + + target.override_configured = dns_server_override_v4_.has_value() || dns_server_override_v6_.has_value(); + target.override_family_matches = dns_server_override_for().has_value(); + + const auto decision = decide_dns_route(dns_mode_, destination_port, + is_upstream_destination_locked(destination, destination_port), target); + + return { decision, decision.action == dns_route_action::proxy ? dns_server_override_for() : std::nullopt }; + } + + /** + * @brief Accounts for a DNS packet dropped by the Proxy-mode policy. The first drop of + * each (family, transport, reason) is described once; the running count is + * reported by the resolver thread at a throttled rate. + */ + template + void note_dns_block(const dns_block_reason reason) + { + dns_blocked_packets_.fetch_add(1, std::memory_order_relaxed); + + const auto family_index = std::is_same_v ? 0u : 1u; + const auto transport_index = Transport == dns_transport::tcp ? 0u : 1u; + const auto index = (static_cast(reason) * 4) + family_index * 2 + transport_index; + if (index < dns_block_reason_logged_.size() && + !dns_block_reason_logged_[index].test_and_set(std::memory_order_relaxed)) + { + NETLIB_LOG(log_level::warning, + "DNS routing: blocking {} {} DNS traffic (port 53) instead of sending it directly: {}.", + family_index == 0 ? "IPv4" : "IPv6", transport_index == 0 ? "TCP" : "UDP", proxy::to_string(reason)); + } + } + + /** + * @brief Handles an outbound UDP datagram addressed to port 53 according to @p route. + * + * In Proxy mode the datagram is redirected to the DNS proxy's local UDP listener via the + * existing socks5_udp_local_redirect, which also writes the SOCKS5 UDP header. With a + * server override the header carries the override while the IP header keeps the + * original destination, and the original server is remembered so the answer can be + * restored to it. Anything that cannot be redirected is dropped, never passed. + */ + template + packet_filter::packet_action handle_dns_udp(netlib::ndisapi::intermediate_buffer& buffer, + const dns_route& route, const AddrT& destination, const uint16_t source_port, + const uint16_t destination_port, const uint8_t* payload, const size_t payload_size) + { + using action_type = packet_filter::packet_action::action_type; + + if (route.decision.action == dns_route_action::pass) + return packet_filter::packet_action{ action_type::pass }; + + if (route.decision.action == dns_route_action::block) + { + note_dns_block(route.decision.reason); + return packet_filter::packet_action{ action_type::drop }; + } + + if (route.server_override) + { + // The answer comes back from the override server; remember which server the + // resolver addressed so that answer can be restored to it. + const auto message_id = dns_message_id(payload, payload_size); + if (!message_id) + { + note_dns_block(dns_block_reason::redirect_failed); + return packet_filter::packet_action{ action_type::drop }; + } + + dns_udp_origins_for().remember(source_port, *message_id, + net::ip_endpoint{ destination, destination_port }); + } + + auto& redirect = udp_redirect_for(); + const auto is_new_endpoint = redirect.is_new_endpoint(buffer); + + if (!redirect.process_client_to_server_packet(buffer, htons(route.decision.listener_port), route.server_override)) + { + note_dns_block(dns_block_reason::redirect_failed); + return packet_filter::packet_action{ action_type::drop }; + } + + { + std::scoped_lock lock(udp_mapper_lock_for()); + udp_mapper_for().insert_or_assign(source_port, std::chrono::steady_clock::now()); + } + + if (is_new_endpoint) + { + NETLIB_LOG(log_level::debug, "Redirecting DNS over UDP from local port {} to {} via the DNS proxy", + source_port, route.server_override + ? route.server_override->to_string() + : net::ip_endpoint{ destination, destination_port }.to_string()); + } + + log_packet_to_pcap(buffer); + return packet_filter::packet_action{ action_type::revert }; + } + + /** + * @brief Handles an outbound TCP segment addressed to port 53 according to @p route. + * + * In Proxy mode the connection is redirected to the DNS proxy's local TCP listener via + * the existing tcp_local_redirect. The source-port mapper records the effective upstream + * destination (the override, when configured) for the SOCKS5 CONNECT, while the packets + * the application sees keep the original destination. Segments that cannot be + * redirected (for example of a connection opened before ProxiFyre started) are dropped. + */ + template + packet_filter::packet_action handle_dns_tcp(netlib::ndisapi::intermediate_buffer& buffer, + const dns_route& route, const AddrT& destination, const uint16_t source_port, + const uint16_t destination_port, const uint8_t tcp_flags) + { + using action_type = packet_filter::packet_action::action_type; + + if (route.decision.action == dns_route_action::pass) + return packet_filter::packet_action{ action_type::pass }; + + if (route.decision.action == dns_route_action::block) + { + note_dns_block(route.decision.reason); + return packet_filter::packet_action{ action_type::drop }; + } + + if ((tcp_flags & (TH_SYN | TH_ACK)) == TH_SYN) + { + const auto upstream_destination = route.server_override + ? *route.server_override + : net::ip_endpoint{ destination, destination_port }; + + { + std::scoped_lock lock(tcp_mapper_lock_for()); + tcp_mapper_for()[source_port] = + tcp_mapper_entry_t{ std::chrono::steady_clock::now(), upstream_destination }; + } + + NETLIB_LOG(log_level::debug, "Redirecting DNS over TCP from local port {} to {} via the DNS proxy", + source_port, upstream_destination.to_string()); + } + + if (!tcp_redirect_for().process_client_to_server_packet(buffer, htons(route.decision.listener_port))) + { + note_dns_block(dns_block_reason::redirect_failed); + return packet_filter::packet_action{ action_type::drop }; + } + + log_packet_to_pcap(buffer); + return packet_filter::packet_action{ action_type::revert }; + } + + /** + * @brief Determines how a reply leaving local UDP proxy listener @p listener_port toward + * client port @p client_port is presented, given the relayed SOCKS5 UDP datagram + * in @p socks_payload. Only answers relayed from the configured server override + * by the DNS proxy's listener are restored (see classify_dns_override_reply()); + * other traffic through the same proxy is unchanged. + */ + template + std::pair>> dns_udp_reply_origin( + const uint16_t listener_port, const uint16_t client_port, + const uint8_t* socks_payload, const size_t socks_payload_size) + { + std::optional> server_override; + { + std::shared_lock lock(lock_); + if (dns_mode_ != dns_routing_mode::proxy || !dns_server_override_for()) + return { dns_reply_restore::unchanged, std::nullopt }; + + if (dns_listener_port_locked() != listener_port) + return { dns_reply_restore::unchanged, std::nullopt }; + + server_override = dns_server_override_for(); + } + + constexpr auto v4 = std::is_same_v; + using raw_address_t = std::conditional_t; + const raw_address_t& raw = server_override->ip; + + return classify_dns_override_reply(socks_payload, socks_payload_size, + static_cast(v4 ? 1 : 4), reinterpret_cast(&raw), sizeof(raw_address_t), + server_override->port, client_port, dns_udp_origins_for()); + } + + /** + * @brief Bytes of the UDP payload of an IPv4/IPv6 frame that are actually captured. + */ + static size_t captured_udp_payload_size(const netlib::ndisapi::intermediate_buffer& buffer, const void* udp_header) noexcept + { + const auto* const start = reinterpret_cast(udp_header); + const auto* const end = buffer.m_IBuffer + buffer.m_Length; + if (start < buffer.m_IBuffer || start + sizeof(udphdr) > end) + return 0; + + const auto declared = static_cast(ntohs(static_cast(udp_header)->length)); + const auto captured = static_cast(end - start); + const auto udp_size = std::min(declared, captured); + return udp_size > sizeof(udphdr) ? udp_size - sizeof(udphdr) : 0; + } + + /** + * @brief Installs the static driver filters that keep DNS in user mode in Proxy mode. + * + * Static PASS filters (LAN bypass and the upstream exemptions) are evaluated in the + * driver before the user-mode handler sees a packet. In Proxy mode DNS must take + * precedence over LAN bypass, so REDIRECT (to user mode) filters are inserted at the + * front of the table for outbound TCP/UDP to port 53 and for the DNS proxy's local + * replies (outbound from its listener ports, which are addressed to the original - often + * LAN - DNS server). Unrelated LAN traffic keeps matching the LAN PASS filters. + * Called from start() under lifecycle_mutex_. + */ + void install_dns_filters() + { + if (dns_filters_installed_) + return; + + std::optional tcp4, udp4, tcp6, udp6; + { + std::shared_lock lock(lock_); + if (dns_mode_ != dns_routing_mode::proxy) + return; + tcp4 = dns_listener_port_locked(); + udp4 = dns_listener_port_locked(); + tcp6 = dns_listener_port_locked(); + udp6 = dns_listener_port_locked(); + } + + bool all_installed = true; + const auto add = [this, &all_installed](const uint8_t protocol, + const std::optional destination_port, const std::optional source_port) + { + ndisapi::filter filter; + filter.set_direction(ndisapi::direction_t::out) + .set_action(ndisapi::action_t::redirect) + .set_protocol(protocol); + if (destination_port) + filter.set_dest_port(std::make_pair(*destination_port, *destination_port)); + if (source_port) + filter.set_source_port(std::make_pair(*source_port, *source_port)); + + if (!static_filters_.add_filter_front(filter)) + all_installed = false; + }; + + for (const auto protocol : { static_cast(IPPROTO_UDP), static_cast(IPPROTO_TCP) }) + { + add.template operator()(protocol, dns_port, std::nullopt); + add.template operator()(protocol, dns_port, std::nullopt); + } + + if (tcp4) add.template operator()(static_cast(IPPROTO_TCP), std::nullopt, *tcp4); + if (udp4) add.template operator()(static_cast(IPPROTO_UDP), std::nullopt, *udp4); + if (tcp6) add.template operator()(static_cast(IPPROTO_TCP), std::nullopt, *tcp6); + if (udp6) add.template operator()(static_cast(IPPROTO_UDP), std::nullopt, *udp6); + + dns_filters_installed_ = true; + + if (!all_installed) + { + NETLIB_LOG(log_level::error, + "DNS routing: failed to install one or more driver filters that give DNS precedence over " + "LAN bypass; DNS addressed to LAN resolvers may not be proxied while bypassLan is enabled."); + } + } + /** * @brief Processes a UDP packet for possible redirection through a proxy. * @@ -1928,23 +2549,37 @@ namespace proxy const auto* const udp_header = reinterpret_cast(reinterpret_cast(ip_header) + sizeof(DWORD) * ip_header->ip_hl); - // If the destination port is 53 (DNS), allow the packet to pass through without redirection - // TODO: We might consider adding a DNS proxy in the future - if (ntohs(udp_header->th_dport) == 53) - { - return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; - } - - // If the packet is from a known proxy port, process for server-to-client redirection + // If the packet is from a known proxy port, process for server-to-client redirection. + // Answers relayed from a DNS server override are presented as coming from the server + // the resolver originally queried. if (is_udp_proxy_port(ntohs(udp_header->th_sport))) { - if (udp_redirect_->process_server_to_client_packet(buffer)) + const auto [restore, origin] = dns_udp_reply_origin( + ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), + reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); + + if (restore == dns_reply_restore::drop) + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + + if (udp_redirect_->process_server_to_client_packet(buffer, origin)) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } } + // Conventional DNS (destination port 53) follows the global DNS policy, before and + // independently of process attribution and application rules: Direct passes it, + // Proxy redirects it to the DNS proxy or drops it. + if (const auto dns = decide_dns( + net::ip_address_v4{ ip_header->ip_dst }, ntohs(udp_header->th_dport)); + dns.decision.action != dns_route_action::not_dns) + { + return handle_dns_udp(buffer, dns, net::ip_address_v4{ ip_header->ip_dst }, + ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), + reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); + } + auto process = process_lookup_v4_. lookup_process_for_udp(net::ip_endpoint{ ip_header->ip_src, ntohs(udp_header->th_sport) @@ -2047,6 +2682,17 @@ namespace proxy } } + // Conventional DNS over TCP follows the global DNS policy. In Direct mode TCP/53 is + // now unconditionally direct (previously it was routed like any other TCP traffic of + // the owning process). + if (const auto dns = decide_dns( + net::ip_address_v4{ ip_header->ip_dst }, ntohs(tcp_header->th_dport)); + dns.decision.action != dns_route_action::not_dns) + { + return handle_dns_tcp(buffer, dns, net::ip_address_v4{ ip_header->ip_dst }, + ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport), tcp_header->th_flags); + } + auto process = process_lookup_v4_. lookup_process_for_tcp(net::ip_session{ ip_header->ip_src, ip_header->ip_dst, ntohs(tcp_header->th_sport), @@ -2199,23 +2845,34 @@ namespace proxy const auto* const udp_header = static_cast(transport); - // If the destination port is 53 (DNS), allow the packet to pass through - // without redirection (mirrors the IPv4 path). - if (ntohs(udp_header->th_dport) == 53) - { - return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; - } - // If the packet is from a known proxy port, process for server-to-client redirection + // (restoring the original server of DNS override answers, as on the IPv4 path). if (is_udp_proxy_port_v6(ntohs(udp_header->th_sport))) { - if (udp_redirect_v6_->process_server_to_client_packet(buffer)) + const auto [restore, origin] = dns_udp_reply_origin( + ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), + reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); + + if (restore == dns_reply_restore::drop) + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + + if (udp_redirect_v6_->process_server_to_client_packet(buffer, origin)) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } } + // Conventional DNS follows the global DNS policy (mirrors the IPv4 path). + if (const auto dns = decide_dns( + net::ip_address_v6{ ip_header->ip6_dst }, ntohs(udp_header->th_dport)); + dns.decision.action != dns_route_action::not_dns) + { + return handle_dns_udp(buffer, dns, net::ip_address_v6{ ip_header->ip6_dst }, + ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), + reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); + } + auto process = process_lookup_v6_. lookup_process_for_udp(net::ip_endpoint{ ip_header->ip6_src, ntohs(udp_header->th_sport) @@ -2314,6 +2971,15 @@ namespace proxy } } + // Conventional DNS over TCP follows the global DNS policy (mirrors the IPv4 path). + if (const auto dns = decide_dns( + net::ip_address_v6{ ip_header->ip6_dst }, ntohs(tcp_header->th_dport)); + dns.decision.action != dns_route_action::not_dns) + { + return handle_dns_tcp(buffer, dns, net::ip_address_v6{ ip_header->ip6_dst }, + ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport), tcp_header->th_flags); + } + auto process = process_lookup_v6_. lookup_process_for_tcp(net::ip_session{ ip_header->ip6_src, ip_header->ip6_dst, ntohs(tcp_header->th_sport), @@ -2473,6 +3139,7 @@ namespace proxy constexpr auto maintenance_interval = tcp_mapper_entry_ttl_ / 2; auto last_sweep = std::chrono::steady_clock::now(); auto last_drop_log = last_sweep; + auto last_dns_block_log = last_sweep; while (true) { @@ -2579,6 +3246,25 @@ namespace proxy } } } + + // Expire DNS override response mappings for queries that were never answered. + dns_udp_origins_v4_.sweep(now); + dns_udp_origins_v6_.sweep(now); + } + + // Report Proxy-mode DNS drops at the same throttled rate as the queue drops so + // a resolver retrying against an unreachable proxy cannot flood the log. + if (const auto now = std::chrono::steady_clock::now(); + now - last_dns_block_log >= drop_log_throttle_interval_ && + dns_blocked_packets_.load(std::memory_order_relaxed) != 0) + { + last_dns_block_log = now; + if (const auto blocked = dns_blocked_packets_.exchange(0, std::memory_order_relaxed); blocked != 0) + { + NETLIB_LOG(log_level::warning, + "DNS routing: dropped {} DNS packet(s) that could not be sent through the DNS proxy " + "(they were not sent directly).", blocked); + } } // Periodically surface the counts of packets dropped due to a diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp new file mode 100644 index 0000000..9e3812c --- /dev/null +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -0,0 +1,439 @@ +// Packet-level DNS routing tests that run netlib's real packet rewriting code. +// +// Each test builds a real Ethernet/IP/UDP or TCP frame, drives it through the production +// socks5_udp_local_redirect / tcp_local_redirect translations exactly as socks_local_router's +// DNS handlers do (handle_dns_udp(), handle_dns_tcp(), dns_udp_reply_origin()), and checks +// every rewritten header field, the SOCKS5 UDP header carried to the relay, the restored source +// of the answer, and the IP/UDP/TCP checksums (verified independently of the product checksum +// code, which is extracted from ndisapi/ndisapi.cpp by run-portable-tests.sh). +// +// The Windows Packet Filter driver and SOCKS5 sockets are not involved: the local proxy's reply +// is synthesized as the bytes socks5_local_udp_proxy_server sends back. This suite builds only on +// non-Windows hosts through winshim/ (see run-portable-tests.sh). + +#include "winshim/packet_env.h" + +#include + +static_assert(sizeof(ether_header) == 14); +static_assert(sizeof(iphdr) == 20); +static_assert(sizeof(ipv6hdr) == 40); +static_assert(sizeof(udphdr) == 8); +static_assert(sizeof(tcphdr) == 20, "tcp_seq must be 32-bit as on Windows"); +static_assert(sizeof(proxy::socks5_udp_header) == 10); +static_assert(sizeof(proxy::socks5_udp_header) == 22); + +namespace +{ + using v4 = net::ip_address_v4; + using v6 = net::ip_address_v6; + using log_level = netlib::log::log_level; + + constexpr uint16_t client_port = 50001; + constexpr uint16_t udp_listener = 41002; + constexpr uint16_t tcp_listener = 41001; + + const uint8_t client_mac[6] = { 0x02, 0, 0, 0, 0, 0x10 }; + const uint8_t gateway_mac[6] = { 0x02, 0, 0, 0, 0, 0x01 }; + + std::vector dns_message(const uint16_t id, const size_t extra = 17) + { + std::vector m{ static_cast(id >> 8), static_cast(id & 0xff), + 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + for (size_t i = 0; i < extra; ++i) + m.push_back(static_cast(0x30 + i)); + return m; + } + + uint32_t sum16(const uint8_t* data, const size_t size, uint32_t sum = 0) + { + for (size_t i = 0; i + 1 < size; i += 2) + sum += static_cast(data[i] << 8 | data[i + 1]); + if (size & 1) + sum += static_cast(data[size - 1] << 8); + return sum; + } + + uint16_t fold(uint32_t sum) + { + while (sum >> 16) + sum = (sum & 0xffff) + (sum >> 16); + return static_cast(sum); + } + + // ------------------------------------------------------------------ frame builders + + struct frame + { + INTERMEDIATE_BUFFER buffer{}; + + ether_header* eth() { return reinterpret_cast(buffer.m_IBuffer); } + iphdr* ip4() { return reinterpret_cast(buffer.m_IBuffer + ETHER_HEADER_LENGTH); } + ipv6hdr* ip6() { return reinterpret_cast(buffer.m_IBuffer + ETHER_HEADER_LENGTH); } + size_t l3_header() { return ntohs(eth()->h_proto) == ETH_P_IP ? ip4()->ip_hl * 4u : sizeof(ipv6hdr); } + uint8_t* l4() { return buffer.m_IBuffer + ETHER_HEADER_LENGTH + l3_header(); } + udphdr* udp() { return reinterpret_cast(l4()); } + tcphdr* tcp() { return reinterpret_cast(l4()); } + uint8_t* udp_payload() { return l4() + sizeof(udphdr); } + size_t udp_payload_size() { return ntohs(udp()->length) - sizeof(udphdr); } + std::vector payload() { return { udp_payload(), udp_payload() + udp_payload_size() }; } + + void set_ethernet(const uint16_t ether_type) + { + memcpy(eth()->h_source, client_mac, 6); + memcpy(eth()->h_dest, gateway_mac, 6); + eth()->h_proto = htons(ether_type); + } + + static frame udp4(const char* source, const char* destination, const uint16_t sport, const uint16_t dport, + const std::vector& payload) + { + frame f; + f.set_ethernet(ETH_P_IP); + auto* ip = f.ip4(); + ip->ip_v = 4; + ip->ip_hl = 5; + ip->ip_len = htons(static_cast(sizeof(iphdr) + sizeof(udphdr) + payload.size())); + ip->ip_ttl = 128; + ip->ip_p = IPPROTO_UDP; + ip->ip_src = v4{ std::string{ source } }; + ip->ip_dst = v4{ std::string{ destination } }; + f.udp()->th_sport = htons(sport); + f.udp()->th_dport = htons(dport); + f.udp()->length = htons(static_cast(sizeof(udphdr) + payload.size())); + memcpy(f.udp_payload(), payload.data(), payload.size()); + f.buffer.m_Length = static_cast(ETHER_HEADER_LENGTH + ntohs(ip->ip_len)); + CNdisApi::RecalculateUDPChecksum(&f.buffer); + CNdisApi::RecalculateIPChecksum(&f.buffer); + return f; + } + + static frame udp6(const char* source, const char* destination, const uint16_t sport, const uint16_t dport, + const std::vector& payload) + { + frame f; + f.set_ethernet(ETH_P_IPV6); + auto* ip = f.ip6(); + ip->ip6_v = 6; + ip->ip6_len = htons(static_cast(sizeof(udphdr) + payload.size())); + ip->ip6_next = IPPROTO_UDP; + ip->ip6_hops = 64; + ip->ip6_src = v6{ std::string{ source } }; + ip->ip6_dst = v6{ std::string{ destination } }; + f.udp()->th_sport = htons(sport); + f.udp()->th_dport = htons(dport); + f.udp()->length = htons(static_cast(sizeof(udphdr) + payload.size())); + memcpy(f.udp_payload(), payload.data(), payload.size()); + f.buffer.m_Length = static_cast(ETHER_HEADER_LENGTH + sizeof(ipv6hdr) + ntohs(ip->ip6_len)); + net::ipv6_helper::recalculate_tcp_udp_checksum(&f.buffer); + return f; + } + + static frame tcp4(const char* source, const char* destination, const uint16_t sport, const uint16_t dport, + const uint8_t flags) + { + frame f; + f.set_ethernet(ETH_P_IP); + auto* ip = f.ip4(); + ip->ip_v = 4; + ip->ip_hl = 5; + ip->ip_len = htons(static_cast(sizeof(iphdr) + sizeof(tcphdr))); + ip->ip_ttl = 128; + ip->ip_p = IPPROTO_TCP; + ip->ip_src = v4{ std::string{ source } }; + ip->ip_dst = v4{ std::string{ destination } }; + f.tcp()->th_sport = htons(sport); + f.tcp()->th_dport = htons(dport); + f.tcp()->th_off = 5; + f.tcp()->th_flags = flags; + f.tcp()->th_win = htons(64240); + f.buffer.m_Length = static_cast(ETHER_HEADER_LENGTH + ntohs(ip->ip_len)); + CNdisApi::RecalculateTCPChecksum(&f.buffer); + CNdisApi::RecalculateIPChecksum(&f.buffer); + return f; + } + + // Independent checksum verification (RFC 1071): a correct checksum folds to 0xffff. + bool ip4_checksum_valid() { return fold(sum16(reinterpret_cast(ip4()), ip4()->ip_hl * 4u)) == 0xffff; } + + bool l4_checksum_valid() + { + uint32_t sum = 0; + size_t l4_size = 0; + uint8_t protocol = 0; + if (ntohs(eth()->h_proto) == ETH_P_IP) + { + l4_size = ntohs(ip4()->ip_len) - ip4()->ip_hl * 4u; + protocol = ip4()->ip_p; + sum = sum16(reinterpret_cast(&ip4()->ip_src), 8); + } + else + { + l4_size = ntohs(ip6()->ip6_len); + protocol = ip6()->ip6_next; + sum = sum16(reinterpret_cast(&ip6()->ip6_src), 32); + } + sum += protocol + static_cast(l4_size); + return fold(sum16(l4(), l4_size, sum)) == 0xffff; + } + + bool ethernet_swapped() + { + return memcmp(eth()->h_source, gateway_mac, 6) == 0 && memcmp(eth()->h_dest, client_mac, 6) == 0; + } + }; + + template + std::vector socks5_udp_datagram(const Addr& address, const uint16_t port, const std::vector& data) + { + proxy::socks5_udp_header header; + header.reserved = 0; + header.fragment = 0; + header.address_type = std::is_same_v ? 1 : 4; + header.dest_address = address; + header.dest_port = htons(port); + std::vector out(reinterpret_cast(&header), reinterpret_cast(&header) + sizeof(header)); + out.insert(out.end(), data.begin(), data.end()); + return out; + } + + // ------------------------------------------------------------------ router-equivalent steps + + /// The local UDP proxy's reply to the redirected client, as socks5_local_udp_proxy_server + /// emits it: from the listener port to the (swapped) original server address and client port, + /// carrying the relay's SOCKS5 UDP header and the DNS answer. + template + frame local_proxy_reply(const char* local_address, const char* original_server, const Addr& relay_source, + const uint16_t relay_port, const std::vector& answer) + { + const auto datagram = socks5_udp_datagram(relay_source, relay_port, answer); + if constexpr (std::is_same_v) + return frame::udp4(local_address, original_server, udp_listener, client_port, datagram); + else + return frame::udp6(local_address, original_server, udp_listener, client_port, datagram); + } + + template + std::pair>> classify(frame& reply, + const net::ip_endpoint& server_override, proxy::dns_udp_origin_tracker>& origins) + { + const Raw& raw = server_override.ip; + return proxy::classify_dns_override_reply(reply.udp_payload(), reply.udp_payload_size(), + static_cast(std::is_same_v ? 1 : 4), reinterpret_cast(&raw), sizeof(Raw), + server_override.port, ntohs(reply.udp()->th_dport), origins); + } +} + +// 6./7. IPv4 UDP query to a private resolver with an IPv4 override: the relay is asked for the +// override, the IP packet keeps the original destination, and the answer is presented to +// the client as coming from the original server. +TEST(DnsPacketRedirect, Ipv4UdpOverrideRewritesTheSocksDestinationAndRestoresTheAnswer) +{ + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + proxy::dns_udp_origin_tracker> origins; + const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; + const auto query = dns_message(0xabcd); + + auto packet = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, query); + ASSERT_TRUE(packet.ip4_checksum_valid()); + ASSERT_TRUE(packet.l4_checksum_valid()); + + // handle_dns_udp(): remember the original server, register the endpoint, redirect. + origins.remember(client_port, *proxy::dns_message_id(query.data(), query.size()), + net::ip_endpoint{ v4{ packet.ip4()->ip_dst }, 53 }); + EXPECT_TRUE(redirect.is_new_endpoint(packet.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(packet.buffer, htons(udp_listener), server_override)); + + // Hairpinned to the local listener; the IP packet keeps the original server address. + EXPECT_TRUE(packet.ethernet_swapped()); + EXPECT_EQ(v4{ packet.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(v4{ packet.ip4()->ip_dst }, v4{ std::string{ "192.168.1.10" } }); + EXPECT_EQ(ntohs(packet.udp()->th_sport), client_port); + EXPECT_EQ(ntohs(packet.udp()->th_dport), udp_listener); + + // The SOCKS5 UDP header carried to the relay names the override. + const auto relayed = packet.payload(); + const auto view = proxy::parse_socks5_udp_datagram(relayed.data(), relayed.size()); + ASSERT_TRUE(view.has_value()); + EXPECT_EQ(view->address_type, 1); + EXPECT_EQ(std::vector(view->address, view->address + 4), (std::vector{ 1, 1, 1, 1 })); + EXPECT_EQ(view->port, 53); + EXPECT_EQ(std::vector(view->data, view->data + view->data_size), query); + EXPECT_TRUE(packet.ip4_checksum_valid()); + EXPECT_TRUE(packet.l4_checksum_valid()); + + // The relay answers from the override; dns_udp_reply_origin() restores the original server. + const auto answer = dns_message(0xabcd, 40); + auto reply = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, answer); + const auto [restore, origin] = classify(reply, server_override, origins); + ASSERT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(origin.has_value()); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); + + EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(v4{ reply.ip4()->ip_dst }, v4{ std::string{ "192.168.1.10" } }); + EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); + EXPECT_EQ(ntohs(reply.udp()->th_dport), client_port); + EXPECT_EQ(reply.payload(), answer); + EXPECT_EQ(ntohs(reply.ip4()->ip_len), sizeof(iphdr) + sizeof(udphdr) + answer.size()); + EXPECT_TRUE(reply.ip4_checksum_valid()); + EXPECT_TRUE(reply.l4_checksum_valid()); +} + +// 2./7. Without an override the original destination is preserved end to end. +TEST(DnsPacketRedirect, Ipv4UdpWithoutOverrideKeepsTheOriginalDestination) +{ + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + const auto query = dns_message(0x0102); + + auto packet = frame::udp4("10.0.0.20", "8.8.8.8", client_port, 53, query); + EXPECT_TRUE(redirect.is_new_endpoint(packet.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(packet.buffer, htons(udp_listener))); + + const auto relayed = packet.payload(); + const auto view = proxy::parse_socks5_udp_datagram(relayed.data(), relayed.size()); + ASSERT_TRUE(view.has_value()); + EXPECT_EQ(std::vector(view->address, view->address + 4), (std::vector{ 8, 8, 8, 8 })); + EXPECT_EQ(view->port, 53); + + const auto answer = dns_message(0x0102, 5); + auto reply = local_proxy_reply("10.0.0.20", "8.8.8.8", v4{ std::string{ "8.8.8.8" } }, 53, answer); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer)); + EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "8.8.8.8" } }); + EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); + EXPECT_EQ(reply.payload(), answer); + EXPECT_TRUE(reply.ip4_checksum_valid()); + EXPECT_TRUE(reply.l4_checksum_valid()); +} + +// 2./6./7. IPv6 UDP query with an IPv6 override. +TEST(DnsPacketRedirect, Ipv6UdpOverrideRewritesTheSocksDestinationAndRestoresTheAnswer) +{ + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + proxy::dns_udp_origin_tracker> origins; + const net::ip_endpoint server_override{ v6{ std::string{ "2606:4700:4700::1111" } }, 53 }; + const auto query = dns_message(0x7777); + + auto packet = frame::udp6("fd00::10", "fd00::1", client_port, 53, query); + ASSERT_TRUE(packet.l4_checksum_valid()); + + origins.remember(client_port, 0x7777, net::ip_endpoint{ v6{ packet.ip6()->ip6_dst }, 53 }); + EXPECT_TRUE(redirect.is_new_endpoint(packet.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(packet.buffer, htons(udp_listener), server_override)); + + EXPECT_TRUE(packet.ethernet_swapped()); + EXPECT_EQ(v6{ packet.ip6()->ip6_src }, v6{ std::string{ "fd00::1" } }); + EXPECT_EQ(ntohs(packet.udp()->th_dport), udp_listener); + const auto relayed = packet.payload(); + const auto view = proxy::parse_socks5_udp_datagram(relayed.data(), relayed.size()); + ASSERT_TRUE(view.has_value()); + EXPECT_EQ(view->address_type, 4); + EXPECT_EQ(v6{ *reinterpret_cast(view->address) }, server_override.ip); + EXPECT_EQ(view->port, 53); + EXPECT_TRUE(packet.l4_checksum_valid()); + + const auto answer = dns_message(0x7777, 64); + auto reply = local_proxy_reply("fd00::10", "fd00::1", server_override.ip, 53, answer); + const auto [restore, origin] = classify(reply, server_override, origins); + ASSERT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); + + EXPECT_EQ(v6{ reply.ip6()->ip6_src }, v6{ std::string{ "fd00::1" } }); + EXPECT_EQ(v6{ reply.ip6()->ip6_dst }, v6{ std::string{ "fd00::10" } }); + EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); + EXPECT_EQ(reply.payload(), answer); + EXPECT_TRUE(reply.l4_checksum_valid()); +} + +// 7. Answers that are not override answers (other traffic through the same proxy) are left to +// the relay's header; override answers to an unknown query are dropped. +TEST(DnsPacketRedirect, OnlyOverrideAnswersToKnownQueriesAreRestored) +{ + proxy::dns_udp_origin_tracker> origins; + const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; + origins.remember(client_port, 0x1111, net::ip_endpoint{ v4{ std::string{ "192.168.1.1" } }, 53 }); + + // A different relay source (application traffic sharing the proxy): unchanged. + auto other = local_proxy_reply("192.168.1.10", "203.0.113.5", v4{ std::string{ "203.0.113.5" } }, 443, dns_message(0x1111)); + EXPECT_EQ((classify(other, server_override, origins).first), proxy::dns_reply_restore::unchanged); + + // The override address on another port: unchanged. + auto other_port = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 5353, dns_message(0x1111)); + EXPECT_EQ((classify(other_port, server_override, origins).first), proxy::dns_reply_restore::unchanged); + + // An override answer to a query that was never sent: dropped. + auto unknown = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x2222)); + EXPECT_EQ((classify(unknown, server_override, origins).first), proxy::dns_reply_restore::drop); + + // A truncated DNS message from the override: dropped. + auto truncated = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, std::vector{ 0x11, 0x11, 0x01 }); + EXPECT_EQ((classify(truncated, server_override, origins).first), proxy::dns_reply_restore::drop); + + // A malformed SOCKS5 header (non-zero FRAG) is not parsed. + auto fragmented = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x1111)); + fragmented.udp_payload()[2] = 1; + EXPECT_EQ((classify(fragmented, server_override, origins).first), proxy::dns_reply_restore::unchanged); + + auto known = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x1111)); + const auto [restore, origin] = classify(known, server_override, origins); + EXPECT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(origin.has_value()); + EXPECT_EQ(origin->ip, v4{ std::string{ "192.168.1.1" } }); +} + +// 8. A datagram that cannot be redirected is reported as such (the router then drops it rather +// than passing it): here a near-MTU datagram that has no room for the SOCKS5 header. +TEST(DnsPacketRedirect, UnredirectableUdpIsRejectedSoTheRouterDropsIt) +{ + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + const auto big = dns_message(0x3333, MAX_ETHER_FRAME - ETHER_HEADER_LENGTH - sizeof(iphdr) - sizeof(udphdr) - 12 - 4); + auto packet = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, big); + EXPECT_TRUE(redirect.is_new_endpoint(packet.buffer)); + EXPECT_FALSE(redirect.process_client_to_server_packet(packet.buffer, htons(udp_listener))); + + // An unregistered endpoint is not redirected either. + ndisapi::socks5_udp_local_redirect fresh{ log_level::error }; + auto small = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, dns_message(1)); + EXPECT_FALSE(fresh.process_client_to_server_packet(small.buffer, htons(udp_listener))); +} + +// 2./14. TCP DNS (for example the retry after a truncated UDP answer): the SYN and later +// segments are hairpinned to the DNS proxy's TCP listener; the listener's replies are +// presented as coming from the original server. The upstream CONNECT target (original or +// override) is recorded separately in the router's source-port mapper. +TEST(DnsPacketRedirect, Ipv4TcpIsRedirectedToTheListenerAndRepliesKeepTheOriginalServer) +{ + ndisapi::tcp_local_redirect redirect{ log_level::error }; + + auto syn = frame::tcp4("192.168.1.10", "192.168.1.1", client_port, 53, TH_SYN); + ASSERT_TRUE(redirect.process_client_to_server_packet(syn.buffer, htons(tcp_listener))); + EXPECT_TRUE(syn.ethernet_swapped()); + EXPECT_EQ(v4{ syn.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(v4{ syn.ip4()->ip_dst }, v4{ std::string{ "192.168.1.10" } }); + EXPECT_EQ(ntohs(syn.tcp()->th_sport), client_port); + EXPECT_EQ(ntohs(syn.tcp()->th_dport), tcp_listener); + EXPECT_TRUE(syn.ip4_checksum_valid()); + EXPECT_TRUE(syn.l4_checksum_valid()); + + // The listener's SYN-ACK: from the listener port to the swapped original server address. + auto syn_ack = frame::tcp4("192.168.1.10", "192.168.1.1", tcp_listener, client_port, TH_SYN | TH_ACK); + ASSERT_TRUE(redirect.process_server_to_client_packet(syn_ack.buffer)); + EXPECT_EQ(v4{ syn_ack.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(ntohs(syn_ack.tcp()->th_sport), 53); + EXPECT_EQ(ntohs(syn_ack.tcp()->th_dport), client_port); + EXPECT_TRUE(syn_ack.ip4_checksum_valid()); + EXPECT_TRUE(syn_ack.l4_checksum_valid()); + + auto ack = frame::tcp4("192.168.1.10", "192.168.1.1", client_port, 53, TH_ACK); + EXPECT_TRUE(redirect.process_client_to_server_packet(ack.buffer, htons(tcp_listener))); +} + +// 9. A TCP segment of a DNS connection that is not being redirected (for example one opened +// before ProxiFyre started, or after the redirect entry expired) is rejected, and the router +// drops it instead of passing it to the real server. +TEST(DnsPacketRedirect, TcpSegmentOfAnUnknownConnectionIsRejectedSoTheRouterDropsIt) +{ + ndisapi::tcp_local_redirect redirect{ log_level::error }; + auto data = frame::tcp4("192.168.1.10", "192.168.1.1", client_port, 53, TH_ACK | TH_PSH); + EXPECT_FALSE(redirect.process_client_to_server_packet(data.buffer, htons(tcp_listener))); +} diff --git a/netlib/test/portable/pch.h b/netlib/test/portable/pch.h new file mode 100644 index 0000000..7bf26f8 --- /dev/null +++ b/netlib/test/portable/pch.h @@ -0,0 +1,18 @@ +// pch.h: minimal precompiled-header stand-in for the portable native test runner. +// +// The Windows netlib-tests project resolves "pch.h" to netlib-tests/pch.h. Platform-independent +// test sources (those that include only Windows-free netlib headers) are also built by +// run-portable-tests.sh with this directory first on the include path, so they can run on any +// host with a C++20 compiler and GoogleTest. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +#include diff --git a/netlib/test/portable/run-portable-tests.sh b/netlib/test/portable/run-portable-tests.sh new file mode 100755 index 0000000..f505d01 --- /dev/null +++ b/netlib/test/portable/run-portable-tests.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +# Builds and runs the platform-independent native tests with the host C++ compiler and +# GoogleTest. The full netlib-tests suite still requires Windows (see netlib/README.md); this +# runner exists so the DNS routing policy and the real packet-rewriting code it drives can also +# be exercised on Linux/macOS CI hosts and developer machines. +# +# * ../proxy/dns_routing_policy_test.cpp - also part of the Windows netlib-tests project +# * dns_packet_redirect_test.cpp - portable only: compiles the production +# tcp_local_redirect.h / socks5_udp_local_redirect.h against winshim/ and the product +# CNdisApi checksum routines extracted verbatim from ndisapi/ndisapi.cpp +# +# Usage: netlib/test/portable/run-portable-tests.sh [extra gtest arguments] +# Requires: a C++20 compiler (CXX, default g++), GoogleTest, and the Microsoft GSL headers. +# Set SANITIZE=1 to build with AddressSanitizer and UndefinedBehaviorSanitizer. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +repo="$(cd "$here/../../.." && pwd)" +out="${PORTABLE_TEST_OUT:-$(mktemp -d)}" +cxx="${CXX:-g++}" +mkdir -p "$out" + +flags=(-std=c++20 -O1 -g -Wall -Wextra -Werror -Wno-unknown-pragmas -pthread) +if [[ "${SANITIZE:-0}" == "1" ]]; then + # Packet headers follow the 14-byte Ethernet header, so netlib (like the driver API) accesses + # in_addr fields at 2-byte alignment by design; x86 and ARM64 permit this. + flags+=(-fsanitize=address,undefined -fno-sanitize=alignment -fno-omit-frame-pointer) +fi + +# Product checksum routines, extracted verbatim so the packet tests verify the shipped code. +checksums="$out/ndisapi_checksums.cpp" +{ + echo '// Generated by run-portable-tests.sh from ndisapi/ndisapi.cpp. Do not edit.' + echo '#include "winshim/packet_env.h"' + awk '/^void CNdisApi::Recalculate(IP|TCP|UDP)Checksum\(/{p=1} p{print} p&&/^}/{p=0; print ""}' \ + "$repo/ndisapi/ndisapi.cpp" +} > "$checksums" +if [[ "$(grep -c '^void CNdisApi::Recalculate' "$checksums")" != "3" ]]; then + echo "Failed to extract the CNdisApi checksum routines from ndisapi/ndisapi.cpp" >&2 + exit 1 +fi + +"$cxx" "${flags[@]}" -I"$here" -I"$here/winshim" \ + "$here/../proxy/dns_routing_policy_test.cpp" \ + "$here/dns_packet_redirect_test.cpp" \ + "$checksums" \ + -lgtest -lgtest_main \ + -o "$out/netlib-portable-tests" + +"$out/netlib-portable-tests" "$@" diff --git a/netlib/test/portable/winshim/WinIoctl.h b/netlib/test/portable/winshim/WinIoctl.h new file mode 100644 index 0000000..6f70f09 --- /dev/null +++ b/netlib/test/portable/winshim/WinIoctl.h @@ -0,0 +1 @@ +#pragma once diff --git a/netlib/test/portable/winshim/in6addr.h b/netlib/test/portable/winshim/in6addr.h new file mode 100644 index 0000000..6f70f09 --- /dev/null +++ b/netlib/test/portable/winshim/in6addr.h @@ -0,0 +1 @@ +#pragma once diff --git a/netlib/test/portable/winshim/ip2string.h b/netlib/test/portable/winshim/ip2string.h new file mode 100644 index 0000000..6f70f09 --- /dev/null +++ b/netlib/test/portable/winshim/ip2string.h @@ -0,0 +1 @@ +#pragma once diff --git a/netlib/test/portable/winshim/packet_env.h b/netlib/test/portable/winshim/packet_env.h new file mode 100644 index 0000000..2399eea --- /dev/null +++ b/netlib/test/portable/winshim/packet_env.h @@ -0,0 +1,24 @@ +// packet_env.h: compiles netlib's real packet-rewriting headers on a non-Windows host for the +// portable packet tests (see winshim.h). +#pragma once + +#include "winshim.h" +#include "../../../../include/Common.h" +// iphlp.h declares tcp_seq as u_long, which is 32-bit on Windows but 64-bit on LP64 hosts (and +// the host C library already declares its own u_long). Give iphlp.h a private u_long with the +// Windows (LLP64) width so tcphdr has its on-wire size. +#define u_long winshim_u_long +#define long int +#include "../../../src/iphlp.h" +#undef long +#include "../../../../ndisapi/inet_checksum.h" +#include "../../../src/tools/generic.h" +#include "../../../src/log/log.h" +#include "../../../src/net/ip_address.h" +#include "../../../src/net/ip_endpoint.h" +#include "../../../src/net/ipv6_helper.h" +#include "../../../src/proxy/proxy_common.h" +#include "../../../src/proxy/socks5_common.h" +#include "../../../src/ndisapi/tcp_local_redirect.h" +#include "../../../src/ndisapi/socks5_udp_local_redirect.h" +#include "../../../src/proxy/dns_routing_policy.h" diff --git a/netlib/test/portable/winshim/winshim.h b/netlib/test/portable/winshim/winshim.h new file mode 100644 index 0000000..a8dc9a4 --- /dev/null +++ b/netlib/test/portable/winshim/winshim.h @@ -0,0 +1,142 @@ +// winshim.h: the small subset of Windows SDK and Windows Packet Filter API declarations needed +// to compile netlib's packet-rewriting headers (tcp_local_redirect.h, +// socks5_udp_local_redirect.h) on a non-Windows host for the portable packet tests. +// +// Only types, byte-order helpers, the address-string conversions used by net/ip_address.h and +// the three CNdisApi checksum routines are provided. Structure layouts match the Windows SDK so +// the netlib packet code operates on the same bytes it does on Windows. Nothing here is used by +// the product build. + +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +typedef uint32_t DWORD, *PDWORD; +typedef uint32_t ULONG; +typedef int32_t LONG; +typedef int INT; +typedef int BOOL; +typedef unsigned char UCHAR, *PUCHAR, BYTE; +typedef unsigned short USHORT, WORD; +typedef uint64_t ULONGLONG; +typedef void* HANDLE; +typedef unsigned short ADDRESS_FAMILY; +typedef const char* PCSTR; +typedef char* PSTR; +typedef const wchar_t* LPCWSTR; +typedef wchar_t* PWSTR; +typedef uintptr_t ULONG_PTR; + +#ifndef TRUE +#define TRUE 1 +#define FALSE 0 +#endif + +#define AF_INET 2 +#define AF_INET6 23 + +typedef union _ULARGE_INTEGER +{ + struct { DWORD LowPart; DWORD HighPart; } u; + ULONGLONG QuadPart; +} ULARGE_INTEGER; + +typedef struct _LIST_ENTRY +{ + _LIST_ENTRY* Flink; + _LIST_ENTRY* Blink; +} LIST_ENTRY; + +struct in_addr +{ + union + { + struct { UCHAR s_b1, s_b2, s_b3, s_b4; } S_un_b; + struct { USHORT s_w1, s_w2; } S_un_w; + ULONG S_addr; + } S_un; +}; + +struct in6_addr +{ + union + { + UCHAR Byte[16]; + USHORT Word[8]; + } u; +}; +typedef in6_addr IN6_ADDR, in_addr6; + +constexpr uint16_t htons(const uint16_t v) noexcept { return static_cast((v << 8) | (v >> 8)); } +constexpr uint16_t ntohs(const uint16_t v) noexcept { return htons(v); } +constexpr uint32_t htonl(const uint32_t v) noexcept { return __builtin_bswap32(v); } +constexpr uint32_t ntohl(const uint32_t v) noexcept { return htonl(v); } + +namespace winshim +{ + // Host C library address conversions, declared here so the host's own in_addr/in6_addr + // definitions (which differ from the Windows ones above) are never included. + extern "C" int inet_pton(int, const char*, void*); + extern "C" const char* inet_ntop(int, const void*, char*, unsigned); + inline constexpr int host_af_inet = 2; + inline constexpr int host_af_inet6 = 10; +} + +inline LONG RtlIpv4StringToAddressA(const char* s, BOOL, PCSTR* terminator, in_addr* address) +{ + if (terminator) *terminator = s + std::strlen(s); + return winshim::inet_pton(winshim::host_af_inet, s, address) == 1 ? 0 : -1; +} +inline LONG RtlIpv6StringToAddressA(const char* s, PCSTR* terminator, in6_addr* address) +{ + if (terminator) *terminator = s + std::strlen(s); + return winshim::inet_pton(winshim::host_af_inet6, s, address) == 1 ? 0 : -1; +} +inline PSTR RtlIpv4AddressToStringA(const in_addr* address, PSTR s) +{ + winshim::inet_ntop(winshim::host_af_inet, address, s, 16); + return s + std::strlen(s); +} +inline PSTR RtlIpv6AddressToStringA(const in6_addr* address, PSTR s) +{ + winshim::inet_ntop(winshim::host_af_inet6, address, s, 46); + return s + std::strlen(s); +} +// Wide variants are compiled into net/ip_address.h but unused by the tests. +inline LONG RtlIpv4StringToAddressW(LPCWSTR, BOOL, LPCWSTR*, in_addr*) { return -1; } +inline LONG RtlIpv6StringToAddressW(LPCWSTR, LPCWSTR*, in6_addr*) { return -1; } +inline PWSTR RtlIpv4AddressToStringW(const in_addr*, PWSTR s) { if (s) *s = 0; return s; } +inline PWSTR RtlIpv6AddressToStringW(const in6_addr*, PWSTR s) { if (s) *s = 0; return s; } + +#define IN6ADDR_LOOPBACK_INIT { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } } } + +// CNdisApi: only the static checksum routines used by the redirect headers. Their definitions +// are extracted verbatim from ndisapi/ndisapi.cpp by run-portable-tests.sh, so the tests run the +// product implementations. +struct _INTERMEDIATE_BUFFER; +class CNdisApi +{ +public: + static void RecalculateIPChecksum(_INTERMEDIATE_BUFFER* pPacket); + static void RecalculateTCPChecksum(_INTERMEDIATE_BUFFER* pPacket); + static void RecalculateUDPChecksum(_INTERMEDIATE_BUFFER* pPacket); +}; diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp new file mode 100644 index 0000000..b72865d --- /dev/null +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -0,0 +1,404 @@ +// Global DNS routing policy (dns_routing_policy.h). +// +// These are the decisions socks_local_router's IPv4/IPv6 UDP/TCP packet handlers apply to every +// outbound packet before process attribution: Direct mode passes port-53 traffic, Proxy mode +// redirects it to the selected proxy's listener or blocks it (never passes it), ProxiFyre's own +// upstream traffic is never captured, and non-DNS traffic keeps its ordinary routing. They also +// cover the DNS server override syntax and the bookkeeping that restores override answers to +// the server the resolver originally queried. +// +// The header has no Windows dependencies, so this file also builds outside the Windows test +// project (see netlib/test/portable/run-portable-tests.sh). + +#include "pch.h" +#include "../../src/proxy/dns_routing_policy.h" + +#include +#include +#include + +namespace +{ + using proxy::decide_dns_route; + using proxy::dns_block_reason; + using proxy::dns_family; + using proxy::dns_message_id; + using proxy::dns_port; + using proxy::dns_proxy_target; + using proxy::dns_route_action; + using proxy::dns_routing_mode; + using proxy::dns_transport; + using proxy::split_dns_server_override; + + constexpr auto direct = dns_routing_mode::direct; + constexpr auto proxy_mode = dns_routing_mode::proxy; + + /// A selected proxy with listeners for every transport and family, mirroring the router's + /// dns_listener_port_locked() for one proxy index. + struct dns_proxy + { + bool tcp{ true }; + bool udp{ true }; + bool ipv4{ true }; + bool ipv6{ true }; + uint16_t tcp4{ 41001 }; + uint16_t udp4{ 41002 }; + uint16_t tcp6{ 41003 }; + uint16_t udp6{ 41004 }; + std::optional server_override; + + [[nodiscard]] dns_proxy_target target(const dns_transport transport, const dns_family family) const + { + const bool is_tcp = transport == dns_transport::tcp; + const bool is_v4 = family == dns_family::ipv4; + const uint16_t port = is_tcp ? (is_v4 ? tcp4 : tcp6) : (is_v4 ? udp4 : udp6); + + dns_proxy_target t; + t.selected = true; + t.transport_supported = is_tcp ? tcp : udp; + t.family_supported = is_v4 ? ipv4 : ipv6; + t.listener_port = port ? std::optional{ port } : std::nullopt; + t.override_configured = server_override.has_value(); + t.override_family_matches = server_override == family; + return t; + } + }; + + struct route_case + { + dns_transport transport; + dns_family family; + }; + + const route_case all_cases[] = { + { dns_transport::udp, dns_family::ipv4 }, + { dns_transport::udp, dns_family::ipv6 }, + { dns_transport::tcp, dns_family::ipv4 }, + { dns_transport::tcp, dns_family::ipv6 }, + }; +} + +// 1. Direct mode: UDP and TCP DNS over IPv4 and IPv6 pass, whatever proxy state exists. TCP/53 +// is now unconditionally direct (previously only UDP/53 was). +TEST(DnsRoutingPolicy, DirectModePassesUdpAndTcpDnsForBothFamilies) +{ + const dns_proxy configured{}; + for (const auto& c : all_cases) + { + EXPECT_EQ(decide_dns_route(direct, dns_port, false, configured.target(c.transport, c.family)).action, + dns_route_action::pass); + // No proxy selected at all: Direct still passes. + EXPECT_EQ(decide_dns_route(direct, dns_port, false, dns_proxy_target{}).action, dns_route_action::pass); + } +} + +// 2. Proxy mode: UDP DNS uses the UDP listener, TCP DNS the TCP listener, per address family. +TEST(DnsRoutingPolicy, ProxyModeRedirectsToTheListenerOfTheTransportAndFamily) +{ + const dns_proxy p{}; + const auto udp4 = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::udp, dns_family::ipv4)); + const auto udp6 = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::udp, dns_family::ipv6)); + const auto tcp4 = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::tcp, dns_family::ipv4)); + const auto tcp6 = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::tcp, dns_family::ipv6)); + + EXPECT_EQ(udp4.action, dns_route_action::proxy); + EXPECT_EQ(udp4.listener_port, p.udp4); + EXPECT_EQ(udp6.action, dns_route_action::proxy); + EXPECT_EQ(udp6.listener_port, p.udp6); + EXPECT_EQ(tcp4.action, dns_route_action::proxy); + EXPECT_EQ(tcp4.listener_port, p.tcp4); + EXPECT_EQ(tcp6.action, dns_route_action::proxy); + EXPECT_EQ(tcp6.listener_port, p.tcp6); +} + +// 3./4. The decision has no process input: queries from the Windows DNS Client service +// (svchost.exe), from an application with its own resolver, from an excluded application, +// or from an owner that cannot be resolved are all decided by port 53 and the global mode. +TEST(DnsRoutingPolicy, DecisionDoesNotDependOnTheSendingProcess) +{ + const dns_proxy p{}; + const auto target = p.target(dns_transport::udp, dns_family::ipv4); + const auto expected = decide_dns_route(proxy_mode, dns_port, false, target); + + // The only inputs are the mode, the destination port, the upstream guard, and the proxy. + // Calling the decision repeatedly (as each sender would) yields the same result. + for (int sender = 0; sender < 4; ++sender) + { + const auto decision = decide_dns_route(proxy_mode, dns_port, false, target); + EXPECT_EQ(decision.action, expected.action); + EXPECT_EQ(decision.listener_port, expected.listener_port); + } +} + +// 8./9. Fail closed: Proxy mode never passes DNS that the selected proxy cannot carry. +TEST(DnsRoutingPolicy, ProxyModeBlocksInsteadOfFallingBackToDirect) +{ + // No usable proxy (invalid reference or the proxy could not be created). + for (const auto& c : all_cases) + { + (void)c; + const auto d = decide_dns_route(proxy_mode, dns_port, false, dns_proxy_target{}); + EXPECT_EQ(d.action, dns_route_action::block); + EXPECT_EQ(d.reason, dns_block_reason::proxy_unavailable); + } + + // The proxy lacks the transport (unsupported protocol combination). + dns_proxy tcp_only{}; + tcp_only.udp = false; + auto d = decide_dns_route(proxy_mode, dns_port, false, tcp_only.target(dns_transport::udp, dns_family::ipv4)); + EXPECT_EQ(d.action, dns_route_action::block); + EXPECT_EQ(d.reason, dns_block_reason::transport_unsupported); + + // The proxy does not accept IPv6 destinations. + dns_proxy v4_only{}; + v4_only.ipv6 = false; + d = decide_dns_route(proxy_mode, dns_port, false, v4_only.target(dns_transport::tcp, dns_family::ipv6)); + EXPECT_EQ(d.action, dns_route_action::block); + EXPECT_EQ(d.reason, dns_block_reason::family_unsupported); + + // The listener is not running (for example the IPv6 listener failed to start). + dns_proxy no_v6_listener{}; + no_v6_listener.udp6 = 0; + d = decide_dns_route(proxy_mode, dns_port, false, no_v6_listener.target(dns_transport::udp, dns_family::ipv6)); + EXPECT_EQ(d.action, dns_route_action::block); + EXPECT_EQ(d.reason, dns_block_reason::listener_unavailable); + + // A missing listener port value and an explicit zero are both unusable. + auto target = dns_proxy{}.target(dns_transport::udp, dns_family::ipv4); + target.listener_port = std::nullopt; + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, false, target).action, dns_route_action::block); +} + +// 6. A server override applies to queries of its own family; queries of the other family are +// blocked rather than sent to their original (often local) server. +TEST(DnsRoutingPolicy, ServerOverrideFamilyIsHandledExplicitly) +{ + dns_proxy with_v4_override{}; + with_v4_override.server_override = dns_family::ipv4; + + for (const auto transport : { dns_transport::udp, dns_transport::tcp }) + { + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, false, with_v4_override.target(transport, dns_family::ipv4)).action, + dns_route_action::proxy); + + const auto other = decide_dns_route(proxy_mode, dns_port, false, with_v4_override.target(transport, dns_family::ipv6)); + EXPECT_EQ(other.action, dns_route_action::block); + EXPECT_EQ(other.reason, dns_block_reason::override_family_mismatch); + } + + dns_proxy with_v6_override{}; + with_v6_override.server_override = dns_family::ipv6; + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, false, with_v6_override.target(dns_transport::udp, dns_family::ipv6)).action, + dns_route_action::proxy); + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, false, with_v6_override.target(dns_transport::udp, dns_family::ipv4)).action, + dns_route_action::block); +} + +// 11. Recursion prevention: ProxiFyre's own traffic to an upstream SOCKS5 server (even one +// listening on port 53) is never redirected into the DNS proxy. +TEST(DnsRoutingPolicy, UpstreamProxyTrafficIsNeverCaptured) +{ + const dns_proxy p{}; + for (const auto& c : all_cases) + { + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, true, p.target(c.transport, c.family)).action, + dns_route_action::pass); + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, true, dns_proxy_target{}).action, dns_route_action::pass); + } +} + +// 15. Non-DNS traffic keeps its ordinary application routing in both modes; only the +// destination port classifies traffic. +TEST(DnsRoutingPolicy, NonDnsTrafficIsNotClassified) +{ + const dns_proxy p{}; + for (const uint16_t port : { uint16_t{ 0 }, uint16_t{ 52 }, uint16_t{ 54 }, uint16_t{ 80 }, uint16_t{ 443 }, + uint16_t{ 853 }, uint16_t{ 5353 }, uint16_t{ 5355 }, uint16_t{ 65535 } }) + { + for (const auto mode : { direct, proxy_mode }) + { + EXPECT_EQ(decide_dns_route(mode, port, false, p.target(dns_transport::udp, dns_family::ipv4)).action, + dns_route_action::not_dns) << port; + EXPECT_EQ(decide_dns_route(mode, port, true, dns_proxy_target{}).action, dns_route_action::not_dns) << port; + } + } +} + +// 14. A resolver that receives a truncated UDP answer retries over TCP to the same server. Both +// queries are routed through the same proxy, each through its own transport's listener. +TEST(DnsRoutingPolicy, TruncatedUdpAnswerTcpRetryUsesTheSameProxy) +{ + dns_proxy p{}; + p.server_override = dns_family::ipv4; + + const auto udp = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::udp, dns_family::ipv4)); + const auto tcp = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::tcp, dns_family::ipv4)); + EXPECT_EQ(udp.action, dns_route_action::proxy); + EXPECT_EQ(tcp.action, dns_route_action::proxy); + EXPECT_EQ(udp.listener_port, p.udp4); + EXPECT_EQ(tcp.listener_port, p.tcp4); +} + +TEST(DnsRoutingPolicy, BlockReasonsHaveDiagnostics) +{ + for (auto reason = static_cast(dns_block_reason::proxy_unavailable); + reason < static_cast(dns_block_reason::count); ++reason) + { + const std::string text = proxy::to_string(static_cast(reason)); + EXPECT_FALSE(text.empty()); + EXPECT_NE(text, "unknown"); + } +} + +TEST(DnsServerOverrideSyntax, AcceptsLiteralsWithOptionalPorts) +{ + struct expected + { + const char* input; + const char* address; + uint16_t port; + bool bracketed; + }; + + const expected cases[] = { + { "1.1.1.1", "1.1.1.1", 53, false }, + { " 1.1.1.1 ", "1.1.1.1", 53, false }, + { "1.1.1.1:5353", "1.1.1.1", 5353, false }, + { "192.168.1.1:53", "192.168.1.1", 53, false }, + { "2606:4700:4700::1111", "2606:4700:4700::1111", 53, false }, + { "::1", "::1", 53, false }, + { "[2606:4700:4700::1111]", "2606:4700:4700::1111", 53, true }, + { "[2606:4700:4700::1111]:853", "2606:4700:4700::1111", 853, true }, + { "[fe80::1]:65535", "fe80::1", 65535, true }, + }; + + for (const auto& c : cases) + { + const auto parsed = split_dns_server_override(c.input); + ASSERT_TRUE(parsed.has_value()) << c.input; + EXPECT_EQ(parsed->address, c.address) << c.input; + EXPECT_EQ(parsed->port, c.port) << c.input; + EXPECT_EQ(parsed->bracketed, c.bracketed) << c.input; + } +} + +TEST(DnsServerOverrideSyntax, RejectsMalformedValues) +{ + for (const auto* input : { "", " ", "1.1.1.1:", "1.1.1.1:0", "1.1.1.1:65536", "1.1.1.1:abc", "1.1.1.1:123456", + ":53", "[", "[]", "[]:53", "[::1", "[::1]53", "[::1]:", "[::1]:0", "dns server", + "fe80::1%12", "[fe80::1%eth0]:53", "a/b", "1.1.1.1 :53" }) + { + EXPECT_FALSE(split_dns_server_override(input).has_value()) << '"' << input << '"'; + } +} + +TEST(DnsMessageId, ReadsTheIdOfACompleteHeaderOnly) +{ + const uint8_t query[] = { 0xbe, 0xef, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + EXPECT_EQ(dns_message_id(query, sizeof(query)), uint16_t{ 0xbeef }); + EXPECT_FALSE(dns_message_id(query, sizeof(query) - 1).has_value()); + EXPECT_FALSE(dns_message_id(nullptr, 64).has_value()); +} + +namespace +{ + struct endpoint + { + std::string address; + uint16_t port{}; + bool operator==(const endpoint&) const = default; + }; + + using tracker = proxy::dns_udp_origin_tracker; + using clock = tracker::clock; +} + +// 6./7. Answers relayed from the override are mapped back to the original (often private) server +// by client port and DNS message ID. +TEST(DnsUdpOriginTracker, MapsOverrideAnswersToTheOriginalServer) +{ + tracker origins; + const auto now = clock::now(); + + origins.remember(50001, 0x1234, { "192.168.1.1", 53 }, now); + origins.remember(50001, 0x9999, { "10.0.0.53", 53 }, now); + origins.remember(50002, 0x1234, { "fd00::53", 53 }, now); + + EXPECT_EQ(origins.resolve(50001, 0x1234, now), (endpoint{ "192.168.1.1", 53 })); + EXPECT_EQ(origins.resolve(50001, 0x9999, now), (endpoint{ "10.0.0.53", 53 })); + EXPECT_EQ(origins.resolve(50002, 0x1234, now), (endpoint{ "fd00::53", 53 })); + + // Unknown query: no mapping (the router drops such an answer). + EXPECT_FALSE(origins.resolve(50003, 0x1234, now).has_value()); + EXPECT_FALSE(origins.resolve(50001, 0x4321, now).has_value()); + + // A lookup does not consume the entry: duplicate answers to a retransmitted query are + // restored consistently. + EXPECT_EQ(origins.resolve(50001, 0x1234, now), (endpoint{ "192.168.1.1", 53 })); + + // A retransmission to another server with the same port and ID updates the mapping. + origins.remember(50001, 0x1234, { "192.168.1.2", 53 }, now); + EXPECT_EQ(origins.resolve(50001, 0x1234, now), (endpoint{ "192.168.1.2", 53 })); +} + +TEST(DnsUdpOriginTracker, EntriesExpire) +{ + tracker origins{ std::chrono::seconds{ 30 } }; + const auto start = clock::now(); + origins.remember(50001, 1, { "192.168.1.1", 53 }, start); + origins.remember(50002, 2, { "192.168.1.1", 53 }, start + std::chrono::seconds{ 20 }); + + EXPECT_TRUE(origins.resolve(50001, 1, start + std::chrono::seconds{ 30 }).has_value()); + EXPECT_FALSE(origins.resolve(50001, 1, start + std::chrono::seconds{ 31 }).has_value()); + + origins.sweep(start + std::chrono::seconds{ 45 }); + EXPECT_EQ(origins.size(), 1u); + origins.sweep(start + std::chrono::seconds{ 60 }); + EXPECT_EQ(origins.size(), 0u); + + origins.remember(50003, 3, { "192.168.1.1", 53 }, start); + origins.clear(); + EXPECT_EQ(origins.size(), 0u); +} + +TEST(DnsUdpOriginTracker, IsBoundedAndEvictsTheOldestLiveEntry) +{ + tracker origins{ std::chrono::seconds{ 30 }, 3 }; + const auto start = clock::now(); + origins.remember(1, 1, { "a", 53 }, start); + origins.remember(2, 1, { "b", 53 }, start + std::chrono::milliseconds{ 1 }); + origins.remember(3, 1, { "c", 53 }, start + std::chrono::milliseconds{ 2 }); + origins.remember(4, 1, { "d", 53 }, start + std::chrono::milliseconds{ 3 }); + + EXPECT_EQ(origins.size(), 3u); + EXPECT_FALSE(origins.resolve(1, 1, start + std::chrono::milliseconds{ 4 }).has_value()); + EXPECT_TRUE(origins.resolve(4, 1, start + std::chrono::milliseconds{ 4 }).has_value()); + + // Expired entries are reclaimed before a live entry is evicted. + origins.remember(5, 1, { "e", 53 }, start + std::chrono::seconds{ 40 }); + EXPECT_EQ(origins.size(), 1u); +} + +TEST(DnsUdpOriginTracker, IsSafeForConcurrentPacketAndMaintenanceThreads) +{ + tracker origins{ std::chrono::seconds{ 30 }, 4096 }; + std::vector threads; + for (uint16_t t = 0; t < 4; ++t) + { + threads.emplace_back([&origins, t] + { + for (uint16_t i = 0; i < 2000; ++i) + { + const auto port = static_cast(10000 + t * 2000 + i); + origins.remember(port, i, { "server", 53 }); + EXPECT_TRUE(origins.resolve(port, i).has_value()); + if (i % 100 == 0) + origins.sweep(); + } + }); + } + for (auto& thread : threads) + thread.join(); + + EXPECT_LE(origins.size(), 4096u); +} diff --git a/socksify/Socksifier.cpp b/socksify/Socksifier.cpp index 205d89d..a8db69b 100644 --- a/socksify/Socksifier.cpp +++ b/socksify/Socksifier.cpp @@ -400,3 +400,29 @@ bool Socksifier::Socksifier::ExcludeProcessName(String^ excludedEntry) } return unmanaged_ptr_->exclude_process_name(msclr::interop::marshal_as(excludedEntry)); } + +/// +/// Configures global DNS routing via the unmanaged core. +/// +/// Direct or Proxy. +/// Handle of the DNS proxy, or -1 when it is unavailable. +/// Optional upstream DNS server literal. +/// True when the configuration was applied as requested, otherwise false. +bool Socksifier::Socksifier::SetDnsRouting(const DnsRoutingModeEnum mode, IntPtr proxy, String^ serverOverride) +{ + if (!unmanaged_ptr_) + return false; + + const auto mode_mx = mode == DnsRoutingModeEnum::Proxy + ? dns_routing_mode_mx::proxy + : dns_routing_mode_mx::direct; + const auto server_override_mx = String::IsNullOrWhiteSpace(serverOverride) + ? std::string{} + : msclr::interop::marshal_as(serverOverride->Trim()); + +#if _WIN64 + return unmanaged_ptr_->set_dns_routing(mode_mx, static_cast(proxy.ToInt64()), server_override_mx); +#else + return unmanaged_ptr_->set_dns_routing(mode_mx, static_cast(proxy.ToInt32()), server_override_mx); +#endif //_WIN64 +} diff --git a/socksify/Socksifier.h b/socksify/Socksifier.h index 4eebd2d..7a10f0a 100644 --- a/socksify/Socksifier.h +++ b/socksify/Socksifier.h @@ -109,6 +109,17 @@ namespace Socksifier TLS }; + /// + /// Specifies the global DNS routing mode. + /// + public enum class DnsRoutingModeEnum + { + /// Conventional DNS (UDP/TCP port 53) bypasses the SOCKS5 proxies. + Direct, + /// Conventional DNS is sent through one selected SOCKS5 proxy, or dropped. + Proxy + }; + /// /// Represents a single log entry for Socksifier events. /// @@ -340,6 +351,17 @@ namespace Socksifier /// True if exclusion was successful, otherwise false. bool ExcludeProcessName(String^ excludedEntry); + /// + /// Configures global DNS routing. Must be called before Start(). + /// + /// Direct or Proxy. + /// Handle of the proxy that carries DNS in Proxy mode, or -1 when the + /// selected proxy could not be created (DNS is then blocked rather than sent directly). + /// Optional IPv4/IPv6 literal (with optional port) used as the + /// upstream DNS server; null or empty keeps the original destination. + /// True when the configuration was applied as requested. + bool SetDnsRouting(DnsRoutingModeEnum mode, IntPtr proxy, String^ serverOverride); + /// /// Gets or sets the interval (in milliseconds) for log event notifications. /// diff --git a/socksify/mixed_types.h b/socksify/mixed_types.h index b577c8e..f178797 100644 --- a/socksify/mixed_types.h +++ b/socksify/mixed_types.h @@ -72,6 +72,17 @@ enum class socks5_transport_mx : uint8_t tls = 1 }; +/** + * @brief Specifies the global DNS routing mode. + */ +enum class dns_routing_mode_mx : uint8_t +{ + /// UDP/TCP port 53 traffic bypasses the SOCKS5 proxies. + direct = 0, + /// UDP/TCP port 53 traffic is sent through one selected SOCKS5 proxy or dropped. + proxy = 1 +}; + /** * @brief Enumerates the types of events that can occur in the proxy gateway. */ diff --git a/socksify/socksify.vcxproj b/socksify/socksify.vcxproj index 62081a9..efcc49d 100644 --- a/socksify/socksify.vcxproj +++ b/socksify/socksify.vcxproj @@ -268,6 +268,7 @@ + diff --git a/socksify/socksify.vcxproj.filters b/socksify/socksify.vcxproj.filters index 0e70381..23cba15 100644 --- a/socksify/socksify.vcxproj.filters +++ b/socksify/socksify.vcxproj.filters @@ -141,6 +141,9 @@ Header Files\netlib\proxy + + Header Files\netlib\proxy + Header Files\netlib\proxy diff --git a/socksify/socksify_unmanaged.cpp b/socksify/socksify_unmanaged.cpp index 040a67b..db653dc 100644 --- a/socksify/socksify_unmanaged.cpp +++ b/socksify/socksify_unmanaged.cpp @@ -384,6 +384,23 @@ bool socksify_unmanaged::exclude_process_name(const std::wstring& process_name) return proxy_->exclude_process_name(process_name); } +/** + * @brief Configures global DNS routing on the router. + */ +bool socksify_unmanaged::set_dns_routing(const dns_routing_mode_mx mode, const LONG_PTR proxy_id, + const std::string& server_override) const +{ + proxy::socks_local_router::dns_routing_settings settings; + settings.mode = mode == dns_routing_mode_mx::proxy + ? proxy::dns_routing_mode::proxy + : proxy::dns_routing_mode::direct; + if (proxy_id >= 0) + settings.proxy_id = static_cast(proxy_id); + settings.server_override = server_override; + + return proxy_->set_dns_routing(settings); +} + /** * @brief Sets the maximum number of log entries to keep. * @param log_limit The new log limit. diff --git a/socksify/socksify_unmanaged.h b/socksify/socksify_unmanaged.h index 780bef9..acc5bde 100644 --- a/socksify/socksify_unmanaged.h +++ b/socksify/socksify_unmanaged.h @@ -129,6 +129,18 @@ class socksify_unmanaged // NOLINT(clang-diagnostic-padded) LONG_PTR proxy_id) const; [[nodiscard]] bool exclude_process_name(const std::wstring& process_name) const; + /** + * @brief Configures global DNS routing. Must be called before start(). + * @param mode Direct or Proxy. + * @param proxy_id Handle returned by add_socks5_proxy() of the proxy that carries DNS in + * Proxy mode; -1 when the selected proxy could not be created (DNS is then blocked). + * @param server_override Optional IPv4/IPv6 literal (with optional port) used as the + * upstream DNS server; empty keeps the original destination. + * @return True when the configuration was applied as requested. + */ + [[nodiscard]] bool set_dns_routing(dns_routing_mode_mx mode, LONG_PTR proxy_id, + const std::string& server_override) const; + /** * @brief Sets the maximum number of log entries to keep. * @param log_limit The new log limit. From 510efc04bb80f7d0c4ae17874e9bb47373566a9e Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:41:08 +0000 Subject: [PATCH 02/62] fix: never pass local proxy listener replies to the wire; track TCP closes A packet sourced from a local proxy listener is addressed to the original server only because redirection swapped its addresses. When process_server_to_client_packet could not translate it, all four handlers fell through and passed it; for the DNS listener that sent the SOCKS5 header and the DNS answer toward the original resolver in clear (for example an answer large enough to fragment, or a relay replying with another ATYP). Such packets are now dropped (decide_listener_reply) and counted, with a throttled debug report. This must land together with the TCP close tracking: tcp_local_redirect erased its entry on the first FIN or RST, so the rest of an ordinary close found no entry. On the application path those segments reached the real server and provoked a RST, which is what tore the connection down; on the DNS path they were dropped and reported as blocked DNS. The entry is now kept through the close in both directions (half-closed 2 min, 10 s linger after both FINs, 5 min idle while open) and removed immediately on RST. A SYN on a closing key starts a new connection. This changes the application path too: trailing close segments are now translated instead of being passed to the real server. Tests: TCP client- and listener-initiated closes, FIN retransmits, RST from either side, the timeouts, key reuse, and the listener-drop rule. --- netlib/src/ndisapi/tcp_local_redirect.h | 357 +++++++++--------- netlib/src/proxy/dns_routing_policy.h | 28 ++ netlib/src/proxy/socks_local_router.h | 57 ++- .../portable/dns_packet_redirect_test.cpp | 191 ++++++++++ netlib/test/proxy/dns_routing_policy_test.cpp | 13 + 5 files changed, 468 insertions(+), 178 deletions(-) diff --git a/netlib/src/ndisapi/tcp_local_redirect.h b/netlib/src/ndisapi/tcp_local_redirect.h index 3b6c2a8..c3bd143 100644 --- a/netlib/src/ndisapi/tcp_local_redirect.h +++ b/netlib/src/ndisapi/tcp_local_redirect.h @@ -18,13 +18,51 @@ namespace ndisapi { using log_level = netlib::log::log_level; using logger = netlib::log::logger; - using timestamp_endpoint = std::pair; + public: + using clock = std::chrono::steady_clock; + + /// Idle lifetime of a redirected connection that has not started closing. + static constexpr std::chrono::seconds open_timeout{ 5 * 60 }; + + /// Idle lifetime once one side has sent FIN (half-closed). Data may still flow the other way. + static constexpr std::chrono::seconds half_closed_timeout{ 2 * 60 }; + + /// Lifetime once both sides have sent FIN, so the final ACK and FIN retransmissions of + /// either side are still translated instead of reaching the real server. + static constexpr std::chrono::seconds closed_linger{ 10 }; + + /** + * @brief Tracking state of one redirected connection. + * + * The entry is kept through the whole close: removing it on the first FIN (as earlier + * versions did) left the rest of the close untranslated, so the peer's ACK/FIN and FIN + * retransmissions were passed toward the real server. An RST removes the entry at once. + */ + struct connection_state + { + u_short original_port{}; ///< original destination port (network byte order) + clock::time_point last_activity; + bool client_fin{}; ///< the client sent FIN + bool server_fin{}; ///< the local proxy sent FIN + + /// The time after which the entry may be removed. + [[nodiscard]] clock::time_point expires_at() const noexcept + { + if (client_fin && server_fin) + return last_activity + closed_linger; + if (client_fin || server_fin) + return last_activity + half_closed_timeout; + return last_activity + open_timeout; + } + }; + + private: /** - * @brief Maps client TCP endpoint to a pair of (proxy port, last activity timestamp). - * Used for tracking active TCP connections. + * @brief Maps the client TCP endpoint (original destination address, client source port) + * to its tracking state. */ - std::unordered_map, timestamp_endpoint> redirected_connections_; + std::unordered_map, connection_state> redirected_connections_; /** * @brief Mutex for synchronizing access to redirected_connections_. @@ -49,8 +87,8 @@ namespace ndisapi /** * @brief Starts the background cleanup thread. * - * The thread periodically scans the redirected_connections_ map and removes entries - * that have been inactive for more than 5 minutes. + * The thread periodically removes entries whose lifetime has elapsed (see + * connection_state::expires_at()). */ void start_cleanup_thread() { @@ -58,27 +96,7 @@ namespace ndisapi { while (!terminate_) { - { - auto current_time = std::chrono::steady_clock::now(); - std::lock_guard lock(lock_); - - tools::generic::erase_if(redirected_connections_, redirected_connections_.begin(), - redirected_connections_.end(), - [¤t_time, this](auto&& a) - { - using namespace std::chrono_literals; - if (current_time - a.second.second > 5min) - { - NETLIB_DEBUG( - "DELETE TCP (timeout): {} -> {} : {}", - ntohs(a.first.port), - std::string{ a.first.ip }, - ntohs(a.second.first)); - return true; - } - return false; - }); - } + remove_expired(clock::now()); // Check terminate_ more frequently during sleep to allow faster shutdown using namespace std::chrono_literals; @@ -176,6 +194,133 @@ namespace ndisapi proxy_port_ = htons(proxy_port); } + /** + * @brief Removes connection entries whose lifetime has elapsed at @p now. + * + * Called periodically by the cleanup thread; public so the timeouts can be exercised + * deterministically. + */ + void remove_expired(const clock::time_point now) + { + std::lock_guard lock(lock_); + + tools::generic::erase_if(redirected_connections_, redirected_connections_.begin(), + redirected_connections_.end(), + [&now, this](auto&& a) + { + if (now < a.second.expires_at()) + return false; + + NETLIB_DEBUG( + "DELETE TCP (timeout): {} -> {} : {}", + ntohs(a.first.port), + std::string{ a.first.ip }, + ntohs(a.second.original_port)); + return true; + }); + } + + /** + * @brief Returns a copy of the tracking state for client endpoint + * (@p original_destination, @p client_port), where @p client_port is in network + * byte order. For diagnostics and tests. + */ + [[nodiscard]] std::optional find_connection(const T& original_destination, + const u_short client_port) + { + std::lock_guard lock(lock_); + const auto it = redirected_connections_.find(net::ip_endpoint{ original_destination, client_port }); + if (it == redirected_connections_.cend()) + return std::nullopt; + return it->second; + } + + private: + /** + * @brief Updates the tracking state for a client-to-server segment. The caller holds lock_. + * + * A SYN (without ACK) starts or restarts tracking: a retransmitted SYN refreshes the entry, + * and a SYN on a key whose previous connection is closing starts a new connection. Any + * other segment must belong to a tracked connection. + * + * @return false when the segment belongs to no tracked connection and must not be rewritten. + */ + bool track_client_segment(const net::ip_endpoint& key, const u_char flags, const u_short destination_port, + const T& source, const T& destination) + { + const auto now = clock::now(); + + if ((flags & (TH_SYN | TH_ACK)) == TH_SYN) + { + const auto [it, inserted] = redirected_connections_.try_emplace(key); + if (inserted) + { + NETLIB_DEBUG( + "NEW TCP: {}:{} -> {}:{}", + std::string{ source }, + ntohs(key.port), + std::string{ destination }, + ntohs(destination_port)); + } + + // A SYN whose key already exists is either a retransmission for a connection that + // is still being set up (the local listener has not completed the handshake) or a + // new connection reusing the key after the previous one closed. Both are rewritten + // to the local proxy: returning false would pass the SYN to the real destination, + // an unproxied leak of a connection we own. + it->second = connection_state{ destination_port, now, false, false }; + return true; + } + + const auto it = redirected_connections_.find(key); + if (it == redirected_connections_.cend()) + return false; + + if (flags & TH_RST) + { + NETLIB_DEBUG("DELETE TCP (client RST): {} -> {} : {}", + ntohs(it->first.port), std::string{ it->first.ip }, ntohs(it->second.original_port)); + redirected_connections_.erase(it); + return true; + } + + if (flags & TH_FIN) + it->second.client_fin = true; + + it->second.last_activity = now; + return true; + } + + /** + * @brief Updates the tracking state for a segment from the local proxy to the client. + * The caller holds lock_. + * @return the original destination port (network byte order) to present as the source + * port, or std::nullopt when the segment belongs to no tracked connection. + */ + std::optional track_server_segment(const net::ip_endpoint& key, const u_char flags) + { + const auto it = redirected_connections_.find(key); + if (it == redirected_connections_.cend()) + return std::nullopt; + + const auto original_port = it->second.original_port; + + if (flags & TH_RST) + { + NETLIB_DEBUG("DELETE TCP (proxy RST): {} -> {} : {}", + ntohs(it->first.port), std::string{ it->first.ip }, ntohs(original_port)); + redirected_connections_.erase(it); + return original_port; + } + + if (flags & TH_FIN) + it->second.server_fin = true; + + it->second.last_activity = clock::now(); + return original_port; + } + + public: /** * @brief Redirects a C2S TCP packet to the local proxy and applies NAT to the source port. * @@ -215,58 +360,9 @@ namespace ndisapi std::lock_guard lock(lock_); - if ((tcp_header->th_flags & (TH_SYN | TH_ACK)) == TH_SYN) - { - if (const auto [it, result] = redirected_connections_.emplace( - net::ip_endpoint{T{ ip_header->ip_dst }, tcp_header->th_sport}, - timestamp_endpoint{ - tcp_header->th_dport, - std::chrono::steady_clock::now() - }); result) - { - NETLIB_DEBUG( - "NEW TCP: {}:{} -> {}:{}", - std::string{ T{ip_header->ip_src} }, - ntohs(tcp_header->th_sport), - std::string{ T{ip_header->ip_dst} }, - ntohs(tcp_header->th_dport)); - } - else - { - // A SYN whose {dst, src-port} key already exists is a SYN RETRANSMISSION - // for a connection we are already redirecting (the local listener has not - // finished the handshake yet, so the client retransmits). Returning false - // here would make the caller PASS the retransmit to the real destination -- - // an unproxied leak of a connection we own. Refresh the timestamp and fall - // through to rewrite this SYN to the local proxy, exactly like the first one. - it->second.second = std::chrono::steady_clock::now(); - } - } - else - { - // existing connection - const auto it = redirected_connections_.find(net::ip_endpoint{ - T{ ip_header->ip_dst }, tcp_header->th_sport - }); - if (it == redirected_connections_.cend()) - return false; - - if (tcp_header->th_flags & TH_RST || tcp_header->th_flags & TH_FIN) - { - // pass through but erase the corresponding entry - NETLIB_DEBUG( - "DELETE TCP: {} -> {} : {}", - ntohs(it->first.port), - std::string{ it->first.ip }, - ntohs(it->second.first)); - - redirected_connections_.erase(it); - } - else - { - it->second.second = std::chrono::steady_clock::now(); - } - } + if (!track_client_segment(net::ip_endpoint{ T{ ip_header->ip_dst }, tcp_header->th_sport }, + tcp_header->th_flags, tcp_header->th_dport, T{ ip_header->ip_src }, T{ ip_header->ip_dst })) + return false; // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -297,56 +393,9 @@ namespace ndisapi std::lock_guard lock(lock_); - if ((tcp_header->th_flags & (TH_SYN | TH_ACK)) == TH_SYN) - { - if (const auto [it, result] = redirected_connections_.emplace( - net::ip_endpoint{T{ ip_header->ip6_dst }, tcp_header->th_sport}, - timestamp_endpoint{ - tcp_header->th_dport, - std::chrono::steady_clock::now() - }); result) - { - NETLIB_DEBUG( - "NEW TCP: {}:{} -> {}:{}", - std::string{ T{ip_header->ip6_src} }, - ntohs(tcp_header->th_sport), - std::string{ T{ip_header->ip6_dst} }, - ntohs(tcp_header->th_dport)); - } - else - { - // SYN retransmission for a connection we already redirect (see the IPv4 - // path): refresh the timestamp and rewrite it to the local proxy instead - // of leaking the retransmit to the real destination. - it->second.second = std::chrono::steady_clock::now(); - } - } - else - { - // existing connection - const auto it = redirected_connections_.find(net::ip_endpoint{ - T{ ip_header->ip6_dst }, tcp_header->th_sport - }); - if (it == redirected_connections_.cend()) - return false; - - if (tcp_header->th_flags & TH_RST || tcp_header->th_flags & TH_FIN) - { - // pass through but erase the corresponding entry - NETLIB_DEBUG( - "DELETE TCP: {}:{} -> {}:{}", - std::string{ it->first.ip }, - ntohs(it->first.port), - std::string{ it->first.ip }, - ntohs(it->second.first)); - - redirected_connections_.erase(it); - } - else - { - it->second.second = std::chrono::steady_clock::now(); - } - } + if (!track_client_segment(net::ip_endpoint{ T{ ip_header->ip6_dst }, tcp_header->th_sport }, + tcp_header->th_flags, tcp_header->th_dport, T{ ip_header->ip6_src }, T{ ip_header->ip6_dst })) + return false; //Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -399,29 +448,12 @@ namespace ndisapi std::lock_guard lock(lock_); - const auto it = redirected_connections_.find(net::ip_endpoint{ - T{ ip_header->ip_dst }, tcp_header->th_dport - }); - if (it == redirected_connections_.cend()) + const auto original_port = track_server_segment( + net::ip_endpoint{ T{ ip_header->ip_dst }, tcp_header->th_dport }, tcp_header->th_flags); + if (!original_port) return false; - tcp_header->th_sport = it->second.first; - - if (tcp_header->th_flags & TH_RST || tcp_header->th_flags & TH_FIN) - { - // pass through but erase the corresponding entry - NETLIB_DEBUG( - "DELETE TCP: {} -> {} : {}", - ntohs(it->first.port), - std::string{ it->first.ip }, - ntohs(it->second.first)); - - redirected_connections_.erase(it); - } - else - { - it->second.second = std::chrono::steady_clock::now(); - } + tcp_header->th_sport = *original_port; // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -450,29 +482,12 @@ namespace ndisapi std::lock_guard lock(lock_); - const auto it = redirected_connections_.find(net::ip_endpoint{ - T{ ip_header->ip6_dst }, tcp_header->th_dport - }); - if (it == redirected_connections_.cend()) + const auto original_port = track_server_segment( + net::ip_endpoint{ T{ ip_header->ip6_dst }, tcp_header->th_dport }, tcp_header->th_flags); + if (!original_port) return false; - tcp_header->th_sport = it->second.first; - - if (tcp_header->th_flags & TH_RST || tcp_header->th_flags & TH_FIN) - { - // pass through but erase the corresponding entry - NETLIB_DEBUG( - "DELETE TCP: {} -> {} : {}", - ntohs(it->first.port), - std::string{ it->first.ip }, - ntohs(it->second.first)); - - redirected_connections_.erase(it); - } - else - { - it->second.second = std::chrono::steady_clock::now(); - } + tcp_header->th_sport = *original_port; // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index e94c90b..4ca7ddb 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -146,6 +146,32 @@ namespace proxy } } + /// What a packet handler does with an outbound packet whose source port is the port of one of + /// ProxiFyre's local proxy listeners. + enum class listener_reply_action : uint8_t + { + not_listener, ///< not sourced from a local listener: continue with the normal routing + revert, ///< translated back to the original server/client: re-inject it to the stack + drop ///< not translatable: drop it + }; + + /** + * @brief Decides what to do with a packet sourced from a local proxy listener. + * + * A listener reply is addressed to the original server only because redirection swapped the + * addresses; it never belongs on the wire. When it cannot be translated back (no tracked + * connection or endpoint, a fragmented or malformed datagram, a relay header of the wrong + * address type), passing it would send the listener's bytes - for the DNS proxy, the SOCKS5 + * header and the DNS answer - toward the real server in clear, so it is dropped. + */ + [[nodiscard]] constexpr listener_reply_action decide_listener_reply( + const bool source_is_listener, const bool translated) noexcept + { + if (!source_is_listener) + return listener_reply_action::not_listener; + return translated ? listener_reply_action::revert : listener_reply_action::drop; + } + /// A DNS server override split into its literal address text and port. struct dns_server_override_text { @@ -466,6 +492,8 @@ namespace proxy } // Compile-time checks of the decision table's key invariants. + static_assert(decide_listener_reply(true, false) == listener_reply_action::drop, + "An untranslatable listener reply must never be passed to the wire."); static_assert(decide_dns_route(dns_routing_mode::direct, 443, false, {}).action == dns_route_action::not_dns, "Non-DNS traffic must keep its ordinary routing."); static_assert(decide_dns_route(dns_routing_mode::direct, dns_port, false, {}).action == dns_route_action::pass, diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 00a6b6a..5fa9848 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -284,6 +284,13 @@ namespace proxy */ std::atomic dns_blocked_packets_{ 0 }; + /** + * @brief Count of packets sourced from a local proxy listener that could not be + * translated back and were dropped instead of being passed to the wire. Reported + * at a throttled rate by the resolver thread. + */ + std::atomic untranslated_listener_replies_{ 0 }; + /** * @brief One-shot flags so that each (family, transport, reason) block cause is * described once in the log instead of once per packet. @@ -961,6 +968,7 @@ namespace proxy dns_udp_origins_v4_.clear(); dns_udp_origins_v6_.clear(); dns_blocked_packets_.store(0, std::memory_order_relaxed); + untranslated_listener_replies_.store(0, std::memory_order_relaxed); for (auto& flag : dns_block_reason_logged_) flag.clear(std::memory_order_relaxed); install_dns_filters(); @@ -2561,11 +2569,16 @@ namespace proxy if (restore == dns_reply_restore::drop) return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; - if (udp_redirect_->process_server_to_client_packet(buffer, origin)) + // A listener reply never belongs on the wire: drop it when it cannot be translated. + if (decide_listener_reply(true, udp_redirect_->process_server_to_client_packet(buffer, origin)) == + listener_reply_action::revert) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } + + untranslated_listener_replies_.fetch_add(1, std::memory_order_relaxed); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; } // Conventional DNS (destination port 53) follows the global DNS policy, before and @@ -2675,11 +2688,19 @@ namespace proxy // If the packet is from a known proxy port, process for server-to-client redirection if (is_tcp_proxy_port(ntohs(tcp_header->th_sport))) { - if (tcp_redirect_->process_server_to_client_packet(buffer)) + // A listener segment never belongs on the wire: drop it when it cannot be + // translated (for example after its connection entry expired), instead of letting + // it reach the real server. tcp_local_redirect tracks the whole close, so ordinary + // FIN/ACK exchanges are translated. + if (decide_listener_reply(true, tcp_redirect_->process_server_to_client_packet(buffer)) == + listener_reply_action::revert) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } + + untranslated_listener_replies_.fetch_add(1, std::memory_order_relaxed); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; } // Conventional DNS over TCP follows the global DNS policy. In Direct mode TCP/53 is @@ -2856,11 +2877,16 @@ namespace proxy if (restore == dns_reply_restore::drop) return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; - if (udp_redirect_v6_->process_server_to_client_packet(buffer, origin)) + // A listener reply never belongs on the wire: drop it when it cannot be translated. + if (decide_listener_reply(true, udp_redirect_v6_->process_server_to_client_packet(buffer, origin)) == + listener_reply_action::revert) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } + + untranslated_listener_replies_.fetch_add(1, std::memory_order_relaxed); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; } // Conventional DNS follows the global DNS policy (mirrors the IPv4 path). @@ -2964,11 +2990,19 @@ namespace proxy // If the packet is from a known proxy port, process for server-to-client redirection if (is_tcp_proxy_port_v6(ntohs(tcp_header->th_sport))) { - if (tcp_redirect_v6_->process_server_to_client_packet(buffer)) + // A listener segment never belongs on the wire: drop it when it cannot be + // translated (for example after its connection entry expired), instead of letting + // it reach the real server. tcp_local_redirect tracks the whole close, so ordinary + // FIN/ACK exchanges are translated. + if (decide_listener_reply(true, tcp_redirect_v6_->process_server_to_client_packet(buffer)) == + listener_reply_action::revert) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } + + untranslated_listener_replies_.fetch_add(1, std::memory_order_relaxed); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; } // Conventional DNS over TCP follows the global DNS policy (mirrors the IPv4 path). @@ -3252,11 +3286,13 @@ namespace proxy dns_udp_origins_v6_.sweep(now); } - // Report Proxy-mode DNS drops at the same throttled rate as the queue drops so - // a resolver retrying against an unreachable proxy cannot flood the log. + // Report Proxy-mode DNS drops and untranslatable listener replies at the same + // throttled rate as the queue drops so a resolver retrying against an + // unreachable proxy cannot flood the log. if (const auto now = std::chrono::steady_clock::now(); now - last_dns_block_log >= drop_log_throttle_interval_ && - dns_blocked_packets_.load(std::memory_order_relaxed) != 0) + (dns_blocked_packets_.load(std::memory_order_relaxed) != 0 || + untranslated_listener_replies_.load(std::memory_order_relaxed) != 0)) { last_dns_block_log = now; if (const auto blocked = dns_blocked_packets_.exchange(0, std::memory_order_relaxed); blocked != 0) @@ -3265,6 +3301,13 @@ namespace proxy "DNS routing: dropped {} DNS packet(s) that could not be sent through the DNS proxy " "(they were not sent directly).", blocked); } + if (const auto untranslated = untranslated_listener_replies_.exchange(0, std::memory_order_relaxed); + untranslated != 0) + { + NETLIB_LOG(log_level::debug, + "Dropped {} packet(s) from local proxy listeners that could not be translated back " + "(no tracked connection, fragmented, or malformed).", untranslated); + } } // Periodically surface the counts of packets dropped due to a diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index 9e3812c..b5b9752 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -437,3 +437,194 @@ TEST(DnsPacketRedirect, TcpSegmentOfAnUnknownConnectionIsRejectedSoTheRouterDrop auto data = frame::tcp4("192.168.1.10", "192.168.1.1", client_port, 53, TH_ACK | TH_PSH); EXPECT_FALSE(redirect.process_client_to_server_packet(data.buffer, htons(tcp_listener))); } + +// ------------------------------------------------------------------ TCP close tracking +// +// tcp_local_redirect keeps a connection's entry through the whole close. Every segment of an +// ordinary close is translated in both directions, so nothing is left for the router to drop +// (and count as blocked DNS) or, on the application path, to pass toward the real server. + +namespace +{ + using tcp_redirect4 = ndisapi::tcp_local_redirect; + constexpr const char* tcp_client = "192.168.1.10"; + constexpr const char* tcp_server = "192.168.1.1"; + + /// A client-to-server segment, before redirection. + frame client_segment(const uint8_t flags, const uint16_t dport = 53) + { + return frame::tcp4(tcp_client, tcp_server, client_port, dport, flags); + } + + /// A segment from the local listener to the (swapped) original server address. + frame listener_segment(const uint8_t flags) + { + return frame::tcp4(tcp_client, tcp_server, tcp_listener, client_port, flags); + } + + bool send_client(tcp_redirect4& redirect, const uint8_t flags, const uint16_t dport = 53) + { + auto segment = client_segment(flags, dport); + return redirect.process_client_to_server_packet(segment.buffer, htons(tcp_listener)); + } + + /// Sends a listener segment and returns the source port the client sees, if translated. + std::optional send_listener(tcp_redirect4& redirect, const uint8_t flags) + { + auto segment = listener_segment(flags); + if (!redirect.process_server_to_client_packet(segment.buffer)) + return std::nullopt; + EXPECT_EQ(v4{ segment.ip4()->ip_src }, v4{ std::string{ tcp_server } }); + EXPECT_TRUE(segment.ip4_checksum_valid()); + EXPECT_TRUE(segment.l4_checksum_valid()); + return ntohs(segment.tcp()->th_sport); + } + + std::optional state_of(tcp_redirect4& redirect) + { + return redirect.find_connection(v4{ std::string{ tcp_server } }, htons(client_port)); + } + + void establish(tcp_redirect4& redirect) + { + ASSERT_TRUE(send_client(redirect, TH_SYN)); + ASSERT_EQ(send_listener(redirect, TH_SYN | TH_ACK), uint16_t{ 53 }); + ASSERT_TRUE(send_client(redirect, TH_ACK)); + } +} + +TEST(DnsTcpCloseTracking, ClientInitiatedCloseIsTranslatedToTheEnd) +{ + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + + EXPECT_TRUE(send_client(redirect, TH_FIN | TH_ACK)); + ASSERT_TRUE(state_of(redirect).has_value()); + EXPECT_TRUE(state_of(redirect)->client_fin); + EXPECT_FALSE(state_of(redirect)->server_fin); + + // The listener's ACK and FIN still reach the client as coming from the server's port 53. + EXPECT_EQ(send_listener(redirect, TH_ACK), uint16_t{ 53 }); + EXPECT_EQ(send_listener(redirect, TH_FIN | TH_ACK), uint16_t{ 53 }); + ASSERT_TRUE(state_of(redirect).has_value()); + EXPECT_TRUE(state_of(redirect)->server_fin); + + // The client's final ACK is translated too. + EXPECT_TRUE(send_client(redirect, TH_ACK)); + + // The entry lingers briefly after the close completes, then expires. + const auto now = std::chrono::steady_clock::now(); + redirect.remove_expired(now); + EXPECT_TRUE(state_of(redirect).has_value()); + redirect.remove_expired(now + tcp_redirect4::closed_linger + std::chrono::seconds{ 1 }); + EXPECT_FALSE(state_of(redirect).has_value()); + + // A listener segment after expiry is not translated (the router then drops it). + EXPECT_FALSE(send_listener(redirect, TH_ACK).has_value()); +} + +TEST(DnsTcpCloseTracking, ListenerInitiatedCloseAllowsTheHalfClosedSideToFinish) +{ + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + + EXPECT_EQ(send_listener(redirect, TH_FIN | TH_ACK), uint16_t{ 53 }); + EXPECT_TRUE(state_of(redirect)->server_fin); + + // Half-closed: the client may still send data before its own FIN. + EXPECT_TRUE(send_client(redirect, TH_ACK)); + EXPECT_TRUE(send_client(redirect, TH_PSH | TH_ACK)); + EXPECT_TRUE(send_client(redirect, TH_FIN | TH_ACK)); + EXPECT_EQ(send_listener(redirect, TH_ACK), uint16_t{ 53 }); +} + +TEST(DnsTcpCloseTracking, FinRetransmissionsAreTranslated) +{ + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + + EXPECT_TRUE(send_client(redirect, TH_FIN | TH_ACK)); + EXPECT_TRUE(send_client(redirect, TH_FIN | TH_ACK)); + EXPECT_EQ(send_listener(redirect, TH_FIN | TH_ACK), uint16_t{ 53 }); + EXPECT_EQ(send_listener(redirect, TH_FIN | TH_ACK), uint16_t{ 53 }); + EXPECT_TRUE(send_client(redirect, TH_FIN | TH_ACK)); + EXPECT_TRUE(send_client(redirect, TH_ACK)); +} + +TEST(DnsTcpCloseTracking, RstFromEitherSideIsTranslatedAndEndsTrackingImmediately) +{ + { + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + EXPECT_TRUE(send_client(redirect, TH_RST | TH_ACK)); + EXPECT_FALSE(state_of(redirect).has_value()); + EXPECT_FALSE(send_client(redirect, TH_ACK)); + } + { + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + EXPECT_TRUE(send_client(redirect, TH_FIN | TH_ACK)); + EXPECT_EQ(send_listener(redirect, TH_RST), uint16_t{ 53 }); + EXPECT_FALSE(state_of(redirect).has_value()); + EXPECT_FALSE(send_listener(redirect, TH_ACK).has_value()); + } +} + +TEST(DnsTcpCloseTracking, IdleTimeoutsDependOnTheCloseState) +{ + const auto now = std::chrono::steady_clock::now(); + + tcp_redirect4 open{ log_level::error }; + establish(open); + open.remove_expired(now + tcp_redirect4::open_timeout - std::chrono::seconds{ 5 }); + EXPECT_TRUE(state_of(open).has_value()); + open.remove_expired(now + tcp_redirect4::open_timeout + std::chrono::seconds{ 5 }); + EXPECT_FALSE(state_of(open).has_value()); + + tcp_redirect4 half_closed{ log_level::error }; + establish(half_closed); + EXPECT_TRUE(send_client(half_closed, TH_FIN | TH_ACK)); + half_closed.remove_expired(now + tcp_redirect4::half_closed_timeout - std::chrono::seconds{ 5 }); + EXPECT_TRUE(state_of(half_closed).has_value()); + half_closed.remove_expired(now + tcp_redirect4::half_closed_timeout + std::chrono::seconds{ 5 }); + EXPECT_FALSE(state_of(half_closed).has_value()); + + static_assert(tcp_redirect4::closed_linger < tcp_redirect4::half_closed_timeout); + static_assert(tcp_redirect4::half_closed_timeout < tcp_redirect4::open_timeout); +} + +TEST(DnsTcpCloseTracking, NewSynOnAClosingKeyStartsANewConnection) +{ + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + EXPECT_TRUE(send_client(redirect, TH_FIN | TH_ACK)); + EXPECT_EQ(send_listener(redirect, TH_FIN | TH_ACK), uint16_t{ 53 }); + + // The client reuses its source port for a connection to another destination port. + ASSERT_TRUE(send_client(redirect, TH_SYN, 853)); + ASSERT_TRUE(state_of(redirect).has_value()); + EXPECT_FALSE(state_of(redirect)->client_fin); + EXPECT_FALSE(state_of(redirect)->server_fin); + EXPECT_EQ(send_listener(redirect, TH_SYN | TH_ACK), uint16_t{ 853 }); + + // A retransmitted SYN of a connection being set up refreshes it and is still redirected. + EXPECT_TRUE(send_client(redirect, TH_SYN, 853)); + EXPECT_EQ(send_listener(redirect, TH_SYN | TH_ACK), uint16_t{ 853 }); +} + +// 1. A listener segment that cannot be translated is dropped by the router rather than passed: +// the decision the four handlers apply to process_server_to_client_packet's result. +TEST(DnsTcpCloseTracking, UntranslatableListenerSegmentIsDropped) +{ + tcp_redirect4 redirect{ log_level::error }; + auto stray = listener_segment(TH_ACK); + const bool translated = redirect.process_server_to_client_packet(stray.buffer); + EXPECT_FALSE(translated); + EXPECT_EQ(proxy::decide_listener_reply(true, translated), proxy::listener_reply_action::drop); + + ndisapi::socks5_udp_local_redirect udp{ log_level::error }; + auto unknown = local_proxy_reply("192.168.1.10", "192.168.1.1", v4{ std::string{ "192.168.1.1" } }, 53, dns_message(1)); + const bool udp_translated = udp.process_server_to_client_packet(unknown.buffer); + EXPECT_FALSE(udp_translated); + EXPECT_EQ(proxy::decide_listener_reply(true, udp_translated), proxy::listener_reply_action::drop); +} diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index b72865d..8c78f2a 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -402,3 +402,16 @@ TEST(DnsUdpOriginTracker, IsSafeForConcurrentPacketAndMaintenanceThreads) EXPECT_LE(origins.size(), 4096u); } + +// 1. Packets sourced from a local proxy listener are re-injected when translated and dropped +// otherwise; they are never passed to the wire. Other packets continue with normal routing. +TEST(ListenerReplyPolicy, UntranslatedListenerRepliesAreDroppedNeverPassed) +{ + using proxy::decide_listener_reply; + using proxy::listener_reply_action; + + EXPECT_EQ(decide_listener_reply(true, true), listener_reply_action::revert); + EXPECT_EQ(decide_listener_reply(true, false), listener_reply_action::drop); + EXPECT_EQ(decide_listener_reply(false, false), listener_reply_action::not_listener); + EXPECT_EQ(decide_listener_reply(false, true), listener_reply_action::not_listener); +} From cdebe109550911c2f35dcbb61ebd99d67f83b52b Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:44:01 +0000 Subject: [PATCH 03/62] fix: exempt only ProxiFyre's own traffic to a SOCKS5 server from the DNS policy The recursion guard matched UDP by destination address only, so when a host was both the SOCKS5 server and the resolver every UDP query to it went direct, ignoring serverOverride, with no log line. The address (and, for TCP, port) match is now only a cheap pre-filter. A matching port-53 packet is exempt only when its owner is ProxiFyre's own process. The process lookup runs only for such packets and without holding lock_. An owner that cannot be resolved inline defers the packet to the existing deferred-resolve path; if it is still unknown there, the packet is dropped and counted (upstream_sender_unknown): passing it could leak a query and redirecting ProxiFyre's own traffic would loop. The TCP guard uses the same sender check. The decision is in decide_dns_upstream_guard() and decide_dns_route() (dns_routing_policy.h) and covered by the policy tests. The stated limitation is removed from docs/configuration.md. --- docs/configuration.md | 2 +- netlib/src/proxy/dns_routing_policy.h | 84 +++++++--- netlib/src/proxy/socks_local_router.h | 144 ++++++++++++++---- netlib/test/proxy/dns_routing_policy_test.cpp | 89 +++++++---- 4 files changed, 244 insertions(+), 75 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 8f0d8b3..1cbaa3e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -190,7 +190,7 @@ Proxy with an IPv4 override for a configuration that uses a router-provided reso ### Recursion and ProxiFyre's own traffic -SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. Traffic addressed to a configured SOCKS5 server itself (TCP to its address and port, UDP to its address) is never redirected, even if the server listens on port 53. A consequence is that a DNS query addressed to the SOCKS5 server's own IP address is sent directly to that server. +SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. ProxiFyre's own traffic to a configured SOCKS5 server is never redirected into the DNS proxy, even if the server listens on port 53: a port-53 packet addressed to a SOCKS5 server (TCP: its address and port; UDP: its address) is exempt only when its sending process is ProxiFyre itself. Queries from any other process to a host that is both the SOCKS5 server and a resolver follow the DNS policy like any other query, including `serverOverride`. If the sender of such a packet cannot be determined, even after the connection table is refreshed, the packet is dropped rather than passed or redirected. ### Limitations diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 4ca7ddb..a84f959 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -40,7 +40,8 @@ namespace proxy not_dns, ///< not conventional DNS: continue with the ordinary application routing pass, ///< DNS that stays direct proxy, ///< redirect to the selected proxy's local listener (dns_route_decision::listener_port) - block ///< DNS that must use the proxy but cannot: drop it, never send it direct + block, ///< DNS that must use the proxy but cannot: drop it, never send it direct + defer ///< addressed to a SOCKS5 server and its sender is not known yet: resolve it later }; /// Why Proxy mode blocked a DNS packet; used for throttled diagnostics. @@ -54,6 +55,7 @@ namespace proxy override_family_mismatch, ///< a server override of the other address family is configured redirect_failed, ///< the packet could not be redirected (e.g. fragmented, oversized, ///< or a TCP segment of a connection opened before ProxiFyre started) + upstream_sender_unknown, ///< addressed to a SOCKS5 server, and its sender could not be resolved count }; @@ -81,27 +83,65 @@ namespace proxy bool override_family_matches{}; ///< the override has the family of this packet }; + /// Outcome of the recursion guard for a port-53 packet in Proxy mode. + enum class dns_upstream_guard : uint8_t + { + apply_policy, ///< not ProxiFyre's own traffic to a SOCKS5 server: apply the DNS policy + exempt, ///< ProxiFyre's own traffic to one of its SOCKS5 servers: pass it + defer, ///< addressed to a SOCKS5 server, sender not resolved yet: resolve it later + drop ///< addressed to a SOCKS5 server, sender still unresolved: drop it + }; + + /** + * @brief The recursion guard: keeps ProxiFyre's own SOCKS5 traffic out of the DNS proxy. + * + * Matching the destination against the configured SOCKS5 servers is only a cheap pre-filter. + * A host can be both the SOCKS5 server and a resolver, so a packet addressed to it is exempt + * only when its sender is ProxiFyre itself; anyone else's query to that host is subject to + * the DNS policy like any other. When the sender cannot be determined inline the packet is + * deferred to the resolver thread; if it is still unknown there it is dropped: passing it + * could leak a query, and redirecting ProxiFyre's own traffic would loop. + * + * @param destination_matches_upstream The destination is a configured SOCKS5 server (UDP: its + * address; TCP: its address and port). + * @param sender_is_proxifyre Whether the resolved owner is ProxiFyre's own process; nullopt + * when the owner is not resolved. Only consulted when the destination matches. + * @param sender_lookup_final The lookup used a refreshed connection table (deferred path). + */ + [[nodiscard]] constexpr dns_upstream_guard decide_dns_upstream_guard( + const bool destination_matches_upstream, + const std::optional sender_is_proxifyre, + const bool sender_lookup_final) noexcept + { + if (!destination_matches_upstream) + return dns_upstream_guard::apply_policy; + if (sender_is_proxifyre) + return *sender_is_proxifyre ? dns_upstream_guard::exempt : dns_upstream_guard::apply_policy; + return sender_lookup_final ? dns_upstream_guard::drop : dns_upstream_guard::defer; + } + /** * @brief Decides how a captured outbound packet addressed to @p destination_port is routed. * - * The decision depends only on the destination port, the global mode, and the selected - * proxy. It never depends on the process that sent the packet, so traffic from the Windows - * DNS Client service (svchost.exe) and from applications with their own resolvers is - * treated identically, independently of application rules and exclusions. + * Apart from the recursion guard (see decide_dns_upstream_guard()), the decision depends + * only on the destination port, the global mode, and the selected proxy. It does not depend + * on the process that sent the packet, so traffic from the Windows DNS Client service + * (svchost.exe) and from applications with their own resolvers is treated identically, + * independently of application rules and exclusions. * - * @param destination_is_upstream The packet is addressed to one of ProxiFyre's own SOCKS5 - * upstream servers (recursion guard: ProxiFyre's own proxy traffic is never captured). + * @param guard The recursion guard's outcome for this packet (apply_policy when the + * destination is not a SOCKS5 server). */ [[nodiscard]] constexpr dns_route_decision decide_dns_route( const dns_routing_mode mode, const uint16_t destination_port, - const bool destination_is_upstream, + const dns_upstream_guard guard, const dns_proxy_target& target) noexcept { if (destination_port != dns_port) return { dns_route_action::not_dns, dns_block_reason::none, 0 }; - if (mode == dns_routing_mode::direct || destination_is_upstream) + if (mode == dns_routing_mode::direct || guard == dns_upstream_guard::exempt) return { dns_route_action::pass, dns_block_reason::none, 0 }; const auto block = [](const dns_block_reason reason) constexpr @@ -109,6 +149,11 @@ namespace proxy return dns_route_decision{ dns_route_action::block, reason, 0 }; }; + if (guard == dns_upstream_guard::defer) + return { dns_route_action::defer, dns_block_reason::none, 0 }; + if (guard == dns_upstream_guard::drop) + return block(dns_block_reason::upstream_sender_unknown); + if (!target.selected) return block(dns_block_reason::proxy_unavailable); if (!target.transport_supported) @@ -141,6 +186,9 @@ namespace proxy case dns_block_reason::redirect_failed: return "the packet could not be redirected to the DNS proxy (fragmented, oversized, " "not a DNS message, or part of a TCP connection opened before ProxiFyre started)"; + case dns_block_reason::upstream_sender_unknown: + return "the packet is addressed to a configured SOCKS5 server and its sending process could not be " + "resolved, so it cannot be identified as ProxiFyre's own traffic"; default: return "unknown"; } @@ -494,12 +542,14 @@ namespace proxy // Compile-time checks of the decision table's key invariants. static_assert(decide_listener_reply(true, false) == listener_reply_action::drop, "An untranslatable listener reply must never be passed to the wire."); - static_assert(decide_dns_route(dns_routing_mode::direct, 443, false, {}).action == dns_route_action::not_dns, - "Non-DNS traffic must keep its ordinary routing."); - static_assert(decide_dns_route(dns_routing_mode::direct, dns_port, false, {}).action == dns_route_action::pass, - "Direct mode must pass DNS without consulting a proxy."); - static_assert(decide_dns_route(dns_routing_mode::proxy, dns_port, false, {}).action == dns_route_action::block, - "Proxy mode without a usable proxy must fail closed."); - static_assert(decide_dns_route(dns_routing_mode::proxy, dns_port, true, {}).action == dns_route_action::pass, - "ProxiFyre's own upstream traffic must never be captured recursively."); + static_assert(decide_dns_route(dns_routing_mode::direct, 443, dns_upstream_guard::apply_policy, {}).action == + dns_route_action::not_dns, "Non-DNS traffic must keep its ordinary routing."); + static_assert(decide_dns_route(dns_routing_mode::direct, dns_port, dns_upstream_guard::apply_policy, {}).action == + dns_route_action::pass, "Direct mode must pass DNS without consulting a proxy."); + static_assert(decide_dns_route(dns_routing_mode::proxy, dns_port, dns_upstream_guard::apply_policy, {}).action == + dns_route_action::block, "Proxy mode without a usable proxy must fail closed."); + static_assert(decide_dns_route(dns_routing_mode::proxy, dns_port, dns_upstream_guard::exempt, {}).action == + dns_route_action::pass, "ProxiFyre's own upstream traffic must never be captured recursively."); + static_assert(decide_dns_upstream_guard(true, std::nullopt, true) == dns_upstream_guard::drop, + "Unattributed traffic to a SOCKS5 server must be neither passed nor redirected."); } diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 5fa9848..b4ac689 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -2196,11 +2196,12 @@ namespace proxy /** * @brief True when @p destination (and, for TCP, @p port) is one of ProxiFyre's own - * SOCKS5 upstream servers. Such traffic is never captured by the DNS policy so a - * SOCKS5 server listening on port 53 cannot cause a redirect loop. UDP is matched by - * address only because a UDP ASSOCIATE relay port is unrelated to the configured - * port; this mirrors the upstream PASS filters installed by add_socks5_proxy(). - * The caller holds lock_. + * SOCKS5 upstream servers. This is only the cheap pre-filter of the recursion guard + * (decide_dns_upstream_guard()): a matching port-53 packet is exempt from the DNS + * policy only when its sender is ProxiFyre itself, so a SOCKS5 server listening on + * port 53 cannot cause a redirect loop while other processes' queries to a host that + * is also a resolver are still proxied. UDP is matched by address only because a UDP + * ASSOCIATE relay port is unrelated to the configured port. The caller holds lock_. */ template bool is_upstream_destination_locked(const AddrT& destination, const uint16_t port) const @@ -2235,44 +2236,71 @@ namespace proxy std::optional> server_override; ///< set when the destination is rewritten }; + /** + * @brief Whether a resolved owner is ProxiFyre itself; nullopt when the owner is unknown + * (no owner, or the shared unresolved default owner). + */ + static std::optional sender_is_proxifyre(const std::shared_ptr& owner) noexcept + { + if (!owner || !owner->resolved) + return std::nullopt; + return owner->id == ::GetCurrentProcessId(); + } + /** * @brief Applies the global DNS policy to an outbound packet addressed to * @p destination : @p destination_port. Non-DNS packets return not_dns without * taking any lock. + * + * @param postponed The packet is being processed by the deferred-resolve thread with a + * refreshed connection table; the result is then never `defer`. + * @param sender_lookup (bool refresh) -> std::optional: whether the packet's sender + * is ProxiFyre (see sender_is_proxifyre()). Called only for packets addressed to a + * configured SOCKS5 server in Proxy mode, and never while lock_ is held. */ - template - dns_route decide_dns(const AddrT& destination, const uint16_t destination_port) + template + dns_route decide_dns(const AddrT& destination, const uint16_t destination_port, const bool postponed, + SenderLookup&& sender_lookup) { if (destination_port != dns_port) return {}; - std::shared_lock lock(lock_); - - if (dns_mode_ == dns_routing_mode::direct) - return { decide_dns_route(dns_mode_, destination_port, false, {}), std::nullopt }; - constexpr auto v4 = std::is_same_v; dns_proxy_target target; - target.selected = dns_proxy_id_.has_value() && *dns_proxy_id_ < proxy_protocols_.size(); - if (target.selected) + bool destination_matches_upstream = false; + std::optional> server_override; { - const auto id = *dns_proxy_id_; - target.transport_supported = Transport == dns_transport::tcp - ? protocol_supports_tcp(proxy_protocols_[id]) - : protocol_supports_udp(proxy_protocols_[id]); - target.family_supported = id >= proxy_address_families_.size() || - (v4 ? family_supports_ipv4(proxy_address_families_[id]) : family_supports_ipv6(proxy_address_families_[id])); - target.listener_port = dns_listener_port_locked(); - } + std::shared_lock lock(lock_); + + if (dns_mode_ == dns_routing_mode::direct) + return { decide_dns_route(dns_mode_, destination_port, dns_upstream_guard::apply_policy, {}), std::nullopt }; - target.override_configured = dns_server_override_v4_.has_value() || dns_server_override_v6_.has_value(); - target.override_family_matches = dns_server_override_for().has_value(); + target.selected = dns_proxy_id_.has_value() && *dns_proxy_id_ < proxy_protocols_.size(); + if (target.selected) + { + const auto id = *dns_proxy_id_; + target.transport_supported = Transport == dns_transport::tcp + ? protocol_supports_tcp(proxy_protocols_[id]) + : protocol_supports_udp(proxy_protocols_[id]); + target.family_supported = id >= proxy_address_families_.size() || + (v4 ? family_supports_ipv4(proxy_address_families_[id]) : family_supports_ipv6(proxy_address_families_[id])); + target.listener_port = dns_listener_port_locked(); + } + + target.override_configured = dns_server_override_v4_.has_value() || dns_server_override_v6_.has_value(); + target.override_family_matches = dns_server_override_for().has_value(); + server_override = dns_server_override_for(); + destination_matches_upstream = is_upstream_destination_locked(destination, destination_port); + } - const auto decision = decide_dns_route(dns_mode_, destination_port, - is_upstream_destination_locked(destination, destination_port), target); + // The DNS mode and proxy selection cannot change while the router runs + // (set_dns_routing() refuses), so releasing lock_ before the process lookup is safe. + const auto guard = decide_dns_upstream_guard(destination_matches_upstream, + destination_matches_upstream ? sender_lookup(postponed) : std::optional{}, postponed); - return { decision, decision.action == dns_route_action::proxy ? dns_server_override_for() : std::nullopt }; + const auto decision = decide_dns_route(dns_routing_mode::proxy, destination_port, guard, target); + return { decision, decision.action == dns_route_action::proxy ? server_override : std::nullopt }; } /** @@ -2322,6 +2350,14 @@ namespace proxy return packet_filter::packet_action{ action_type::drop }; } + if (route.decision.action != dns_route_action::proxy) + { + // `defer` is handled by the caller (queued for deferred resolution); anything + // else that is not a redirect must fail closed. + note_dns_block(dns_block_reason::upstream_sender_unknown); + return packet_filter::packet_action{ action_type::drop }; + } + if (route.server_override) { // The answer comes back from the override server; remember which server the @@ -2388,6 +2424,14 @@ namespace proxy return packet_filter::packet_action{ action_type::drop }; } + if (route.decision.action != dns_route_action::proxy) + { + // `defer` is handled by the caller (queued for deferred resolution); anything + // else that is not a redirect must fail closed. + note_dns_block(dns_block_reason::upstream_sender_unknown); + return packet_filter::packet_action{ action_type::drop }; + } + if ((tcp_flags & (TH_SYN | TH_ACK)) == TH_SYN) { const auto upstream_destination = route.server_override @@ -2585,9 +2629,18 @@ namespace proxy // independently of process attribution and application rules: Direct passes it, // Proxy redirects it to the DNS proxy or drops it. if (const auto dns = decide_dns( - net::ip_address_v4{ ip_header->ip_dst }, ntohs(udp_header->th_dport)); + net::ip_address_v4{ ip_header->ip_dst }, ntohs(udp_header->th_dport), postponed, + [&](const bool refresh) + { + const net::ip_endpoint sender{ ip_header->ip_src, ntohs(udp_header->th_sport) }; + return sender_is_proxifyre(refresh + ? process_lookup_v4_.lookup_process_for_udp(sender) + : process_lookup_v4_.lookup_process_for_udp(sender)); + }); dns.decision.action != dns_route_action::not_dns) { + if (dns.decision.action == dns_route_action::defer) + return std::nullopt; return handle_dns_udp(buffer, dns, net::ip_address_v4{ ip_header->ip_dst }, ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); @@ -2707,9 +2760,19 @@ namespace proxy // now unconditionally direct (previously it was routed like any other TCP traffic of // the owning process). if (const auto dns = decide_dns( - net::ip_address_v4{ ip_header->ip_dst }, ntohs(tcp_header->th_dport)); + net::ip_address_v4{ ip_header->ip_dst }, ntohs(tcp_header->th_dport), postponed, + [&](const bool refresh) + { + const net::ip_session session{ ip_header->ip_src, ip_header->ip_dst, + ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport) }; + return sender_is_proxifyre(refresh + ? process_lookup_v4_.lookup_process_for_tcp(session) + : process_lookup_v4_.lookup_process_for_tcp(session)); + }); dns.decision.action != dns_route_action::not_dns) { + if (dns.decision.action == dns_route_action::defer) + return std::nullopt; return handle_dns_tcp(buffer, dns, net::ip_address_v4{ ip_header->ip_dst }, ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport), tcp_header->th_flags); } @@ -2891,9 +2954,18 @@ namespace proxy // Conventional DNS follows the global DNS policy (mirrors the IPv4 path). if (const auto dns = decide_dns( - net::ip_address_v6{ ip_header->ip6_dst }, ntohs(udp_header->th_dport)); + net::ip_address_v6{ ip_header->ip6_dst }, ntohs(udp_header->th_dport), postponed, + [&](const bool refresh) + { + const net::ip_endpoint sender{ ip_header->ip6_src, ntohs(udp_header->th_sport) }; + return sender_is_proxifyre(refresh + ? process_lookup_v6_.lookup_process_for_udp(sender) + : process_lookup_v6_.lookup_process_for_udp(sender)); + }); dns.decision.action != dns_route_action::not_dns) { + if (dns.decision.action == dns_route_action::defer) + return std::nullopt; return handle_dns_udp(buffer, dns, net::ip_address_v6{ ip_header->ip6_dst }, ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); @@ -3007,9 +3079,19 @@ namespace proxy // Conventional DNS over TCP follows the global DNS policy (mirrors the IPv4 path). if (const auto dns = decide_dns( - net::ip_address_v6{ ip_header->ip6_dst }, ntohs(tcp_header->th_dport)); + net::ip_address_v6{ ip_header->ip6_dst }, ntohs(tcp_header->th_dport), postponed, + [&](const bool refresh) + { + const net::ip_session session{ ip_header->ip6_src, ip_header->ip6_dst, + ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport) }; + return sender_is_proxifyre(refresh + ? process_lookup_v6_.lookup_process_for_tcp(session) + : process_lookup_v6_.lookup_process_for_tcp(session)); + }); dns.decision.action != dns_route_action::not_dns) { + if (dns.decision.action == dns_route_action::defer) + return std::nullopt; return handle_dns_tcp(buffer, dns, net::ip_address_v6{ ip_header->ip6_dst }, ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport), tcp_header->th_flags); } diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 8c78f2a..1f0d7d1 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -32,6 +32,8 @@ namespace constexpr auto direct = dns_routing_mode::direct; constexpr auto proxy_mode = dns_routing_mode::proxy; + constexpr auto apply = proxy::dns_upstream_guard::apply_policy; + constexpr auto exempt = proxy::dns_upstream_guard::exempt; /// A selected proxy with listeners for every transport and family, mirroring the router's /// dns_listener_port_locked() for one proxy index. @@ -85,10 +87,10 @@ TEST(DnsRoutingPolicy, DirectModePassesUdpAndTcpDnsForBothFamilies) const dns_proxy configured{}; for (const auto& c : all_cases) { - EXPECT_EQ(decide_dns_route(direct, dns_port, false, configured.target(c.transport, c.family)).action, + EXPECT_EQ(decide_dns_route(direct, dns_port, apply, configured.target(c.transport, c.family)).action, dns_route_action::pass); // No proxy selected at all: Direct still passes. - EXPECT_EQ(decide_dns_route(direct, dns_port, false, dns_proxy_target{}).action, dns_route_action::pass); + EXPECT_EQ(decide_dns_route(direct, dns_port, apply, dns_proxy_target{}).action, dns_route_action::pass); } } @@ -96,10 +98,10 @@ TEST(DnsRoutingPolicy, DirectModePassesUdpAndTcpDnsForBothFamilies) TEST(DnsRoutingPolicy, ProxyModeRedirectsToTheListenerOfTheTransportAndFamily) { const dns_proxy p{}; - const auto udp4 = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::udp, dns_family::ipv4)); - const auto udp6 = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::udp, dns_family::ipv6)); - const auto tcp4 = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::tcp, dns_family::ipv4)); - const auto tcp6 = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::tcp, dns_family::ipv6)); + const auto udp4 = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::udp, dns_family::ipv4)); + const auto udp6 = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::udp, dns_family::ipv6)); + const auto tcp4 = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::tcp, dns_family::ipv4)); + const auto tcp6 = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::tcp, dns_family::ipv6)); EXPECT_EQ(udp4.action, dns_route_action::proxy); EXPECT_EQ(udp4.listener_port, p.udp4); @@ -118,13 +120,13 @@ TEST(DnsRoutingPolicy, DecisionDoesNotDependOnTheSendingProcess) { const dns_proxy p{}; const auto target = p.target(dns_transport::udp, dns_family::ipv4); - const auto expected = decide_dns_route(proxy_mode, dns_port, false, target); + const auto expected = decide_dns_route(proxy_mode, dns_port, apply, target); // The only inputs are the mode, the destination port, the upstream guard, and the proxy. // Calling the decision repeatedly (as each sender would) yields the same result. for (int sender = 0; sender < 4; ++sender) { - const auto decision = decide_dns_route(proxy_mode, dns_port, false, target); + const auto decision = decide_dns_route(proxy_mode, dns_port, apply, target); EXPECT_EQ(decision.action, expected.action); EXPECT_EQ(decision.listener_port, expected.listener_port); } @@ -137,7 +139,7 @@ TEST(DnsRoutingPolicy, ProxyModeBlocksInsteadOfFallingBackToDirect) for (const auto& c : all_cases) { (void)c; - const auto d = decide_dns_route(proxy_mode, dns_port, false, dns_proxy_target{}); + const auto d = decide_dns_route(proxy_mode, dns_port, apply, dns_proxy_target{}); EXPECT_EQ(d.action, dns_route_action::block); EXPECT_EQ(d.reason, dns_block_reason::proxy_unavailable); } @@ -145,28 +147,28 @@ TEST(DnsRoutingPolicy, ProxyModeBlocksInsteadOfFallingBackToDirect) // The proxy lacks the transport (unsupported protocol combination). dns_proxy tcp_only{}; tcp_only.udp = false; - auto d = decide_dns_route(proxy_mode, dns_port, false, tcp_only.target(dns_transport::udp, dns_family::ipv4)); + auto d = decide_dns_route(proxy_mode, dns_port, apply, tcp_only.target(dns_transport::udp, dns_family::ipv4)); EXPECT_EQ(d.action, dns_route_action::block); EXPECT_EQ(d.reason, dns_block_reason::transport_unsupported); // The proxy does not accept IPv6 destinations. dns_proxy v4_only{}; v4_only.ipv6 = false; - d = decide_dns_route(proxy_mode, dns_port, false, v4_only.target(dns_transport::tcp, dns_family::ipv6)); + d = decide_dns_route(proxy_mode, dns_port, apply, v4_only.target(dns_transport::tcp, dns_family::ipv6)); EXPECT_EQ(d.action, dns_route_action::block); EXPECT_EQ(d.reason, dns_block_reason::family_unsupported); // The listener is not running (for example the IPv6 listener failed to start). dns_proxy no_v6_listener{}; no_v6_listener.udp6 = 0; - d = decide_dns_route(proxy_mode, dns_port, false, no_v6_listener.target(dns_transport::udp, dns_family::ipv6)); + d = decide_dns_route(proxy_mode, dns_port, apply, no_v6_listener.target(dns_transport::udp, dns_family::ipv6)); EXPECT_EQ(d.action, dns_route_action::block); EXPECT_EQ(d.reason, dns_block_reason::listener_unavailable); // A missing listener port value and an explicit zero are both unusable. auto target = dns_proxy{}.target(dns_transport::udp, dns_family::ipv4); target.listener_port = std::nullopt; - EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, false, target).action, dns_route_action::block); + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, apply, target).action, dns_route_action::block); } // 6. A server override applies to queries of its own family; queries of the other family are @@ -178,32 +180,67 @@ TEST(DnsRoutingPolicy, ServerOverrideFamilyIsHandledExplicitly) for (const auto transport : { dns_transport::udp, dns_transport::tcp }) { - EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, false, with_v4_override.target(transport, dns_family::ipv4)).action, + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, apply, with_v4_override.target(transport, dns_family::ipv4)).action, dns_route_action::proxy); - const auto other = decide_dns_route(proxy_mode, dns_port, false, with_v4_override.target(transport, dns_family::ipv6)); + const auto other = decide_dns_route(proxy_mode, dns_port, apply, with_v4_override.target(transport, dns_family::ipv6)); EXPECT_EQ(other.action, dns_route_action::block); EXPECT_EQ(other.reason, dns_block_reason::override_family_mismatch); } dns_proxy with_v6_override{}; with_v6_override.server_override = dns_family::ipv6; - EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, false, with_v6_override.target(dns_transport::udp, dns_family::ipv6)).action, + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, apply, with_v6_override.target(dns_transport::udp, dns_family::ipv6)).action, dns_route_action::proxy); - EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, false, with_v6_override.target(dns_transport::udp, dns_family::ipv4)).action, + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, apply, with_v6_override.target(dns_transport::udp, dns_family::ipv4)).action, dns_route_action::block); } -// 11. Recursion prevention: ProxiFyre's own traffic to an upstream SOCKS5 server (even one -// listening on port 53) is never redirected into the DNS proxy. -TEST(DnsRoutingPolicy, UpstreamProxyTrafficIsNeverCaptured) +// 11. Recursion prevention: a packet to a configured SOCKS5 server is exempt only when its sender +// is ProxiFyre itself. Another process's query to a host that is both the SOCKS5 server and a +// resolver is subject to the policy; an unattributed one is deferred, then dropped. +TEST(DnsRoutingPolicy, UpstreamGuardExemptsOnlyProxiFyresOwnTraffic) +{ + using proxy::decide_dns_upstream_guard; + using guard = proxy::dns_upstream_guard; + + // Not addressed to a SOCKS5 server: the sender is irrelevant. + EXPECT_EQ(decide_dns_upstream_guard(false, std::nullopt, false), guard::apply_policy); + EXPECT_EQ(decide_dns_upstream_guard(false, true, true), guard::apply_policy); + + EXPECT_EQ(decide_dns_upstream_guard(true, true, false), guard::exempt); + EXPECT_EQ(decide_dns_upstream_guard(true, true, true), guard::exempt); + EXPECT_EQ(decide_dns_upstream_guard(true, false, false), guard::apply_policy); + EXPECT_EQ(decide_dns_upstream_guard(true, false, true), guard::apply_policy); + EXPECT_EQ(decide_dns_upstream_guard(true, std::nullopt, false), guard::defer); + EXPECT_EQ(decide_dns_upstream_guard(true, std::nullopt, true), guard::drop); +} + +TEST(DnsRoutingPolicy, UpstreamGuardOutcomesMapToFailClosedActions) { const dns_proxy p{}; for (const auto& c : all_cases) { - EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, true, p.target(c.transport, c.family)).action, + const auto target = p.target(c.transport, c.family); + + // ProxiFyre's own traffic passes, even with no usable DNS proxy. + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, exempt, target).action, dns_route_action::pass); + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, exempt, dns_proxy_target{}).action, dns_route_action::pass); + + // Another process's query to the SOCKS5 host is proxied like any other query. + const auto other = decide_dns_route(proxy_mode, dns_port, apply, target); + EXPECT_EQ(other.action, dns_route_action::proxy); + + // Unknown sender: deferred inline, dropped after the deferred lookup; never passed. + EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, proxy::dns_upstream_guard::defer, target).action, + dns_route_action::defer); + const auto dropped = decide_dns_route(proxy_mode, dns_port, proxy::dns_upstream_guard::drop, target); + EXPECT_EQ(dropped.action, dns_route_action::block); + EXPECT_EQ(dropped.reason, dns_block_reason::upstream_sender_unknown); + + // Direct mode passes DNS whatever the guard says. + EXPECT_EQ(decide_dns_route(direct, dns_port, proxy::dns_upstream_guard::drop, target).action, dns_route_action::pass); - EXPECT_EQ(decide_dns_route(proxy_mode, dns_port, true, dns_proxy_target{}).action, dns_route_action::pass); } } @@ -217,9 +254,9 @@ TEST(DnsRoutingPolicy, NonDnsTrafficIsNotClassified) { for (const auto mode : { direct, proxy_mode }) { - EXPECT_EQ(decide_dns_route(mode, port, false, p.target(dns_transport::udp, dns_family::ipv4)).action, + EXPECT_EQ(decide_dns_route(mode, port, apply, p.target(dns_transport::udp, dns_family::ipv4)).action, dns_route_action::not_dns) << port; - EXPECT_EQ(decide_dns_route(mode, port, true, dns_proxy_target{}).action, dns_route_action::not_dns) << port; + EXPECT_EQ(decide_dns_route(mode, port, exempt, dns_proxy_target{}).action, dns_route_action::not_dns) << port; } } } @@ -231,8 +268,8 @@ TEST(DnsRoutingPolicy, TruncatedUdpAnswerTcpRetryUsesTheSameProxy) dns_proxy p{}; p.server_override = dns_family::ipv4; - const auto udp = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::udp, dns_family::ipv4)); - const auto tcp = decide_dns_route(proxy_mode, dns_port, false, p.target(dns_transport::tcp, dns_family::ipv4)); + const auto udp = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::udp, dns_family::ipv4)); + const auto tcp = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::tcp, dns_family::ipv4)); EXPECT_EQ(udp.action, dns_route_action::proxy); EXPECT_EQ(tcp.action, dns_route_action::proxy); EXPECT_EQ(udp.listener_port, p.udp4); From d9c1bfaa3e33007b7766da506a0e6676e984c255 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:46:44 +0000 Subject: [PATCH 04/62] fix: classify DNS in first fragments only and drop fragmented DNS in Proxy mode IPv6 fragments returned pass before any DNS check, and the IPv4 handlers read "ports" from the payload of non-first fragments. - IPv4: a later fragment (non-zero offset) is no longer classified as DNS. A first fragment addressed to port 53 that Proxy mode would redirect is dropped (reason "fragmented"): a fragmented datagram cannot be redirected and passing its first fragment would send DNS directly. - IPv6: in Proxy mode, a first fragment (offset 0) whose upper-layer header is UDP or TCP with destination port 53 is dropped. A new parse_ipv6_first_fragment() reads that header from raw bytes instead of changing what find_transport_header() returns to existing callers. - Later fragments carry no ports and are left alone, so unrelated fragmented traffic is unaffected. The helpers (classify_ipv4_fragment, apply_fragmentation, parse_ipv6_first_fragment) are in dns_routing_policy.h with tests. docs/configuration.md now states exactly what is and is not dropped. --- docs/configuration.md | 5 +- netlib/src/proxy/dns_routing_policy.h | 110 +++++++++++++++++ netlib/src/proxy/socks_local_router.h | 99 ++++++++++----- netlib/test/proxy/dns_routing_policy_test.cpp | 116 ++++++++++++++++++ 4 files changed, 297 insertions(+), 33 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 1cbaa3e..3de66f9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -114,7 +114,7 @@ IPv6 destination routing also requires: - a SOCKS5 server that accepts IPv6 target addresses (`ATYP=4`); and - an upstream proxy reachable through IPv4. The endpoint itself must be an IPv4 literal or a hostname with an A record; IPv6-literal and AAAA-only upstreams are not supported. -Fragmented IPv6 datagrams are passed through directly to avoid rewriting an incomplete packet. Applications that emit oversized fragmented UDP datagrams can therefore bypass the proxy; TCP and path-MTU-aware UDP such as normal QUIC traffic are unaffected. +Fragmented IPv6 datagrams are passed through directly to avoid rewriting an incomplete packet. Applications that emit oversized fragmented UDP datagrams can therefore bypass the proxy; TCP and path-MTU-aware UDP such as normal QUIC traffic are unaffected. DNS `Proxy` mode is the exception for port 53: see [Proxy mode](#proxy-mode). ## LAN bypass @@ -156,7 +156,8 @@ ProxiFyre never falls back to sending DNS directly. DNS is dropped, and a warnin - the SOCKS5 connection, authentication, TLS handshake, or `UDP ASSOCIATE` fails, or the proxy disconnects; - the proxy does not accept the destination's address family (for example IPv6 DNS with an IPv4-only rule); - a `serverOverride` is configured and the query is addressed to a server of the other address family (an IPv4 override blocks queries to IPv6 servers and vice versa; Windows then uses its other configured DNS servers); or -- the packet cannot be redirected, such as a fragmented datagram or a TCP connection to port 53 that was opened before ProxiFyre started. +- the packet cannot be redirected, such as a TCP connection to port 53 that was opened before ProxiFyre started, or a datagram too large to carry the SOCKS5 UDP header; or +- the datagram is fragmented. Only the first fragment carries the UDP or TCP header, so only a first fragment (IPv4 or IPv6) addressed to port 53 can be recognized as DNS; it is dropped, which also prevents the datagram from being reassembled at the server. Later fragments carry no ports, cannot be classified, and are passed unchanged, so other fragmented traffic is not affected. In `Direct` mode fragmented DNS is passed like any other DNS. Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index a84f959..9f9eb2e 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -56,6 +56,7 @@ namespace proxy redirect_failed, ///< the packet could not be redirected (e.g. fragmented, oversized, ///< or a TCP segment of a connection opened before ProxiFyre started) upstream_sender_unknown, ///< addressed to a SOCKS5 server, and its sender could not be resolved + fragmented, ///< the first fragment of a fragmented datagram addressed to port 53 count }; @@ -186,6 +187,9 @@ namespace proxy case dns_block_reason::redirect_failed: return "the packet could not be redirected to the DNS proxy (fragmented, oversized, " "not a DNS message, or part of a TCP connection opened before ProxiFyre started)"; + case dns_block_reason::fragmented: + return "the datagram is fragmented and cannot be redirected through the DNS proxy; only its first " + "fragment, which carries the port, is dropped"; case dns_block_reason::upstream_sender_unknown: return "the packet is addressed to a configured SOCKS5 server and its sending process could not be " "resolved, so it cannot be identified as ProxiFyre's own traffic"; @@ -194,6 +198,112 @@ namespace proxy } } + // --------------------------------------------------------------------------------------- + // Fragments + // + // Only the first fragment of a fragmented datagram carries the transport header, so only it + // can be classified as DNS. Redirection rewrites single packets, so a fragmented DNS datagram + // cannot be sent through the DNS proxy; in Proxy mode its first fragment is dropped, which + // keeps the datagram from being reassembled at the real server. Later fragments carry no + // ports and are left alone, so unrelated fragmented traffic is not affected. + // --------------------------------------------------------------------------------------- + + /// Fragmentation state of an IPv4 packet. + enum class ipv4_fragment : uint8_t + { + none, ///< not fragmented + first, ///< fragment offset 0 with More Fragments set: carries the transport header + later ///< non-zero fragment offset: no transport header, its "ports" are payload bytes + }; + + /// Classifies an IPv4 packet from its flags/fragment-offset field (host byte order). + [[nodiscard]] constexpr ipv4_fragment classify_ipv4_fragment(const uint16_t flags_and_offset) noexcept + { + if ((flags_and_offset & 0x1fff) != 0) + return ipv4_fragment::later; + return (flags_and_offset & 0x2000) != 0 ? ipv4_fragment::first : ipv4_fragment::none; + } + + /** + * @brief Applies fragmentation to a DNS routing decision: a datagram that would be redirected + * but is fragmented cannot be, so it is blocked instead of being passed. + */ + [[nodiscard]] constexpr dns_route_decision apply_fragmentation(const dns_route_decision decision, + const bool first_fragment) noexcept + { + if (first_fragment && decision.action == dns_route_action::proxy) + return { dns_route_action::block, dns_block_reason::fragmented, 0 }; + return decision; + } + + /// Upper-layer protocol and destination port read from the first fragment of an IPv6 datagram. + struct ipv6_first_fragment + { + uint8_t protocol{}; ///< IPPROTO_UDP (17) or IPPROTO_TCP (6) + uint16_t destination_port{}; ///< host byte order + }; + + /** + * @brief For an IPv6 packet that is the first fragment (offset 0) of a fragmented datagram + * whose upper-layer header is UDP or TCP, returns that protocol and its destination + * port. + * + * Walks the hop-by-hop, routing, and destination-options extension headers and the + * fragment header. Returns std::nullopt for an unfragmented packet (the normal path handles + * it), a later fragment (no ports), another upper-layer protocol, or a header chain that is + * truncated within @p size bytes. + * + * @param ipv6_packet The IPv6 header followed by the captured payload. + */ + [[nodiscard]] constexpr std::optional parse_ipv6_first_fragment( + const uint8_t* ipv6_packet, const std::size_t size) noexcept + { + constexpr std::size_t ipv6_header_size = 40; + constexpr uint8_t hop_by_hop = 0, tcp = 6, udp = 17, routing = 43, fragment = 44, destination_options = 60; + + if (ipv6_packet == nullptr || size < ipv6_header_size || (ipv6_packet[0] >> 4) != 6) + return std::nullopt; + + uint8_t next = ipv6_packet[6]; + std::size_t offset = ipv6_header_size; + bool fragmented = false; + + // A bound on the chain length keeps a malformed chain from looping. + for (int headers = 0; headers < 16; ++headers) + { + if (next == hop_by_hop || next == routing || next == destination_options) + { + if (offset + 2 > size) + return std::nullopt; + const auto length = (static_cast(ipv6_packet[offset + 1]) + 1) * 8; + next = ipv6_packet[offset]; + offset += length; + continue; + } + + if (next == fragment) + { + if (fragmented || offset + 8 > size) + return std::nullopt; + const auto offset_and_flags = static_cast((ipv6_packet[offset + 2] << 8) | ipv6_packet[offset + 3]); + if ((offset_and_flags >> 3) != 0) + return std::nullopt; // a later fragment: no upper-layer header + fragmented = true; + next = ipv6_packet[offset]; + offset += 8; + continue; + } + + if (!fragmented || (next != udp && next != tcp) || offset + 4 > size) + return std::nullopt; + + return ipv6_first_fragment{ next, + static_cast((ipv6_packet[offset + 2] << 8) | ipv6_packet[offset + 3]) }; + } + + return std::nullopt; + } + /// What a packet handler does with an outbound packet whose source port is the port of one of /// ProxiFyre's local proxy listeners. enum class listener_reply_action : uint8_t diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index b4ac689..12ee2d7 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -2236,6 +2236,13 @@ namespace proxy std::optional> server_override; ///< set when the destination is rewritten }; + /// True when DNS routing is in Proxy mode. + bool dns_proxy_mode() + { + std::shared_lock lock(lock_); + return dns_mode_ == dns_routing_mode::proxy; + } + /** * @brief Whether a resolved owner is ProxiFyre itself; nullopt when the owner is unknown * (no owner, or the shared unresolved default owner). @@ -2627,23 +2634,29 @@ namespace proxy // Conventional DNS (destination port 53) follows the global DNS policy, before and // independently of process attribution and application rules: Direct passes it, - // Proxy redirects it to the DNS proxy or drops it. - if (const auto dns = decide_dns( - net::ip_address_v4{ ip_header->ip_dst }, ntohs(udp_header->th_dport), postponed, - [&](const bool refresh) - { - const net::ip_endpoint sender{ ip_header->ip_src, ntohs(udp_header->th_sport) }; - return sender_is_proxifyre(refresh - ? process_lookup_v4_.lookup_process_for_udp(sender) - : process_lookup_v4_.lookup_process_for_udp(sender)); - }); - dns.decision.action != dns_route_action::not_dns) + // Proxy redirects it to the DNS proxy or drops it. A later IPv4 fragment carries no + // UDP header, so its "port" is payload and it is not classified. + if (const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); fragment != ipv4_fragment::later) { - if (dns.decision.action == dns_route_action::defer) - return std::nullopt; - return handle_dns_udp(buffer, dns, net::ip_address_v4{ ip_header->ip_dst }, - ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), - reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); + if (auto dns = decide_dns( + net::ip_address_v4{ ip_header->ip_dst }, ntohs(udp_header->th_dport), postponed, + [&](const bool refresh) + { + const net::ip_endpoint sender{ ip_header->ip_src, ntohs(udp_header->th_sport) }; + return sender_is_proxifyre(refresh + ? process_lookup_v4_.lookup_process_for_udp(sender) + : process_lookup_v4_.lookup_process_for_udp(sender)); + }); + dns.decision.action != dns_route_action::not_dns) + { + if (dns.decision.action == dns_route_action::defer) + return std::nullopt; + + dns.decision = apply_fragmentation(dns.decision, fragment == ipv4_fragment::first); + return handle_dns_udp(buffer, dns, net::ip_address_v4{ ip_header->ip_dst }, + ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), + reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); + } } auto process = process_lookup_v4_. @@ -2759,22 +2772,28 @@ namespace proxy // Conventional DNS over TCP follows the global DNS policy. In Direct mode TCP/53 is // now unconditionally direct (previously it was routed like any other TCP traffic of // the owning process). - if (const auto dns = decide_dns( - net::ip_address_v4{ ip_header->ip_dst }, ntohs(tcp_header->th_dport), postponed, - [&](const bool refresh) - { - const net::ip_session session{ ip_header->ip_src, ip_header->ip_dst, - ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport) }; - return sender_is_proxifyre(refresh - ? process_lookup_v4_.lookup_process_for_tcp(session) - : process_lookup_v4_.lookup_process_for_tcp(session)); - }); - dns.decision.action != dns_route_action::not_dns) + // A later IPv4 fragment carries no TCP header and is not classified (see the UDP path). + if (const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); fragment != ipv4_fragment::later) { - if (dns.decision.action == dns_route_action::defer) - return std::nullopt; - return handle_dns_tcp(buffer, dns, net::ip_address_v4{ ip_header->ip_dst }, - ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport), tcp_header->th_flags); + if (auto dns = decide_dns( + net::ip_address_v4{ ip_header->ip_dst }, ntohs(tcp_header->th_dport), postponed, + [&](const bool refresh) + { + const net::ip_session session{ ip_header->ip_src, ip_header->ip_dst, + ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport) }; + return sender_is_proxifyre(refresh + ? process_lookup_v4_.lookup_process_for_tcp(session) + : process_lookup_v4_.lookup_process_for_tcp(session)); + }); + dns.decision.action != dns_route_action::not_dns) + { + if (dns.decision.action == dns_route_action::defer) + return std::nullopt; + + dns.decision = apply_fragmentation(dns.decision, fragment == ipv4_fragment::first); + return handle_dns_tcp(buffer, dns, net::ip_address_v4{ ip_header->ip_dst }, + ntohs(tcp_header->th_sport), ntohs(tcp_header->th_dport), tcp_header->th_flags); + } } auto process = process_lookup_v4_. @@ -2863,6 +2882,24 @@ namespace proxy if (transport == nullptr) { + // In DNS Proxy mode, the first fragment of a fragmented UDP/TCP datagram addressed + // to port 53 is dropped: the datagram cannot be redirected, and passing it would + // send DNS directly. Later fragments carry no ports and cannot be classified, so + // they are left alone and unrelated fragmented traffic is unaffected. + if (buffer.m_Length > ETHER_HEADER_LENGTH) + { + if (const auto first = parse_ipv6_first_fragment(reinterpret_cast(ip_header), + buffer.m_Length - ETHER_HEADER_LENGTH); + first && first->destination_port == dns_port && dns_proxy_mode()) + { + if (first->protocol == IPPROTO_UDP) + note_dns_block(dns_block_reason::fragmented); + else + note_dns_block(dns_block_reason::fragmented); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + } + } + // No usable transport header: either a fragmented IPv6 datagram (which // this build deliberately does not rewrite, to avoid corrupting a // partially-rewritten datagram) or an unsupported extension chain. Such diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 1f0d7d1..6607458 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -452,3 +452,119 @@ TEST(ListenerReplyPolicy, UntranslatedListenerRepliesAreDroppedNeverPassed) EXPECT_EQ(decide_listener_reply(false, false), listener_reply_action::not_listener); EXPECT_EQ(decide_listener_reply(false, true), listener_reply_action::not_listener); } + +// 5. Fragments: only a first fragment carries ports. IPv4 later fragments are not classified; +// a fragmented datagram that would be redirected is blocked instead. +TEST(DnsFragmentPolicy, Ipv4FragmentClassification) +{ + using proxy::classify_ipv4_fragment; + using proxy::ipv4_fragment; + + EXPECT_EQ(classify_ipv4_fragment(0x0000), ipv4_fragment::none); + EXPECT_EQ(classify_ipv4_fragment(0x4000), ipv4_fragment::none); // DF only + EXPECT_EQ(classify_ipv4_fragment(0x2000), ipv4_fragment::first); // MF, offset 0 + EXPECT_EQ(classify_ipv4_fragment(0x2001), ipv4_fragment::later); // MF, offset 8 + EXPECT_EQ(classify_ipv4_fragment(0x00b9), ipv4_fragment::later); // last fragment +} + +TEST(DnsFragmentPolicy, FragmentedDatagramsThatWouldBeRedirectedAreBlocked) +{ + using proxy::apply_fragmentation; + const dns_proxy p{}; + const auto redirect = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::udp, dns_family::ipv4)); + ASSERT_EQ(redirect.action, dns_route_action::proxy); + + const auto fragmented = apply_fragmentation(redirect, true); + EXPECT_EQ(fragmented.action, dns_route_action::block); + EXPECT_EQ(fragmented.reason, dns_block_reason::fragmented); + EXPECT_EQ(apply_fragmentation(redirect, false).action, dns_route_action::proxy); + + // Direct mode and non-DNS decisions are unaffected by fragmentation. + const auto direct_pass = decide_dns_route(direct, dns_port, apply, {}); + EXPECT_EQ(apply_fragmentation(direct_pass, true).action, dns_route_action::pass); + EXPECT_EQ(apply_fragmentation(decide_dns_route(proxy_mode, 443, apply, {}), true).action, dns_route_action::not_dns); +} + +namespace +{ + /// Builds an IPv6 packet: 40-byte header followed by @p chain bytes. + std::vector ipv6_packet(const uint8_t next_header, const std::vector& chain) + { + std::vector packet(40, 0); + packet[0] = 0x60; + packet[4] = static_cast(chain.size() >> 8); + packet[5] = static_cast(chain.size() & 0xff); + packet[6] = next_header; + packet[7] = 64; + packet.insert(packet.end(), chain.begin(), chain.end()); + return packet; + } + + std::vector fragment_header(const uint8_t next, const uint16_t offset_in_8_bytes, const bool more) + { + const auto field = static_cast((offset_in_8_bytes << 3) | (more ? 1 : 0)); + return { next, 0, static_cast(field >> 8), static_cast(field & 0xff), 0, 0, 0x12, 0x34 }; + } + + std::vector ports(const uint16_t source, const uint16_t destination) + { + return { static_cast(source >> 8), static_cast(source & 0xff), + static_cast(destination >> 8), static_cast(destination & 0xff), + 0, 8, 0, 0 }; + } + + std::vector concat(std::initializer_list> parts) + { + std::vector out; + for (const auto& part : parts) + out.insert(out.end(), part.begin(), part.end()); + return out; + } + + std::optional parse(const std::vector& packet) + { + return proxy::parse_ipv6_first_fragment(packet.data(), packet.size()); + } + + constexpr uint8_t udp_proto = 17, tcp_proto = 6, fragment_proto = 44, hop_proto = 0, dest_opts_proto = 60; +} + +TEST(DnsFragmentPolicy, Ipv6FirstFragmentExposesTheUpperLayerDestinationPort) +{ + const auto udp_first = parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(50001, 53) }))); + ASSERT_TRUE(udp_first.has_value()); + EXPECT_EQ(udp_first->protocol, udp_proto); + EXPECT_EQ(udp_first->destination_port, 53); + + const auto tcp_first = parse(ipv6_packet(fragment_proto, concat({ fragment_header(tcp_proto, 0, true), ports(50001, 53) }))); + ASSERT_TRUE(tcp_first.has_value()); + EXPECT_EQ(tcp_first->protocol, tcp_proto); + + // Extension headers before and after the fragment header are skipped. + const std::vector hop_by_hop{ fragment_proto, 0, 1, 4, 0, 0, 0, 0 }; + const std::vector destination_options{ udp_proto, 0, 1, 4, 0, 0, 0, 0 }; + const auto chained = parse(ipv6_packet(hop_proto, + concat({ hop_by_hop, fragment_header(dest_opts_proto, 0, true), destination_options, ports(50001, 443) }))); + ASSERT_TRUE(chained.has_value()); + EXPECT_EQ(chained->protocol, udp_proto); + EXPECT_EQ(chained->destination_port, 443); +} + +TEST(DnsFragmentPolicy, Ipv6PacketsWithoutAClassifiableFirstFragmentAreNotReported) +{ + // Unfragmented: handled by the normal path. + EXPECT_FALSE(parse(ipv6_packet(udp_proto, ports(50001, 53))).has_value()); + // A later fragment has no upper-layer header: its leading bytes must not be read as ports. + EXPECT_FALSE(parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 185, false), ports(1, 53) }))).has_value()); + // Another upper-layer protocol (ICMPv6). + EXPECT_FALSE(parse(ipv6_packet(fragment_proto, concat({ fragment_header(58, 0, true), ports(1, 53) }))).has_value()); + // Truncated: fragment header, but not the ports. + EXPECT_FALSE(parse(ipv6_packet(fragment_proto, fragment_header(udp_proto, 0, true))).has_value()); + // Not IPv6, empty, or a nested fragment header. + auto not_v6 = ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(1, 53) })); + not_v6[0] = 0x45; + EXPECT_FALSE(parse(not_v6).has_value()); + EXPECT_FALSE(proxy::parse_ipv6_first_fragment(nullptr, 100).has_value()); + EXPECT_FALSE(parse(ipv6_packet(fragment_proto, + concat({ fragment_header(fragment_proto, 0, true), fragment_header(udp_proto, 0, true), ports(1, 53) }))).has_value()); +} From fd648528151f03fe9849a56871a975264abec74f Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:48:08 +0000 Subject: [PATCH 05/62] fix: reinstall DNS driver filters on every start and fail closed install_dns_filters() ran once per router and only logged when a filter could not be inserted. - Every start() now removes the DNS filters installed earlier (the only REDIRECT filters the router installs) and inserts the current plan at the front again, so they stay ahead of LAN-bypass PASS filters added between runs and use the current listener ports and proxy selection. In Direct mode they are only removed. - If any filter Proxy mode needs cannot be inserted, start() fails through the existing failure cleanup instead of running with DNS able to bypass the policy. - No source-port filter is installed for a listener that is not running or reports port 0. The filter set is computed by plan_dns_filters() in dns_routing_policy.h and covered by tests. --- netlib/src/proxy/dns_routing_policy.h | 61 ++++++++ netlib/src/proxy/socks_local_router.h | 135 ++++++++++-------- netlib/test/proxy/dns_routing_policy_test.cpp | 43 ++++++ 3 files changed, 176 insertions(+), 63 deletions(-) diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 9f9eb2e..10bdc39 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -18,6 +18,7 @@ #include #include #include +#include namespace proxy { @@ -198,6 +199,66 @@ namespace proxy } } + // --------------------------------------------------------------------------------------- + // Driver filters + // --------------------------------------------------------------------------------------- + + /// Local listener ports (host byte order) of the DNS proxy; nullopt or 0 when not running. + struct dns_listener_ports + { + std::optional tcp4; + std::optional udp4; + std::optional tcp6; + std::optional udp6; + }; + + /// One outbound REDIRECT (to user mode) driver filter the DNS policy needs. + struct dns_filter_spec + { + dns_family family{}; + dns_transport transport{}; + std::optional destination_port; ///< host byte order + std::optional source_port; ///< host byte order + + bool operator==(const dns_filter_spec&) const = default; + }; + + /** + * @brief The driver filters the DNS policy installs for @p mode. + * + * Static PASS filters (LAN bypass, the SOCKS5 upstream exemptions) are evaluated in the + * driver before the user-mode handler sees a packet. In Proxy mode, REDIRECT filters at the + * front of the table keep outbound TCP/UDP to port 53, and the DNS proxy listeners' replies + * (outbound from their ports and addressed to the original, often LAN, server), in user mode + * for both address families. Direct mode needs none. A listener that is not running (no port + * or port 0) gets no filter: a source-port filter for port 0 would be meaningless. + */ + [[nodiscard]] inline std::vector plan_dns_filters(const dns_routing_mode mode, + const dns_listener_ports& listeners) + { + std::vector plan; + if (mode != dns_routing_mode::proxy) + return plan; + + for (const auto family : { dns_family::ipv4, dns_family::ipv6 }) + { + for (const auto transport : { dns_transport::udp, dns_transport::tcp }) + plan.push_back({ family, transport, dns_port, std::nullopt }); + } + + const auto add_listener = [&plan](const dns_family family, const dns_transport transport, + const std::optional port) + { + if (port && *port != 0) + plan.push_back({ family, transport, std::nullopt, *port }); + }; + add_listener(dns_family::ipv4, dns_transport::tcp, listeners.tcp4); + add_listener(dns_family::ipv4, dns_transport::udp, listeners.udp4); + add_listener(dns_family::ipv6, dns_transport::tcp, listeners.tcp6); + add_listener(dns_family::ipv6, dns_transport::udp, listeners.udp6); + return plan; + } + // --------------------------------------------------------------------------------------- // Fragments // diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 12ee2d7..b958346 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -271,13 +271,6 @@ namespace proxy dns_udp_origin_tracker> dns_udp_origins_v4_; dns_udp_origin_tracker> dns_udp_origins_v6_; - /** - * @brief True once the static driver filters that keep port-53 traffic (and the DNS - * proxy's own local replies) in user mode, ahead of the LAN-bypass PASS filters, - * have been installed. - */ - bool dns_filters_installed_{ false }; - /** * @brief Count of DNS packets dropped by the Proxy-mode policy since the last * throttled report from the resolver thread. @@ -963,15 +956,20 @@ namespace proxy if (udp) udp->stop(); - // Proxy-mode DNS must take precedence over the LAN-bypass PASS filters; install the - // front-of-table REDIRECT filters once the DNS proxy's listener ports are known. + // Proxy-mode DNS must take precedence over the LAN-bypass PASS filters: (re)install + // the front-of-table REDIRECT filters with the current listener ports. If that fails, + // fail start() instead of running with DNS able to bypass the policy. dns_udp_origins_v4_.clear(); dns_udp_origins_v6_.clear(); dns_blocked_packets_.store(0, std::memory_order_relaxed); untranslated_listener_replies_.store(0, std::memory_order_relaxed); for (auto& flag : dns_block_reason_logged_) flag.clear(std::memory_order_relaxed); - install_dns_filters(); + if (!install_dns_filters()) + { + start_failure_cleanup(); + return false; + } process_resolve_thread_ = std::thread(&socks_local_router::process_resolve_thread_proc, this); @@ -1180,8 +1178,8 @@ namespace proxy { add_lan_passover_filters_v4(); add_lan_passover_filters_v6(); - // In DNS Proxy mode, start() inserts port-53 REDIRECT filters ahead of these PASS - // filters, so DNS addressed to LAN resolvers is still proxied. + // In DNS Proxy mode, every start() (re)inserts port-53 REDIRECT filters ahead of these + // PASS filters, so DNS addressed to LAN resolvers is still proxied. } /** @@ -2515,68 +2513,79 @@ namespace proxy } /** - * @brief Installs the static driver filters that keep DNS in user mode in Proxy mode. + * @brief Removes the DNS policy's driver filters from an earlier start(). They are the + * only REDIRECT filters this router installs; every other static filter is PASS. + */ + void remove_dns_filters() + { + const auto is_dns_filter = [](const auto& filter) { return filter.get_action() == ndisapi::action_t::redirect; }; + static_filters_.remove_filters_if( + [&is_dns_filter](const ndisapi::filter& filter) { return is_dns_filter(filter); }); + static_filters_.remove_filters_if( + [&is_dns_filter](const ndisapi::filter& filter) { return is_dns_filter(filter); }); + } + + /** + * @brief (Re)installs the static driver filters the DNS policy needs (plan_dns_filters()). * - * Static PASS filters (LAN bypass and the upstream exemptions) are evaluated in the - * driver before the user-mode handler sees a packet. In Proxy mode DNS must take - * precedence over LAN bypass, so REDIRECT (to user mode) filters are inserted at the - * front of the table for outbound TCP/UDP to port 53 and for the DNS proxy's local - * replies (outbound from its listener ports, which are addressed to the original - often - * LAN - DNS server). Unrelated LAN traffic keeps matching the LAN PASS filters. + * Runs on every start(): the filters from an earlier run are removed and the current plan + * is inserted at the front of the table, so the filters stay ahead of LAN-bypass PASS + * filters added between runs and use the current listener ports and proxy selection. In + * Direct mode the plan is empty, so earlier filters are only removed. * Called from start() under lifecycle_mutex_. + * + * @return false when a filter needed by Proxy mode could not be installed; the caller + * then fails start() rather than running with DNS able to bypass the policy. */ - void install_dns_filters() + bool install_dns_filters() { - if (dns_filters_installed_) - return; - - std::optional tcp4, udp4, tcp6, udp6; + dns_routing_mode mode; + dns_listener_ports listeners; { std::shared_lock lock(lock_); - if (dns_mode_ != dns_routing_mode::proxy) - return; - tcp4 = dns_listener_port_locked(); - udp4 = dns_listener_port_locked(); - tcp6 = dns_listener_port_locked(); - udp6 = dns_listener_port_locked(); - } - - bool all_installed = true; - const auto add = [this, &all_installed](const uint8_t protocol, - const std::optional destination_port, const std::optional source_port) - { - ndisapi::filter filter; - filter.set_direction(ndisapi::direction_t::out) - .set_action(ndisapi::action_t::redirect) - .set_protocol(protocol); - if (destination_port) - filter.set_dest_port(std::make_pair(*destination_port, *destination_port)); - if (source_port) - filter.set_source_port(std::make_pair(*source_port, *source_port)); - - if (!static_filters_.add_filter_front(filter)) - all_installed = false; - }; - - for (const auto protocol : { static_cast(IPPROTO_UDP), static_cast(IPPROTO_TCP) }) - { - add.template operator()(protocol, dns_port, std::nullopt); - add.template operator()(protocol, dns_port, std::nullopt); + mode = dns_mode_; + listeners.tcp4 = dns_listener_port_locked(); + listeners.udp4 = dns_listener_port_locked(); + listeners.tcp6 = dns_listener_port_locked(); + listeners.udp6 = dns_listener_port_locked(); } - if (tcp4) add.template operator()(static_cast(IPPROTO_TCP), std::nullopt, *tcp4); - if (udp4) add.template operator()(static_cast(IPPROTO_UDP), std::nullopt, *udp4); - if (tcp6) add.template operator()(static_cast(IPPROTO_TCP), std::nullopt, *tcp6); - if (udp6) add.template operator()(static_cast(IPPROTO_UDP), std::nullopt, *udp6); - - dns_filters_installed_ = true; + remove_dns_filters(); - if (!all_installed) + for (const auto& spec : plan_dns_filters(mode, listeners)) { - NETLIB_LOG(log_level::error, - "DNS routing: failed to install one or more driver filters that give DNS precedence over " - "LAN bypass; DNS addressed to LAN resolvers may not be proxied while bypassLan is enabled."); + const auto protocol = static_cast(spec.transport == dns_transport::tcp ? IPPROTO_TCP : IPPROTO_UDP); + const auto add = [this, &spec, protocol](auto filter) -> bool + { + filter.set_direction(ndisapi::direction_t::out) + .set_action(ndisapi::action_t::redirect) + .set_protocol(protocol); + if (spec.destination_port) + filter.set_dest_port(std::make_pair(*spec.destination_port, *spec.destination_port)); + if (spec.source_port) + filter.set_source_port(std::make_pair(*spec.source_port, *spec.source_port)); + return static_filters_.add_filter_front(filter); + }; + + const bool added = spec.family == dns_family::ipv4 + ? add(ndisapi::filter{}) + : add(ndisapi::filter{}); + + if (!added) + { + NETLIB_LOG(log_level::error, + "DNS routing: failed to install the {} {} driver filter for {} port {}; refusing to start so " + "DNS cannot bypass the DNS proxy.", + spec.family == dns_family::ipv4 ? "IPv4" : "IPv6", + spec.transport == dns_transport::tcp ? "TCP" : "UDP", + spec.destination_port ? "destination" : "source", + spec.destination_port ? *spec.destination_port : spec.source_port.value_or(0)); + remove_dns_filters(); + return false; + } } + + return true; } /** diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 6607458..2a89c58 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -568,3 +568,46 @@ TEST(DnsFragmentPolicy, Ipv6PacketsWithoutAClassifiableFirstFragmentAreNotReport EXPECT_FALSE(parse(ipv6_packet(fragment_proto, concat({ fragment_header(fragment_proto, 0, true), fragment_header(udp_proto, 0, true), ports(1, 53) }))).has_value()); } + +// 6. Driver filters: Proxy mode keeps port-53 traffic of both families and transports, and the +// DNS listeners' replies, in user mode; Direct mode installs none; no port-0 filters. +TEST(DnsFilterPlan, DirectModeInstallsNoFilters) +{ + proxy::dns_listener_ports listeners{ 41001, 41002, 41003, 41004 }; + EXPECT_TRUE(proxy::plan_dns_filters(direct, listeners).empty()); +} + +TEST(DnsFilterPlan, ProxyModeCoversPort53AndEveryRunningListener) +{ + using proxy::dns_filter_spec; + const auto plan = proxy::plan_dns_filters(proxy_mode, { 41001, 41002, 41003, 41004 }); + + const std::vector expected{ + { dns_family::ipv4, dns_transport::udp, dns_port, std::nullopt }, + { dns_family::ipv4, dns_transport::tcp, dns_port, std::nullopt }, + { dns_family::ipv6, dns_transport::udp, dns_port, std::nullopt }, + { dns_family::ipv6, dns_transport::tcp, dns_port, std::nullopt }, + { dns_family::ipv4, dns_transport::tcp, std::nullopt, uint16_t{ 41001 } }, + { dns_family::ipv4, dns_transport::udp, std::nullopt, uint16_t{ 41002 } }, + { dns_family::ipv6, dns_transport::tcp, std::nullopt, uint16_t{ 41003 } }, + { dns_family::ipv6, dns_transport::udp, std::nullopt, uint16_t{ 41004 } }, + }; + EXPECT_EQ(plan, expected); +} + +TEST(DnsFilterPlan, ListenersThatAreNotRunningGetNoSourcePortFilter) +{ + // IPv6 listeners disabled (nullopt) and an IPv4 UDP listener reporting port 0. + const auto plan = proxy::plan_dns_filters(proxy_mode, { 41001, uint16_t{ 0 }, std::nullopt, std::nullopt }); + + ASSERT_EQ(plan.size(), 5u); + for (const auto& spec : plan) + { + EXPECT_NE(spec.source_port, std::optional{ 0 }); + EXPECT_TRUE(spec.destination_port.has_value() != spec.source_port.has_value()); + } + EXPECT_EQ(plan.back().source_port, std::optional{ 41001 }); + + // Even with no listener at all, port 53 stays in user mode (where it is then blocked). + EXPECT_EQ(proxy::plan_dns_filters(proxy_mode, {}).size(), 4u); +} From 26a3f770972df86e3d74b7ef3ccbdb4ff6f40d31 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:50:01 +0000 Subject: [PATCH 06/62] fix: restore override answers whatever source the relay reports With a serverOverride, a reply whose SOCKS5 header did not name the override server was left unchanged and then discarded by the resolver, so relays that report another source (for example their own address) broke DNS. classify_dns_override_reply() now restores any reply on the DNS listener whose (client port, DNS message ID) matches a tracked query, whatever its header source. Replies that name the override but match no query are still dropped, and unmatched replies from other sources are still left unchanged. The header's address type must still match the listener's family, since the redirect strips a header of that size. Tests cover a relay reporting another source end to end; the "Server override" section of docs/configuration.md is updated. --- docs/configuration.md | 2 +- netlib/src/proxy/dns_routing_policy.h | 40 ++++++----- .../portable/dns_packet_redirect_test.cpp | 70 ++++++++++++++----- 3 files changed, 75 insertions(+), 37 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 3de66f9..7c2e72b 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -167,7 +167,7 @@ The selection is made by `proxyId`, never by position, so reordering rules does Without `serverOverride`, each query keeps its original destination: the SOCKS5 server is asked to reach the DNS server Windows queried. That fails when Windows uses a local resolver, such as a home router at `192.168.1.1`, which the remote SOCKS5 server cannot reach. Set `serverOverride` to a resolver that is reachable from the SOCKS5 server, such as `1.1.1.1`. -With an override, only the SOCKS5 destination changes: the `UDP ASSOCIATE` datagram header or the `CONNECT` target names the override, while the packets the application sees keep the original server address. For UDP, ProxiFyre remembers the original server for each query (by client port and DNS message ID, for 30 seconds) and presents the answer as coming from that server, because a resolver discards answers from an address it did not query. Answers relayed from the override that match no outstanding query are dropped. Checksums are recalculated on every rewritten packet. +With an override, only the SOCKS5 destination changes: the `UDP ASSOCIATE` datagram header or the `CONNECT` target names the override, while the packets the application sees keep the original server address. For UDP, ProxiFyre remembers the original server for each query (by client port and DNS message ID, for 30 seconds) and presents the answer as coming from that server, because a resolver discards answers from an address it did not query. An answer that matches an outstanding query is restored this way whatever source address the SOCKS5 relay reports for it: RFC 1928 relays report the override server, but some report another address. A datagram that names the override server but matches no outstanding query is dropped; other datagrams relayed through the same proxy are delivered unchanged. Checksums are recalculated on every rewritten packet. ### Examples diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 10bdc39..b461174 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -669,22 +669,26 @@ namespace proxy /// How a datagram leaving a local UDP proxy listener is presented to the client. enum class dns_reply_restore : uint8_t { - unchanged, ///< not a DNS override answer: present the relay's SOCKS5 header source - restore, ///< DNS override answer: present it as coming from the original server - drop ///< DNS override answer to no known query: drop it + unchanged, ///< not an answer to a tracked query: present the relay's SOCKS5 header source + restore, ///< answer to a tracked query: present it as coming from the original server + drop ///< names the override server but answers no tracked query: drop it }; /** * @brief Classifies a datagram relayed back by the DNS proxy while a server override is * configured, and finds the server the resolver originally queried. * - * Only an answer whose SOCKS5 header names the override server (address and port) is - * treated as a DNS override answer; anything else relayed through the same proxy is left - * unchanged. An override answer is restored to the original server recorded for - * (@p client_port, DNS message ID), or dropped when there is no such query: delivering it - * from the override address would only be rejected by the resolver. + * A datagram whose (@p client_port, DNS message ID) matches a tracked query is restored to + * the original server whatever source its SOCKS5 header reports: RFC 1928 relays report the + * override server, but some report another address (for example their own), and an answer + * presented from any address other than the queried server is discarded by the resolver. + * A datagram that names the override server but matches no tracked query is dropped. Any + * other datagram relayed through the same proxy is left unchanged. * - * @param socks_datagram The UDP payload as relayed: SOCKS5 UDP header followed by the DNS message. + * The datagram's ATYP must match the listener's family (@p expected_address_type): the + * redirect strips a header of that family's size. + * + * @param socks_datagram The UDP payload as relayed: SOCKS5 UDP header followed by the data. * @param expected_address_type 1 for the IPv4 path, 4 for the IPv6 path. * @param override_address The override address bytes (network byte order). */ @@ -695,19 +699,19 @@ namespace proxy const uint16_t client_port, dns_udp_origin_tracker& origins) { const auto view = parse_socks5_udp_datagram(socks_datagram, size); - if (!view || view->address_type != expected_address_type || view->address_size != override_address_size || - view->port != override_port || - !std::equal(view->address, view->address + view->address_size, override_address)) + if (!view || view->address_type != expected_address_type) return { dns_reply_restore::unchanged, std::nullopt }; - const auto message_id = dns_message_id(view->data, view->data_size); - if (!message_id) - return { dns_reply_restore::drop, std::nullopt }; + if (const auto message_id = dns_message_id(view->data, view->data_size)) + { + if (auto original = origins.resolve(client_port, *message_id)) + return { dns_reply_restore::restore, std::move(original) }; + } - if (auto original = origins.resolve(client_port, *message_id)) - return { dns_reply_restore::restore, std::move(original) }; + const bool names_override = view->address_size == override_address_size && view->port == override_port && + std::equal(view->address, view->address + view->address_size, override_address); - return { dns_reply_restore::drop, std::nullopt }; + return { names_override ? dns_reply_restore::drop : dns_reply_restore::unchanged, std::nullopt }; } // Compile-time checks of the decision table's key invariants. diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index b5b9752..c8ef3e4 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -345,40 +345,74 @@ TEST(DnsPacketRedirect, Ipv6UdpOverrideRewritesTheSocksDestinationAndRestoresThe EXPECT_TRUE(reply.l4_checksum_valid()); } -// 7. Answers that are not override answers (other traffic through the same proxy) are left to -// the relay's header; override answers to an unknown query are dropped. -TEST(DnsPacketRedirect, OnlyOverrideAnswersToKnownQueriesAreRestored) +// 7./8. Answers to tracked queries are restored whatever source the relay reports; answers +// naming the override that match no query are dropped; other traffic is unchanged. +TEST(DnsPacketRedirect, AnswersToTrackedQueriesAreRestoredWhateverSourceTheRelayReports) { proxy::dns_udp_origin_tracker> origins; const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; origins.remember(client_port, 0x1111, net::ip_endpoint{ v4{ std::string{ "192.168.1.1" } }, 53 }); - // A different relay source (application traffic sharing the proxy): unchanged. - auto other = local_proxy_reply("192.168.1.10", "203.0.113.5", v4{ std::string{ "203.0.113.5" } }, 443, dns_message(0x1111)); - EXPECT_EQ((classify(other, server_override, origins).first), proxy::dns_reply_restore::unchanged); + // Tracked query, relay reports the override: restored. + auto known = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x1111)); + const auto [restore, origin] = classify(known, server_override, origins); + EXPECT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(origin.has_value()); + EXPECT_EQ(origin->ip, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(origin->port, 53); - // The override address on another port: unchanged. - auto other_port = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 5353, dns_message(0x1111)); - EXPECT_EQ((classify(other_port, server_override, origins).first), proxy::dns_reply_restore::unchanged); + // Tracked query, relay reports another source (its own address, another port): restored too. + auto relay_source = local_proxy_reply("192.168.1.10", "192.168.1.1", v4{ std::string{ "203.0.113.5" } }, 40000, dns_message(0x1111)); + const auto [relay_restore, relay_origin] = classify(relay_source, server_override, origins); + EXPECT_EQ(relay_restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(relay_origin.has_value()); + EXPECT_EQ(relay_origin->ip, v4{ std::string{ "192.168.1.1" } }); - // An override answer to a query that was never sent: dropped. + // Names the override but answers no tracked query: dropped. auto unknown = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x2222)); EXPECT_EQ((classify(unknown, server_override, origins).first), proxy::dns_reply_restore::drop); - - // A truncated DNS message from the override: dropped. auto truncated = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, std::vector{ 0x11, 0x11, 0x01 }); EXPECT_EQ((classify(truncated, server_override, origins).first), proxy::dns_reply_restore::drop); - // A malformed SOCKS5 header (non-zero FRAG) is not parsed. + // Other traffic through the same proxy that matches no tracked query: unchanged. + auto other = local_proxy_reply("192.168.1.10", "203.0.113.5", v4{ std::string{ "203.0.113.5" } }, 443, dns_message(0x2222)); + EXPECT_EQ((classify(other, server_override, origins).first), proxy::dns_reply_restore::unchanged); + auto other_port = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 5353, dns_message(0x2222)); + EXPECT_EQ((classify(other_port, server_override, origins).first), proxy::dns_reply_restore::unchanged); + + // A malformed SOCKS5 header (non-zero FRAG) or the other family's ATYP is not restored; the + // redirect then fails to translate it and the router drops it. auto fragmented = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x1111)); fragmented.udp_payload()[2] = 1; EXPECT_EQ((classify(fragmented, server_override, origins).first), proxy::dns_reply_restore::unchanged); + auto wrong_family = frame::udp4("192.168.1.10", "192.168.1.1", udp_listener, client_port, + socks5_udp_datagram(v6{ std::string{ "2001:db8::1" } }, 53, dns_message(0x1111))); + EXPECT_EQ((classify(wrong_family, server_override, origins).first), proxy::dns_reply_restore::unchanged); +} - auto known = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x1111)); - const auto [restore, origin] = classify(known, server_override, origins); - EXPECT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(origin.has_value()); - EXPECT_EQ(origin->ip, v4{ std::string{ "192.168.1.1" } }); +// 8. End to end: a relay that reports its own address as the answer's source still produces an +// answer the resolver accepts (source = the server it queried). +TEST(DnsPacketRedirect, RelayReportingAnotherSourceStillRestoresTheQueriedServer) +{ + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + proxy::dns_udp_origin_tracker> origins; + const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; + + auto query = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, dns_message(0x4242)); + origins.remember(client_port, 0x4242, net::ip_endpoint{ v4{ query.ip4()->ip_dst }, 53 }); + ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener), server_override)); + + const auto answer = dns_message(0x4242, 30); + auto reply = local_proxy_reply("192.168.1.10", "192.168.1.1", v4{ std::string{ "198.51.100.7" } }, 1080, answer); + const auto [restore, origin] = classify(reply, server_override, origins); + ASSERT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); + EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); + EXPECT_EQ(reply.payload(), answer); + EXPECT_TRUE(reply.ip4_checksum_valid()); + EXPECT_TRUE(reply.l4_checksum_valid()); } // 8. A datagram that cannot be redirected is reported as such (the router then drops it rather From f42036090b18f7a0000bdc3bd62d308340b70e4b Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:50:37 +0000 Subject: [PATCH 07/62] perf: skip lock_ on the UDP listener reply path unless an override is active dns_udp_reply_origin() took lock_ for every reply leaving any local UDP listener, in every mode. set_dns_routing() now sets an atomic flag only in Proxy mode with a usable proxy and a server override (dns_reply_restore_needed()), and the reply path returns early without locking when it is clear, so Direct mode and override-free Proxy mode add no locking to application UDP replies. --- netlib/src/proxy/dns_routing_policy.h | 11 +++++++++++ netlib/src/proxy/socks_local_router.h | 16 ++++++++++++++++ netlib/test/proxy/dns_routing_policy_test.cpp | 11 +++++++++++ 3 files changed, 38 insertions(+) diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index b461174..4f5d218 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -666,6 +666,17 @@ namespace proxy return view; } + /** + * @brief Whether replies leaving the DNS proxy's UDP listener may need their source restored + * (classify_dns_override_reply()): only in Proxy mode with a usable proxy and a server + * override. Otherwise the reply path needs no DNS work at all. + */ + [[nodiscard]] constexpr bool dns_reply_restore_needed(const dns_routing_mode mode, const bool proxy_selected, + const bool server_override_configured) noexcept + { + return mode == dns_routing_mode::proxy && proxy_selected && server_override_configured; + } + /// How a datagram leaving a local UDP proxy listener is presented to the client. enum class dns_reply_restore : uint8_t { diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index b958346..0746740 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -264,6 +264,14 @@ namespace proxy std::optional> dns_server_override_v4_; std::optional> dns_server_override_v6_; + /** + * @brief True when replies from the DNS proxy's UDP listener may need their source + * restored (dns_reply_restore_needed()). Lets every listener reply skip lock_ in + * Direct mode and in Proxy mode without an override. Written by set_dns_routing() + * while the router is inactive. + */ + std::atomic_bool dns_reply_restore_active_{ false }; + /** * @brief Original server of each UDP DNS query rewritten to the server override, so the * answer can be restored to the server the resolver actually queried. @@ -1791,6 +1799,7 @@ namespace proxy dns_proxy_id_.reset(); dns_server_override_v4_.reset(); dns_server_override_v6_.reset(); + dns_reply_restore_active_.store(false, std::memory_order_release); if (settings.mode == dns_routing_mode::direct) { @@ -1846,6 +1855,8 @@ namespace proxy } dns_proxy_id_ = proxy_id; + dns_reply_restore_active_.store(dns_reply_restore_needed(dns_mode_, true, + dns_server_override_v4_.has_value() || dns_server_override_v6_.has_value()), std::memory_order_release); const auto upstream = proxy_id < proxy_upstreams_.size() ? proxy_upstreams_[proxy_id].to_string() @@ -2475,6 +2486,11 @@ namespace proxy const uint16_t listener_port, const uint16_t client_port, const uint8_t* socks_payload, const size_t socks_payload_size) { + // Lock-free early exit for every listener reply in Direct mode and in Proxy mode + // without an override. + if (!dns_reply_restore_active_.load(std::memory_order_acquire)) + return { dns_reply_restore::unchanged, std::nullopt }; + std::optional> server_override; { std::shared_lock lock(lock_); diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 2a89c58..70db0c1 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -611,3 +611,14 @@ TEST(DnsFilterPlan, ListenersThatAreNotRunningGetNoSourcePortFilter) // Even with no listener at all, port 53 stays in user mode (where it is then blocked). EXPECT_EQ(proxy::plan_dns_filters(proxy_mode, {}).size(), 4u); } + +// 9. Listener replies need DNS work (and lock_) only in Proxy mode with a usable proxy and an override. +TEST(DnsReplyRestore, NeededOnlyInProxyModeWithAnOverride) +{ + using proxy::dns_reply_restore_needed; + EXPECT_TRUE(dns_reply_restore_needed(proxy_mode, true, true)); + EXPECT_FALSE(dns_reply_restore_needed(proxy_mode, true, false)); + EXPECT_FALSE(dns_reply_restore_needed(proxy_mode, false, true)); + EXPECT_FALSE(dns_reply_restore_needed(direct, true, true)); + EXPECT_FALSE(dns_reply_restore_needed(direct, false, false)); +} From 0fa1e323da80d8ffdcc3b7cc8ebaa7269707cc8c Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:53:25 +0000 Subject: [PATCH 08/62] perf: evict DNS origin tracker entries by insertion order When the table was full of live entries, each insert on the packet thread ran a full sweep plus a linear min_element under the mutex. Entries are now also recorded in an insertion-ordered queue: expiry and eviction of the oldest entry pop from its front (amortized O(1)), stale records left by refreshed or resolved-and-expired keys are skipped, and the queue is compacted when stale records outnumber live entries. Semantics are unchanged: lookups do not consume entries, re-remembering a key refreshes its time, the TTL is 30 seconds and the table is bounded. Tests cover refresh-aware eviction, the queue bound, and the cost of inserting into a full table (about 10 ms for 200k inserts, versus about 6.7 s before). --- netlib/src/proxy/dns_routing_policy.h | 104 +++++++++++++++--- netlib/test/proxy/dns_routing_policy_test.cpp | 57 ++++++++++ 2 files changed, 143 insertions(+), 18 deletions(-) diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 4f5d218..38b1d40 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -527,7 +528,14 @@ namespace proxy { } - /// Records the original server of a query sent from @p client_port with @p message_id. + /** + * @brief Records the original server of a query sent from @p client_port with + * @p message_id. Re-remembering a key refreshes its time. + * + * Runs on the packet thread, so it costs amortized O(1) even when the table is full of + * live entries: expired and then oldest entries are found at the front of an + * insertion-ordered queue instead of by scanning the table. + */ void remember(const uint16_t client_port, const uint16_t message_id, const Endpoint& original, const clock::time_point now = clock::now()) { @@ -536,24 +544,24 @@ namespace proxy if (const auto it = entries_.find(key); it != entries_.end()) { + // The key's earlier queue record becomes stale; it is skipped when it reaches + // the front. it->second = entry{ now, original }; + order_.push_back({ key, now }); + compact_if_needed_locked(); return; } if (entries_.size() >= capacity_) { - sweep_locked(now); + expire_front_locked(now); if (entries_.size() >= capacity_) - { - // Still full of live entries: evict the oldest one. Linear, but only reached - // when more than `capacity_` queries are outstanding within one TTL. - const auto oldest = std::min_element(entries_.begin(), entries_.end(), - [](const auto& left, const auto& right) { return left.second.created_at < right.second.created_at; }); - entries_.erase(oldest); - } + evict_oldest_locked(); } entries_.emplace(key, entry{ now, original }); + order_.push_back({ key, now }); + compact_if_needed_locked(); } /// Returns the original server for a response to @p client_port with @p message_id. @@ -574,18 +582,26 @@ namespace proxy return it->second.original; } - /// Removes expired entries. + /// Removes every expired entry (maintenance thread). void sweep(const clock::time_point now = clock::now()) { std::scoped_lock lock(lock_); - sweep_locked(now); + for (auto it = entries_.begin(); it != entries_.end();) + { + if (now - it->second.created_at > ttl_) + it = entries_.erase(it); + else + ++it; + } + expire_front_locked(now); } - /// Removes every entry (router stop). + /// Removes every entry (router start). void clear() { std::scoped_lock lock(lock_); entries_.clear(); + order_.clear(); } [[nodiscard]] std::size_t size() const @@ -594,6 +610,13 @@ namespace proxy return entries_.size(); } + /// Number of insertion-order records, including stale ones (bounded; for tests). + [[nodiscard]] std::size_t order_records() const + { + std::scoped_lock lock(lock_); + return order_.size(); + } + private: struct entry { @@ -601,24 +624,69 @@ namespace proxy Endpoint original; }; + struct record + { + uint32_t key; + clock::time_point created_at; + }; + static constexpr uint32_t make_key(const uint16_t client_port, const uint16_t message_id) noexcept { return (static_cast(client_port) << 16) | message_id; } - void sweep_locked(const clock::time_point now) + /// True when @p r is the current record of a live entry. + [[nodiscard]] bool is_current_locked(const record& r) const { - for (auto it = entries_.begin(); it != entries_.end();) + const auto it = entries_.find(r.key); + return it != entries_.end() && it->second.created_at == r.created_at; + } + + /// Pops expired records from the front, erasing the entries they still describe. + void expire_front_locked(const clock::time_point now) + { + while (!order_.empty() && now - order_.front().created_at > ttl_) { - if (now - it->second.created_at > ttl_) - it = entries_.erase(it); - else - ++it; + if (is_current_locked(order_.front())) + entries_.erase(order_.front().key); + order_.pop_front(); + } + } + + /// Erases the oldest live entry, skipping stale records. + void evict_oldest_locked() + { + while (!order_.empty()) + { + const auto front = order_.front(); + order_.pop_front(); + if (is_current_locked(front)) + { + entries_.erase(front.key); + return; + } } } + /// Keeps the queue bounded when keys are refreshed repeatedly: rebuilds it from the + /// live entries, oldest first, once stale records outnumber them. + void compact_if_needed_locked() + { + if (order_.size() <= 2 * capacity_ + 16) + return; + + std::vector live; + live.reserve(entries_.size()); + for (const auto& [key, value] : entries_) + live.push_back({ key, value.created_at }); + std::sort(live.begin(), live.end(), + [](const record& left, const record& right) { return left.created_at < right.created_at; }); + order_.assign(live.begin(), live.end()); + } + mutable std::mutex lock_; std::unordered_map entries_; + std::deque order_; std::chrono::seconds ttl_; std::size_t capacity_; }; diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 70db0c1..ea9ec78 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -622,3 +622,60 @@ TEST(DnsReplyRestore, NeededOnlyInProxyModeWithAnOverride) EXPECT_FALSE(dns_reply_restore_needed(direct, true, true)); EXPECT_FALSE(dns_reply_restore_needed(direct, false, false)); } + +// 10. Eviction uses insertion order: a refreshed key is not the oldest, the queue of insertion +// records stays bounded under repeated refreshes, and inserting into a full table is cheap. +TEST(DnsUdpOriginTracker, RefreshedKeysAreEvictedByTheirLatestTime) +{ + tracker origins{ std::chrono::seconds{ 30 }, 2 }; + const auto start = clock::now(); + origins.remember(1, 1, { "a", 53 }, start); + origins.remember(2, 1, { "b", 53 }, start + std::chrono::milliseconds{ 1 }); + origins.remember(1, 1, { "a2", 53 }, start + std::chrono::milliseconds{ 2 }); // refresh: now newest + origins.remember(3, 1, { "c", 53 }, start + std::chrono::milliseconds{ 3 }); // evicts key 2 + + const auto at = start + std::chrono::milliseconds{ 4 }; + EXPECT_EQ(origins.resolve(1, 1, at), (endpoint{ "a2", 53 })); + EXPECT_FALSE(origins.resolve(2, 1, at).has_value()); + EXPECT_TRUE(origins.resolve(3, 1, at).has_value()); + EXPECT_EQ(origins.size(), 2u); +} + +TEST(DnsUdpOriginTracker, InsertionRecordsStayBoundedUnderRepeatedRefreshes) +{ + constexpr std::size_t capacity = 64; + tracker origins{ std::chrono::seconds{ 30 }, capacity }; + const auto start = clock::now(); + for (int i = 0; i < 100000; ++i) + origins.remember(static_cast(i % 8), 7, { "x", 53 }, start + std::chrono::microseconds{ i }); + + EXPECT_EQ(origins.size(), 8u); + EXPECT_LE(origins.order_records(), 2 * capacity + 16); + for (uint16_t port = 0; port < 8; ++port) + EXPECT_TRUE(origins.resolve(port, 7, start + std::chrono::seconds{ 1 }).has_value()); +} + +TEST(DnsUdpOriginTracker, InsertingIntoAFullTableOfLiveEntriesIsCheap) +{ + constexpr std::size_t capacity = 8192; + tracker origins{ std::chrono::seconds{ 30 }, capacity }; + const auto start = clock::now(); + + // 200k inserts with the table permanently full of live entries. With a linear scan per + // insert this is ~1.6e9 entry visits; with insertion-order eviction it is linear overall. + const auto timer = std::chrono::steady_clock::now(); + for (uint32_t i = 0; i < 200000; ++i) + origins.remember(static_cast(i >> 16), static_cast(i), { "s", 53 }, + start + std::chrono::microseconds{ i }); + const auto elapsed = std::chrono::steady_clock::now() - timer; + + EXPECT_EQ(origins.size(), capacity); + EXPECT_LE(origins.order_records(), 2 * capacity + 16); + // The newest entries survive, the oldest are evicted. + EXPECT_TRUE(origins.resolve(3, static_cast(199999 & 0xffff), start + std::chrono::seconds{ 1 }).has_value()); + EXPECT_FALSE(origins.resolve(0, 0, start + std::chrono::seconds{ 1 }).has_value()); + // Measured on the portable runner: ~10 ms with insertion-order eviction, ~6.7 s with the + // earlier per-insert sweep and linear search for the oldest entry. The bound leaves two + // orders of magnitude of headroom for slow or sanitized builds and still fails the latter. + EXPECT_LT(elapsed, std::chrono::seconds{ 2 }); +} From 2592907fd4312043bb26ff8c7224b28fa2125676 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:53:53 +0000 Subject: [PATCH 09/62] docs: make the Direct-mode TCP/53 change prominent for upgrades Direct mode, which also applies to configurations without a dns section, now always sends TCP port 53 directly. Add a clearly marked upgrade note to README.md and extend the docs/configuration.md callout: rules that previously carried TCP port 53 through a proxy no longer do so, and Proxy mode is the way to route DNS through a proxy. --- README.md | 5 ++++- docs/configuration.md | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 6e4f3f9..43d267e 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,10 @@ DNS (UDP/TCP port 53) bypasses the proxies by default. To prevent DNS leaks, giv "dns": { "mode": "Proxy", "proxyId": "office", "serverOverride": "1.1.1.1" } ``` -In `Proxy` mode DNS is never sent directly: if the selected proxy cannot carry a query, the query is dropped. See [DNS routing](docs/configuration.md#dns-routing) for the behavior, the TCP port 53 change in `Direct` mode, and limitations. +In `Proxy` mode DNS is never sent directly: if the selected proxy cannot carry a query, the query is dropped. See [DNS routing](docs/configuration.md#dns-routing) for the behavior and limitations. + +> [!IMPORTANT] +> **Upgrade note — DNS over TCP port 53.** In the default `Direct` DNS mode, which also applies to existing configurations without a `dns` section, DNS over TCP port 53 now always bypasses the proxies, as DNS over UDP port 53 already did. Rules that previously carried TCP port 53 through a proxy, for example a catch-all rule, no longer do so. To route DNS through a proxy, use DNS `Proxy` mode. See the [configuration reference](docs/configuration.md) for matching rules, authentication, LAN bypass, DNS routing, logging, TLS options, and complete examples. The repository also includes a ready-to-edit [sample configuration](app-config.sample.json). diff --git a/docs/configuration.md b/docs/configuration.md index 7c2e72b..f1531e9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -144,7 +144,7 @@ The optional `dns` object controls conventional DNS: UDP and TCP traffic to dest UDP and TCP DNS to port 53 bypass every SOCKS5 proxy for both address families, whatever process sends it. This is the behavior of configurations without a `dns` section. -> **Behavior change:** earlier releases bypassed only UDP port 53. TCP port 53 was routed like any other TCP traffic of the owning process, so a catch-all rule could send it through a proxy. In `Direct` mode TCP/53 is now also always direct, so DNS uses one consistent path whether or not an answer was truncated. +> **Behavior change on upgrade:** earlier releases bypassed only UDP port 53. TCP port 53 was routed like any other TCP traffic of the owning process, so a catch-all or application rule could send it through a proxy. In `Direct` mode, which also applies to existing configurations without a `dns` section, TCP/53 is now always direct as well, so DNS uses one consistent path whether or not an answer was truncated. Rules that previously carried TCP port 53 through a proxy no longer do so; use `Proxy` mode to route DNS through a proxy. ### Proxy mode From 7c4ae9765557f66e6c36fb98263a56dfc9e4a7b7 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:54:26 +0000 Subject: [PATCH 10/62] fix: state plainly that DNS stays blocked until restart; refuse unknown DNS modes When the selected DNS proxy cannot be created at startup, the service keeps running and blocks all DNS by design. The error log now says explicitly that all DNS is blocked until the service is restarted after the cause is fixed, logs it once instead of twice, and the Proxy mode section of docs/configuration.md states the same. ConfigureDnsRouting() now uses DnsConfiguration.TryGetMode() and fails the service start on an unknown mode instead of relying on GetMode(), which maps any unknown value to Direct. --- ProxiFyre/Program.cs | 28 ++++++++++++++++++++++------ docs/configuration.md | 2 ++ 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/ProxiFyre/Program.cs b/ProxiFyre/Program.cs index 7745837..a9fa38f 100644 --- a/ProxiFyre/Program.cs +++ b/ProxiFyre/Program.cs @@ -209,7 +209,18 @@ public void Start() /// private void ConfigureDnsRouting(ProxiFyreConfiguration settings, IntPtr[] proxyHandles) { - if (DnsConfiguration.GetMode(settings.Dns) == DnsRoutingMode.Direct) + // Validation rejects an unknown mode, but never let one fall back to Direct here: + // a typo in "Proxy" must not silently send DNS around the proxy. + DnsRoutingMode mode; + if (!DnsConfiguration.TryGetMode(settings.Dns == null ? null : settings.Dns.Mode, out mode)) + { + var message = $"DNS routing: the DNS mode '{settings.Dns.Mode}' is not recognized; use Direct or Proxy. " + + "ProxiFyre will not start with an unknown DNS mode."; + LoggerInstance.Error(message); + throw new InvalidOperationException(message); + } + + if (mode == DnsRoutingMode.Direct) { if (!_socksify.SetDnsRouting(DnsRoutingModeEnum.Direct, new IntPtr(-1), null)) LoggerInstance.Warn("Failed to apply Direct DNS routing."); @@ -221,19 +232,24 @@ private void ConfigureDnsRouting(ProxiFyreConfiguration settings, IntPtr[] proxy var dns = settings.Dns; var ruleIndex = DnsConfiguration.FindProxyRuleIndex(settings.Proxies, dns.ProxyId); var handle = ruleIndex >= 0 && ruleIndex < proxyHandles.Length ? proxyHandles[ruleIndex] : new IntPtr(-1); + var proxyUnavailable = handle.ToInt64() == -1; - if (handle.ToInt64() == -1) + if (proxyUnavailable) { LoggerInstance.Error( $"DNS routing: the selected DNS proxy '{dns.ProxyId}' is not available because its SOCKS5 proxy could not be created. " + - "All DNS queries will be blocked instead of being sent directly or through another proxy."); + "ALL DNS QUERIES ARE BLOCKED until the service is restarted after the cause is fixed; DNS is not sent " + + "directly or through another proxy. See the preceding errors for why the proxy could not be created."); } if (!_socksify.SetDnsRouting(DnsRoutingModeEnum.Proxy, handle, dns.ServerOverride)) { - LoggerInstance.Error( - "DNS routing: the engine rejected the Proxy mode configuration; DNS queries will be blocked. " + - "See the preceding engine log entries for the reason."); + if (!proxyUnavailable) + { + LoggerInstance.Error( + "DNS routing: the engine rejected the Proxy mode configuration. ALL DNS QUERIES ARE BLOCKED until the " + + "configuration is corrected and the service is restarted. See the preceding engine log entries for the reason."); + } return; } diff --git a/docs/configuration.md b/docs/configuration.md index f1531e9..7569a91 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -161,6 +161,8 @@ ProxiFyre never falls back to sending DNS directly. DNS is dropped, and a warnin Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. +If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. + The selection is made by `proxyId`, never by position, so reordering rules does not change the DNS proxy. If the referenced rule is removed or renamed, validation fails with `DNS_PROXY_NOT_FOUND`; ProxiFyre never silently switches to another proxy. The GUI assigns an id such as `proxy-1` to a rule when it is selected as the DNS proxy, and clears the id on a duplicated copy. ### Server override From c7c45bf309726c4b72e1bfd88f406e54a5c0606e Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:54:48 +0000 Subject: [PATCH 11/62] docs: limit the "one warning per cause" claim to drops by the DNS policy The one-warning-per-cause and throttled drop count apply only to packets the DNS policy itself blocks. SOCKS5 connection, authentication, TLS and UDP ASSOCIATE failures, and proxy disconnects, happen after a successful redirect and are reported by the local proxy server. Separate the two in the Proxy mode section of docs/configuration.md and in manual validation step 5 of docs/gui.md, list the new drop causes (fragments, unknown sender to a SOCKS5 server), and stop promising that Windows falls back to other DNS servers. --- docs/configuration.md | 16 +++++++++++----- docs/gui.md | 2 +- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 7569a91..e985017 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -150,14 +150,20 @@ UDP and TCP DNS to port 53 bypass every SOCKS5 proxy for both address families, All captured UDP and TCP DNS is sent through the selected proxy: UDP through a SOCKS5 `UDP ASSOCIATE`, TCP through a SOCKS5 `CONNECT`, reusing the same engine paths as application traffic. Queries from the Windows DNS Client service and from applications with their own resolvers are treated the same. -ProxiFyre never falls back to sending DNS directly. DNS is dropped, and a warning is logged once per cause with a throttled count of dropped packets, when: +ProxiFyre never falls back to sending DNS directly. The DNS policy itself drops a query when: - the selected proxy could not be created at startup, or the configuration is rejected by the engine; -- the SOCKS5 connection, authentication, TLS handshake, or `UDP ASSOCIATE` fails, or the proxy disconnects; - the proxy does not accept the destination's address family (for example IPv6 DNS with an IPv4-only rule); -- a `serverOverride` is configured and the query is addressed to a server of the other address family (an IPv4 override blocks queries to IPv6 servers and vice versa; Windows then uses its other configured DNS servers); or -- the packet cannot be redirected, such as a TCP connection to port 53 that was opened before ProxiFyre started, or a datagram too large to carry the SOCKS5 UDP header; or -- the datagram is fragmented. Only the first fragment carries the UDP or TCP header, so only a first fragment (IPv4 or IPv6) addressed to port 53 can be recognized as DNS; it is dropped, which also prevents the datagram from being reassembled at the server. Later fragments carry no ports, cannot be classified, and are passed unchanged, so other fragmented traffic is not affected. In `Direct` mode fragmented DNS is passed like any other DNS. +- a `serverOverride` is configured and the query is addressed to a server of the other address family (an IPv4 override blocks queries to IPv6 servers and vice versa); +- the packet cannot be redirected, such as a TCP connection to port 53 that was opened before ProxiFyre started, or a datagram too large to carry the SOCKS5 UDP header; +- the datagram is fragmented. Only the first fragment carries the UDP or TCP header, so only a first fragment (IPv4 or IPv6) addressed to port 53 can be recognized as DNS; it is dropped, which also prevents the datagram from being reassembled at the server. Later fragments carry no ports, cannot be classified, and are passed unchanged, so other fragmented traffic is not affected. In `Direct` mode fragmented DNS is passed like any other DNS; or +- it is addressed to a configured SOCKS5 server and its sending process cannot be determined (see [Recursion and ProxiFyre's own traffic](#recursion-and-proxifyres-own-traffic)). + +For these drops the engine logs one warning per cause, address family, and transport, followed by a count of dropped packets at most every five seconds. + +A query can also fail after it has been redirected to the DNS proxy's local listener: the SOCKS5 connection, authentication, TLS handshake, or `UDP ASSOCIATE` fails, or the proxy disconnects. The query is then not sent directly either, but these failures are reported by the local proxy server in the same way as for application traffic, not by the DNS policy's warnings and counts. + +Whether name resolution still succeeds after a drop depends on Windows: it retries, and may try its other configured DNS servers, but ProxiFyre does not control that. Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. diff --git a/docs/gui.md b/docs/gui.md index 038fb41..c82b1f3 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -164,5 +164,5 @@ The routing policy and the packet rewriting are covered by automated tests (`net 2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). 3. Enable `bypassLan` with a router resolver (`192.168.x.1`): without an override the SOCKS5 server is asked for the router address; with `serverOverride: "1.1.1.1"` it is asked for `1.1.1.1` and `Resolve-DnsName` still reports answers from the router address. 4. Reorder the rules, Apply & Restart, and confirm DNS still uses the selected proxy. -5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; confirm the engine log shows one warning per cause and throttled drop counts. +5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log reports the SOCKS5 connection or `UDP ASSOCIATE` failures from the local proxy server. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. 6. Configure an IPv4 override with an IPv6 resolver and confirm IPv6 queries are dropped while IPv4 queries succeed. From abea47c8772ec4e277e93886ccdcc3f635758827 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:55:15 +0000 Subject: [PATCH 12/62] fix: normalize a blank proxy id to null; reword the other-family warning - ConfigurationNormalizer turns a whitespace-only rule id into null instead of an empty string, so a saved configuration does not gain an "id": "" property. - DNS_SERVER_OVERRIDE_OTHER_FAMILY_BLOCKED no longer promises that Windows falls back to other DNS servers; it says name resolution relies on Windows querying a server of the override's family. NUnit cases cover both, and that TryGetMode rejects an unknown mode. --- .../ConfigurationNormalizer.cs | 2 +- .../ConfigurationValidator.cs | 3 +- ProxiFyre.Tests/DnsConfigurationTests.cs | 35 +++++++++++++++++++ 3 files changed, 38 insertions(+), 2 deletions(-) diff --git a/ProxiFyre.Configuration/ConfigurationNormalizer.cs b/ProxiFyre.Configuration/ConfigurationNormalizer.cs index 2578ea1..d588ec4 100644 --- a/ProxiFyre.Configuration/ConfigurationNormalizer.cs +++ b/ProxiFyre.Configuration/ConfigurationNormalizer.cs @@ -92,7 +92,7 @@ public ProxyRule NormalizeRule(ProxyRule rule) var hasCanonicalTransport = TryGetCanonicalTransport(rule.Socks5Transport, out transport); return new ProxyRule { - Id = rule.Id == null ? null : rule.Id.Trim(), + Id = EmptyToNull(rule.Id), AppNames = appNames, Socks5ProxyEndpoint = rule.Socks5ProxyEndpoint == null ? null : rule.Socks5ProxyEndpoint.Trim(), Username = rule.Username, diff --git a/ProxiFyre.Configuration/ConfigurationValidator.cs b/ProxiFyre.Configuration/ConfigurationValidator.cs index 52ee118..904aba7 100644 --- a/ProxiFyre.Configuration/ConfigurationValidator.cs +++ b/ProxiFyre.Configuration/ConfigurationValidator.cs @@ -655,7 +655,8 @@ private static void ValidateDns(DnsSettings dns, IList rules, ICollec issues.Add(Warning( "DNS_SERVER_OVERRIDE_OTHER_FAMILY_BLOCKED", "DNS queries addressed to " + (serverOverride.IsIpv6 ? "IPv4" : "IPv6") + " servers are blocked because the " + - "server override is " + (serverOverride.IsIpv6 ? "IPv6" : "IPv4") + ". Windows falls back to its other configured DNS servers.", + "server override is " + (serverOverride.IsIpv6 ? "IPv6" : "IPv4") + ". Name resolution then relies on Windows " + + "querying a DNS server of the override's address family.", "dns.serverOverride")); } else if (families != ProxyAddressFamilySelection.Both) diff --git a/ProxiFyre.Tests/DnsConfigurationTests.cs b/ProxiFyre.Tests/DnsConfigurationTests.cs index 5706eb1..db7ad2a 100644 --- a/ProxiFyre.Tests/DnsConfigurationTests.cs +++ b/ProxiFyre.Tests/DnsConfigurationTests.cs @@ -378,6 +378,41 @@ public void NormalizationCanonicalizesDnsSettingsWithoutChangingMeaning() Assert.That(_normalizer.Normalize(TestModels.ValidConfiguration()).Dns, Is.Null); } + [TestCase(" ")] + [TestCase("")] + [TestCase("\t")] + public void NormalizationTurnsABlankProxyIdIntoNoId(string id) + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[0].Id = id; + + var normalized = _normalizer.Normalize(configuration); + + Assert.That(normalized.Proxies[0].Id, Is.Null); + Assert.That(((JObject)JObject.Parse(_serializer.Serialize(normalized))["proxies"][0]).Property("id"), Is.Null); + } + + [Test] + public void OtherFamilyWarningDoesNotPromiseAFallback() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.ServerOverride = "2606:4700:4700::1111"; + + var warning = _validator.Validate(configuration).Warnings + .Single(issue => issue.Code == "DNS_SERVER_OVERRIDE_OTHER_FAMILY_BLOCKED"); + StringAssert.Contains("IPv4 servers are blocked", warning.Message); + StringAssert.DoesNotContain("falls back", warning.Message); + } + + [Test] + public void UnknownModeIsNotAcceptedByTryGetMode() + { + DnsRoutingMode mode; + Assert.That(DnsConfiguration.TryGetMode("Tunnel", out mode), Is.False); + Assert.That(DnsConfiguration.TryGetMode("Proxy", out mode), Is.True); + Assert.That(mode, Is.EqualTo(DnsRoutingMode.Proxy)); + } + [Test] public void NormalizationKeepsAnUnknownModeVisibleForValidation() { From 33c38b0c32c657fdabeb9df9b464b2674bafbfea Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:55:45 +0000 Subject: [PATCH 13/62] fix(gui): give the DNS labels tab indices so their mnemonics focus the field Each DNS label now has the TabIndex immediately before its control (&mode -> DNS mode, &proxy -> DNS proxy, &Server override -> server override text box), and the Uninstall button gets an explicit tab position after the DNS group. The layout is unchanged: the DNS group plus the Uninstall button do not fit the 487-pixel design height of the Settings tab without rearranging other groups, so the page relies on its existing AutoScroll. This needs a visual check on Windows. --- ProxiFyreUI/Forms/MainForm.Designer.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/ProxiFyreUI/Forms/MainForm.Designer.cs b/ProxiFyreUI/Forms/MainForm.Designer.cs index 16fee7c..b4e801f 100644 --- a/ProxiFyreUI/Forms/MainForm.Designer.cs +++ b/ProxiFyreUI/Forms/MainForm.Designer.cs @@ -575,15 +575,15 @@ private void InitializeComponent() // DNS routing this.dnsGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsGroupBox.Location = new System.Drawing.Point(10, 358); this.dnsGroupBox.Name = "dnsGroupBox"; this.dnsGroupBox.Size = new System.Drawing.Size(1078, 154); this.dnsGroupBox.TabIndex = 3; this.dnsGroupBox.TabStop = false; this.dnsGroupBox.Text = "DNS routing (UDP/TCP port 53)"; this.dnsGroupBox.Controls.Add(this.dnsExplanationLabel); this.dnsGroupBox.Controls.Add(this.dnsServerOverrideHintLabel); this.dnsGroupBox.Controls.Add(this.dnsServerOverrideTextBox); this.dnsGroupBox.Controls.Add(this.dnsServerOverrideLabel); this.dnsGroupBox.Controls.Add(this.dnsProxyComboBox); this.dnsGroupBox.Controls.Add(this.dnsProxyLabel); this.dnsGroupBox.Controls.Add(this.dnsModeComboBox); this.dnsGroupBox.Controls.Add(this.dnsModeLabel); - this.dnsModeLabel.AutoSize = true; this.dnsModeLabel.Location = new System.Drawing.Point(13, 31); this.dnsModeLabel.Text = "DNS &mode:"; + this.dnsModeLabel.AutoSize = true; this.dnsModeLabel.Location = new System.Drawing.Point(13, 31); this.dnsModeLabel.TabIndex = 0; this.dnsModeLabel.Text = "DNS &mode:"; this.dnsModeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.dnsModeComboBox.Items.AddRange(new object[] { "Direct", "Proxy" }); this.dnsModeComboBox.Location = new System.Drawing.Point(122, 27); this.dnsModeComboBox.Size = new System.Drawing.Size(108, 23); this.dnsModeComboBox.TabIndex = 1; this.dnsModeComboBox.SelectedIndexChanged += new System.EventHandler(this.DnsControlChanged); - this.dnsProxyLabel.AutoSize = true; this.dnsProxyLabel.Location = new System.Drawing.Point(250, 31); this.dnsProxyLabel.Text = "DNS &proxy:"; + this.dnsProxyLabel.AutoSize = true; this.dnsProxyLabel.Location = new System.Drawing.Point(250, 31); this.dnsProxyLabel.TabIndex = 2; this.dnsProxyLabel.Text = "DNS &proxy:"; this.dnsProxyComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsProxyComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.dnsProxyComboBox.Location = new System.Drawing.Point(340, 27); this.dnsProxyComboBox.Size = new System.Drawing.Size(723, 23); this.dnsProxyComboBox.TabIndex = 3; this.dnsProxyComboBox.SelectedIndexChanged += new System.EventHandler(this.DnsControlChanged); - this.dnsServerOverrideLabel.AutoSize = true; this.dnsServerOverrideLabel.Location = new System.Drawing.Point(13, 66); this.dnsServerOverrideLabel.Text = "&Server override:"; + this.dnsServerOverrideLabel.AutoSize = true; this.dnsServerOverrideLabel.Location = new System.Drawing.Point(13, 66); this.dnsServerOverrideLabel.TabIndex = 4; this.dnsServerOverrideLabel.Text = "&Server override:"; this.dnsServerOverrideTextBox.Location = new System.Drawing.Point(122, 62); this.dnsServerOverrideTextBox.Size = new System.Drawing.Size(210, 23); this.dnsServerOverrideTextBox.TabIndex = 5; this.dnsServerOverrideTextBox.TextChanged += new System.EventHandler(this.DnsControlChanged); - this.dnsServerOverrideHintLabel.AutoSize = true; this.dnsServerOverrideHintLabel.ForeColor = System.Drawing.SystemColors.GrayText; this.dnsServerOverrideHintLabel.Location = new System.Drawing.Point(340, 66); this.dnsServerOverrideHintLabel.Text = "Optional IP literal, e.g. 1.1.1.1 or [2606:4700:4700::1111]:53. Empty keeps the server Windows queried."; - this.dnsExplanationLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsExplanationLabel.ForeColor = System.Drawing.SystemColors.GrayText; this.dnsExplanationLabel.Location = new System.Drawing.Point(13, 96); this.dnsExplanationLabel.Size = new System.Drawing.Size(1050, 50); this.dnsExplanationLabel.Text = "Direct: DNS bypasses the proxies. Proxy: DNS from every application, including the Windows DNS Client service, uses the selected proxy (which must support TCP and UDP), takes precedence over LAN bypass, and is blocked rather than sent directly if that proxy cannot carry it. Encrypted DNS (DoH/DoT) is not affected. Takes effect after service restart."; - this.uninstallServiceButton.Location = new System.Drawing.Point(10, 522); this.uninstallServiceButton.Size = new System.Drawing.Size(125, 29); this.uninstallServiceButton.Text = "Uninstall service…"; this.uninstallServiceButton.UseVisualStyleBackColor = true; this.uninstallServiceButton.Click += new System.EventHandler(this.UninstallServiceButton_Click); + this.dnsServerOverrideHintLabel.AutoSize = true; this.dnsServerOverrideHintLabel.TabIndex = 6; this.dnsServerOverrideHintLabel.ForeColor = System.Drawing.SystemColors.GrayText; this.dnsServerOverrideHintLabel.Location = new System.Drawing.Point(340, 66); this.dnsServerOverrideHintLabel.Text = "Optional IP literal, e.g. 1.1.1.1 or [2606:4700:4700::1111]:53. Empty keeps the server Windows queried."; + this.dnsExplanationLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsExplanationLabel.TabIndex = 7; this.dnsExplanationLabel.ForeColor = System.Drawing.SystemColors.GrayText; this.dnsExplanationLabel.Location = new System.Drawing.Point(13, 96); this.dnsExplanationLabel.Size = new System.Drawing.Size(1050, 50); this.dnsExplanationLabel.Text = "Direct: DNS bypasses the proxies. Proxy: DNS from every application, including the Windows DNS Client service, uses the selected proxy (which must support TCP and UDP), takes precedence over LAN bypass, and is blocked rather than sent directly if that proxy cannot carry it. Encrypted DNS (DoH/DoT) is not affected. Takes effect after service restart."; + this.uninstallServiceButton.Location = new System.Drawing.Point(10, 522); this.uninstallServiceButton.TabIndex = 4; this.uninstallServiceButton.Size = new System.Drawing.Size(125, 29); this.uninstallServiceButton.Text = "Uninstall service…"; this.uninstallServiceButton.UseVisualStyleBackColor = true; this.uninstallServiceButton.Click += new System.EventHandler(this.UninstallServiceButton_Click); this.uninstallNoteLabel.AutoSize = true; this.uninstallNoteLabel.Location = new System.Drawing.Point(145, 529); this.uninstallNoteLabel.Text = "Uninstalling preserves " + ProxiFyre.Configuration.ProxiFyrePaths.ConfigurationFileName + ", its backup, and all log files."; // action/status this.actionPanel.Controls.Add(this.operationProgressBar); this.actionPanel.Controls.Add(this.applyRestartButton); this.actionPanel.Controls.Add(this.saveButton); this.actionPanel.Controls.Add(this.validateButton); this.actionPanel.Controls.Add(this.reloadButton); this.actionPanel.Dock = System.Windows.Forms.DockStyle.Bottom; this.actionPanel.Location = new System.Drawing.Point(0, 617); this.actionPanel.Name = "actionPanel"; this.actionPanel.Size = new System.Drawing.Size(1114, 51); this.actionPanel.TabIndex = 2; From 6947d7d07bd29952d50e2929487391fe9386d6e7 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 13:57:49 +0000 Subject: [PATCH 14/62] test: replace DNS policy tests that restated the implementation - DecisionDoesNotDependOnTheSendingProcess called the same pure function repeatedly. It is replaced by SenderNeverAffectsQueriesToOrdinaryResolvers, which fails if the recursion guard's sender check ever applies to queries that are not addressed to a SOCKS5 server (an unresolved Dnscache owner would then be deferred or dropped). - TruncatedUdpAnswerTcpRetryUsesTheSameProxy compared two listener ports from the same fixture. It is replaced by TcpRetryIsRedirectedOrBlockedNeverPassed (TCP/53 is redirected to the proxy's TCP listener, or blocked when the proxy has no TCP, for both families) and by a packet-level test that sends a truncated UDP answer and the TCP retry through the real redirects, checking the TC bit, restored source, listener replies through the close, and checksums. --- .../portable/dns_packet_redirect_test.cpp | 47 ++++++++++++++ netlib/test/proxy/dns_routing_policy_test.cpp | 65 ++++++++++++------- 2 files changed, 87 insertions(+), 25 deletions(-) diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index c8ef3e4..5e40164 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -662,3 +662,50 @@ TEST(DnsTcpCloseTracking, UntranslatableListenerSegmentIsDropped) EXPECT_FALSE(udp_translated); EXPECT_EQ(proxy::decide_listener_reply(true, udp_translated), proxy::listener_reply_action::drop); } + +// 14. Truncation fallback end to end: the truncated UDP answer reaches the resolver unchanged +// (TC bit intact, source = the server it queried), and the TCP retry to that same server is +// redirected to the DNS proxy's TCP listener, with the listener's replies presented as the +// server's port 53 through the end of the connection. +TEST(DnsPacketRedirect, TruncatedUdpAnswerAndTcpRetryBothGoThroughTheDnsProxy) +{ + ndisapi::socks5_udp_local_redirect udp{ log_level::error }; + ndisapi::tcp_local_redirect tcp{ log_level::error }; + proxy::dns_udp_origin_tracker> origins; + const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; + + // UDP query, redirected with the override. + auto query = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, dns_message(0x5151)); + origins.remember(client_port, 0x5151, net::ip_endpoint{ v4{ query.ip4()->ip_dst }, 53 }); + ASSERT_TRUE(udp.is_new_endpoint(query.buffer)); + ASSERT_TRUE(udp.process_client_to_server_packet(query.buffer, htons(udp_listener), server_override)); + + // Truncated answer (TC bit, byte 2 bit 0x02) relayed from the override. + auto truncated_answer = dns_message(0x5151, 20); + truncated_answer[2] = static_cast(0x80 | 0x02); + auto reply = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, truncated_answer); + const auto [restore, origin] = classify(reply, server_override, origins); + ASSERT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(udp.process_server_to_client_packet(reply.buffer, origin)); + EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(reply.payload(), truncated_answer); + EXPECT_EQ(reply.payload()[2] & 0x02, 0x02); + EXPECT_TRUE(reply.l4_checksum_valid()); + + // The resolver retries over TCP to the same server from a new port. + constexpr uint16_t retry_port = client_port + 1; + auto syn = frame::tcp4("192.168.1.10", "192.168.1.1", retry_port, 53, TH_SYN); + ASSERT_TRUE(tcp.process_client_to_server_packet(syn.buffer, htons(tcp_listener))); + EXPECT_EQ(ntohs(syn.tcp()->th_dport), tcp_listener); + + for (const uint8_t flags : { uint8_t{ TH_SYN | TH_ACK }, uint8_t{ TH_PSH | TH_ACK }, uint8_t{ TH_FIN | TH_ACK } }) + { + auto segment = frame::tcp4("192.168.1.10", "192.168.1.1", tcp_listener, retry_port, flags); + ASSERT_TRUE(tcp.process_server_to_client_packet(segment.buffer)); + EXPECT_EQ(v4{ segment.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(ntohs(segment.tcp()->th_sport), 53); + EXPECT_TRUE(segment.l4_checksum_valid()); + } + auto final_ack = frame::tcp4("192.168.1.10", "192.168.1.1", retry_port, 53, TH_FIN | TH_ACK); + EXPECT_TRUE(tcp.process_client_to_server_packet(final_ack.buffer, htons(tcp_listener))); +} diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index ea9ec78..5db7afe 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -113,22 +113,30 @@ TEST(DnsRoutingPolicy, ProxyModeRedirectsToTheListenerOfTheTransportAndFamily) EXPECT_EQ(tcp6.listener_port, p.tcp6); } -// 3./4. The decision has no process input: queries from the Windows DNS Client service -// (svchost.exe), from an application with its own resolver, from an excluded application, -// or from an owner that cannot be resolved are all decided by port 53 and the global mode. -TEST(DnsRoutingPolicy, DecisionDoesNotDependOnTheSendingProcess) +// 3./4. Queries from the Windows DNS Client service, from applications with their own resolver, +// and from owners that cannot be resolved are routed identically: the sender is consulted +// only for packets addressed to a configured SOCKS5 server. This fails if the recursion +// guard's sender check is ever applied to ordinary DNS (Dnscache's owner can be +// unresolved, which would then defer or drop every query). +TEST(DnsRoutingPolicy, SenderNeverAffectsQueriesToOrdinaryResolvers) { const dns_proxy p{}; - const auto target = p.target(dns_transport::udp, dns_family::ipv4); - const auto expected = decide_dns_route(proxy_mode, dns_port, apply, target); - - // The only inputs are the mode, the destination port, the upstream guard, and the proxy. - // Calling the decision repeatedly (as each sender would) yields the same result. - for (int sender = 0; sender < 4; ++sender) + for (const auto& c : all_cases) { - const auto decision = decide_dns_route(proxy_mode, dns_port, apply, target); - EXPECT_EQ(decision.action, expected.action); - EXPECT_EQ(decision.listener_port, expected.listener_port); + const auto target = p.target(c.transport, c.family); + const auto expected = decide_dns_route(proxy_mode, dns_port, apply, target); + ASSERT_EQ(expected.action, dns_route_action::proxy); + + for (const std::optional sender : { std::optional{}, std::optional{ false }, std::optional{ true } }) + { + for (const bool lookup_final : { false, true }) + { + const auto guard = proxy::decide_dns_upstream_guard(false, sender, lookup_final); + const auto decision = decide_dns_route(proxy_mode, dns_port, guard, target); + EXPECT_EQ(decision.action, dns_route_action::proxy); + EXPECT_EQ(decision.listener_port, expected.listener_port); + } + } } } @@ -261,19 +269,26 @@ TEST(DnsRoutingPolicy, NonDnsTrafficIsNotClassified) } } -// 14. A resolver that receives a truncated UDP answer retries over TCP to the same server. Both -// queries are routed through the same proxy, each through its own transport's listener. -TEST(DnsRoutingPolicy, TruncatedUdpAnswerTcpRetryUsesTheSameProxy) +// 14. The TCP retry after a truncated UDP answer must take the same path as the UDP query: in +// Proxy mode TCP/53 is redirected to the same proxy (its TCP listener), never passed, and a +// proxy that cannot carry TCP blocks the retry instead of letting it leak. (The packet-level +// retry is in netlib/test/portable/dns_packet_redirect_test.cpp.) +TEST(DnsRoutingPolicy, TcpRetryIsRedirectedOrBlockedNeverPassed) { - dns_proxy p{}; - p.server_override = dns_family::ipv4; - - const auto udp = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::udp, dns_family::ipv4)); - const auto tcp = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::tcp, dns_family::ipv4)); - EXPECT_EQ(udp.action, dns_route_action::proxy); - EXPECT_EQ(tcp.action, dns_route_action::proxy); - EXPECT_EQ(udp.listener_port, p.udp4); - EXPECT_EQ(tcp.listener_port, p.tcp4); + for (const auto family : { dns_family::ipv4, dns_family::ipv6 }) + { + dns_proxy p{}; + p.server_override = family; + const auto tcp = decide_dns_route(proxy_mode, dns_port, apply, p.target(dns_transport::tcp, family)); + EXPECT_EQ(tcp.action, dns_route_action::proxy); + EXPECT_EQ(tcp.listener_port, family == dns_family::ipv4 ? p.tcp4 : p.tcp6); + + dns_proxy udp_only{}; + udp_only.tcp = false; + const auto blocked = decide_dns_route(proxy_mode, dns_port, apply, udp_only.target(dns_transport::tcp, family)); + EXPECT_EQ(blocked.action, dns_route_action::block); + EXPECT_EQ(blocked.reason, dns_block_reason::transport_unsupported); + } } TEST(DnsRoutingPolicy, BlockReasonsHaveDiagnostics) From 8dc151206d354dde95987db6b403d43f38626991 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 15:18:39 +0000 Subject: [PATCH 15/62] fix: fragment-aware listener-reply handling, with visible drop reports Three related problems in how packets from local proxy listeners are handled: 1. A fragmented IPv6 listener reply was passed to the wire. When the stack fragments a reply (a DNS answer over about 1430 bytes), find_transport_header() returns null, and the first-fragment check only looked for destination port 53, which a reply never has. The first fragment, carrying the SOCKS5 header and the start of the answer, went toward the original resolver. parse_ipv6_first_fragment() now also returns the source port, and decide_ipv6_fragment() drops a first fragment whose source port is an IPv6 listener port of its protocol, in every mode, counted with the other untranslated listener replies. The Proxy-mode port-53 drop is kept. 2. Later IPv4 fragments of unrelated traffic could be dropped: the listener-port check ran before fragment classification, so a later fragment whose first payload bytes equalled a listener port was treated as an untranslatable listener reply. Both IPv4 handlers now classify the fragment first and skip the listener check and DNS classification for later fragments (ipv4_transport_header_present()), which are passed as before. 3. Listener-reply drops were invisible at the default log level, and the UDP override-classification drop was not counted. Both UDP drop paths now go through decide_udp_listener_reply() and are counted; the first drop per run is logged at warning level and the throttled count at info level. The one-shot flag is reset in start(). Tests cover each decision and fail when it is reverted. --- netlib/src/proxy/dns_routing_policy.h | 69 +++++++++++- netlib/src/proxy/socks_local_router.h | 102 ++++++++++++------ netlib/test/proxy/dns_routing_policy_test.cpp | 76 +++++++++++++ 3 files changed, 215 insertions(+), 32 deletions(-) diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 38b1d40..dea0c56 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -286,6 +286,20 @@ namespace proxy return (flags_and_offset & 0x2000) != 0 ? ipv4_fragment::first : ipv4_fragment::none; } + /** + * @brief Whether an IPv4 packet carries a transport header, so its "ports" are ports. + * + * A later fragment's first payload bytes are application data. Nothing that keys on ports, + * neither the local-listener check nor DNS classification, may use them: a later fragment + * of an unrelated datagram whose data happens to equal a listener port would otherwise be + * dropped as an untranslatable listener reply. Later fragments are left to the ordinary + * path and passed. + */ + [[nodiscard]] constexpr bool ipv4_transport_header_present(const ipv4_fragment fragment) noexcept + { + return fragment != ipv4_fragment::later; + } + /** * @brief Applies fragmentation to a DNS routing decision: a datagram that would be redirected * but is fragmented cannot be, so it is blocked instead of being passed. @@ -303,6 +317,7 @@ namespace proxy { uint8_t protocol{}; ///< IPPROTO_UDP (17) or IPPROTO_TCP (6) uint16_t destination_port{}; ///< host byte order + uint16_t source_port{}; ///< host byte order }; /** @@ -360,7 +375,8 @@ namespace proxy return std::nullopt; return ipv6_first_fragment{ next, - static_cast((ipv6_packet[offset + 2] << 8) | ipv6_packet[offset + 3]) }; + static_cast((ipv6_packet[offset + 2] << 8) | ipv6_packet[offset + 3]), + static_cast((ipv6_packet[offset] << 8) | ipv6_packet[offset + 1]) }; } return std::nullopt; @@ -392,6 +408,41 @@ namespace proxy return translated ? listener_reply_action::revert : listener_reply_action::drop; } + /// What the IPv6 handler does with a packet that has no usable transport header. + enum class ipv6_fragment_action : uint8_t + { + pass, ///< not classifiable, or nothing to enforce: pass it (existing behaviour) + drop_listener_reply, ///< first fragment of a local listener's reply: never send it to the wire + drop_dns ///< first fragment of a DNS datagram in Proxy mode: never send it direct + }; + + /** + * @brief Decides what to do with an IPv6 packet whose transport header cannot be used + * (a fragment, or an unsupported extension chain). + * + * A large listener reply (for example a DNS answer over about 1430 bytes) is fragmented by + * the stack, so its first fragment carries the SOCKS5 header and the start of the answer. + * It cannot be translated, so it is dropped in every mode, like an unfragmented listener + * reply that cannot be translated. In Proxy mode the first fragment of a datagram addressed + * to port 53 is dropped so DNS is never sent directly. Everything else, including later + * fragments, which carry no ports, is passed as before. + * + * @param first The parsed first fragment (parse_ipv6_first_fragment()), or nullopt. + * @param source_is_listener The first fragment's source port is a local IPv6 proxy listener + * port of its protocol. + */ + [[nodiscard]] constexpr ipv6_fragment_action decide_ipv6_fragment(const std::optional& first, + const bool source_is_listener, const bool dns_proxy_mode) noexcept + { + if (!first) + return ipv6_fragment_action::pass; + if (source_is_listener) + return ipv6_fragment_action::drop_listener_reply; + if (dns_proxy_mode && first->destination_port == dns_port) + return ipv6_fragment_action::drop_dns; + return ipv6_fragment_action::pass; + } + /// A DNS server override split into its literal address text and port. struct dns_server_override_text { @@ -753,6 +804,22 @@ namespace proxy drop ///< names the override server but answers no tracked query: drop it }; + /** + * @brief Decides what to do with a reply leaving a local UDP proxy listener. + * + * An override answer that matches no tracked query (@p restore == drop) is dropped without + * being translated; otherwise the reply is re-injected when translated and dropped when not. + * Both drops are listener replies that are not sent to the network and are reported the same + * way. + */ + [[nodiscard]] constexpr listener_reply_action decide_udp_listener_reply(const dns_reply_restore restore, + const bool translated) noexcept + { + if (restore == dns_reply_restore::drop) + return listener_reply_action::drop; + return decide_listener_reply(true, translated); + } + /** * @brief Classifies a datagram relayed back by the DNS proxy while a server override is * configured, and finds the server the resolver originally queried. diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 0746740..1764171 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -292,6 +292,12 @@ namespace proxy */ std::atomic untranslated_listener_replies_{ 0 }; + /** + * @brief Set once the first untranslatable listener reply of this run has been reported + * at warning level; later ones are only counted. Reset by start(). + */ + std::atomic_flag untranslated_listener_reply_logged_{}; + /** * @brief One-shot flags so that each (family, transport, reason) block cause is * described once in the log instead of once per packet. @@ -971,6 +977,7 @@ namespace proxy dns_udp_origins_v6_.clear(); dns_blocked_packets_.store(0, std::memory_order_relaxed); untranslated_listener_replies_.store(0, std::memory_order_relaxed); + untranslated_listener_reply_logged_.clear(std::memory_order_relaxed); for (auto& flag : dns_block_reason_logged_) flag.clear(std::memory_order_relaxed); if (!install_dns_filters()) @@ -2245,6 +2252,23 @@ namespace proxy std::optional> server_override; ///< set when the destination is rewritten }; + /** + * @brief Accounts for a packet from a local proxy listener that could not be translated + * back and was dropped. The first one per run is reported at warning level; the + * running count is reported by the resolver thread at a throttled rate. + */ + void note_untranslated_listener_reply() + { + untranslated_listener_replies_.fetch_add(1, std::memory_order_relaxed); + if (!untranslated_listener_reply_logged_.test_and_set(std::memory_order_relaxed)) + { + NETLIB_LOG(log_level::warning, + "A packet from a local proxy listener could not be translated back to its client and was dropped " + "rather than sent to the network (for example a fragmented or malformed reply, or one for a " + "connection that is no longer tracked). Further occurrences are counted."); + } + } + /// True when DNS routing is in Proxy mode. bool dns_proxy_mode() { @@ -2633,35 +2657,37 @@ namespace proxy const auto* const udp_header = reinterpret_cast(reinterpret_cast(ip_header) + sizeof(DWORD) * ip_header->ip_hl); + // A later IPv4 fragment carries no UDP header: its "ports" are payload, so neither the + // listener check nor DNS classification may use them (ipv4_transport_header_present()). + const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); + const bool has_ports = ipv4_transport_header_present(fragment); + // If the packet is from a known proxy port, process for server-to-client redirection. // Answers relayed from a DNS server override are presented as coming from the server // the resolver originally queried. - if (is_udp_proxy_port(ntohs(udp_header->th_sport))) + if (has_ports && is_udp_proxy_port(ntohs(udp_header->th_sport))) { const auto [restore, origin] = dns_udp_reply_origin( ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); - if (restore == dns_reply_restore::drop) - return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; - // A listener reply never belongs on the wire: drop it when it cannot be translated. - if (decide_listener_reply(true, udp_redirect_->process_server_to_client_packet(buffer, origin)) == - listener_reply_action::revert) + const bool translated = restore != dns_reply_restore::drop && + udp_redirect_->process_server_to_client_packet(buffer, origin); + if (decide_udp_listener_reply(restore, translated) == listener_reply_action::revert) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } - untranslated_listener_replies_.fetch_add(1, std::memory_order_relaxed); + note_untranslated_listener_reply(); return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; } // Conventional DNS (destination port 53) follows the global DNS policy, before and // independently of process attribution and application rules: Direct passes it, - // Proxy redirects it to the DNS proxy or drops it. A later IPv4 fragment carries no - // UDP header, so its "port" is payload and it is not classified. - if (const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); fragment != ipv4_fragment::later) + // Proxy redirects it to the DNS proxy or drops it. Later fragments are not classified. + if (has_ports) { if (auto dns = decide_dns( net::ip_address_v4{ ip_header->ip_dst }, ntohs(udp_header->th_dport), postponed, @@ -2776,8 +2802,13 @@ namespace proxy ip_header) + sizeof(DWORD) * ip_header->ip_hl); + // A later IPv4 fragment carries no TCP header: its "ports" are payload, so neither the + // listener check nor DNS classification may use them (see the UDP path). + const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); + const bool has_ports = ipv4_transport_header_present(fragment); + // If the packet is from a known proxy port, process for server-to-client redirection - if (is_tcp_proxy_port(ntohs(tcp_header->th_sport))) + if (has_ports && is_tcp_proxy_port(ntohs(tcp_header->th_sport))) { // A listener segment never belongs on the wire: drop it when it cannot be // translated (for example after its connection entry expired), instead of letting @@ -2790,15 +2821,14 @@ namespace proxy return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } - untranslated_listener_replies_.fetch_add(1, std::memory_order_relaxed); + note_untranslated_listener_reply(); return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; } // Conventional DNS over TCP follows the global DNS policy. In Direct mode TCP/53 is // now unconditionally direct (previously it was routed like any other TCP traffic of - // the owning process). - // A later IPv4 fragment carries no TCP header and is not classified (see the UDP path). - if (const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); fragment != ipv4_fragment::later) + // the owning process). Later fragments are not classified. + if (has_ports) { if (auto dns = decide_dns( net::ip_address_v4{ ip_header->ip_dst }, ntohs(tcp_header->th_dport), postponed, @@ -2907,21 +2937,32 @@ namespace proxy if (transport == nullptr) { - // In DNS Proxy mode, the first fragment of a fragmented UDP/TCP datagram addressed - // to port 53 is dropped: the datagram cannot be redirected, and passing it would - // send DNS directly. Later fragments carry no ports and cannot be classified, so - // they are left alone and unrelated fragmented traffic is unaffected. + // First fragments carry the transport header (decide_ipv6_fragment()): a local + // listener's fragmented reply is dropped in every mode, and in DNS Proxy mode a + // fragmented datagram addressed to port 53 is dropped so DNS is never sent + // directly. Later fragments carry no ports and cannot be classified, so they are + // left alone and unrelated fragmented traffic is unaffected. if (buffer.m_Length > ETHER_HEADER_LENGTH) { - if (const auto first = parse_ipv6_first_fragment(reinterpret_cast(ip_header), - buffer.m_Length - ETHER_HEADER_LENGTH); - first && first->destination_port == dns_port && dns_proxy_mode()) + const auto first = parse_ipv6_first_fragment(reinterpret_cast(ip_header), + buffer.m_Length - ETHER_HEADER_LENGTH); + const bool source_is_listener = first && + (first->protocol == IPPROTO_UDP ? is_udp_proxy_port_v6(first->source_port) + : is_tcp_proxy_port_v6(first->source_port)); + + switch (decide_ipv6_fragment(first, source_is_listener, first && dns_proxy_mode())) { + case ipv6_fragment_action::drop_listener_reply: + note_untranslated_listener_reply(); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + case ipv6_fragment_action::drop_dns: if (first->protocol == IPPROTO_UDP) note_dns_block(dns_block_reason::fragmented); else note_dns_block(dns_block_reason::fragmented); return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + case ipv6_fragment_action::pass: + break; } } @@ -2999,18 +3040,16 @@ namespace proxy ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); - if (restore == dns_reply_restore::drop) - return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; - // A listener reply never belongs on the wire: drop it when it cannot be translated. - if (decide_listener_reply(true, udp_redirect_v6_->process_server_to_client_packet(buffer, origin)) == - listener_reply_action::revert) + const bool translated = restore != dns_reply_restore::drop && + udp_redirect_v6_->process_server_to_client_packet(buffer, origin); + if (decide_udp_listener_reply(restore, translated) == listener_reply_action::revert) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } - untranslated_listener_replies_.fetch_add(1, std::memory_order_relaxed); + note_untranslated_listener_reply(); return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; } @@ -3135,7 +3174,7 @@ namespace proxy return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; } - untranslated_listener_replies_.fetch_add(1, std::memory_order_relaxed); + note_untranslated_listener_reply(); return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; } @@ -3448,9 +3487,10 @@ namespace proxy if (const auto untranslated = untranslated_listener_replies_.exchange(0, std::memory_order_relaxed); untranslated != 0) { - NETLIB_LOG(log_level::debug, + NETLIB_LOG(log_level::info, "Dropped {} packet(s) from local proxy listeners that could not be translated back " - "(no tracked connection, fragmented, or malformed).", untranslated); + "(no tracked connection, fragmented, or malformed); they were not sent to the network.", + untranslated); } } diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 5db7afe..f51b302 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -694,3 +694,79 @@ TEST(DnsUdpOriginTracker, InsertingIntoAFullTableOfLiveEntriesIsCheap) // orders of magnitude of headroom for slow or sanitized builds and still fails the latter. EXPECT_LT(elapsed, std::chrono::seconds{ 2 }); } + +// ------------------------------------------------------------------ listener replies and fragments +// +// A fragmented listener reply must not reach the wire, and a later fragment's payload must never +// be read as ports. + +TEST(ListenerFragmentPolicy, Ipv6FirstFragmentExposesTheSourcePort) +{ + constexpr uint16_t listener = 41004; + const auto first = parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(listener, 50001) }))); + ASSERT_TRUE(first.has_value()); + EXPECT_EQ(first->source_port, listener); + EXPECT_EQ(first->destination_port, 50001); +} + +TEST(ListenerFragmentPolicy, FragmentedListenerReplyIsDroppedInEveryMode) +{ + using proxy::decide_ipv6_fragment; + using proxy::ipv6_fragment_action; + constexpr uint16_t listener = 41004; + + // A large DNS answer from the UDP listener to client port 50001, fragmented by the stack. + const auto reply = parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(listener, 50001) }))); + ASSERT_TRUE(reply.has_value()); + for (const bool proxy_mode_active : { false, true }) + EXPECT_EQ(decide_ipv6_fragment(reply, true, proxy_mode_active), ipv6_fragment_action::drop_listener_reply); + + // A listener reply to client port 53 is still a listener reply, not DNS. + const auto to_port_53 = parse(ipv6_packet(fragment_proto, concat({ fragment_header(tcp_proto, 0, true), ports(listener, 53) }))); + EXPECT_EQ(decide_ipv6_fragment(to_port_53, true, true), ipv6_fragment_action::drop_listener_reply); +} + +TEST(ListenerFragmentPolicy, OtherIpv6FragmentsKeepTheirBehaviour) +{ + using proxy::decide_ipv6_fragment; + using proxy::ipv6_fragment_action; + + const auto dns_query = parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(50001, 53) }))); + EXPECT_EQ(decide_ipv6_fragment(dns_query, false, true), ipv6_fragment_action::drop_dns); + EXPECT_EQ(decide_ipv6_fragment(dns_query, false, false), ipv6_fragment_action::pass); + + const auto unrelated = parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(50001, 443) }))); + EXPECT_EQ(decide_ipv6_fragment(unrelated, false, true), ipv6_fragment_action::pass); + + // Later fragments and unparsable chains carry no ports: passed in every mode. + const auto later = parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 185, false), ports(41004, 53) }))); + ASSERT_FALSE(later.has_value()); + EXPECT_EQ(decide_ipv6_fragment(later, true, true), ipv6_fragment_action::pass); +} + +TEST(ListenerFragmentPolicy, LaterIpv4FragmentsAreNeverReadForPorts) +{ + using proxy::classify_ipv4_fragment; + using proxy::ipv4_transport_header_present; + + // A later fragment of an unrelated datagram whose payload happens to start with a listener port. + EXPECT_FALSE(ipv4_transport_header_present(classify_ipv4_fragment(0x00b9))); + EXPECT_FALSE(ipv4_transport_header_present(classify_ipv4_fragment(0x2001))); + EXPECT_TRUE(ipv4_transport_header_present(classify_ipv4_fragment(0x2000))); + EXPECT_TRUE(ipv4_transport_header_present(classify_ipv4_fragment(0x4000))); + EXPECT_TRUE(ipv4_transport_header_present(classify_ipv4_fragment(0x0000))); +} + +TEST(ListenerFragmentPolicy, UdpListenerRepliesAreDroppedOnBothPaths) +{ + using proxy::decide_udp_listener_reply; + using proxy::dns_reply_restore; + using proxy::listener_reply_action; + + EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::unchanged, true), listener_reply_action::revert); + EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::restore, true), listener_reply_action::revert); + EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::unchanged, false), listener_reply_action::drop); + // An override answer to no tracked query is dropped even if it could be translated. + EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::drop, true), listener_reply_action::drop); + EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::drop, false), listener_reply_action::drop); +} From 5e2600207349827aadc82b985a0ab74335385c66 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 15:20:05 +0000 Subject: [PATCH 16/62] test: assert DNS origin tracker cost structurally, not by wall-clock time The full-table test asserted that 200,000 inserts finish in 2 seconds. It measured 13 ms in a plain gcc build and 436 ms under ASan/UBSan, was never measured in an MSVC Debug build, and its comment overstated the headroom. The tracker now counts every table entry and queue record it examines (expiry, eviction, compaction and sweeps all go through the counter; visits() exposes it for tests). The test fills the table with live entries and asserts that 100,000 further inserts examine at most 4 per insert; a per-insert sweep examines the whole table (8193 per insert) and fails. A second test bounds the work of repeated refreshes. No test in this suite depends on wall-clock time any more. --- netlib/src/proxy/dns_routing_policy.h | 20 ++++++++ netlib/test/proxy/dns_routing_policy_test.cpp | 48 ++++++++++++++----- 2 files changed, 56 insertions(+), 12 deletions(-) diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index dea0c56..0771f74 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -639,6 +639,7 @@ namespace proxy std::scoped_lock lock(lock_); for (auto it = entries_.begin(); it != entries_.end();) { + ++visits_; if (now - it->second.created_at > ttl_) it = entries_.erase(it); else @@ -668,6 +669,19 @@ namespace proxy return order_.size(); } + /** + * @brief Total number of table entries and queue records examined by expiry, eviction, + * compaction, and sweeps since construction. + * + * Every loop over the table or the queue counts here, so tests can assert that the work + * done by remember() stays bounded per call when the table is full, without measuring time. + */ + [[nodiscard]] std::uint64_t visits() const + { + std::scoped_lock lock(lock_); + return visits_; + } + private: struct entry { @@ -698,6 +712,7 @@ namespace proxy { while (!order_.empty() && now - order_.front().created_at > ttl_) { + ++visits_; if (is_current_locked(order_.front())) entries_.erase(order_.front().key); order_.pop_front(); @@ -709,6 +724,7 @@ namespace proxy { while (!order_.empty()) { + ++visits_; const auto front = order_.front(); order_.pop_front(); if (is_current_locked(front)) @@ -729,7 +745,10 @@ namespace proxy std::vector live; live.reserve(entries_.size()); for (const auto& [key, value] : entries_) + { + ++visits_; live.push_back({ key, value.created_at }); + } std::sort(live.begin(), live.end(), [](const record& left, const record& right) { return left.created_at < right.created_at; }); order_.assign(live.begin(), live.end()); @@ -738,6 +757,7 @@ namespace proxy mutable std::mutex lock_; std::unordered_map entries_; std::deque order_; + std::uint64_t visits_{}; std::chrono::seconds ttl_; std::size_t capacity_; }; diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index f51b302..b4bd155 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -670,29 +670,53 @@ TEST(DnsUdpOriginTracker, InsertionRecordsStayBoundedUnderRepeatedRefreshes) EXPECT_TRUE(origins.resolve(port, 7, start + std::chrono::seconds{ 1 }).has_value()); } -TEST(DnsUdpOriginTracker, InsertingIntoAFullTableOfLiveEntriesIsCheap) +TEST(DnsUdpOriginTracker, InsertingIntoAFullTableOfLiveEntriesDoesBoundedWorkPerInsert) { constexpr std::size_t capacity = 8192; + constexpr uint32_t inserts = 100000; tracker origins{ std::chrono::seconds{ 30 }, capacity }; const auto start = clock::now(); - - // 200k inserts with the table permanently full of live entries. With a linear scan per - // insert this is ~1.6e9 entry visits; with insertion-order eviction it is linear overall. - const auto timer = std::chrono::steady_clock::now(); - for (uint32_t i = 0; i < 200000; ++i) + const auto remember = [&](const uint32_t i) + { origins.remember(static_cast(i >> 16), static_cast(i), { "s", 53 }, start + std::chrono::microseconds{ i }); - const auto elapsed = std::chrono::steady_clock::now() - timer; + }; + + // Fill the table with live entries (nothing expires within the test's time span). + for (uint32_t i = 0; i < capacity; ++i) + remember(i); + ASSERT_EQ(origins.size(), capacity); + + // Every further insert must evict one live entry. Count the entries and records examined: + // insertion-order eviction examines a constant amortized number per insert, while a sweep or + // a search for the oldest entry examines the whole table (8192) on every insert. + const auto before = origins.visits(); + for (uint32_t i = capacity; i < capacity + inserts; ++i) + remember(i); + const auto work = origins.visits() - before; EXPECT_EQ(origins.size(), capacity); + EXPECT_LE(work, 4ull * inserts) << "entries/records examined per insert: " << double(work) / inserts; EXPECT_LE(origins.order_records(), 2 * capacity + 16); // The newest entries survive, the oldest are evicted. - EXPECT_TRUE(origins.resolve(3, static_cast(199999 & 0xffff), start + std::chrono::seconds{ 1 }).has_value()); + const auto newest = capacity + inserts - 1; + EXPECT_TRUE(origins.resolve(static_cast(newest >> 16), static_cast(newest), start + std::chrono::seconds{ 1 }).has_value()); EXPECT_FALSE(origins.resolve(0, 0, start + std::chrono::seconds{ 1 }).has_value()); - // Measured on the portable runner: ~10 ms with insertion-order eviction, ~6.7 s with the - // earlier per-insert sweep and linear search for the oldest entry. The bound leaves two - // orders of magnitude of headroom for slow or sanitized builds and still fails the latter. - EXPECT_LT(elapsed, std::chrono::seconds{ 2 }); +} + +TEST(DnsUdpOriginTracker, RepeatedRefreshesDoBoundedWork) +{ + constexpr std::size_t capacity = 64; + constexpr int refreshes = 100000; + tracker origins{ std::chrono::seconds{ 30 }, capacity }; + const auto start = clock::now(); + const auto before = origins.visits(); + for (int i = 0; i < refreshes; ++i) + origins.remember(static_cast(i % 8), 7, { "x", 53 }, start + std::chrono::microseconds{ i }); + + // Compaction rebuilds the queue from the 8 live entries only after at least `capacity` + // stale records have accumulated, so its cost is amortized to well under one visit per call. + EXPECT_LE(origins.visits() - before, static_cast(refreshes)); } // ------------------------------------------------------------------ listener replies and fragments From ce386de20c54b69712840c474843f3e415ec55ef Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 15:21:07 +0000 Subject: [PATCH 17/62] fix: let RST take precedence over SYN in TCP redirect tracking A segment with both SYN and RST was treated as a SYN and restarted tracking. tcp_local_redirect now checks RST first: on a tracked key it ends tracking (the segment is still translated), and on an untracked key it neither creates an entry nor is rewritten. A portable test covers both cases and fails with the previous ordering. --- netlib/src/ndisapi/tcp_local_redirect.h | 28 +++++++++++-------- .../portable/dns_packet_redirect_test.cpp | 18 ++++++++++++ 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/netlib/src/ndisapi/tcp_local_redirect.h b/netlib/src/ndisapi/tcp_local_redirect.h index c3bd143..79b2ee1 100644 --- a/netlib/src/ndisapi/tcp_local_redirect.h +++ b/netlib/src/ndisapi/tcp_local_redirect.h @@ -239,9 +239,10 @@ namespace ndisapi /** * @brief Updates the tracking state for a client-to-server segment. The caller holds lock_. * - * A SYN (without ACK) starts or restarts tracking: a retransmitted SYN refreshes the entry, - * and a SYN on a key whose previous connection is closing starts a new connection. Any - * other segment must belong to a tracked connection. + * An RST ends tracking at once, even when SYN is also set. A SYN (without ACK) starts or + * restarts tracking: a retransmitted SYN refreshes the entry, and a SYN on a key whose + * previous connection is closing starts a new connection. Any other segment must belong + * to a tracked connection. * * @return false when the segment belongs to no tracked connection and must not be rewritten. */ @@ -250,6 +251,19 @@ namespace ndisapi { const auto now = clock::now(); + // RST takes precedence over SYN: a segment carrying both must not (re)start tracking. + if (flags & TH_RST) + { + const auto it = redirected_connections_.find(key); + if (it == redirected_connections_.cend()) + return false; + + NETLIB_DEBUG("DELETE TCP (client RST): {} -> {} : {}", + ntohs(it->first.port), std::string{ it->first.ip }, ntohs(it->second.original_port)); + redirected_connections_.erase(it); + return true; + } + if ((flags & (TH_SYN | TH_ACK)) == TH_SYN) { const auto [it, inserted] = redirected_connections_.try_emplace(key); @@ -276,14 +290,6 @@ namespace ndisapi if (it == redirected_connections_.cend()) return false; - if (flags & TH_RST) - { - NETLIB_DEBUG("DELETE TCP (client RST): {} -> {} : {}", - ntohs(it->first.port), std::string{ it->first.ip }, ntohs(it->second.original_port)); - redirected_connections_.erase(it); - return true; - } - if (flags & TH_FIN) it->second.client_fin = true; diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index 5e40164..86175ba 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -709,3 +709,21 @@ TEST(DnsPacketRedirect, TruncatedUdpAnswerAndTcpRetryBothGoThroughTheDnsProxy) auto final_ack = frame::tcp4("192.168.1.10", "192.168.1.1", retry_port, 53, TH_FIN | TH_ACK); EXPECT_TRUE(tcp.process_client_to_server_packet(final_ack.buffer, htons(tcp_listener))); } + +// 5. RST takes precedence over SYN: a segment carrying both ends tracking instead of starting it. +TEST(DnsTcpCloseTracking, SynWithRstEndsTrackingInsteadOfStartingIt) +{ + { + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + EXPECT_TRUE(send_client(redirect, TH_SYN | TH_RST)); + EXPECT_FALSE(state_of(redirect).has_value()); + EXPECT_FALSE(send_listener(redirect, TH_ACK).has_value()); + } + { + // On an untracked key it neither creates an entry nor is rewritten. + tcp_redirect4 redirect{ log_level::error }; + EXPECT_FALSE(send_client(redirect, TH_SYN | TH_RST)); + EXPECT_FALSE(state_of(redirect).has_value()); + } +} From f13d01999bc768044018918a48ef0265e60cb4bd Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 15:21:44 +0000 Subject: [PATCH 18/62] fix: name DNS filter installation in the engine start-failure message; document idle and recursion limits - ProxiFyre/Program.cs: when the engine fails to start in DNS Proxy mode, the message now says that a driver filter needed to keep DNS in the DNS proxy may have failed to install and that the engine log has the cause, instead of naming only the driver. - docs/configuration.md: state that a proxied TCP connection idle for more than 5 minutes loses its redirect entry, after which segments the local proxy sends first are dropped instead of reaching the real server, so the connection stalls rather than being reset. In "Recursion and ProxiFyre's own traffic", give examples of senders that cannot be determined: traffic forwarded for virtual machines or containers, and kernel- or driver-owned sockets. --- ProxiFyre/Program.cs | 5 +++++ docs/configuration.md | 3 ++- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/ProxiFyre/Program.cs b/ProxiFyre/Program.cs index a9fa38f..5bfa691 100644 --- a/ProxiFyre/Program.cs +++ b/ProxiFyre/Program.cs @@ -192,6 +192,11 @@ public void Start() "Administrator console." : "Failed to start the ProxiFyre proxy engine. Ensure the Windows Packet Filter " + "(NDIS lightweight filter) driver is installed and running, then restart the service."; + if (DnsConfiguration.GetMode(serviceSettings.Dns) == DnsRoutingMode.Proxy) + { + message += " In DNS Proxy mode the engine also refuses to start when a driver filter needed " + + "to keep DNS inside the DNS proxy cannot be installed; the engine log above has the cause."; + } LoggerInstance.Error(message); throw new InvalidOperationException(message); } diff --git a/docs/configuration.md b/docs/configuration.md index e985017..e692558 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -199,7 +199,7 @@ Proxy with an IPv4 override for a configuration that uses a router-provided reso ### Recursion and ProxiFyre's own traffic -SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. ProxiFyre's own traffic to a configured SOCKS5 server is never redirected into the DNS proxy, even if the server listens on port 53: a port-53 packet addressed to a SOCKS5 server (TCP: its address and port; UDP: its address) is exempt only when its sending process is ProxiFyre itself. Queries from any other process to a host that is both the SOCKS5 server and a resolver follow the DNS policy like any other query, including `serverOverride`. If the sender of such a packet cannot be determined, even after the connection table is refreshed, the packet is dropped rather than passed or redirected. +SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. ProxiFyre's own traffic to a configured SOCKS5 server is never redirected into the DNS proxy, even if the server listens on port 53: a port-53 packet addressed to a SOCKS5 server (TCP: its address and port; UDP: its address) is exempt only when its sending process is ProxiFyre itself. Queries from any other process to a host that is both the SOCKS5 server and a resolver follow the DNS policy like any other query, including `serverOverride`. If the sender of such a packet cannot be determined, even after the connection table is refreshed, the packet is dropped rather than passed or redirected. Senders that typically cannot be determined include traffic that Windows forwards on behalf of virtual machines or containers (for example through Hyper-V, WSL, or Internet Connection Sharing), which has no owning local process, and sockets owned by the kernel or by drivers rather than by a user-mode process. Queries from such sources to a host that is also a SOCKS5 server are therefore blocked in `Proxy` mode. ### Limitations @@ -208,6 +208,7 @@ SOCKS5 endpoint host names are resolved once while the configuration is loaded, - Only traffic visible to the Windows Packet Filter layer is captured. Loopback and local resolvers (for example a resolver on `127.0.0.1` or `::1`, or a resolver inside a local VM or container reached through a virtual adapter that is not filtered) are not routed, and their own upstream queries are subject to the same policy only if they leave through a filtered adapter. - Each new UDP source port needs its own SOCKS5 control connection and `UDP ASSOCIATE`, as for application UDP traffic. The Windows DNS Client uses a fresh source port for most queries, so the first answer through the proxy is delayed by the SOCKS5 (and, for `TLS`, the TLS) handshake. - When the service is stopped, packet filtering stops and all traffic, including DNS, is direct. +- A proxied TCP connection that stays idle for more than 5 minutes loses its redirect entry. This applies to every proxied TCP connection, not only DNS. If the local proxy then sends first on that connection, its segments are dropped rather than sent to the real server, so the connection stalls until the application or the proxy times it out instead of being reset. A segment the application sends on such a connection is no longer redirected either: for application traffic it goes to the real server as before, which normally resets the connection; for DNS in `Proxy` mode it is dropped. - Changing DNS settings requires a service restart. ## Authentication From 6d7d3f055f87371f9c956626b0d259109c4d6206 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 15:22:42 +0000 Subject: [PATCH 19/62] docs: document the residual recursion-guard race on cached connection tables The recursion guard exempts a port-53 packet addressed to a SOCKS5 server when process_lookup's cached tables say its owner is ProxiFyre. Those tables are replaced only by actualize(), which runs when the resolver thread processes deferred packets, so a row for a ProxiFyre socket that has since closed can survive until the next refresh. A packet that hits the stale row is answered inline and does not trigger a refresh itself. The race is real but narrow: it needs another process to reuse the exact local UDP port (TCP rows are keyed by the full 4-tuple, which TIME_WAIT normally protects) and to send DNS to the SOCKS5 server's own address before any other deferral refreshes the table. The exact fix, tracking ProxiFyre's own upstream sockets, would have to cover about 70 close paths across the proxy servers and sockets, where sockets change owners. That is not a contained change, and a missed removal would recreate the same stale-entry problem. Deferring every such packet instead was ruled out. The race, its preconditions and how to avoid it are documented in "Recursion and ProxiFyre's own traffic", and at sender_is_proxifyre(). --- docs/configuration.md | 2 ++ netlib/src/proxy/socks_local_router.h | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/docs/configuration.md b/docs/configuration.md index e692558..0a4410b 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -201,6 +201,8 @@ Proxy with an IPv4 override for a configuration that uses a router-provided reso SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. ProxiFyre's own traffic to a configured SOCKS5 server is never redirected into the DNS proxy, even if the server listens on port 53: a port-53 packet addressed to a SOCKS5 server (TCP: its address and port; UDP: its address) is exempt only when its sending process is ProxiFyre itself. Queries from any other process to a host that is both the SOCKS5 server and a resolver follow the DNS policy like any other query, including `serverOverride`. If the sender of such a packet cannot be determined, even after the connection table is refreshed, the packet is dropped rather than passed or redirected. Senders that typically cannot be determined include traffic that Windows forwards on behalf of virtual machines or containers (for example through Hyper-V, WSL, or Internet Connection Sharing), which has no owning local process, and sockets owned by the kernel or by drivers rather than by a user-mode process. Queries from such sources to a host that is also a SOCKS5 server are therefore blocked in `Proxy` mode. +The sender is taken from ProxiFyre's cached copy of the Windows connection tables, which is refreshed whenever a packet has to wait for its owner to be resolved, not on a timer. This leaves a narrow residual race: if ProxiFyre closes one of its own UDP sockets and another process reuses the same local port before the cache is next refreshed, that process's UDP query to a host that is both a SOCKS5 server and a resolver can be treated as ProxiFyre's own and sent directly to that host. The reverse, ProxiFyre's own packet attributed to a stale foreign owner, would send it into the DNS proxy, where it fails rather than leaving the machine directly. Both require the stale entry, an immediate port reuse, and DNS addressed to the SOCKS5 server's own IP address. To avoid the race entirely, do not use the SOCKS5 server's address as a resolver while `Proxy` mode is enabled; a `serverOverride` does not help here, because the guard runs before the override is applied. + ### Limitations - Only conventional DNS on port 53 is affected. DNS over HTTPS, DNS over TLS, DNS over QUIC, mDNS (5353), and LLMNR (5355) are outside the scope of this feature; applications that resolve names internally over encrypted transports (for example browsers with secure DNS enabled) are routed according to their ordinary application rules. diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 1764171..ab1c716 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -2279,6 +2279,14 @@ namespace proxy /** * @brief Whether a resolved owner is ProxiFyre itself; nullopt when the owner is unknown * (no owner, or the shared unresolved default owner). + * + * The owner comes from process_lookup's cached tables, which are replaced only by + * actualize() when the resolver thread processes deferred packets. A row for one of + * ProxiFyre's own sockets that has since closed can therefore still be found if another + * process reuses that local port before the next refresh (documented in + * docs/configuration.md, "Recursion and ProxiFyre's own traffic"). Closing the race exactly + * would mean tracking ProxiFyre's own upstream sockets through every close path of the + * proxy servers and sockets, which is not done here. */ static std::optional sender_is_proxifyre(const std::shared_ptr& owner) noexcept { From 7dedf9bbfdef0b8ca0b69d71e921f7a9259bddfb Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 16:04:50 +0000 Subject: [PATCH 20/62] fix: drop listener segments after a reset quietly instead of reporting a fault tcp_local_redirect erased a connection's entry as soon as an RST was seen, so when an application aborted a proxied connection while the local proxy was still sending, the proxy's in-flight segments found no entry and were reported like any untranslatable listener packet: a warning per run plus an info-level count, making an ordinary abort look like a fault. - An RST now ends the connection but keeps its key as a short-lived record (connection_state::reset) for closed_linger. Nothing on that key is translated after the RST, except that a new SYN starts a new connection as it does on a closing key. Client-to-server segments on a reset key behave exactly as on an untracked key. - process_server_to_client_segment() reports translated, recently_reset or unknown; process_server_to_client_packet() keeps its bool contract. - The router's TCP handlers map the result through decide_tcp_listener_segment(): a recently-reset segment is dropped without the warning or the info-level count and counted separately at debug level; unknown segments keep today's reporting. Tests cover a listener segment after a client RST and after a listener RST, client segments on a reset key, expiry of the record, a new SYN on a reset key, and the pure decision. --- netlib/src/ndisapi/tcp_local_redirect.h | 126 +++++++++++++----- netlib/src/proxy/dns_routing_policy.h | 39 ++++++ netlib/src/proxy/socks_local_router.h | 78 ++++++++--- .../portable/dns_packet_redirect_test.cpp | 103 ++++++++++++++ netlib/test/proxy/dns_routing_policy_test.cpp | 13 ++ 5 files changed, 304 insertions(+), 55 deletions(-) diff --git a/netlib/src/ndisapi/tcp_local_redirect.h b/netlib/src/ndisapi/tcp_local_redirect.h index 79b2ee1..cc79589 100644 --- a/netlib/src/ndisapi/tcp_local_redirect.h +++ b/netlib/src/ndisapi/tcp_local_redirect.h @@ -45,11 +45,12 @@ namespace ndisapi clock::time_point last_activity; bool client_fin{}; ///< the client sent FIN bool server_fin{}; ///< the local proxy sent FIN + bool reset{}; ///< ended by an RST: a record only, nothing is translated /// The time after which the entry may be removed. [[nodiscard]] clock::time_point expires_at() const noexcept { - if (client_fin && server_fin) + if (reset || (client_fin && server_fin)) return last_activity + closed_linger; if (client_fin || server_fin) return last_activity + half_closed_timeout; @@ -57,6 +58,14 @@ namespace ndisapi } }; + /// Outcome of processing a segment from the local proxy to the client. + enum class server_segment_result : uint8_t + { + translated, ///< belongs to a tracked connection: rewritten for the client + recently_reset, ///< belongs to a connection ended by an RST within closed_linger: not rewritten + unknown ///< belongs to no known connection (or is not a usable TCP segment): not rewritten + }; + private: /** * @brief Maps the client TCP endpoint (original destination address, client source port) @@ -230,19 +239,33 @@ namespace ndisapi { std::lock_guard lock(lock_); const auto it = redirected_connections_.find(net::ip_endpoint{ original_destination, client_port }); - if (it == redirected_connections_.cend()) + if (it == redirected_connections_.cend() || it->second.reset) return std::nullopt; return it->second; } + /** + * @brief Whether client endpoint (@p original_destination, @p client_port) belongs to a + * connection that was ended by an RST and whose record has not expired. For + * diagnostics and tests. + */ + [[nodiscard]] bool is_recently_reset(const T& original_destination, const u_short client_port) + { + std::lock_guard lock(lock_); + const auto it = redirected_connections_.find(net::ip_endpoint{ original_destination, client_port }); + return it != redirected_connections_.cend() && it->second.reset; + } + private: /** * @brief Updates the tracking state for a client-to-server segment. The caller holds lock_. * - * An RST ends tracking at once, even when SYN is also set. A SYN (without ACK) starts or - * restarts tracking: a retransmitted SYN refreshes the entry, and a SYN on a key whose - * previous connection is closing starts a new connection. Any other segment must belong - * to a tracked connection. + * An RST ends the connection at once, even when SYN is also set; its key is kept only as a + * short-lived record (connection_state::reset) so that the proxy's segments still in + * flight can be recognized as part of the abort. A reset key is otherwise treated exactly + * like an untracked one. A SYN (without ACK) starts or restarts tracking: a retransmitted + * SYN refreshes the entry, and a SYN on a key whose previous connection is closing or was + * reset starts a new connection. Any other segment must belong to a tracked connection. * * @return false when the segment belongs to no tracked connection and must not be rewritten. */ @@ -255,12 +278,12 @@ namespace ndisapi if (flags & TH_RST) { const auto it = redirected_connections_.find(key); - if (it == redirected_connections_.cend()) + if (it == redirected_connections_.cend() || it->second.reset) return false; - NETLIB_DEBUG("DELETE TCP (client RST): {} -> {} : {}", + NETLIB_DEBUG("RESET TCP (client RST): {} -> {} : {}", ntohs(it->first.port), std::string{ it->first.ip }, ntohs(it->second.original_port)); - redirected_connections_.erase(it); + mark_reset(it->second, now); return true; } @@ -279,7 +302,7 @@ namespace ndisapi // A SYN whose key already exists is either a retransmission for a connection that // is still being set up (the local listener has not completed the handshake) or a - // new connection reusing the key after the previous one closed. Both are rewritten + // new connection reusing the key after the previous one closed or was reset. Both are rewritten // to the local proxy: returning false would pass the SYN to the real destination, // an unproxied leak of a connection we own. it->second = connection_state{ destination_port, now, false, false }; @@ -287,7 +310,7 @@ namespace ndisapi } const auto it = redirected_connections_.find(key); - if (it == redirected_connections_.cend()) + if (it == redirected_connections_.cend() || it->second.reset) return false; if (flags & TH_FIN) @@ -297,33 +320,53 @@ namespace ndisapi return true; } + /// Ends a connection on RST, keeping its key as a short-lived record. + static void mark_reset(connection_state& state, const clock::time_point now) noexcept + { + state.reset = true; + state.client_fin = false; + state.server_fin = false; + state.last_activity = now; + } + + struct server_segment_tracking + { + server_segment_result result{ server_segment_result::unknown }; + u_short original_port{}; ///< network byte order; valid when translated + }; + /** * @brief Updates the tracking state for a segment from the local proxy to the client. * The caller holds lock_. - * @return the original destination port (network byte order) to present as the source - * port, or std::nullopt when the segment belongs to no tracked connection. + * @return translated with the original destination port (network byte order) to present + * as the source port; recently_reset for a segment of a connection ended by an RST + * whose record has not expired (not refreshed, not rewritten); unknown otherwise. */ - std::optional track_server_segment(const net::ip_endpoint& key, const u_char flags) + server_segment_tracking track_server_segment(const net::ip_endpoint& key, const u_char flags) { const auto it = redirected_connections_.find(key); if (it == redirected_connections_.cend()) - return std::nullopt; + return {}; + + if (it->second.reset) + return { server_segment_result::recently_reset, 0 }; const auto original_port = it->second.original_port; + const auto now = clock::now(); if (flags & TH_RST) { - NETLIB_DEBUG("DELETE TCP (proxy RST): {} -> {} : {}", + NETLIB_DEBUG("RESET TCP (proxy RST): {} -> {} : {}", ntohs(it->first.port), std::string{ it->first.ip }, ntohs(original_port)); - redirected_connections_.erase(it); - return original_port; + mark_reset(it->second, now); + return { server_segment_result::translated, original_port }; } if (flags & TH_FIN) it->second.server_fin = true; - it->second.last_activity = clock::now(); - return original_port; + it->second.last_activity = now; + return { server_segment_result::translated, original_port }; } public: @@ -429,17 +472,28 @@ namespace ndisapi * @return True if the packet was translated, false otherwise. */ bool process_server_to_client_packet(INTERMEDIATE_BUFFER& packet) + { + return process_server_to_client_segment(packet) == server_segment_result::translated; + } + + /** + * @brief Processes an S2C packet like process_server_to_client_packet(), and reports + * whether an untranslated segment belongs to a connection that was just reset. + * + * @param packet S2C network packet; modified in place only when translated. + */ + server_segment_result process_server_to_client_segment(INTERMEDIATE_BUFFER& packet) { if constexpr (auto* const eth_header = reinterpret_cast(packet.m_IBuffer); std::is_same_v< net::ip_address_v4, std::decay_t>) { if (ntohs(eth_header->h_proto) != ETH_P_IP) - return false; + return server_segment_result::unknown; auto* ip_header = reinterpret_cast(packet.m_IBuffer + ETHER_HEADER_LENGTH); if (ip_header->ip_p != IPPROTO_TCP) - return false; + return server_segment_result::unknown; // This is TCP packet, get TCP header pointer auto* tcp_header = reinterpret_cast(reinterpret_cast(ip_header) + @@ -450,16 +504,16 @@ namespace ndisapi // bytes for a short/forged IPv4 frame. if (ip_header->ip_hl < 5 || ETHER_HEADER_LENGTH + sizeof(DWORD) * ip_header->ip_hl + sizeof(tcphdr) > packet.m_Length) - return false; + return server_segment_result::unknown; std::lock_guard lock(lock_); - const auto original_port = track_server_segment( + const auto tracking = track_server_segment( net::ip_endpoint{ T{ ip_header->ip_dst }, tcp_header->th_dport }, tcp_header->th_flags); - if (!original_port) - return false; + if (tracking.result != server_segment_result::translated) + return tracking.result; - tcp_header->th_sport = *original_port; + tcp_header->th_sport = tracking.original_port; // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -470,30 +524,30 @@ namespace ndisapi CNdisApi::RecalculateTCPChecksum(&packet); CNdisApi::RecalculateIPChecksum(&packet); - return true; + return server_segment_result::translated; } else if constexpr (std::is_same_v>) { if (ntohs(eth_header->h_proto) != ETH_P_IPV6) - return false; + return server_segment_result::unknown; auto* const ip_header = reinterpret_cast(eth_header + 1); auto [p_header, proto] = net::ipv6_helper::find_transport_header(ip_header, packet.m_Length - ETHER_HEADER_LENGTH); if (p_header == nullptr || proto != IPPROTO_TCP) - return false; + return server_segment_result::unknown; auto* tcp_header = static_cast(p_header); std::lock_guard lock(lock_); - const auto original_port = track_server_segment( + const auto tracking = track_server_segment( net::ip_endpoint{ T{ ip_header->ip6_dst }, tcp_header->th_dport }, tcp_header->th_flags); - if (!original_port) - return false; + if (tracking.result != server_segment_result::translated) + return tracking.result; - tcp_header->th_sport = *original_port; + tcp_header->th_sport = tracking.original_port; // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -504,10 +558,10 @@ namespace ndisapi // Recalculate checksum net::ipv6_helper::recalculate_tcp_udp_checksum(&packet); - return true; + return server_segment_result::translated; } - return false; + return server_segment_result::unknown; } /** diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 0771f74..490c205 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -408,6 +408,45 @@ namespace proxy return translated ? listener_reply_action::revert : listener_reply_action::drop; } + /// What tcp_local_redirect reported for a segment from a local TCP listener. + enum class listener_segment_outcome : uint8_t + { + translated, ///< rewritten for the client + recently_reset, ///< belongs to a connection the client or the proxy just aborted with RST + unknown ///< belongs to no known connection + }; + + /// What a handler does with a segment from a local TCP listener. + enum class listener_segment_action : uint8_t + { + revert, ///< re-inject the translated segment to the client + drop_quietly, ///< drop it; an expected part of an abort, counted at debug level only + drop_reported ///< drop it and report it as an untranslatable listener reply + }; + + /** + * @brief Decides what to do with a segment from a local TCP listener. + * + * When a connection is aborted with RST while the local proxy is still sending, the segments + * the proxy emitted before its stack saw the RST arrive after the redirect has ended the + * connection. They are dropped like any untranslatable listener segment (they must never reach + * the wire), but they are an expected part of an abort, so they are not reported as faults. + */ + [[nodiscard]] constexpr listener_segment_action decide_tcp_listener_segment( + const listener_segment_outcome outcome) noexcept + { + switch (outcome) + { + case listener_segment_outcome::translated: + return listener_segment_action::revert; + case listener_segment_outcome::recently_reset: + return listener_segment_action::drop_quietly; + case listener_segment_outcome::unknown: + break; + } + return listener_segment_action::drop_reported; + } + /// What the IPv6 handler does with a packet that has no usable transport header. enum class ipv6_fragment_action : uint8_t { diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index ab1c716..10e6d5a 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -298,6 +298,12 @@ namespace proxy */ std::atomic_flag untranslated_listener_reply_logged_{}; + /** + * @brief Count of listener segments dropped because their connection had just been + * aborted with RST. Expected during aborts, so reported at debug level only. + */ + std::atomic listener_segments_after_reset_{ 0 }; + /** * @brief One-shot flags so that each (family, transport, reason) block cause is * described once in the log instead of once per packet. @@ -978,6 +984,7 @@ namespace proxy dns_blocked_packets_.store(0, std::memory_order_relaxed); untranslated_listener_replies_.store(0, std::memory_order_relaxed); untranslated_listener_reply_logged_.clear(std::memory_order_relaxed); + listener_segments_after_reset_.store(0, std::memory_order_relaxed); for (auto& flag : dns_block_reason_logged_) flag.clear(std::memory_order_relaxed); if (!install_dns_filters()) @@ -2269,6 +2276,47 @@ namespace proxy } } + /// Maps tcp_local_redirect's result for a listener segment to the policy's outcome. + template + static listener_segment_outcome to_listener_segment_outcome(const Result result) noexcept + { + switch (result) + { + case Result::translated: + return listener_segment_outcome::translated; + case Result::recently_reset: + return listener_segment_outcome::recently_reset; + case Result::unknown: + break; + } + return listener_segment_outcome::unknown; + } + + /** + * @brief Applies decide_tcp_listener_segment() to a segment from a local TCP listener: + * re-inject it when translated, otherwise drop it, quietly when it belongs to a + * connection that was just aborted with RST. + */ + template + packet_filter::packet_action handle_tcp_listener_segment(netlib::ndisapi::intermediate_buffer& buffer, + const Result result) + { + switch (decide_tcp_listener_segment(to_listener_segment_outcome(result))) + { + case listener_segment_action::revert: + log_packet_to_pcap(buffer); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; + case listener_segment_action::drop_quietly: + listener_segments_after_reset_.fetch_add(1, std::memory_order_relaxed); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + case listener_segment_action::drop_reported: + break; + } + + note_untranslated_listener_reply(); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + } + /// True when DNS routing is in Proxy mode. bool dns_proxy_mode() { @@ -2822,15 +2870,7 @@ namespace proxy // translated (for example after its connection entry expired), instead of letting // it reach the real server. tcp_local_redirect tracks the whole close, so ordinary // FIN/ACK exchanges are translated. - if (decide_listener_reply(true, tcp_redirect_->process_server_to_client_packet(buffer)) == - listener_reply_action::revert) - { - log_packet_to_pcap(buffer); - return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; - } - - note_untranslated_listener_reply(); - return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + return handle_tcp_listener_segment(buffer, tcp_redirect_->process_server_to_client_segment(buffer)); } // Conventional DNS over TCP follows the global DNS policy. In Direct mode TCP/53 is @@ -3175,15 +3215,7 @@ namespace proxy // translated (for example after its connection entry expired), instead of letting // it reach the real server. tcp_local_redirect tracks the whole close, so ordinary // FIN/ACK exchanges are translated. - if (decide_listener_reply(true, tcp_redirect_v6_->process_server_to_client_packet(buffer)) == - listener_reply_action::revert) - { - log_packet_to_pcap(buffer); - return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; - } - - note_untranslated_listener_reply(); - return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + return handle_tcp_listener_segment(buffer, tcp_redirect_v6_->process_server_to_client_segment(buffer)); } // Conventional DNS over TCP follows the global DNS policy (mirrors the IPv4 path). @@ -3483,7 +3515,8 @@ namespace proxy if (const auto now = std::chrono::steady_clock::now(); now - last_dns_block_log >= drop_log_throttle_interval_ && (dns_blocked_packets_.load(std::memory_order_relaxed) != 0 || - untranslated_listener_replies_.load(std::memory_order_relaxed) != 0)) + untranslated_listener_replies_.load(std::memory_order_relaxed) != 0 || + listener_segments_after_reset_.load(std::memory_order_relaxed) != 0)) { last_dns_block_log = now; if (const auto blocked = dns_blocked_packets_.exchange(0, std::memory_order_relaxed); blocked != 0) @@ -3500,6 +3533,13 @@ namespace proxy "(no tracked connection, fragmented, or malformed); they were not sent to the network.", untranslated); } + if (const auto after_reset = listener_segments_after_reset_.exchange(0, std::memory_order_relaxed); + after_reset != 0) + { + NETLIB_LOG(log_level::debug, + "Dropped {} segment(s) from local TCP listeners for connections that had just been reset " + "(expected during aborts).", after_reset); + } } // Periodically surface the counts of packets dropped due to a diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index 86175ba..6eb079c 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -727,3 +727,106 @@ TEST(DnsTcpCloseTracking, SynWithRstEndsTrackingInsteadOfStartingIt) EXPECT_FALSE(state_of(redirect).has_value()); } } + +// ------------------------------------------------------------------ segments after a reset +// +// After an RST, the proxy's segments still in flight are not translated (the connection is over) +// but are recognized as part of the abort, so the router drops them without reporting a fault. + +namespace +{ + using segment_result = tcp_redirect4::server_segment_result; + + segment_result listener_segment_result(tcp_redirect4& redirect, const uint8_t flags) + { + auto segment = listener_segment(flags); + const auto before = std::vector(segment.buffer.m_IBuffer, segment.buffer.m_IBuffer + segment.buffer.m_Length); + const auto result = redirect.process_server_to_client_segment(segment.buffer); + if (result != segment_result::translated) + { + // Untranslated segments are left untouched. + EXPECT_EQ(std::vector(segment.buffer.m_IBuffer, segment.buffer.m_IBuffer + segment.buffer.m_Length), before); + } + return result; + } + + bool recently_reset(tcp_redirect4& redirect) + { + return redirect.is_recently_reset(v4{ std::string{ tcp_server } }, htons(client_port)); + } +} + +TEST(DnsTcpResetTracking, ListenerSegmentAfterClientRstIsRecognizedAsPartOfTheAbort) +{ + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + ASSERT_TRUE(send_client(redirect, TH_RST | TH_ACK)); + + EXPECT_TRUE(recently_reset(redirect)); + EXPECT_FALSE(state_of(redirect).has_value()); + EXPECT_EQ(listener_segment_result(redirect, TH_PSH | TH_ACK), segment_result::recently_reset); + EXPECT_EQ(listener_segment_result(redirect, TH_FIN | TH_ACK), segment_result::recently_reset); + // The bool entry point still reports "not translated". + auto segment = listener_segment(TH_ACK); + EXPECT_FALSE(redirect.process_server_to_client_packet(segment.buffer)); +} + +TEST(DnsTcpResetTracking, ListenerSegmentAfterListenerRstIsRecognizedAsPartOfTheAbort) +{ + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + // The proxy's RST itself is still translated to the client. + ASSERT_EQ(send_listener(redirect, TH_RST | TH_ACK), uint16_t{ 53 }); + + EXPECT_TRUE(recently_reset(redirect)); + EXPECT_EQ(listener_segment_result(redirect, TH_ACK), segment_result::recently_reset); + // A further RST from the proxy is not translated again. + EXPECT_EQ(listener_segment_result(redirect, TH_RST), segment_result::recently_reset); +} + +TEST(DnsTcpResetTracking, ClientSegmentsOnAResetKeyBehaveAsUntracked) +{ + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + ASSERT_TRUE(send_client(redirect, TH_RST | TH_ACK)); + + EXPECT_FALSE(send_client(redirect, TH_ACK)); + EXPECT_FALSE(send_client(redirect, TH_FIN | TH_ACK)); + EXPECT_FALSE(send_client(redirect, TH_RST)); + EXPECT_FALSE(send_client(redirect, TH_SYN | TH_RST)); + // None of these revived or refreshed the connection. + EXPECT_FALSE(state_of(redirect).has_value()); + EXPECT_TRUE(recently_reset(redirect)); +} + +TEST(DnsTcpResetTracking, ResetRecordExpiresAfterTheLinger) +{ + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + ASSERT_TRUE(send_client(redirect, TH_RST | TH_ACK)); + + const auto now = std::chrono::steady_clock::now(); + redirect.remove_expired(now); + EXPECT_TRUE(recently_reset(redirect)); + redirect.remove_expired(now + tcp_redirect4::closed_linger + std::chrono::seconds{ 1 }); + EXPECT_FALSE(recently_reset(redirect)); + EXPECT_EQ(listener_segment_result(redirect, TH_ACK), segment_result::unknown); +} + +TEST(DnsTcpResetTracking, NewSynOnAResetKeyStartsANewConnection) +{ + tcp_redirect4 redirect{ log_level::error }; + establish(redirect); + ASSERT_TRUE(send_client(redirect, TH_RST | TH_ACK)); + + ASSERT_TRUE(send_client(redirect, TH_SYN, 853)); + EXPECT_FALSE(recently_reset(redirect)); + ASSERT_TRUE(state_of(redirect).has_value()); + EXPECT_EQ(send_listener(redirect, TH_SYN | TH_ACK), uint16_t{ 853 }); +} + +TEST(DnsTcpResetTracking, UnknownConnectionsStillReportUnknown) +{ + tcp_redirect4 redirect{ log_level::error }; + EXPECT_EQ(listener_segment_result(redirect, TH_ACK), segment_result::unknown); +} diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index b4bd155..75c3e6b 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -794,3 +794,16 @@ TEST(ListenerFragmentPolicy, UdpListenerRepliesAreDroppedOnBothPaths) EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::drop, true), listener_reply_action::drop); EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::drop, false), listener_reply_action::drop); } + +// Listener segments: translated ones are re-injected; those of a connection that was just reset +// are dropped quietly (an expected part of an abort); others are dropped and reported. +TEST(ListenerSegmentPolicy, OutcomesMapToRevertQuietDropAndReportedDrop) +{ + using proxy::decide_tcp_listener_segment; + using proxy::listener_segment_action; + using proxy::listener_segment_outcome; + + EXPECT_EQ(decide_tcp_listener_segment(listener_segment_outcome::translated), listener_segment_action::revert); + EXPECT_EQ(decide_tcp_listener_segment(listener_segment_outcome::recently_reset), listener_segment_action::drop_quietly); + EXPECT_EQ(decide_tcp_listener_segment(listener_segment_outcome::unknown), listener_segment_action::drop_reported); +} From e05e77b13e81682c52a1398e121f84b56eb93046 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 16:07:16 +0000 Subject: [PATCH 21/62] fix: exempt UDP to a SOCKS5 server only once a relay on port 53 exists The recursion guard exempted a port-53 packet addressed to a configured SOCKS5 server when the cached connection table said its sender was ProxiFyre. The table is refreshed only when a packet is deferred, so a stale row for a closed ProxiFyre UDP socket could send another process's UDP query to a host that is both SOCKS5 server and resolver directly. ProxiFyre has two UDP sockets per UDP proxy server: the local listener, which only sends to local clients, and the relay socket, which is connected to the endpoint associate_to_socks5_proxy() returns, {socks_server_address, BND.PORT}, and sends nothing else. So ProxiFyre sends UDP to a SOCKS5 server's address on port 53 only if a relay endpoint has port 53. - socks5_local_udp_proxy_server reports each relay endpoint through a new optional callback, before the relay socket is created; the router passes it like its other callbacks (both address families) and sets an atomic flag, never cleared, when a relay uses port 53 (logged once). - is_upstream_exemption_candidate(): for UDP, a destination matching a SOCKS5 server is a candidate for exemption only when the flag is set; otherwise the packet follows the DNS policy with no sender lookup and no deferral. TCP is unchanged (it already requires a server configured on port 53). - The comment at sender_is_proxifyre() and "Recursion and ProxiFyre's own traffic" now limit the residual race to a SOCKS5 server on TCP port 53 or with a UDP relay on port 53. Policy tests cover the flag in both states for UDP and TCP with a known, unknown and ProxiFyre sender, and fail when the flag is ignored. --- docs/configuration.md | 9 +++- netlib/src/proxy/dns_routing_policy.h | 22 +++++++++ .../src/proxy/socks5_local_udp_proxy_server.h | 24 +++++++++- netlib/src/proxy/socks_local_router.h | 48 +++++++++++++++---- netlib/test/proxy/dns_routing_policy_test.cpp | 46 ++++++++++++++++++ 5 files changed, 138 insertions(+), 11 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 0a4410b..427d681 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -199,9 +199,14 @@ Proxy with an IPv4 override for a configuration that uses a router-provided reso ### Recursion and ProxiFyre's own traffic -SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. ProxiFyre's own traffic to a configured SOCKS5 server is never redirected into the DNS proxy, even if the server listens on port 53: a port-53 packet addressed to a SOCKS5 server (TCP: its address and port; UDP: its address) is exempt only when its sending process is ProxiFyre itself. Queries from any other process to a host that is both the SOCKS5 server and a resolver follow the DNS policy like any other query, including `serverOverride`. If the sender of such a packet cannot be determined, even after the connection table is refreshed, the packet is dropped rather than passed or redirected. Senders that typically cannot be determined include traffic that Windows forwards on behalf of virtual machines or containers (for example through Hyper-V, WSL, or Internet Connection Sharing), which has no owning local process, and sockets owned by the kernel or by drivers rather than by a user-mode process. Queries from such sources to a host that is also a SOCKS5 server are therefore blocked in `Proxy` mode. +SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. ProxiFyre's own traffic to a configured SOCKS5 server is never redirected into the DNS proxy, even if it is addressed to port 53, while queries from any other process to a host that is both a SOCKS5 server and a resolver follow the DNS policy like any other query, including `serverOverride`: -The sender is taken from ProxiFyre's cached copy of the Windows connection tables, which is refreshed whenever a packet has to wait for its owner to be resolved, not on a timer. This leaves a narrow residual race: if ProxiFyre closes one of its own UDP sockets and another process reuses the same local port before the cache is next refreshed, that process's UDP query to a host that is both a SOCKS5 server and a resolver can be treated as ProxiFyre's own and sent directly to that host. The reverse, ProxiFyre's own packet attributed to a stale foreign owner, would send it into the DNS proxy, where it fails rather than leaving the machine directly. Both require the stale entry, an immediate port reuse, and DNS addressed to the SOCKS5 server's own IP address. To avoid the race entirely, do not use the SOCKS5 server's address as a resolver while `Proxy` mode is enabled; a `serverOverride` does not help here, because the guard runs before the override is applied. +- **TCP:** ProxiFyre connects to a SOCKS5 server only on its configured port. A TCP packet to port 53 of a SOCKS5 server is therefore a candidate for ProxiFyre's own traffic only when that server is configured on port 53, and it is exempt only when its sending process is ProxiFyre itself. +- **UDP:** ProxiFyre's only UDP traffic to a SOCKS5 server's address goes to the UDP relay endpoint the server returns for `UDP ASSOCIATE`. Unless a server has returned a relay on port 53, no UDP packet to port 53 of a SOCKS5 server can be ProxiFyre's own, so all of them follow the DNS policy with no sender check. Once a relay on port 53 has been seen (logged once at Info), such a packet is exempt only when its sending process is ProxiFyre itself. + +When a sender check is needed and the sender cannot be determined, even after the connection table is refreshed, the packet is dropped rather than passed or redirected. Senders that typically cannot be determined include traffic that Windows forwards on behalf of virtual machines or containers (for example through Hyper-V, WSL, or Internet Connection Sharing), which has no owning local process, and sockets owned by the kernel or by drivers rather than by a user-mode process. + +The sender is taken from ProxiFyre's cached copy of the Windows connection tables, which is refreshed whenever a packet has to wait for its owner to be resolved, not on a timer. When a sender check is needed, this leaves a narrow residual race: if ProxiFyre closes one of its own sockets and another process reuses the same local port before the cache is next refreshed, that process's query can be treated as ProxiFyre's own and sent directly to the SOCKS5 server's address. The reverse, ProxiFyre's own packet attributed to a stale foreign owner, would send it into the DNS proxy, where it fails rather than leaving the machine directly. The race therefore applies only when a SOCKS5 server is configured on TCP port 53 or returns a UDP relay on port 53, and DNS is addressed to that server's own IP address. To avoid it, do not run a SOCKS5 server or its UDP relay on port 53 while using that server's address as a resolver in `Proxy` mode. ### Limitations diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 490c205..ce7cb77 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -123,6 +123,28 @@ namespace proxy return sender_lookup_final ? dns_upstream_guard::drop : dns_upstream_guard::defer; } + /** + * @brief Whether a port-53 packet addressed to a configured SOCKS5 server can be ProxiFyre's + * own traffic, and so needs the sender check of decide_dns_upstream_guard(). + * + * ProxiFyre's TCP traffic to a SOCKS5 server goes to its configured port, so for TCP the + * destination match (address and port 53) already implies a server configured on port 53. + * ProxiFyre's only UDP traffic to a SOCKS5 server's address goes to the relay endpoint + * returned by UDP ASSOCIATE, so for UDP the packet can be ProxiFyre's own only if a server + * has returned a relay on port 53. Otherwise it cannot be, and it follows the DNS policy + * with no sender lookup and no deferral, which also removes any dependence on the cached + * connection table. + * + * @param udp_relay_on_dns_port A SOCKS5 server has returned a UDP relay endpoint on port 53. + * @param destination_matches_upstream The destination is a configured SOCKS5 server (UDP: its + * address; TCP: its address and port). + */ + [[nodiscard]] constexpr bool is_upstream_exemption_candidate(const dns_transport transport, + const bool udp_relay_on_dns_port, const bool destination_matches_upstream) noexcept + { + return destination_matches_upstream && (transport == dns_transport::tcp || udp_relay_on_dns_port); + } + /** * @brief Decides how a captured outbound packet addressed to @p destination_port is routed. * diff --git a/netlib/src/proxy/socks5_local_udp_proxy_server.h b/netlib/src/proxy/socks5_local_udp_proxy_server.h index 0bd1892..7e87987 100644 --- a/netlib/src/proxy/socks5_local_udp_proxy_server.h +++ b/netlib/src/proxy/socks5_local_udp_proxy_server.h @@ -84,6 +84,16 @@ namespace proxy */ using commit_remote_peer_t = void(address_type_t, uint16_t); + /** + * @brief Callback invoked with the UDP relay endpoint returned by a successful SOCKS5 + * UDP ASSOCIATE, before the relay socket is created or sends anything. + * + * The relay socket is connected to this endpoint and sends nothing else, so it is the + * only destination ProxiFyre's UDP traffic to a SOCKS5 server can have. The router uses + * it to know whether any of its own UDP traffic can be addressed to port 53. + */ + using relay_endpoint_observed_t = void(const net::ip_endpoint&); + private: /** * @brief Maximum number of simultaneous proxy connections. @@ -211,6 +221,11 @@ namespace proxy */ std::function commit_remote_peer_; + /** + * @brief Optional callback that observes each UDP relay endpoint before it is used. + */ + std::function relay_endpoint_observed_; + /** * @brief Completion key associated with the server socket in the I/O completion port. */ @@ -520,11 +535,13 @@ namespace proxy const std::function& query_remote_peer_fn, const log_level log_level = log_level::error, std::shared_ptr log_stream = nullptr, - const std::function& commit_remote_peer_fn = {}) + const std::function& commit_remote_peer_fn = {}, + const std::function& relay_endpoint_observed_fn = {}) : logger(log_level, std::move(log_stream)), completion_port_(completion_port), query_remote_peer_(query_remote_peer_fn), commit_remote_peer_(commit_remote_peer_fn), + relay_endpoint_observed_(relay_endpoint_observed_fn), proxy_port_(proxy_port) { if (!create_server_socket()) @@ -1809,6 +1826,11 @@ namespace proxy udp_endpoint->ip, udp_endpoint->port); + // Report the relay endpoint before the relay socket exists, so the router knows about + // it before any datagram can be sent to it. + if (relay_endpoint_observed_) + relay_endpoint_observed_(*udp_endpoint); + auto remote_socket = WSASocket(address_type_t::af_type, SOCK_DGRAM, IPPROTO_UDP, nullptr, 0, WSA_FLAG_OVERLAPPED); diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 10e6d5a..40b1e13 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -272,6 +272,15 @@ namespace proxy */ std::atomic_bool dns_reply_restore_active_{ false }; + /** + * @brief Set once any SOCKS5 server has returned a UDP relay endpoint on port 53, before + * the relay socket sends anything. Only then can ProxiFyre's own UDP traffic to a + * SOCKS5 server's address be addressed to port 53, so only then does the recursion + * guard need a sender check for UDP (is_upstream_exemption_candidate()). Never + * cleared: relays already in use keep their port for the router's lifetime. + */ + std::atomic_bool udp_relay_on_dns_port_{ false }; + /** * @brief Original server of each UDP DNS query rewritten to the server override, so the * answer can be restored to the server the resolver actually queried. @@ -1331,6 +1340,10 @@ namespace proxy auto& mapper = udp_mapper_for(); std::scoped_lock lock(udp_mapper_lock_for()); mapper.erase(port); + }, + [this](const net::ip_endpoint& relay) + { + note_udp_relay_endpoint(relay.port); }) : nullptr; @@ -2317,6 +2330,18 @@ namespace proxy return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; } + /// Records a UDP relay endpoint returned by a SOCKS5 server (see udp_relay_on_dns_port_). + void note_udp_relay_endpoint(const uint16_t relay_port) + { + if (relay_port == dns_port && !udp_relay_on_dns_port_.exchange(true, std::memory_order_seq_cst)) + { + NETLIB_LOG(log_level::info, + "A SOCKS5 server returned a UDP relay on port 53. UDP DNS addressed to a SOCKS5 server's own " + "address is now exempted from the DNS policy only when it comes from ProxiFyre itself, as " + "determined from the cached connection table."); + } + } + /// True when DNS routing is in Proxy mode. bool dns_proxy_mode() { @@ -2329,12 +2354,14 @@ namespace proxy * (no owner, or the shared unresolved default owner). * * The owner comes from process_lookup's cached tables, which are replaced only by - * actualize() when the resolver thread processes deferred packets. A row for one of - * ProxiFyre's own sockets that has since closed can therefore still be found if another - * process reuses that local port before the next refresh (documented in - * docs/configuration.md, "Recursion and ProxiFyre's own traffic"). Closing the race exactly - * would mean tracking ProxiFyre's own upstream sockets through every close path of the - * proxy servers and sockets, which is not done here. + * actualize() when the resolver thread processes deferred packets, so a row for one of + * ProxiFyre's own sockets that has since closed can still be found if another process + * reuses that local port before the next refresh. The check is therefore consulted only + * when the packet can actually be ProxiFyre's own (is_upstream_exemption_candidate()): + * for UDP, only after a SOCKS5 server has returned a relay on port 53, because the relay + * endpoint is the only UDP destination ProxiFyre sends to on a SOCKS5 server's address. + * The residual race is limited to that case (docs/configuration.md, "Recursion and + * ProxiFyre's own traffic"). */ static std::optional sender_is_proxifyre(const std::shared_ptr& owner) noexcept { @@ -2390,10 +2417,15 @@ namespace proxy destination_matches_upstream = is_upstream_destination_locked(destination, destination_port); } + // Only a packet that can be ProxiFyre's own needs the sender check; for UDP that + // requires a SOCKS5 server to have returned a relay on port 53. + const bool exemption_candidate = is_upstream_exemption_candidate(Transport, + udp_relay_on_dns_port_.load(std::memory_order_seq_cst), destination_matches_upstream); + // The DNS mode and proxy selection cannot change while the router runs // (set_dns_routing() refuses), so releasing lock_ before the process lookup is safe. - const auto guard = decide_dns_upstream_guard(destination_matches_upstream, - destination_matches_upstream ? sender_lookup(postponed) : std::optional{}, postponed); + const auto guard = decide_dns_upstream_guard(exemption_candidate, + exemption_candidate ? sender_lookup(postponed) : std::optional{}, postponed); const auto decision = decide_dns_route(dns_routing_mode::proxy, destination_port, guard, target); return { decision, decision.action == dns_route_action::proxy ? server_override : std::nullopt }; diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 75c3e6b..623e0a2 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -807,3 +807,49 @@ TEST(ListenerSegmentPolicy, OutcomesMapToRevertQuietDropAndReportedDrop) EXPECT_EQ(decide_tcp_listener_segment(listener_segment_outcome::recently_reset), listener_segment_action::drop_quietly); EXPECT_EQ(decide_tcp_listener_segment(listener_segment_outcome::unknown), listener_segment_action::drop_reported); } + +// Recursion guard and the UDP relay port: a UDP packet to a SOCKS5 server's address can be +// ProxiFyre's own only if a server has returned a relay on port 53. Until then no sender lookup or +// deferral happens for UDP, whatever the (possibly stale) table says. TCP is unchanged. +TEST(DnsRoutingPolicy, UpstreamExemptionCandidatesDependOnTheUdpRelayPort) +{ + using proxy::decide_dns_upstream_guard; + using proxy::is_upstream_exemption_candidate; + using guard = proxy::dns_upstream_guard; + + const std::optional senders[] = { std::optional{}, std::optional{ false }, std::optional{ true } }; + + // The guard as the router computes it: the sender is looked up only for candidates. + const auto route = [](const dns_transport transport, const bool relay_on_53, const bool matches, + const std::optional sender, const bool lookup_final) + { + const bool candidate = is_upstream_exemption_candidate(transport, relay_on_53, matches); + return decide_dns_upstream_guard(candidate, candidate ? sender : std::optional{}, lookup_final); + }; + + for (const bool lookup_final : { false, true }) + { + for (const auto& sender : senders) + { + // UDP, no relay on port 53: never exempt, never deferred or dropped by the guard. + EXPECT_EQ(route(dns_transport::udp, false, true, sender, lookup_final), guard::apply_policy); + EXPECT_EQ(route(dns_transport::udp, false, false, sender, lookup_final), guard::apply_policy); + + // Not addressed to a SOCKS5 server: the sender is irrelevant in every state. + EXPECT_EQ(route(dns_transport::udp, true, false, sender, lookup_final), guard::apply_policy); + EXPECT_EQ(route(dns_transport::tcp, false, false, sender, lookup_final), guard::apply_policy); + EXPECT_EQ(route(dns_transport::tcp, true, false, sender, lookup_final), guard::apply_policy); + } + + // UDP with a relay on port 53, and TCP whatever the flag: the sender decides. + for (const auto& [transport, relay_on_53] : { std::pair{ dns_transport::udp, true }, + std::pair{ dns_transport::tcp, false }, + std::pair{ dns_transport::tcp, true } }) + { + EXPECT_EQ(route(transport, relay_on_53, true, true, lookup_final), guard::exempt); + EXPECT_EQ(route(transport, relay_on_53, true, false, lookup_final), guard::apply_policy); + EXPECT_EQ(route(transport, relay_on_53, true, std::nullopt, lookup_final), + lookup_final ? guard::drop : guard::defer); + } + } +} From 79f8980c734eb578b9c9583e5053559a15465488 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 16:08:43 +0000 Subject: [PATCH 22/62] test: count every tracker iteration through one helper per container The tracker cost test bounds visits(), but each loop incremented the counter itself, so a scan added without the increment (for example in evict_oldest_locked) went unnoticed. Every iteration over the table now goes through for_each_entry_locked() and every examination of the queue through consume_front_locked(); both count each element they visit, and the existing expiry, eviction, compaction and sweep loops are rewritten on top of them. A loop copied from any of them is therefore counted: a linear search added through the helper in evict_oldest_locked fails the test at 8194 visits per insert. The test comment states the remaining limitation: it bounds counted work and cannot see a raw loop that bypasses the helpers. No time-based assertion is reintroduced. --- netlib/src/proxy/dns_routing_policy.h | 86 ++++++++++++++----- netlib/test/proxy/dns_routing_policy_test.cpp | 4 + 2 files changed, 67 insertions(+), 23 deletions(-) diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index ce7cb77..e936832 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -698,14 +699,10 @@ namespace proxy void sweep(const clock::time_point now = clock::now()) { std::scoped_lock lock(lock_); - for (auto it = entries_.begin(); it != entries_.end();) + for_each_entry_locked([this, now](const auto it) { - ++visits_; - if (now - it->second.created_at > ttl_) - it = entries_.erase(it); - else - ++it; - } + return now - it->second.created_at > ttl_ ? entries_.erase(it) : std::next(it); + }); expire_front_locked(now); } @@ -768,34 +765,77 @@ namespace proxy return it != entries_.end() && it->second.created_at == r.created_at; } - /// Pops expired records from the front, erasing the entries they still describe. - void expire_front_locked(const clock::time_point now) + // Every iteration over entries_ or order_ goes through one of the two helpers below, + // which count each element examined in visits_. Do not add raw loops over either + // container: visits() is how tests bound the work done on the packet thread. + + /** + * @brief Visits table entries, counting each. @p step receives an iterator to the current + * entry and returns the iterator to continue from (the erase() result or the next). + */ + template + void for_each_entry_locked(Step&& step) { - while (!order_.empty() && now - order_.front().created_at > ttl_) + for (auto it = entries_.begin(); it != entries_.end();) { ++visits_; - if (is_current_locked(order_.front())) - entries_.erase(order_.front().key); - order_.pop_front(); + it = step(it); } } - /// Erases the oldest live entry, skipping stale records. - void evict_oldest_locked() + /// What consume_front_locked() does after examining the front record. + enum class front_step : uint8_t + { + pop_and_continue, + pop_and_stop, + stop + }; + + /** + * @brief Examines records at the front of the queue, counting each, and pops them as + * @p step decides. + */ + template + void consume_front_locked(Step&& step) { while (!order_.empty()) { ++visits_; const auto front = order_.front(); + const front_step next = step(front); + if (next == front_step::stop) + return; order_.pop_front(); - if (is_current_locked(front)) - { - entries_.erase(front.key); + if (next == front_step::pop_and_stop) return; - } } } + /// Pops expired records from the front, erasing the entries they still describe. + void expire_front_locked(const clock::time_point now) + { + consume_front_locked([this, now](const record& front) + { + if (!(now - front.created_at > ttl_)) + return front_step::stop; + if (is_current_locked(front)) + entries_.erase(front.key); + return front_step::pop_and_continue; + }); + } + + /// Erases the oldest live entry, skipping stale records. + void evict_oldest_locked() + { + consume_front_locked([this](const record& front) + { + if (!is_current_locked(front)) + return front_step::pop_and_continue; + entries_.erase(front.key); + return front_step::pop_and_stop; + }); + } + /// Keeps the queue bounded when keys are refreshed repeatedly: rebuilds it from the /// live entries, oldest first, once stale records outnumber them. void compact_if_needed_locked() @@ -805,11 +845,11 @@ namespace proxy std::vector live; live.reserve(entries_.size()); - for (const auto& [key, value] : entries_) + for_each_entry_locked([&live](const auto it) { - ++visits_; - live.push_back({ key, value.created_at }); - } + live.push_back({ it->first, it->second.created_at }); + return std::next(it); + }); std::sort(live.begin(), live.end(), [](const record& left, const record& right) { return left.created_at < right.created_at; }); order_.assign(live.begin(), live.end()); diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 623e0a2..7e2a23e 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -690,6 +690,10 @@ TEST(DnsUdpOriginTracker, InsertingIntoAFullTableOfLiveEntriesDoesBoundedWorkPer // Every further insert must evict one live entry. Count the entries and records examined: // insertion-order eviction examines a constant amortized number per insert, while a sweep or // a search for the oldest entry examines the whole table (8192) on every insert. + // + // Limitation: visits() counts work done through the tracker's two iteration helpers, which + // every loop over its table and queue uses. The test bounds that counted work; it cannot see a + // raw loop added later that bypasses the helpers. const auto before = origins.visits(); for (uint32_t i = capacity; i < capacity + inserts; ++i) remember(i); From ca744922fdfce166a52481eeddb5edf034749dc7 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 16:10:49 +0000 Subject: [PATCH 23/62] fix: read the DNS mode only when a fragment needs it; drop IPv4 TCP listener first fragments - Every parsed IPv6 first fragment called dns_proxy_mode(), which takes lock_. ipv6_fragment_needs_dns_mode() now limits that to a first fragment that is not from a listener and is addressed to port 53; decide_ipv6_fragment() behaves exactly as before. - tcp_local_redirect does not check fragmentation, so the first fragment of an IPv4 TCP listener segment was translated on its own, leaving the later fragments untranslated. The IPv4 TCP handler now drops and reports it (ipv4_listener_packet_translatable()), as the UDP path already did because the UDP redirect rejects fragments. Tests cover both predicates and fail when either is reverted. --- netlib/src/proxy/dns_routing_policy.h | 25 ++++++++++++ netlib/src/proxy/socks_local_router.h | 10 ++++- netlib/test/proxy/dns_routing_policy_test.cpp | 40 +++++++++++++++++++ 3 files changed, 74 insertions(+), 1 deletion(-) diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index e936832..923f9bc 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -323,6 +323,20 @@ namespace proxy return fragment != ipv4_fragment::later; } + /** + * @brief Whether a packet sourced from a local listener can be translated back to its client. + * + * A first fragment carries the listener's port but only part of the datagram or segment; + * rewriting it alone would deliver a partial packet whose later fragments are not + * translated. It is dropped and reported like any other untranslatable listener packet. + * (The UDP redirect already rejects fragments; the TCP redirect does not check, so the TCP + * handler applies this first.) + */ + [[nodiscard]] constexpr bool ipv4_listener_packet_translatable(const ipv4_fragment fragment) noexcept + { + return fragment == ipv4_fragment::none; + } + /** * @brief Applies fragmentation to a DNS routing decision: a datagram that would be redirected * but is fragmented cannot be, so it is blocked instead of being passed. @@ -493,6 +507,17 @@ namespace proxy * @param source_is_listener The first fragment's source port is a local IPv6 proxy listener * port of its protocol. */ + /** + * @brief Whether decide_ipv6_fragment() needs the DNS mode for @p first, so the caller reads + * the mode (which takes the router's lock) only for a first fragment that is not a + * listener reply and is addressed to port 53. + */ + [[nodiscard]] constexpr bool ipv6_fragment_needs_dns_mode(const std::optional& first, + const bool source_is_listener) noexcept + { + return first.has_value() && !source_is_listener && first->destination_port == dns_port; + } + [[nodiscard]] constexpr ipv6_fragment_action decide_ipv6_fragment(const std::optional& first, const bool source_is_listener, const bool dns_proxy_mode) noexcept { diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 40b1e13..ac264c9 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -2902,6 +2902,13 @@ namespace proxy // translated (for example after its connection entry expired), instead of letting // it reach the real server. tcp_local_redirect tracks the whole close, so ordinary // FIN/ACK exchanges are translated. + // A first fragment cannot be translated on its own (the TCP redirect does not check). + if (!ipv4_listener_packet_translatable(fragment)) + { + note_untranslated_listener_reply(); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + } + return handle_tcp_listener_segment(buffer, tcp_redirect_->process_server_to_client_segment(buffer)); } @@ -3030,7 +3037,8 @@ namespace proxy (first->protocol == IPPROTO_UDP ? is_udp_proxy_port_v6(first->source_port) : is_tcp_proxy_port_v6(first->source_port)); - switch (decide_ipv6_fragment(first, source_is_listener, first && dns_proxy_mode())) + const bool proxy_mode = ipv6_fragment_needs_dns_mode(first, source_is_listener) && dns_proxy_mode(); + switch (decide_ipv6_fragment(first, source_is_listener, proxy_mode)) { case ipv6_fragment_action::drop_listener_reply: note_untranslated_listener_reply(); diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 7e2a23e..301c9c3 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -857,3 +857,43 @@ TEST(DnsRoutingPolicy, UpstreamExemptionCandidatesDependOnTheUdpRelayPort) } } } + +// The DNS mode (which takes the router's lock) is needed only for a non-listener IPv6 first +// fragment addressed to port 53; the fragment decision itself does not change. +TEST(ListenerFragmentPolicy, DnsModeIsReadOnlyForNonListenerFirstFragmentsToPort53) +{ + using proxy::decide_ipv6_fragment; + using proxy::ipv6_fragment_needs_dns_mode; + + const auto dns_query = parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(50001, 53) }))); + const auto listener_reply = parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(41004, 53) }))); + const auto unrelated = parse(ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(50001, 443) }))); + + EXPECT_TRUE(ipv6_fragment_needs_dns_mode(dns_query, false)); + EXPECT_FALSE(ipv6_fragment_needs_dns_mode(listener_reply, true)); + EXPECT_FALSE(ipv6_fragment_needs_dns_mode(unrelated, false)); + EXPECT_FALSE(ipv6_fragment_needs_dns_mode(std::nullopt, false)); + + // Whenever the mode is not read, the decision is the same in both modes. + for (const auto& [first, listener] : { std::pair{ listener_reply, true }, std::pair{ unrelated, false }, + std::pair{ std::optional{}, false } }) + { + if (!ipv6_fragment_needs_dns_mode(first, listener)) + { + EXPECT_EQ(decide_ipv6_fragment(first, listener, false), decide_ipv6_fragment(first, listener, true)); + } + } +} + +// An IPv4 listener packet is translated only when it is not fragmented: a first fragment carries +// only part of the reply and is dropped and reported (the TCP redirect does not check fragments). +TEST(ListenerFragmentPolicy, Ipv4ListenerFirstFragmentsAreNotTranslated) +{ + using proxy::classify_ipv4_fragment; + using proxy::ipv4_listener_packet_translatable; + + EXPECT_TRUE(ipv4_listener_packet_translatable(classify_ipv4_fragment(0x0000))); + EXPECT_TRUE(ipv4_listener_packet_translatable(classify_ipv4_fragment(0x4000))); + EXPECT_FALSE(ipv4_listener_packet_translatable(classify_ipv4_fragment(0x2000))); + EXPECT_FALSE(ipv4_listener_packet_translatable(classify_ipv4_fragment(0x2001))); +} From 7c820840f6d3d98022af00953a7bb6e9789791ed Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 17:41:18 +0000 Subject: [PATCH 24/62] test: catch a reset record being refreshed by later segments A listener segment that pushed the reset record's time forward passed every reset-tracking test. tcp_local_redirect now exposes the reset record's expiry for tests (reset_record_expiry(), like is_recently_reset()), and ResetRecordExpiresAfterTheLinger asserts that listener and client segments on a reset key leave it unchanged. Making either a listener or a client segment refresh the record, even to the current time, now fails the test. No wall-clock assertion is added. --- netlib/src/ndisapi/tcp_local_redirect.h | 16 ++++++++++++++++ .../test/portable/dns_packet_redirect_test.cpp | 10 ++++++++++ 2 files changed, 26 insertions(+) diff --git a/netlib/src/ndisapi/tcp_local_redirect.h b/netlib/src/ndisapi/tcp_local_redirect.h index cc79589..a6bfde3 100644 --- a/netlib/src/ndisapi/tcp_local_redirect.h +++ b/netlib/src/ndisapi/tcp_local_redirect.h @@ -256,6 +256,22 @@ namespace ndisapi return it != redirected_connections_.cend() && it->second.reset; } + /** + * @brief When the reset record for client endpoint (@p original_destination, + * @p client_port) expires, or std::nullopt when there is none. A reset record is + * never refreshed, so this does not change until the record is removed. For + * diagnostics and tests. + */ + [[nodiscard]] std::optional reset_record_expiry(const T& original_destination, + const u_short client_port) + { + std::lock_guard lock(lock_); + const auto it = redirected_connections_.find(net::ip_endpoint{ original_destination, client_port }); + if (it == redirected_connections_.cend() || !it->second.reset) + return std::nullopt; + return it->second.expires_at(); + } + private: /** * @brief Updates the tracking state for a client-to-server segment. The caller holds lock_. diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index 6eb079c..c0d823a 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -805,6 +805,16 @@ TEST(DnsTcpResetTracking, ResetRecordExpiresAfterTheLinger) establish(redirect); ASSERT_TRUE(send_client(redirect, TH_RST | TH_ACK)); + // Nothing on a reset key refreshes the record: neither the proxy's in-flight segments nor + // the client's later segments move its expiry, so it ends closed_linger after the RST. + const auto expiry = redirect.reset_record_expiry(v4{ std::string{ tcp_server } }, htons(client_port)); + ASSERT_TRUE(expiry.has_value()); + EXPECT_EQ(listener_segment_result(redirect, TH_PSH | TH_ACK), segment_result::recently_reset); + EXPECT_EQ(listener_segment_result(redirect, TH_RST), segment_result::recently_reset); + EXPECT_FALSE(send_client(redirect, TH_ACK)); + EXPECT_FALSE(send_client(redirect, TH_RST)); + EXPECT_EQ(redirect.reset_record_expiry(v4{ std::string{ tcp_server } }, htons(client_port)), expiry); + const auto now = std::chrono::steady_clock::now(); redirect.remove_expired(now); EXPECT_TRUE(recently_reset(redirect)); From e175dbea25ba222d7534a0cce32b7a86c2a16e2a Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 17:43:22 +0000 Subject: [PATCH 25/62] docs: state the UDP-sender claim precisely; fix a misplaced doc comment - The docs and comments said ProxiFyre's only UDP traffic to a SOCKS5 server's address goes to the UDP ASSOCIATE relay. The local UDP listener's replies can also be addressed to a SOCKS5 host; they are handled as listener replies before any DNS decision and never passed. The claim now says the relay is the only such traffic that can reach the recursion guard (docs/configuration.md, the relay-callback comment in socks5_local_udp_proxy_server.h, and the router and policy comments). - ipv6_fragment_needs_dns_mode() had been inserted between decide_ipv6_fragment()'s doc comment and its declaration; each comment now sits on its own function. --- docs/configuration.md | 2 +- netlib/src/proxy/dns_routing_policy.h | 30 ++++++++++--------- .../src/proxy/socks5_local_udp_proxy_server.h | 8 +++-- netlib/src/proxy/socks_local_router.h | 9 +++--- 4 files changed, 27 insertions(+), 22 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 427d681..3f23e8e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -202,7 +202,7 @@ Proxy with an IPv4 override for a configuration that uses a router-provided reso SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. ProxiFyre's own traffic to a configured SOCKS5 server is never redirected into the DNS proxy, even if it is addressed to port 53, while queries from any other process to a host that is both a SOCKS5 server and a resolver follow the DNS policy like any other query, including `serverOverride`: - **TCP:** ProxiFyre connects to a SOCKS5 server only on its configured port. A TCP packet to port 53 of a SOCKS5 server is therefore a candidate for ProxiFyre's own traffic only when that server is configured on port 53, and it is exempt only when its sending process is ProxiFyre itself. -- **UDP:** ProxiFyre's only UDP traffic to a SOCKS5 server's address goes to the UDP relay endpoint the server returns for `UDP ASSOCIATE`. Unless a server has returned a relay on port 53, no UDP packet to port 53 of a SOCKS5 server can be ProxiFyre's own, so all of them follow the DNS policy with no sender check. Once a relay on port 53 has been seen (logged once at Info), such a packet is exempt only when its sending process is ProxiFyre itself. +- **UDP:** the only ProxiFyre UDP traffic to a SOCKS5 server's address that can reach this check goes to the UDP relay endpoint the server returns for `UDP ASSOCIATE`. (Replies from ProxiFyre's local UDP listeners can also be addressed to a SOCKS5 server's host, but they are handled as listener replies before any DNS decision and are never passed.) Unless a server has returned a relay on port 53, no UDP packet to port 53 of a SOCKS5 server can be ProxiFyre's own, so all of them follow the DNS policy with no sender check. Once a relay on port 53 has been seen (logged once at Info), such a packet is exempt only when its sending process is ProxiFyre itself. When a sender check is needed and the sender cannot be determined, even after the connection table is refreshed, the packet is dropped rather than passed or redirected. Senders that typically cannot be determined include traffic that Windows forwards on behalf of virtual machines or containers (for example through Hyper-V, WSL, or Internet Connection Sharing), which has no owning local process, and sockets owned by the kernel or by drivers rather than by a user-mode process. diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 923f9bc..88416d5 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -130,9 +130,11 @@ namespace proxy * * ProxiFyre's TCP traffic to a SOCKS5 server goes to its configured port, so for TCP the * destination match (address and port 53) already implies a server configured on port 53. - * ProxiFyre's only UDP traffic to a SOCKS5 server's address goes to the relay endpoint - * returned by UDP ASSOCIATE, so for UDP the packet can be ProxiFyre's own only if a server - * has returned a relay on port 53. Otherwise it cannot be, and it follows the DNS policy + * The only ProxiFyre UDP traffic to a SOCKS5 server's address that can reach the recursion + * guard goes to the relay endpoint returned by UDP ASSOCIATE (the local listener's replies, + * which can also be addressed to a SOCKS5 host, are handled as listener replies before any + * DNS decision), so for UDP the packet can be ProxiFyre's own only if a server has returned + * a relay on port 53. Otherwise it cannot be, and it follows the DNS policy * with no sender lookup and no deferral, which also removes any dependence on the cached * connection table. * @@ -492,6 +494,17 @@ namespace proxy drop_dns ///< first fragment of a DNS datagram in Proxy mode: never send it direct }; + /** + * @brief Whether decide_ipv6_fragment() needs the DNS mode for @p first, so the caller reads + * the mode (which takes the router's lock) only for a first fragment that is not a + * listener reply and is addressed to port 53. + */ + [[nodiscard]] constexpr bool ipv6_fragment_needs_dns_mode(const std::optional& first, + const bool source_is_listener) noexcept + { + return first.has_value() && !source_is_listener && first->destination_port == dns_port; + } + /** * @brief Decides what to do with an IPv6 packet whose transport header cannot be used * (a fragment, or an unsupported extension chain). @@ -507,17 +520,6 @@ namespace proxy * @param source_is_listener The first fragment's source port is a local IPv6 proxy listener * port of its protocol. */ - /** - * @brief Whether decide_ipv6_fragment() needs the DNS mode for @p first, so the caller reads - * the mode (which takes the router's lock) only for a first fragment that is not a - * listener reply and is addressed to port 53. - */ - [[nodiscard]] constexpr bool ipv6_fragment_needs_dns_mode(const std::optional& first, - const bool source_is_listener) noexcept - { - return first.has_value() && !source_is_listener && first->destination_port == dns_port; - } - [[nodiscard]] constexpr ipv6_fragment_action decide_ipv6_fragment(const std::optional& first, const bool source_is_listener, const bool dns_proxy_mode) noexcept { diff --git a/netlib/src/proxy/socks5_local_udp_proxy_server.h b/netlib/src/proxy/socks5_local_udp_proxy_server.h index 7e87987..ec2155e 100644 --- a/netlib/src/proxy/socks5_local_udp_proxy_server.h +++ b/netlib/src/proxy/socks5_local_udp_proxy_server.h @@ -88,9 +88,11 @@ namespace proxy * @brief Callback invoked with the UDP relay endpoint returned by a successful SOCKS5 * UDP ASSOCIATE, before the relay socket is created or sends anything. * - * The relay socket is connected to this endpoint and sends nothing else, so it is the - * only destination ProxiFyre's UDP traffic to a SOCKS5 server can have. The router uses - * it to know whether any of its own UDP traffic can be addressed to port 53. + * The relay socket is connected to this endpoint and sends nothing else. Apart from the + * local listener's replies, which the router handles as listener replies before any DNS + * decision, it is the only ProxiFyre UDP traffic to a SOCKS5 server's address. The router + * uses it to know whether any of its own UDP traffic that can reach the DNS recursion + * guard can be addressed to port 53. */ using relay_endpoint_observed_t = void(const net::ip_endpoint&); diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index ac264c9..68e0c01 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -274,9 +274,9 @@ namespace proxy /** * @brief Set once any SOCKS5 server has returned a UDP relay endpoint on port 53, before - * the relay socket sends anything. Only then can ProxiFyre's own UDP traffic to a - * SOCKS5 server's address be addressed to port 53, so only then does the recursion - * guard need a sender check for UDP (is_upstream_exemption_candidate()). Never + * the relay socket sends anything. Only then can ProxiFyre's own UDP traffic that + * reaches the recursion guard be addressed to port 53 of a SOCKS5 server, so only + * then does the guard need a sender check for UDP (is_upstream_exemption_candidate()). Never * cleared: relays already in use keep their port for the router's lifetime. */ std::atomic_bool udp_relay_on_dns_port_{ false }; @@ -2359,7 +2359,8 @@ namespace proxy * reuses that local port before the next refresh. The check is therefore consulted only * when the packet can actually be ProxiFyre's own (is_upstream_exemption_candidate()): * for UDP, only after a SOCKS5 server has returned a relay on port 53, because the relay - * endpoint is the only UDP destination ProxiFyre sends to on a SOCKS5 server's address. + * endpoint is the only destination of ProxiFyre's UDP traffic to a SOCKS5 server's address + * that can reach the guard (listener replies are handled before any DNS decision). * The residual race is limited to that case (docs/configuration.md, "Recursion and * ProxiFyre's own traffic"). */ From d7e4abfccbb9c9db0b21b0085bb258bd9b772a96 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 18:58:52 +0000 Subject: [PATCH 26/62] fix: restore UDP DNS answers to the queried server with or without a server override A resolver discards an answer that does not come from the server it queried. Answers were restored to that server only when a server override was configured, so in Proxy mode without an override a SOCKS5 relay that reports another source (for example its own address) broke UDP DNS. Every redirected UDP query that carries a DNS header is now tracked, and an answer matching a tracked query is restored whatever source the relay reports. A datagram too short to carry a DNS header is still redirected untracked without an override, and still dropped with one. Without an override nothing is dropped for matching no query. Also drop the listener decision's unused "not a listener" outcome: every caller has already established that the source port is a listener port. --- netlib/src/proxy/dns_routing_policy.h | 83 +++++++++++++------ netlib/src/proxy/socks_local_router.h | 66 +++++++++------ .../portable/dns_packet_redirect_test.cpp | 56 ++++++++++++- netlib/test/proxy/dns_routing_policy_test.cpp | 36 +++++--- 4 files changed, 174 insertions(+), 67 deletions(-) diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 88416d5..804e2e2 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -425,9 +425,8 @@ namespace proxy /// ProxiFyre's local proxy listeners. enum class listener_reply_action : uint8_t { - not_listener, ///< not sourced from a local listener: continue with the normal routing - revert, ///< translated back to the original server/client: re-inject it to the stack - drop ///< not translatable: drop it + revert, ///< translated back to the original server/client: re-inject it to the stack + drop ///< not translatable: drop it }; /** @@ -438,12 +437,11 @@ namespace proxy * connection or endpoint, a fragmented or malformed datagram, a relay header of the wrong * address type), passing it would send the listener's bytes - for the DNS proxy, the SOCKS5 * header and the DNS answer - toward the real server in clear, so it is dropped. + * + * @param translated The redirect translated the packet back to its client. */ - [[nodiscard]] constexpr listener_reply_action decide_listener_reply( - const bool source_is_listener, const bool translated) noexcept + [[nodiscard]] constexpr listener_reply_action decide_listener_reply(const bool translated) noexcept { - if (!source_is_listener) - return listener_reply_action::not_listener; return translated ? listener_reply_action::revert : listener_reply_action::drop; } @@ -641,12 +639,13 @@ namespace proxy } /** - * @brief Remembers, for UDP DNS queries rewritten to a server override, which server the + * @brief Remembers, for UDP DNS queries redirected to the DNS proxy, which server the * application originally addressed. * - * When a server override is configured, the SOCKS5 relay answers from the override server - * while the requesting resolver only accepts an answer from the server it queried. Each - * rewritten query records (client source port, DNS message ID) -> original server endpoint; + * The requesting resolver only accepts an answer from the server it queried, but the SOCKS5 + * relay may report another source: always when a server override is configured (it answers + * from the override server), and for some relays even without one. Each redirected query + * records (client source port, DNS message ID) -> original server endpoint; * the response carrying the same client port and message ID is restored to that endpoint * before it is delivered. Entries expire after @p ttl and the table is bounded, so it cannot * grow without limit under a flood of queries. Entries are not consumed by a lookup so that @@ -935,13 +934,41 @@ namespace proxy /** * @brief Whether replies leaving the DNS proxy's UDP listener may need their source restored - * (classify_dns_override_reply()): only in Proxy mode with a usable proxy and a server - * override. Otherwise the reply path needs no DNS work at all. + * (classify_dns_override_reply()): in Proxy mode with a usable proxy, with or without + * a server override, because a relay can report a source other than the server the + * resolver queried either way. In Direct mode, or without a usable proxy, no DNS is + * redirected and the reply path needs no DNS work at all. + */ + [[nodiscard]] constexpr bool dns_reply_restore_needed(const dns_routing_mode mode, const bool proxy_selected) noexcept + { + return mode == dns_routing_mode::proxy && proxy_selected; + } + + /// What the UDP handler does about remembering the server a redirected query was addressed to. + enum class dns_query_tracking : uint8_t + { + track, ///< remember the queried server so the answer can be restored to it + untracked, ///< redirect without remembering: the answer keeps the source the relay reports + drop ///< cannot be redirected usefully: drop it + }; + + /** + * @brief Decides whether a UDP datagram about to be redirected to the DNS proxy is tracked. + * + * A datagram that carries a DNS header is tracked by (client port, message ID), so its answer + * can be presented as coming from the server the resolver queried whatever source the relay + * reports. A datagram too short to carry a DNS header cannot be tracked. Without a server + * override it is still redirected: its answer, if any, carries the relay-reported source, + * which for an RFC 1928 relay is the server that was queried. With a server override the + * relay reports the override, the answer could never be matched to the queried server, and + * the resolver would discard it, so the datagram is dropped instead. */ - [[nodiscard]] constexpr bool dns_reply_restore_needed(const dns_routing_mode mode, const bool proxy_selected, - const bool server_override_configured) noexcept + [[nodiscard]] constexpr dns_query_tracking decide_dns_query_tracking(const bool server_override_configured, + const bool has_message_id) noexcept { - return mode == dns_routing_mode::proxy && proxy_selected && server_override_configured; + if (has_message_id) + return dns_query_tracking::track; + return server_override_configured ? dns_query_tracking::drop : dns_query_tracking::untracked; } /// How a datagram leaving a local UDP proxy listener is presented to the client. @@ -965,26 +992,29 @@ namespace proxy { if (restore == dns_reply_restore::drop) return listener_reply_action::drop; - return decide_listener_reply(true, translated); + return decide_listener_reply(translated); } /** - * @brief Classifies a datagram relayed back by the DNS proxy while a server override is - * configured, and finds the server the resolver originally queried. + * @brief Classifies a datagram relayed back by the DNS proxy, with or without a server + * override, and finds the server the resolver originally queried. * * A datagram whose (@p client_port, DNS message ID) matches a tracked query is restored to * the original server whatever source its SOCKS5 header reports: RFC 1928 relays report the - * override server, but some report another address (for example their own), and an answer - * presented from any address other than the queried server is discarded by the resolver. - * A datagram that names the override server but matches no tracked query is dropped. Any - * other datagram relayed through the same proxy is left unchanged. + * server that answered (the override, when one is configured), but some report another + * address (for example their own), and an answer presented from any address other than the + * queried server is discarded by the resolver. With a server override, a datagram that names + * the override server but matches no tracked query is dropped. Any other datagram relayed + * through the same proxy is left unchanged. * * The datagram's ATYP must match the listener's family (@p expected_address_type): the * redirect strips a header of that family's size. * * @param socks_datagram The UDP payload as relayed: SOCKS5 UDP header followed by the data. * @param expected_address_type 1 for the IPv4 path, 4 for the IPv6 path. - * @param override_address The override address bytes (network byte order). + * @param override_address The override address bytes (network byte order), or nullptr when + * no server override is configured for this family; @p override_address_size and + * @p override_port are then ignored. */ template [[nodiscard]] std::pair> classify_dns_override_reply( @@ -1002,14 +1032,15 @@ namespace proxy return { dns_reply_restore::restore, std::move(original) }; } - const bool names_override = view->address_size == override_address_size && view->port == override_port && + const bool names_override = override_address != nullptr && + view->address_size == override_address_size && view->port == override_port && std::equal(view->address, view->address + view->address_size, override_address); return { names_override ? dns_reply_restore::drop : dns_reply_restore::unchanged, std::nullopt }; } // Compile-time checks of the decision table's key invariants. - static_assert(decide_listener_reply(true, false) == listener_reply_action::drop, + static_assert(decide_listener_reply(false) == listener_reply_action::drop, "An untranslatable listener reply must never be passed to the wire."); static_assert(decide_dns_route(dns_routing_mode::direct, 443, dns_upstream_guard::apply_policy, {}).action == dns_route_action::not_dns, "Non-DNS traffic must keep its ordinary routing."); diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 68e0c01..b668a4b 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -266,9 +266,9 @@ namespace proxy /** * @brief True when replies from the DNS proxy's UDP listener may need their source - * restored (dns_reply_restore_needed()). Lets every listener reply skip lock_ in - * Direct mode and in Proxy mode without an override. Written by set_dns_routing() - * while the router is inactive. + * restored (dns_reply_restore_needed()): in Proxy mode with a usable DNS proxy. + * Lets every listener reply skip lock_ in Direct mode. Written by + * set_dns_routing() while the router is inactive. */ std::atomic_bool dns_reply_restore_active_{ false }; @@ -282,8 +282,9 @@ namespace proxy std::atomic_bool udp_relay_on_dns_port_{ false }; /** - * @brief Original server of each UDP DNS query rewritten to the server override, so the - * answer can be restored to the server the resolver actually queried. + * @brief Original server of each UDP DNS query redirected to the DNS proxy, so the answer + * can be restored to the server the resolver actually queried whatever source the + * relay reports (with or without a server override). */ dns_udp_origin_tracker> dns_udp_origins_v4_; dns_udp_origin_tracker> dns_udp_origins_v6_; @@ -1882,8 +1883,7 @@ namespace proxy } dns_proxy_id_ = proxy_id; - dns_reply_restore_active_.store(dns_reply_restore_needed(dns_mode_, true, - dns_server_override_v4_.has_value() || dns_server_override_v6_.has_value()), std::memory_order_release); + dns_reply_restore_active_.store(dns_reply_restore_needed(dns_mode_, true), std::memory_order_release); const auto upstream = proxy_id < proxy_upstreams_.size() ? proxy_upstreams_[proxy_id].to_string() @@ -2460,8 +2460,9 @@ namespace proxy * In Proxy mode the datagram is redirected to the DNS proxy's local UDP listener via the * existing socks5_udp_local_redirect, which also writes the SOCKS5 UDP header. With a * server override the header carries the override while the IP header keeps the - * original destination, and the original server is remembered so the answer can be - * restored to it. Anything that cannot be redirected is dropped, never passed. + * original destination. The server the resolver addressed is remembered, with or without + * an override, so the answer can be restored to it whatever source the relay reports. + * Anything that cannot be redirected is dropped, never passed. */ template packet_filter::packet_action handle_dns_udp(netlib::ndisapi::intermediate_buffer& buffer, @@ -2487,17 +2488,19 @@ namespace proxy return packet_filter::packet_action{ action_type::drop }; } - if (route.server_override) + // The relay may report a source other than the server the resolver addressed (always, + // with a server override), and the resolver accepts an answer only from that server. + // Remember it so the answer can be restored to it (decide_dns_query_tracking()). + const auto message_id = dns_message_id(payload, payload_size); + const auto tracking = decide_dns_query_tracking(route.server_override.has_value(), message_id.has_value()); + if (tracking == dns_query_tracking::drop) { - // The answer comes back from the override server; remember which server the - // resolver addressed so that answer can be restored to it. - const auto message_id = dns_message_id(payload, payload_size); - if (!message_id) - { - note_dns_block(dns_block_reason::redirect_failed); - return packet_filter::packet_action{ action_type::drop }; - } + note_dns_block(dns_block_reason::redirect_failed); + return packet_filter::packet_action{ action_type::drop }; + } + if (tracking == dns_query_tracking::track) + { dns_udp_origins_for().remember(source_port, *message_id, net::ip_endpoint{ destination, destination_port }); } @@ -2590,24 +2593,27 @@ namespace proxy /** * @brief Determines how a reply leaving local UDP proxy listener @p listener_port toward * client port @p client_port is presented, given the relayed SOCKS5 UDP datagram - * in @p socks_payload. Only answers relayed from the configured server override - * by the DNS proxy's listener are restored (see classify_dns_override_reply()); - * other traffic through the same proxy is unchanged. + * in @p socks_payload. Only answers to tracked queries relayed through the DNS + * proxy's listener are restored, with or without a server override (see + * classify_dns_override_reply()); other traffic through the same proxy is unchanged. */ template std::pair>> dns_udp_reply_origin( const uint16_t listener_port, const uint16_t client_port, const uint8_t* socks_payload, const size_t socks_payload_size) { - // Lock-free early exit for every listener reply in Direct mode and in Proxy mode - // without an override. + // Lock-free early exit for every listener reply in Direct mode and when no DNS proxy + // is usable. if (!dns_reply_restore_active_.load(std::memory_order_acquire)) return { dns_reply_restore::unchanged, std::nullopt }; + // Only replies from the DNS proxy's own UDP listener can answer a tracked query. The + // server override, when one is configured for this family, is optional here: tracked + // answers are restored with or without it. std::optional> server_override; { std::shared_lock lock(lock_); - if (dns_mode_ != dns_routing_mode::proxy || !dns_server_override_for()) + if (dns_mode_ != dns_routing_mode::proxy) return { dns_reply_restore::unchanged, std::nullopt }; if (dns_listener_port_locked() != listener_port) @@ -2618,11 +2624,17 @@ namespace proxy constexpr auto v4 = std::is_same_v; using raw_address_t = std::conditional_t; - const raw_address_t& raw = server_override->ip; + const raw_address_t* raw = nullptr; + uint16_t override_port = 0; + if (server_override) + { + raw = &server_override->ip; + override_port = server_override->port; + } return classify_dns_override_reply(socks_payload, socks_payload_size, - static_cast(v4 ? 1 : 4), reinterpret_cast(&raw), sizeof(raw_address_t), - server_override->port, client_port, dns_udp_origins_for()); + static_cast(v4 ? 1 : 4), reinterpret_cast(raw), sizeof(raw_address_t), + override_port, client_port, dns_udp_origins_for()); } /** diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index c0d823a..d3956b6 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -222,6 +222,15 @@ namespace static_cast(std::is_same_v ? 1 : 4), reinterpret_cast(&raw), sizeof(Raw), server_override.port, ntohs(reply.udp()->th_dport), origins); } + + /// classify() for a DNS proxy without a server override, as the router calls it then. + template + std::pair>> classify_without_override(frame& reply, + proxy::dns_udp_origin_tracker>& origins) + { + return proxy::classify_dns_override_reply(reply.udp_payload(), reply.udp_payload_size(), + static_cast(std::is_same_v ? 1 : 4), nullptr, 0, 0, ntohs(reply.udp()->th_dport), origins); + } } // 6./7. IPv4 UDP query to a private resolver with an IPv4 override: the relay is asked for the @@ -415,6 +424,49 @@ TEST(DnsPacketRedirect, RelayReportingAnotherSourceStillRestoresTheQueriedServer EXPECT_TRUE(reply.l4_checksum_valid()); } +// 8. Without a server override the relay is asked for the server the resolver queried. A relay +// that reports another source (here its own address) must still produce an answer the +// resolver accepts; nothing is ever dropped for naming an override, because there is none. +TEST(DnsPacketRedirect, WithoutAnOverrideARelayReportingAnotherSourceIsStillRestored) +{ + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + proxy::dns_udp_origin_tracker> origins; + + auto query = frame::udp4("192.168.1.10", "8.8.8.8", client_port, 53, dns_message(0x6161)); + origins.remember(client_port, 0x6161, net::ip_endpoint{ v4{ query.ip4()->ip_dst }, 53 }); + ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); + + // The relay reports its own address and port instead of 8.8.8.8:53. + const auto answer = dns_message(0x6161, 30); + auto reply = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{ std::string{ "198.51.100.7" } }, 1080, answer); + const auto [restore, origin] = classify_without_override(reply, origins); + ASSERT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(origin.has_value()); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); + EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "8.8.8.8" } }); + EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); + EXPECT_EQ(reply.payload(), answer); + EXPECT_TRUE(reply.ip4_checksum_valid()); + EXPECT_TRUE(reply.l4_checksum_valid()); + + // A relay that reports the queried server is restored to the same endpoint (a no-op). + auto compliant = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{ std::string{ "8.8.8.8" } }, 53, answer); + const auto [compliant_restore, compliant_origin] = classify_without_override(compliant, origins); + EXPECT_EQ(compliant_restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(compliant_origin.has_value()); + EXPECT_EQ(compliant_origin->ip, v4{ std::string{ "8.8.8.8" } }); + + // Anything that matches no tracked query is left unchanged, never dropped: application + // traffic sharing the proxy, an unknown message ID, or a payload too short for a DNS header. + auto other = local_proxy_reply("192.168.1.10", "203.0.113.5", v4{ std::string{ "203.0.113.5" } }, 443, dns_message(0x7777)); + EXPECT_EQ(classify_without_override(other, origins).first, proxy::dns_reply_restore::unchanged); + auto unknown_id = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{ std::string{ "8.8.8.8" } }, 53, dns_message(0x7777)); + EXPECT_EQ(classify_without_override(unknown_id, origins).first, proxy::dns_reply_restore::unchanged); + auto short_payload = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{ std::string{ "8.8.8.8" } }, 53, std::vector{ 0x61, 0x61 }); + EXPECT_EQ(classify_without_override(short_payload, origins).first, proxy::dns_reply_restore::unchanged); +} + // 8. A datagram that cannot be redirected is reported as such (the router then drops it rather // than passing it): here a near-MTU datagram that has no room for the SOCKS5 header. TEST(DnsPacketRedirect, UnredirectableUdpIsRejectedSoTheRouterDropsIt) @@ -654,13 +706,13 @@ TEST(DnsTcpCloseTracking, UntranslatableListenerSegmentIsDropped) auto stray = listener_segment(TH_ACK); const bool translated = redirect.process_server_to_client_packet(stray.buffer); EXPECT_FALSE(translated); - EXPECT_EQ(proxy::decide_listener_reply(true, translated), proxy::listener_reply_action::drop); + EXPECT_EQ(proxy::decide_listener_reply(translated), proxy::listener_reply_action::drop); ndisapi::socks5_udp_local_redirect udp{ log_level::error }; auto unknown = local_proxy_reply("192.168.1.10", "192.168.1.1", v4{ std::string{ "192.168.1.1" } }, 53, dns_message(1)); const bool udp_translated = udp.process_server_to_client_packet(unknown.buffer); EXPECT_FALSE(udp_translated); - EXPECT_EQ(proxy::decide_listener_reply(true, udp_translated), proxy::listener_reply_action::drop); + EXPECT_EQ(proxy::decide_listener_reply(udp_translated), proxy::listener_reply_action::drop); } // 14. Truncation fallback end to end: the truncated UDP answer reaches the resolver unchanged diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 301c9c3..ff616ca 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -456,16 +456,14 @@ TEST(DnsUdpOriginTracker, IsSafeForConcurrentPacketAndMaintenanceThreads) } // 1. Packets sourced from a local proxy listener are re-injected when translated and dropped -// otherwise; they are never passed to the wire. Other packets continue with normal routing. +// otherwise; there is no outcome that passes them to the wire. TEST(ListenerReplyPolicy, UntranslatedListenerRepliesAreDroppedNeverPassed) { using proxy::decide_listener_reply; using proxy::listener_reply_action; - EXPECT_EQ(decide_listener_reply(true, true), listener_reply_action::revert); - EXPECT_EQ(decide_listener_reply(true, false), listener_reply_action::drop); - EXPECT_EQ(decide_listener_reply(false, false), listener_reply_action::not_listener); - EXPECT_EQ(decide_listener_reply(false, true), listener_reply_action::not_listener); + EXPECT_EQ(decide_listener_reply(true), listener_reply_action::revert); + EXPECT_EQ(decide_listener_reply(false), listener_reply_action::drop); } // 5. Fragments: only a first fragment carries ports. IPv4 later fragments are not classified; @@ -627,15 +625,29 @@ TEST(DnsFilterPlan, ListenersThatAreNotRunningGetNoSourcePortFilter) EXPECT_EQ(proxy::plan_dns_filters(proxy_mode, {}).size(), 4u); } -// 9. Listener replies need DNS work (and lock_) only in Proxy mode with a usable proxy and an override. -TEST(DnsReplyRestore, NeededOnlyInProxyModeWithAnOverride) +// 9. Listener replies need DNS work (and lock_) in Proxy mode with a usable proxy, whether or not +// a server override is configured: a relay can report another source either way. Direct mode +// and Proxy mode without a usable proxy redirect no DNS and need none. +TEST(DnsReplyRestore, NeededInProxyModeWithAUsableProxy) { using proxy::dns_reply_restore_needed; - EXPECT_TRUE(dns_reply_restore_needed(proxy_mode, true, true)); - EXPECT_FALSE(dns_reply_restore_needed(proxy_mode, true, false)); - EXPECT_FALSE(dns_reply_restore_needed(proxy_mode, false, true)); - EXPECT_FALSE(dns_reply_restore_needed(direct, true, true)); - EXPECT_FALSE(dns_reply_restore_needed(direct, false, false)); + EXPECT_TRUE(dns_reply_restore_needed(proxy_mode, true)); + EXPECT_FALSE(dns_reply_restore_needed(proxy_mode, false)); + EXPECT_FALSE(dns_reply_restore_needed(direct, true)); + EXPECT_FALSE(dns_reply_restore_needed(direct, false)); +} + +// A redirected query is tracked whenever it carries a DNS header, with or without a server +// override. One that is too short to carry a header is still redirected without an override +// (as before), and dropped with one, because its answer could never be restored. +TEST(DnsReplyRestore, QueriesAreTrackedWithOrWithoutAnOverride) +{ + using proxy::decide_dns_query_tracking; + using proxy::dns_query_tracking; + EXPECT_EQ(decide_dns_query_tracking(false, true), dns_query_tracking::track); + EXPECT_EQ(decide_dns_query_tracking(true, true), dns_query_tracking::track); + EXPECT_EQ(decide_dns_query_tracking(false, false), dns_query_tracking::untracked); + EXPECT_EQ(decide_dns_query_tracking(true, false), dns_query_tracking::drop); } // 10. Eviction uses insertion order: a refreshed key is not the oldest, the queue of insertion From 4801548f9c10af4fc1048f972e53ed211bcdcda1 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 18:58:52 +0000 Subject: [PATCH 27/62] docs: describe listener-reply and TCP close handling; extend the Windows checklist - configuration.md: a section on local listener replies and TCP close handling, which apply to all proxied traffic; answer restoration with or without a server override; the two remaining unclassified pass paths (broadcast/multicast link-layer destinations, unwalkable IPv6 extension chains); previously ignored `id` and `dns` properties are now interpreted. - README.md and configuration.md: fragmented IPv6 is no longer passed without exception. - gui.md: manual validation steps for the upgrade path, restarts, a DNS proxy unavailable at start, TCP closes, aborts, large answers, relay sources, a SOCKS5 server used as a resolver, limited mode, and the GUI. --- README.md | 2 +- docs/configuration.md | 21 ++++++++++++++++++--- docs/gui.md | 10 ++++++++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 43d267e..ef4c0a8 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ Set `socks5Transport` to `"TLS"` to protect the SOCKS5 TCP connection and UDP `A - The SOCKS5 server endpoint must be reachable over IPv4: use an IPv4 literal or a hostname with an A record. Destination traffic may still be IPv4, IPv6, or both. - IPv6 proxying requires working IPv6 connectivity on the client and a SOCKS5 server that accepts IPv6 targets (`ATYP=4`). ProxiFyre redirects packets the application emits; it does not create IPv6 connectivity. -- Fragmented IPv6 datagrams are passed through directly to avoid corrupting partial packets. Applications that emit oversized fragmented UDP datagrams can therefore bypass the proxy. +- Fragmented IPv6 datagrams are passed through directly to avoid corrupting partial packets. Applications that emit oversized fragmented UDP datagrams can therefore bypass the proxy. Two kinds of first fragment are dropped instead: one addressed to port 53 in DNS `Proxy` mode, and one sent by a local proxy listener. - DNS routing covers conventional DNS on port 53 only. DNS over HTTPS/TLS/QUIC used internally by applications, mDNS, LLMNR, and loopback resolvers are not affected, and answers already in the Windows DNS cache are reused. - SOCKS5 usernames and passwords are stored in plaintext in `app-config.json`, although the GUI masks and redacts them from its diagnostics. - The MSI creates program-specific inbound TCP and UDP firewall rules for `ProxiFyre.exe` because redirect listener ports are allocated dynamically. diff --git a/docs/configuration.md b/docs/configuration.md index 3f23e8e..966c245 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -114,7 +114,7 @@ IPv6 destination routing also requires: - a SOCKS5 server that accepts IPv6 target addresses (`ATYP=4`); and - an upstream proxy reachable through IPv4. The endpoint itself must be an IPv4 literal or a hostname with an A record; IPv6-literal and AAAA-only upstreams are not supported. -Fragmented IPv6 datagrams are passed through directly to avoid rewriting an incomplete packet. Applications that emit oversized fragmented UDP datagrams can therefore bypass the proxy; TCP and path-MTU-aware UDP such as normal QUIC traffic are unaffected. DNS `Proxy` mode is the exception for port 53: see [Proxy mode](#proxy-mode). +Fragmented IPv6 datagrams are passed through directly to avoid rewriting an incomplete packet. Applications that emit oversized fragmented UDP datagrams can therefore bypass the proxy; TCP and path-MTU-aware UDP such as normal QUIC traffic are unaffected. There are two exceptions, both for first fragments, which are the only fragments that carry ports: a first fragment addressed to port 53 is dropped in DNS `Proxy` mode (see [Proxy mode](#proxy-mode)), and a first fragment sent by one of ProxiFyre's local proxy listeners is dropped in every mode (see [Local listener replies and TCP close handling](#local-listener-replies-and-tcp-close-handling)). ## LAN bypass @@ -130,6 +130,15 @@ Changing this setting requires a service restart. In DNS `Proxy` mode, DNS takes precedence over LAN bypass: a query addressed to a LAN resolver such as `192.168.1.1:53` is still sent through the DNS proxy, while all other LAN traffic stays direct. See [DNS routing](#dns-routing). +## Local listener replies and TCP close handling + +ProxiFyre redirects a matched connection to a local listener and translates the listener's replies back before the application sees them. Two rules apply to every proxied connection, not only to DNS: + +- **A reply that cannot be translated back is dropped.** A reply from a local listener is addressed to the original server only because redirection swapped the addresses, so it must never reach the network. It is dropped when its TCP connection or UDP endpoint is no longer tracked, when it is the first fragment of a fragmented reply, or when its SOCKS5 relay header is malformed or of the wrong address type. Earlier releases passed such packets toward the original server. The first such drop after the service starts is logged once as a warning, and a count is logged at `Info` level at most every five seconds while drops continue. Later fragments of a fragmented reply carry no ports, cannot be attributed to a listener, and are still passed. +- **A TCP connection is tracked through its whole close.** The FIN/ACK exchange is translated in both directions instead of reaching the real server. A reset (RST) ends the connection immediately; segments the local proxy had already sent when the reset arrived are dropped without the warning and are counted at `Debug` level only. + +A proxied TCP connection that stays idle for more than 5 minutes loses its redirect entry; see [Limitations](#limitations). + ## DNS routing The optional `dns` object controls conventional DNS: UDP and TCP traffic to destination port 53, for IPv4 and IPv6. It is a global policy that applies to every process, independently of `appNames` rules and `excludes`. Windows normally resolves names in the DNS Client service (`Dnscache`, hosted by `svchost.exe`) rather than in the requesting application, so a per-application DNS rule could not be attributed reliably; ProxiFyre therefore does not try to. @@ -140,6 +149,8 @@ The optional `dns` object controls conventional DNS: UDP and TCP traffic to dest | `proxyId` | Required in `Proxy` mode: the `id` of the proxy rule whose SOCKS5 proxy carries DNS. That rule must support both `TCP` and `UDP` (omitting `supportedProtocols` means both). | | `serverOverride` | Optional, `Proxy` mode only: an IPv4 or IPv6 literal with an optional port that the SOCKS5 proxy queries instead of the server Windows addressed, for example `1.1.1.1`, `1.1.1.1:53`, `2606:4700:4700::1111`, or `[2606:4700:4700::1111]:53`. Host names are rejected so the override never needs DNS itself. | +Configurations written before DNS routing existed load and save unchanged. The one exception is a configuration that already contained a rule property named `id` or a top-level property named `dns`: these were preserved but ignored by earlier releases and are now interpreted and validated. + ### Direct mode UDP and TCP DNS to port 53 bypass every SOCKS5 proxy for both address families, whatever process sends it. This is the behavior of configurations without a `dns` section. @@ -155,7 +166,7 @@ ProxiFyre never falls back to sending DNS directly. The DNS policy itself drops - the selected proxy could not be created at startup, or the configuration is rejected by the engine; - the proxy does not accept the destination's address family (for example IPv6 DNS with an IPv4-only rule); - a `serverOverride` is configured and the query is addressed to a server of the other address family (an IPv4 override blocks queries to IPv6 servers and vice versa); -- the packet cannot be redirected, such as a TCP connection to port 53 that was opened before ProxiFyre started, or a datagram too large to carry the SOCKS5 UDP header; +- the packet cannot be redirected, such as a TCP connection to port 53 that was opened before ProxiFyre started, a datagram too large to carry the SOCKS5 UDP header, or, with a `serverOverride`, a datagram too short to carry a DNS header; - the datagram is fragmented. Only the first fragment carries the UDP or TCP header, so only a first fragment (IPv4 or IPv6) addressed to port 53 can be recognized as DNS; it is dropped, which also prevents the datagram from being reassembled at the server. Later fragments carry no ports, cannot be classified, and are passed unchanged, so other fragmented traffic is not affected. In `Direct` mode fragmented DNS is passed like any other DNS; or - it is addressed to a configured SOCKS5 server and its sending process cannot be determined (see [Recursion and ProxiFyre's own traffic](#recursion-and-proxifyres-own-traffic)). @@ -167,6 +178,8 @@ Whether name resolution still succeeds after a drop depends on Windows: it retri Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. +For UDP, ProxiFyre remembers the server each redirected query was addressed to (by client port and DNS message ID, for 30 seconds) and presents the answer as coming from that server, whatever source address the SOCKS5 relay reports for it, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered, but some report another address, such as their own. This applies with or without a `serverOverride`. Datagrams relayed through the same proxy that match no outstanding query are delivered with the source the relay reports. + If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. The selection is made by `proxyId`, never by position, so reordering rules does not change the DNS proxy. If the referenced rule is removed or renamed, validation fails with `DNS_PROXY_NOT_FOUND`; ProxiFyre never silently switches to another proxy. The GUI assigns an id such as `proxy-1` to a rule when it is selected as the DNS proxy, and clears the id on a duplicated copy. @@ -175,7 +188,7 @@ The selection is made by `proxyId`, never by position, so reordering rules does Without `serverOverride`, each query keeps its original destination: the SOCKS5 server is asked to reach the DNS server Windows queried. That fails when Windows uses a local resolver, such as a home router at `192.168.1.1`, which the remote SOCKS5 server cannot reach. Set `serverOverride` to a resolver that is reachable from the SOCKS5 server, such as `1.1.1.1`. -With an override, only the SOCKS5 destination changes: the `UDP ASSOCIATE` datagram header or the `CONNECT` target names the override, while the packets the application sees keep the original server address. For UDP, ProxiFyre remembers the original server for each query (by client port and DNS message ID, for 30 seconds) and presents the answer as coming from that server, because a resolver discards answers from an address it did not query. An answer that matches an outstanding query is restored this way whatever source address the SOCKS5 relay reports for it: RFC 1928 relays report the override server, but some report another address. A datagram that names the override server but matches no outstanding query is dropped; other datagrams relayed through the same proxy are delivered unchanged. Checksums are recalculated on every rewritten packet. +With an override, only the SOCKS5 destination changes: the `UDP ASSOCIATE` datagram header or the `CONNECT` target names the override, while the packets the application sees keep the original server address. A UDP answer is restored to the server the resolver queried as described under [Proxy mode](#proxy-mode); an RFC 1928 relay reports the override server as its source. A datagram that names the override server but matches no outstanding query is dropped; other datagrams relayed through the same proxy are delivered unchanged. Checksums are recalculated on every rewritten packet. ### Examples @@ -215,6 +228,8 @@ The sender is taken from ProxiFyre's cached copy of the Windows connection table - Only traffic visible to the Windows Packet Filter layer is captured. Loopback and local resolvers (for example a resolver on `127.0.0.1` or `::1`, or a resolver inside a local VM or container reached through a virtual adapter that is not filtered) are not routed, and their own upstream queries are subject to the same policy only if they leave through a filtered adapter. - Each new UDP source port needs its own SOCKS5 control connection and `UDP ASSOCIATE`, as for application UDP traffic. The Windows DNS Client uses a fresh source port for most queries, so the first answer through the proxy is delayed by the SOCKS5 (and, for `TLS`, the TLS) handshake. - When the service is stopped, packet filtering stops and all traffic, including DNS, is direct. +- UDP sent to a broadcast or multicast link-layer address is passed before the DNS policy is applied, as it is for application traffic, so a port-53 datagram addressed to a broadcast or multicast address is not proxied. Conventional DNS is unicast. +- An IPv6 packet whose extension-header chain ProxiFyre cannot walk to a UDP or TCP header (for example one protected by AH or ESP, or a truncated chain) is passed without being classified. - A proxied TCP connection that stays idle for more than 5 minutes loses its redirect entry. This applies to every proxied TCP connection, not only DNS. If the local proxy then sends first on that connection, its segments are dropped rather than sent to the real server, so the connection stalls until the application or the proxy times it out instead of being reset. A segment the application sends on such a connection is no longer redirected either: for application traffic it goes to the real server as before, which normally resets the connection; for DNS in `Proxy` mode it is dropped. - Changing DNS settings requires a service restart. diff --git a/docs/gui.md b/docs/gui.md index c82b1f3..e498149 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -166,3 +166,13 @@ The routing policy and the packet rewriting are covered by automated tests (`net 4. Reorder the rules, Apply & Restart, and confirm DNS still uses the selected proxy. 5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log reports the SOCKS5 connection or `UDP ASSOCIATE` failures from the local proxy server. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. 6. Configure an IPv4 override with an IPv6 resolver and confirm IPv6 queries are dropped while IPv4 queries succeed. +7. **Upgrade.** With a configuration from an earlier release (no `dns` section, a catch-all rule), confirm that `Resolve-DnsName -TcpOnly` now leaves the adapter directly, that UDP DNS still does, and that the rule's other traffic is still proxied. +8. **Restart.** With `Proxy` mode and `bypassLan`, use **Apply & Restart** (or stop and start the service) and repeat step 3: DNS to the router resolver must still be proxied. +9. **DNS proxy unavailable at start.** Give the DNS proxy rule an endpoint that cannot be created (for example a host name that does not resolve) and start the service. Confirm the service starts, the log states that all DNS is blocked until the service is restarted, and no port-53 packet leaves the adapter. +10. **TCP close.** Run `Resolve-DnsName -TcpOnly` several times in `Proxy` mode. Confirm each lookup completes, that no FIN, ACK, or RST of those connections reaches the real DNS server, and that the log has no "dropped … DNS packet(s)" lines. +11. **Aborted connection.** Start a large download in a proxied application and cancel it. Confirm no segment from the local listener's port leaves the adapter and that the log has no "could not be translated back" warning. +12. **Large answer.** In `Proxy` mode request a UDP answer larger than about 1,460 bytes over IPv4 and over IPv6, for example with `dig +dnssec +bufsize=4096 DNSKEY org @`. Confirm the first fragment of the local listener's reply (the one that carries a UDP header from the listener's port) does not leave the adapter, and that the listener-reply warning is logged once. Later fragments may leave, and the UDP lookup itself is expected to fail. +13. **Relay source.** If the SOCKS5 server reports an address other than the queried DNS server as the source of UDP replies, confirm lookups succeed both without and with `serverOverride`. +14. **SOCKS5 server used as a resolver.** Send a lookup to the SOCKS5 server's own IP address (`Resolve-DnsName -Server `). Confirm the query goes through the proxy, not directly. If the server listens on TCP port 53 or returns a UDP relay on port 53, also confirm ProxiFyre still reaches it and the one-time `Info` line about the relay appears. +15. **Limited mode.** Repeat step 2 in the optional unelevated console mode. +16. **GUI.** On the **Settings / Diagnostics** tab at 100% and 150% scaling, confirm the DNS routing group and the Uninstall button are reachable (scrolling is expected). Confirm Alt+M, Alt+P, and Alt+S focus the mode, proxy, and override fields; that the DNS proxy selection survives **Move Up**/**Move Down** and a reload; that **Duplicate** does not copy the id; and that removing the selected rule shows the missing id and fails validation. From fc052ee59a5e6a517383dec9b86f83cb51e2ef44 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 19:24:10 +0000 Subject: [PATCH 28/62] fix: restore a tracked DNS answer when the relay header has the other address family A relay that reports its own address as the source of a UDP answer reports an IPv4 address even for an IPv6 query, because SOCKS5 servers are reached over IPv4. Such an answer matched a tracked query but was still dropped: the classifier ignored a header of the other family, and the UDP redirect rejected it. The classifier now restores a tracked answer whatever family its header has. The UDP redirect strips a header of the other family by its real size, but only when the caller supplies the source to present; without it such a header is rejected as before, so application traffic is unchanged. Also: - rename classify_dns_override_reply() to classify_dns_reply() and update comments that still tied restoration to a server override; - tests call the classifier with the arguments the router passes (no override address, the family's address size, port 0), so the null-address guard is covered; add IPv6 and truncated-header cases. Notes on the previous commit, which its message left out: it changed dns_reply_restore_needed() to two parameters, and in Proxy mode without an override every UDP listener reply now takes lock_ (shared) once more, and every reply from the DNS proxy's listener does one tracker lookup. Direct mode is unaffected. --- .../src/ndisapi/socks5_udp_local_redirect.h | 89 +++++++---- netlib/src/proxy/dns_routing_policy.h | 32 ++-- netlib/src/proxy/socks_local_router.h | 12 +- .../portable/dns_packet_redirect_test.cpp | 140 +++++++++++++++++- 4 files changed, 222 insertions(+), 51 deletions(-) diff --git a/netlib/src/ndisapi/socks5_udp_local_redirect.h b/netlib/src/ndisapi/socks5_udp_local_redirect.h index ae7cb77..f0a7d23 100644 --- a/netlib/src/ndisapi/socks5_udp_local_redirect.h +++ b/netlib/src/ndisapi/socks5_udp_local_redirect.h @@ -475,6 +475,39 @@ namespace ndisapi return false; } + /** + * @brief Size of the SOCKS5 UDP header to strip from a relayed datagram, or 0 when the + * datagram must not be translated. + * + * The relay's header normally has this redirect's address family (ATYP 1 for IPv4, 4 for + * IPv6). A header of the other family is rejected: parsing a mismatched layout would hand + * the client a garbage source endpoint. When the caller supplies the source to present + * (@p source_supplied), the header's own address is not used, so a header of the other + * family is accepted and stripped by its real size. + * + * @param udp_payload The UDP payload: the SOCKS5 UDP header followed by the data. + * @param captured Captured bytes available at @p udp_payload. + */ + [[nodiscard]] static std::size_t relay_header_size(const uint8_t* udp_payload, const std::size_t captured, + const bool source_supplied) noexcept + { + constexpr std::size_t prefix_size = 4; // RSV (2), FRAG (1), ATYP (1) + if (captured < prefix_size) + return 0; + + constexpr uint8_t own_address_type = std::is_same_v> ? 1 : 4; + const auto address_type = udp_payload[3]; + if (address_type == own_address_type) + return sizeof(proxy::socks5_udp_header); + if (!source_supplied) + return 0; + if (address_type == 1) + return sizeof(proxy::socks5_udp_header); + if (address_type == 4) + return sizeof(proxy::socks5_udp_header); + return 0; + } + /** * @brief Processes an S2C packet, restoring the original client source port and remote peer. * @@ -484,7 +517,9 @@ namespace ndisapi * @param packet S2C network packet. * @param source_override Optional source endpoint (port in host byte order) presented to * the client instead of the one in the relay's SOCKS5 UDP header. Used to restore - * the server the client originally queried when a DNS server override is active. + * the server a DNS client originally queried. Because the header's own address is + * then not used, a header of the other address family is accepted and stripped by + * its real size; without it such a header is rejected. * @return True if the packet was translated, false otherwise. */ bool process_server_to_client_packet(INTERMEDIATE_BUFFER& packet, @@ -520,27 +555,30 @@ namespace ndisapi // the received datagram. Without these guards a short/forged length makes // udp_payload_size - socks5_header_size underflow into a huge value and the // memmove writes far out of bounds. Mirrors the IPv6 detach guards. - constexpr auto socks5_header_size = sizeof(proxy::socks5_udp_header); const auto* const packet_end = packet.m_IBuffer + packet.m_Length; const auto* const udp_header_bytes = reinterpret_cast(udp_header); - const auto udp_length = ntohs(udp_header->length); if (udp_header_bytes > packet_end || - static_cast(packet_end - udp_header_bytes) < sizeof(udphdr) || + static_cast(packet_end - udp_header_bytes) < sizeof(udphdr)) + { + return false; + } + + // The SOCKS5 UDP header to strip: this relay's family (ATYP 1), or, only when the + // caller supplies the source to present, the other family's (relay_header_size()). + // A mismatched header is otherwise rejected, before any mutation. + const auto udp_length = ntohs(udp_header->length); + const auto captured_udp_size = static_cast(packet_end - udp_header_bytes); + const auto socks5_header_size = relay_header_size(reinterpret_cast(udp_header + 1), + captured_udp_size - sizeof(udphdr), source_override.has_value()); + if (socks5_header_size == 0 || udp_length < sizeof(udphdr) + socks5_header_size || - udp_length > static_cast(packet_end - udp_header_bytes) || + udp_length > captured_udp_size || packet.m_Length < socks5_header_size || ntohs(ip_header->ip_len) < socks5_header_size) { return false; } - // Reject a reply whose SOCKS5 UDP header ATYP doesn't match this relay's family - // (IPv4 = 1): parsing a mismatched layout (e.g. a 16-byte IPv6 address as IPv4) - // would hand the client a spoofed/garbage source endpoint. The bounds check above - // guarantees the SOCKS5 header is fully captured. Done before any mutation. - if (reinterpret_cast*>(udp_header + 1)->address_type != 1) - return false; - NETLIB_DEBUG( "S2C: {}:{} -> {}:{}", std::string{ T{ip_header->ip_src} }, @@ -572,9 +610,9 @@ namespace ndisapi memmove(udp_payload, udp_payload + socks5_header_size, udp_payload_size - socks5_header_size); - packet.m_Length -= sizeof(proxy::socks5_udp_header); - ip_header->ip_len = htons(ntohs(ip_header->ip_len) - sizeof(proxy::socks5_udp_header)); - udp_header->length = htons(ntohs(udp_header->length) - sizeof(proxy::socks5_udp_header)); + packet.m_Length -= static_cast(socks5_header_size); + ip_header->ip_len = htons(static_cast(ntohs(ip_header->ip_len) - socks5_header_size)); + udp_header->length = htons(static_cast(ntohs(udp_header->length) - socks5_header_size)); CNdisApi::RecalculateUDPChecksum(&packet); CNdisApi::RecalculateIPChecksum(&packet); @@ -619,7 +657,6 @@ namespace ndisapi ntohs(udp_header->th_dport)); // Remove SOCK5 UDP header here - constexpr auto socks5_header_size = sizeof(proxy::socks5_udp_header); const auto* const packet_end = packet.m_IBuffer + packet.m_Length; const auto* const udp_header_bytes = reinterpret_cast(udp_header); if (udp_header_bytes > packet_end || @@ -628,9 +665,15 @@ namespace ndisapi return false; } + // The SOCKS5 UDP header to strip: this relay's family (ATYP 4), or, only when the + // caller supplies the source to present, the other family's (relay_header_size()). + // A mismatched header is otherwise rejected, before any mutation. const auto udp_length = ntohs(udp_header->length); const auto captured_udp_size = static_cast(packet_end - udp_header_bytes); - if (udp_length < sizeof(udphdr) + socks5_header_size || + const auto socks5_header_size = relay_header_size(reinterpret_cast(udp_header + 1), + captured_udp_size - sizeof(udphdr), source_override.has_value()); + if (socks5_header_size == 0 || + udp_length < sizeof(udphdr) + socks5_header_size || udp_length > captured_udp_size || packet.m_Length < socks5_header_size || ntohs(ip_header->ip6_len) < socks5_header_size) @@ -641,12 +684,6 @@ namespace ndisapi auto* udp_payload = reinterpret_cast(udp_header + 1); auto* socks5_udp_header_ptr = reinterpret_cast*>(udp_payload); - // Reject a reply whose SOCKS5 UDP header ATYP doesn't match this relay's family - // (IPv6 = 4); see the IPv4 path. The bounds check above guarantees the header is - // fully captured. Done before any mutation. - if (socks5_udp_header_ptr->address_type != 4) - return false; - // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -668,9 +705,9 @@ namespace ndisapi memmove(udp_payload, udp_payload + socks5_header_size, udp_payload_size - socks5_header_size); - packet.m_Length -= socks5_header_size; - ip_header->ip6_len = htons(ntohs(ip_header->ip6_len) - socks5_header_size); - udp_header->length = htons(ntohs(udp_header->length) - socks5_header_size); + packet.m_Length -= static_cast(socks5_header_size); + ip_header->ip6_len = htons(static_cast(ntohs(ip_header->ip6_len) - socks5_header_size)); + udp_header->length = htons(static_cast(ntohs(udp_header->length) - socks5_header_size)); // Recalculate checksum net::ipv6_helper::recalculate_tcp_udp_checksum(&packet); diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 804e2e2..edb1d75 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -629,7 +629,7 @@ namespace proxy /// Minimum size of a DNS message header (RFC 1035 section 4.1.1). inline constexpr std::size_t dns_header_size = 12; - /// Reads the DNS message ID used to map override responses back to their original server. + /// Reads the DNS message ID used to map answers back to the server the resolver queried. /// The payload is not used to classify traffic: classification is by port 53 only. [[nodiscard]] constexpr std::optional dns_message_id(const uint8_t* payload, const std::size_t size) noexcept { @@ -934,7 +934,7 @@ namespace proxy /** * @brief Whether replies leaving the DNS proxy's UDP listener may need their source restored - * (classify_dns_override_reply()): in Proxy mode with a usable proxy, with or without + * (classify_dns_reply()): in Proxy mode with a usable proxy, with or without * a server override, because a relay can report a source other than the server the * resolver queried either way. In Direct mode, or without a usable proxy, no DNS is * redirected and the reply path needs no DNS work at all. @@ -1000,15 +1000,20 @@ namespace proxy * override, and finds the server the resolver originally queried. * * A datagram whose (@p client_port, DNS message ID) matches a tracked query is restored to - * the original server whatever source its SOCKS5 header reports: RFC 1928 relays report the - * server that answered (the override, when one is configured), but some report another - * address (for example their own), and an answer presented from any address other than the - * queried server is discarded by the resolver. With a server override, a datagram that names - * the override server but matches no tracked query is dropped. Any other datagram relayed - * through the same proxy is left unchanged. + * the original server whatever source its SOCKS5 header reports, of either address family: + * RFC 1928 relays report the server that answered (the override, when one is configured), + * but some report another address (for example their own, which is IPv4 even for an IPv6 + * query), and an answer presented from any address other than the queried server is + * discarded by the resolver. The redirect strips such a header by its real size when it is + * given the source to present. With a server override, a datagram that names the override + * server but matches no tracked query is dropped. Any other datagram relayed through the + * same proxy is left unchanged; if its ATYP is not the listener's family + * (@p expected_address_type), the redirect then rejects it and it is dropped. * - * The datagram's ATYP must match the listener's family (@p expected_address_type): the - * redirect strips a header of that family's size. + * The match is on the client port and the first two bytes of the relayed data only. A + * datagram that is not a DNS answer is restored by mistake only if it arrives for a client + * port that sent a port-53 datagram within the tracker's lifetime and begins with that + * datagram's ID. * * @param socks_datagram The UDP payload as relayed: SOCKS5 UDP header followed by the data. * @param expected_address_type 1 for the IPv4 path, 4 for the IPv6 path. @@ -1017,13 +1022,13 @@ namespace proxy * @p override_port are then ignored. */ template - [[nodiscard]] std::pair> classify_dns_override_reply( + [[nodiscard]] std::pair> classify_dns_reply( const uint8_t* socks_datagram, const std::size_t size, const uint8_t expected_address_type, const uint8_t* override_address, const std::size_t override_address_size, const uint16_t override_port, const uint16_t client_port, dns_udp_origin_tracker& origins) { const auto view = parse_socks5_udp_datagram(socks_datagram, size); - if (!view || view->address_type != expected_address_type) + if (!view) return { dns_reply_restore::unchanged, std::nullopt }; if (const auto message_id = dns_message_id(view->data, view->data_size)) @@ -1032,6 +1037,9 @@ namespace proxy return { dns_reply_restore::restore, std::move(original) }; } + if (view->address_type != expected_address_type) + return { dns_reply_restore::unchanged, std::nullopt }; + const bool names_override = override_address != nullptr && view->address_size == override_address_size && view->port == override_port && std::equal(view->address, view->address + view->address_size, override_address); diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index b668a4b..d6465dd 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -2595,7 +2595,7 @@ namespace proxy * client port @p client_port is presented, given the relayed SOCKS5 UDP datagram * in @p socks_payload. Only answers to tracked queries relayed through the DNS * proxy's listener are restored, with or without a server override (see - * classify_dns_override_reply()); other traffic through the same proxy is unchanged. + * classify_dns_reply()); other traffic through the same proxy is unchanged. */ template std::pair>> dns_udp_reply_origin( @@ -2632,7 +2632,7 @@ namespace proxy override_port = server_override->port; } - return classify_dns_override_reply(socks_payload, socks_payload_size, + return classify_dns_reply(socks_payload, socks_payload_size, static_cast(v4 ? 1 : 4), reinterpret_cast(raw), sizeof(raw_address_t), override_port, client_port, dns_udp_origins_for()); } @@ -2764,8 +2764,8 @@ namespace proxy const bool has_ports = ipv4_transport_header_present(fragment); // If the packet is from a known proxy port, process for server-to-client redirection. - // Answers relayed from a DNS server override are presented as coming from the server - // the resolver originally queried. + // Answers to tracked DNS queries are presented as coming from the server the resolver + // originally queried. if (has_ports && is_udp_proxy_port(ntohs(udp_header->th_sport))) { const auto [restore, origin] = dns_udp_reply_origin( @@ -3134,7 +3134,7 @@ namespace proxy const auto* const udp_header = static_cast(transport); // If the packet is from a known proxy port, process for server-to-client redirection - // (restoring the original server of DNS override answers, as on the IPv4 path). + // (restoring the original server of answers to tracked DNS queries, as on the IPv4 path). if (is_udp_proxy_port_v6(ntohs(udp_header->th_sport))) { const auto [restore, origin] = dns_udp_reply_origin( @@ -3557,7 +3557,7 @@ namespace proxy } } - // Expire DNS override response mappings for queries that were never answered. + // Expire DNS answer-origin mappings for queries that were never answered. dns_udp_origins_v4_.sweep(now); dns_udp_origins_v6_.sweep(now); } diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index d3956b6..9e431a0 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -218,18 +218,21 @@ namespace const net::ip_endpoint& server_override, proxy::dns_udp_origin_tracker>& origins) { const Raw& raw = server_override.ip; - return proxy::classify_dns_override_reply(reply.udp_payload(), reply.udp_payload_size(), + return proxy::classify_dns_reply(reply.udp_payload(), reply.udp_payload_size(), static_cast(std::is_same_v ? 1 : 4), reinterpret_cast(&raw), sizeof(Raw), server_override.port, ntohs(reply.udp()->th_dport), origins); } - /// classify() for a DNS proxy without a server override, as the router calls it then. + /// classify() for a DNS proxy without a server override, with the arguments the router + /// passes then: no override address, but still the family's address size, and port 0. template std::pair>> classify_without_override(frame& reply, proxy::dns_udp_origin_tracker>& origins) { - return proxy::classify_dns_override_reply(reply.udp_payload(), reply.udp_payload_size(), - static_cast(std::is_same_v ? 1 : 4), nullptr, 0, 0, ntohs(reply.udp()->th_dport), origins); + constexpr bool is_v4 = std::is_same_v; + return proxy::classify_dns_reply(reply.udp_payload(), reply.udp_payload_size(), + static_cast(is_v4 ? 1 : 4), nullptr, is_v4 ? sizeof(in_addr) : sizeof(in6_addr), 0, + ntohs(reply.udp()->th_dport), origins); } } @@ -389,14 +392,23 @@ TEST(DnsPacketRedirect, AnswersToTrackedQueriesAreRestoredWhateverSourceTheRelay auto other_port = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 5353, dns_message(0x2222)); EXPECT_EQ((classify(other_port, server_override, origins).first), proxy::dns_reply_restore::unchanged); - // A malformed SOCKS5 header (non-zero FRAG) or the other family's ATYP is not restored; the - // redirect then fails to translate it and the router drops it. + // A malformed SOCKS5 header (non-zero FRAG) is not restored, and neither is a header of the + // other family that matches no tracked query; the redirect then fails to translate either + // and the router drops it. auto fragmented = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x1111)); fragmented.udp_payload()[2] = 1; EXPECT_EQ((classify(fragmented, server_override, origins).first), proxy::dns_reply_restore::unchanged); auto wrong_family = frame::udp4("192.168.1.10", "192.168.1.1", udp_listener, client_port, - socks5_udp_datagram(v6{ std::string{ "2001:db8::1" } }, 53, dns_message(0x1111))); + socks5_udp_datagram(v6{ std::string{ "2001:db8::1" } }, 53, dns_message(0x2222))); EXPECT_EQ((classify(wrong_family, server_override, origins).first), proxy::dns_reply_restore::unchanged); + + // A tracked answer is restored even when the relay's header has the other address family. + auto tracked_other_family = frame::udp4("192.168.1.10", "192.168.1.1", udp_listener, client_port, + socks5_udp_datagram(v6{ std::string{ "2001:db8::1" } }, 53, dns_message(0x1111))); + const auto [other_family_restore, other_family_origin] = classify(tracked_other_family, server_override, origins); + EXPECT_EQ(other_family_restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(other_family_origin.has_value()); + EXPECT_EQ(other_family_origin->ip, v4{ std::string{ "192.168.1.1" } }); } // 8. End to end: a relay that reports its own address as the answer's source still produces an @@ -467,6 +479,120 @@ TEST(DnsPacketRedirect, WithoutAnOverrideARelayReportingAnotherSourceIsStillRest EXPECT_EQ(classify_without_override(short_payload, origins).first, proxy::dns_reply_restore::unchanged); } +// 8. IPv6 without an override: the same restoration on the IPv6 path, with the arguments the +// router passes, including a relay-reported port of 0 that must not be compared with anything. +TEST(DnsPacketRedirect, Ipv6WithoutAnOverrideIsRestoredAndUnmatchedRepliesAreUnchanged) +{ + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + proxy::dns_udp_origin_tracker> origins; + + auto query = frame::udp6("fd00::10", "2001:4860:4860::8888", client_port, 53, dns_message(0x6262)); + origins.remember(client_port, 0x6262, net::ip_endpoint{ v6{ query.ip6()->ip6_dst }, 53 }); + ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); + + const auto answer = dns_message(0x6262, 40); + auto reply = local_proxy_reply("fd00::10", "2001:4860:4860::8888", v6{ std::string{ "2001:db8::7" } }, 1080, answer); + const auto [restore, origin] = classify_without_override(reply, origins); + ASSERT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); + EXPECT_EQ(v6{ reply.ip6()->ip6_src }, v6{ std::string{ "2001:4860:4860::8888" } }); + EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); + EXPECT_EQ(reply.payload(), answer); + EXPECT_TRUE(reply.l4_checksum_valid()); + + // Unmatched, with a reported source of all zeroes and port 0: unchanged, never dropped. + auto zero_source = local_proxy_reply("fd00::10", "2001:4860:4860::8888", v6{}, 0, dns_message(0x7777)); + EXPECT_EQ(classify_without_override(zero_source, origins).first, proxy::dns_reply_restore::unchanged); + auto zero_source_v4 = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{}, 0, dns_message(0x7777)); + proxy::dns_udp_origin_tracker> origins_v4; + EXPECT_EQ(classify_without_override(zero_source_v4, origins_v4).first, proxy::dns_reply_restore::unchanged); +} + +// 8. A relay that reports a source of the other address family. Its own address is IPv4 even +// for an IPv6 query, because SOCKS5 servers are reached over IPv4. A tracked answer is +// restored anyway, and the redirect strips the relay's header by its real size. +TEST(DnsPacketRedirect, TrackedAnswerIsRestoredWhenTheRelayHeaderHasTheOtherAddressFamily) +{ + const auto answer = dns_message(0x6363, 48); + + // IPv6 query, IPv4 relay header (10 bytes instead of 22). + { + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + proxy::dns_udp_origin_tracker> origins; + auto query = frame::udp6("fd00::10", "2001:4860:4860::8888", client_port, 53, dns_message(0x6363)); + origins.remember(client_port, 0x6363, net::ip_endpoint{ v6{ query.ip6()->ip6_dst }, 53 }); + ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); + + auto reply = frame::udp6("fd00::10", "2001:4860:4860::8888", udp_listener, client_port, + socks5_udp_datagram(v4{ std::string{ "198.51.100.7" } }, 1080, answer)); + const auto [restore, origin] = classify_without_override(reply, origins); + ASSERT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); + EXPECT_EQ(v6{ reply.ip6()->ip6_src }, v6{ std::string{ "2001:4860:4860::8888" } }); + EXPECT_EQ(v6{ reply.ip6()->ip6_dst }, v6{ std::string{ "fd00::10" } }); + EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); + EXPECT_EQ(ntohs(reply.udp()->th_dport), client_port); + EXPECT_EQ(reply.payload(), answer); + EXPECT_TRUE(reply.l4_checksum_valid()); + } + + // IPv4 query, IPv6 relay header (22 bytes instead of 10). + { + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + proxy::dns_udp_origin_tracker> origins; + auto query = frame::udp4("192.168.1.10", "8.8.8.8", client_port, 53, dns_message(0x6363)); + origins.remember(client_port, 0x6363, net::ip_endpoint{ v4{ query.ip4()->ip_dst }, 53 }); + ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); + + auto reply = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, + socks5_udp_datagram(v6{ std::string{ "2001:db8::7" } }, 1080, answer)); + const auto [restore, origin] = classify_without_override(reply, origins); + ASSERT_EQ(restore, proxy::dns_reply_restore::restore); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); + EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "8.8.8.8" } }); + EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); + EXPECT_EQ(reply.payload(), answer); + EXPECT_TRUE(reply.ip4_checksum_valid()); + EXPECT_TRUE(reply.l4_checksum_valid()); + } +} + +// A header of the other family is stripped only when the caller supplies the source to present. +// Without it, or when the header is not fully captured, the packet is rejected and left untouched. +TEST(DnsPacketRedirect, OtherFamilyRelayHeaderIsRejectedWithoutASuppliedSourceOrWhenTruncated) +{ + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + auto query = frame::udp4("192.168.1.10", "8.8.8.8", client_port, 53, dns_message(0x6464)); + ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); + const std::optional> queried{ net::ip_endpoint{ v4{ std::string{ "8.8.8.8" } }, 53 } }; + + // Not tracked, so no source is supplied: rejected, as before. + auto unsupplied = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, + socks5_udp_datagram(v6{ std::string{ "2001:db8::7" } }, 1080, dns_message(0x6464))); + const auto unsupplied_before = unsupplied.payload(); + EXPECT_FALSE(redirect.process_server_to_client_packet(unsupplied.buffer)); + EXPECT_EQ(unsupplied.payload(), unsupplied_before); + + // An IPv6 header announced by ATYP but cut short after the 4-byte prefix: rejected even + // with a supplied source, without reading or moving anything past the datagram. + auto truncated = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, + std::vector{ 0x00, 0x00, 0x00, 0x04, 0x20, 0x01, 0x0d, 0xb8 }); + const auto truncated_before = truncated.payload(); + EXPECT_FALSE(redirect.process_server_to_client_packet(truncated.buffer, queried)); + EXPECT_EQ(truncated.payload(), truncated_before); + + // Fewer bytes than the prefix, and an address type that is neither IPv4 nor IPv6. + auto tiny = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, std::vector{ 0x00, 0x00 }); + EXPECT_FALSE(redirect.process_server_to_client_packet(tiny.buffer, queried)); + auto domain = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, + std::vector{ 0x00, 0x00, 0x00, 0x03, 0x01, 'a', 0x00, 0x35, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); + EXPECT_FALSE(redirect.process_server_to_client_packet(domain.buffer, queried)); +} + // 8. A datagram that cannot be redirected is reported as such (the router then drops it rather // than passing it): here a near-MTU datagram that has no room for the SOCKS5 header. TEST(DnsPacketRedirect, UnredirectableUdpIsRejectedSoTheRouterDropsIt) From 4588035c951b684c684e7f5f64771803fe3d4a44 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 19:24:10 +0000 Subject: [PATCH 29/62] docs: correct the answer-restoration statements and three validation steps - configuration.md: restoration covers either address family; state what matching on client port and message ID implies (the last-queried server wins, and when a non-DNS datagram can be re-sourced); an unmatched datagram that names the server override is dropped, not delivered, and is one of the listener-reply drop causes. - gui.md: the large-answer step needs a server that sends large UDP answers and a tool that sets the EDNS buffer size, and the warning is logged once per service run; the relay-source step covers IPv6 resolvers; the SOCKS5-as-resolver command now names a host. --- docs/configuration.md | 9 +++++++-- docs/gui.md | 6 +++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 966c245..1871796 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -134,7 +134,7 @@ In DNS `Proxy` mode, DNS takes precedence over LAN bypass: a query addressed to ProxiFyre redirects a matched connection to a local listener and translates the listener's replies back before the application sees them. Two rules apply to every proxied connection, not only to DNS: -- **A reply that cannot be translated back is dropped.** A reply from a local listener is addressed to the original server only because redirection swapped the addresses, so it must never reach the network. It is dropped when its TCP connection or UDP endpoint is no longer tracked, when it is the first fragment of a fragmented reply, or when its SOCKS5 relay header is malformed or of the wrong address type. Earlier releases passed such packets toward the original server. The first such drop after the service starts is logged once as a warning, and a count is logged at `Info` level at most every five seconds while drops continue. Later fragments of a fragmented reply carry no ports, cannot be attributed to a listener, and are still passed. +- **A reply that cannot be translated back is dropped.** A reply from a local listener is addressed to the original server only because redirection swapped the addresses, so it must never reach the network. It is dropped when its TCP connection or UDP endpoint is no longer tracked, when it is the first fragment of a fragmented reply, when its SOCKS5 relay header is malformed or of the wrong address type, or, with a DNS `serverOverride`, when it names the override server but answers no outstanding query. Earlier releases passed such packets toward the original server. The first such drop after the service starts is logged once as a warning, and a count is logged at `Info` level at most every five seconds while drops continue. Later fragments of a fragmented reply carry no ports, cannot be attributed to a listener, and are still passed. - **A TCP connection is tracked through its whole close.** The FIN/ACK exchange is translated in both directions instead of reaching the real server. A reset (RST) ends the connection immediately; segments the local proxy had already sent when the reset arrived are dropped without the warning and are counted at `Debug` level only. A proxied TCP connection that stays idle for more than 5 minutes loses its redirect entry; see [Limitations](#limitations). @@ -178,7 +178,12 @@ Whether name resolution still succeeds after a drop depends on Windows: it retri Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. -For UDP, ProxiFyre remembers the server each redirected query was addressed to (by client port and DNS message ID, for 30 seconds) and presents the answer as coming from that server, whatever source address the SOCKS5 relay reports for it, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered, but some report another address, such as their own. This applies with or without a `serverOverride`. Datagrams relayed through the same proxy that match no outstanding query are delivered with the source the relay reports. +For UDP, ProxiFyre remembers the server each redirected query was addressed to (by client port and DNS message ID, for 30 seconds) and presents the answer as coming from that server, whatever source address the SOCKS5 relay reports for it, IPv4 or IPv6, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered, but some report another address, such as their own. This applies with or without a `serverOverride`. Two consequences follow from matching on the client port and message ID alone: + +- If one socket sends the same message ID to several servers, the answer is presented as coming from the server queried last. +- A datagram that is not a DNS answer is given a DNS server's address by mistake only if it arrives for a client port that sent a port-53 datagram in the last 30 seconds and its first two bytes equal that datagram's message ID. + +Datagrams relayed through the same proxy that match no outstanding query are delivered with the source the relay reports. The exception is a datagram that names the `serverOverride` server, which is dropped (see [Server override](#server-override)). If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. diff --git a/docs/gui.md b/docs/gui.md index e498149..5c018a2 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -171,8 +171,8 @@ The routing policy and the packet rewriting are covered by automated tests (`net 9. **DNS proxy unavailable at start.** Give the DNS proxy rule an endpoint that cannot be created (for example a host name that does not resolve) and start the service. Confirm the service starts, the log states that all DNS is blocked until the service is restarted, and no port-53 packet leaves the adapter. 10. **TCP close.** Run `Resolve-DnsName -TcpOnly` several times in `Proxy` mode. Confirm each lookup completes, that no FIN, ACK, or RST of those connections reaches the real DNS server, and that the log has no "dropped … DNS packet(s)" lines. 11. **Aborted connection.** Start a large download in a proxied application and cancel it. Confirm no segment from the local listener's port leaves the adapter and that the log has no "could not be translated back" warning. -12. **Large answer.** In `Proxy` mode request a UDP answer larger than about 1,460 bytes over IPv4 and over IPv6, for example with `dig +dnssec +bufsize=4096 DNSKEY org @`. Confirm the first fragment of the local listener's reply (the one that carries a UDP header from the listener's port) does not leave the adapter, and that the listener-reply warning is logged once. Later fragments may leave, and the UDP lookup itself is expected to fail. -13. **Relay source.** If the SOCKS5 server reports an address other than the queried DNS server as the source of UDP replies, confirm lookups succeed both without and with `serverOverride`. -14. **SOCKS5 server used as a resolver.** Send a lookup to the SOCKS5 server's own IP address (`Resolve-DnsName -Server `). Confirm the query goes through the proxy, not directly. If the server listens on TCP port 53 or returns a UDP relay on port 53, also confirm ProxiFyre still reaches it and the one-time `Info` line about the relay appears. +12. **Large answer.** In `Proxy` mode request a UDP answer larger than about 1,460 bytes over IPv4, and larger than about 1,430 bytes over IPv6, from a DNS server that sends UDP answers of that size (most public resolvers truncate them instead). `Resolve-DnsName` cannot request this; use a tool that sets the EDNS buffer size, such as BIND's `dig +dnssec +bufsize=4096 +ignore DNSKEY @`, which is not part of Windows. Confirm the first fragment of the local listener's reply (the one that carries a UDP header from the listener's port) does not leave the adapter. The listener-reply warning is logged if it has not been logged since the service started; otherwise only the `Info` count increases. Later fragments may leave, and the UDP lookup itself is expected to fail. +13. **Relay source.** If the SOCKS5 server reports an address other than the queried DNS server as the source of UDP replies (for example its own IPv4 address), confirm lookups succeed without and with `serverOverride`, to an IPv4 resolver and to an IPv6 resolver. +14. **SOCKS5 server used as a resolver.** Send a lookup to the SOCKS5 server's own IP address (`Resolve-DnsName example.com -Server -DnsOnly`). Confirm the query goes through the proxy, not directly. If the server listens on TCP port 53 or returns a UDP relay on port 53, also confirm ProxiFyre still reaches it and the one-time `Info` line about the relay appears. 15. **Limited mode.** Repeat step 2 in the optional unelevated console mode. 16. **GUI.** On the **Settings / Diagnostics** tab at 100% and 150% scaling, confirm the DNS routing group and the Uninstall button are reachable (scrolling is expected). Confirm Alt+M, Alt+P, and Alt+S focus the mode, proxy, and override fields; that the DNS proxy selection survives **Move Up**/**Move Down** and a reload; that **Duplicate** does not copy the id; and that removing the selected rule shows the missing id and fails validation. From 6db1725d6456a207ff039f74086b602577c8e9a4 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 19:35:10 +0000 Subject: [PATCH 30/62] docs: name the second kind of unmatched relayed datagram that is dropped An unmatched datagram whose relay header is of the other address family is dropped, not delivered; a header of the other family is accepted only for an answer to an outstanding DNS query. --- docs/configuration.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 1871796..c619305 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -134,7 +134,7 @@ In DNS `Proxy` mode, DNS takes precedence over LAN bypass: a query addressed to ProxiFyre redirects a matched connection to a local listener and translates the listener's replies back before the application sees them. Two rules apply to every proxied connection, not only to DNS: -- **A reply that cannot be translated back is dropped.** A reply from a local listener is addressed to the original server only because redirection swapped the addresses, so it must never reach the network. It is dropped when its TCP connection or UDP endpoint is no longer tracked, when it is the first fragment of a fragmented reply, when its SOCKS5 relay header is malformed or of the wrong address type, or, with a DNS `serverOverride`, when it names the override server but answers no outstanding query. Earlier releases passed such packets toward the original server. The first such drop after the service starts is logged once as a warning, and a count is logged at `Info` level at most every five seconds while drops continue. Later fragments of a fragmented reply carry no ports, cannot be attributed to a listener, and are still passed. +- **A reply that cannot be translated back is dropped.** A reply from a local listener is addressed to the original server only because redirection swapped the addresses, so it must never reach the network. It is dropped when its TCP connection or UDP endpoint is no longer tracked, when it is the first fragment of a fragmented reply, when its SOCKS5 relay header is malformed, when that header is of the other address family and the reply does not answer an outstanding DNS query, or, with a DNS `serverOverride`, when it names the override server but answers no outstanding query. Earlier releases passed such packets toward the original server. The first such drop after the service starts is logged once as a warning, and a count is logged at `Info` level at most every five seconds while drops continue. Later fragments of a fragmented reply carry no ports, cannot be attributed to a listener, and are still passed. - **A TCP connection is tracked through its whole close.** The FIN/ACK exchange is translated in both directions instead of reaching the real server. A reset (RST) ends the connection immediately; segments the local proxy had already sent when the reset arrived are dropped without the warning and are counted at `Debug` level only. A proxied TCP connection that stays idle for more than 5 minutes loses its redirect entry; see [Limitations](#limitations). @@ -183,7 +183,7 @@ For UDP, ProxiFyre remembers the server each redirected query was addressed to ( - If one socket sends the same message ID to several servers, the answer is presented as coming from the server queried last. - A datagram that is not a DNS answer is given a DNS server's address by mistake only if it arrives for a client port that sent a port-53 datagram in the last 30 seconds and its first two bytes equal that datagram's message ID. -Datagrams relayed through the same proxy that match no outstanding query are delivered with the source the relay reports. The exception is a datagram that names the `serverOverride` server, which is dropped (see [Server override](#server-override)). +Datagrams relayed through the same proxy that match no outstanding query are delivered with the source the relay reports. Two kinds are dropped instead: one that names the `serverOverride` server (see [Server override](#server-override)), and one whose relay header is of the other address family, such as an answer that arrives after its query's 30 seconds from a relay that reports its own IPv4 address for an IPv6 query. If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. From 022cfa36c27a793dd86a024cdc8072155d7369e3 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Thu, 12 Nov 2026 23:10:01 +0000 Subject: [PATCH 31/62] build: use wiresock/ndisapi as a submodule instead of a vendored copy Replace the copied include/ and ndisapi/ sources with a submodule of https://github.com/wiresock/ndisapi at external/ndisapi, pinned to fc03ee7 (master, the 3.6.2 SDK line with the 3.8.2 user-mode backports). The vendored copy was the 3.6.1 SDK plus the checksum backport. The pinned commit is a superset of it: its Common.h differs only by NDISRD_VERSION (3.6.2), comments, an SDK-side macro and the opt-in USER_IOCTLS block, so driver-facing structures and IOCTL codes are unchanged. ndisapi.cpp gains the upstream SDK fixes (reply and handle validation, staged filter tables, OID completion status, bounded event leases). ProxiFyre keeps its own ndisapi.lib project, now compiling the submodule sources, because the upstream project links the static CRT and names its output after the solution. socksify, the portable test harness and its checksum extraction now read from the submodule; CI checks out submodules for the build and test jobs; build docs say to run git submodule update --init. --- .github/copilot-instructions.md | 8 +- .github/workflows/main.yml | 1 + .github/workflows/native-tests.yml | 2 + .gitmodules | 3 + README.md | 2 + docs/gui.md | 1 + docs/installer.md | 1 + external/ndisapi | 1 + include/Common.h | 1011 ----- include/ndisapi.h | 387 -- ndisapi.lib/ndisapilib.vcxproj | 16 +- ndisapi.lib/ndisapilib.vcxproj.filters | 16 +- ndisapi/inet_checksum.h | 148 - ndisapi/iphlp.h | 220 - ndisapi/ndisapi.cpp | 4430 -------------------- ndisapi/ndisapi.rc | 100 - ndisapi/precomp.h | 46 - ndisapi/resource.h | 15 - netlib/README.md | 3 +- netlib/test/portable/run-portable-tests.sh | 13 +- netlib/test/portable/winshim/packet_env.h | 4 +- socksify/unmanaged.h | 4 +- 22 files changed, 46 insertions(+), 6386 deletions(-) create mode 100644 .gitmodules create mode 160000 external/ndisapi delete mode 100644 include/Common.h delete mode 100644 include/ndisapi.h delete mode 100644 ndisapi/inet_checksum.h delete mode 100644 ndisapi/iphlp.h delete mode 100644 ndisapi/ndisapi.cpp delete mode 100644 ndisapi/ndisapi.rc delete mode 100644 ndisapi/precomp.h delete mode 100644 ndisapi/resource.h diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index ec075bb..cb2a807 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -218,8 +218,8 @@ Create this file in the same directory as `ProxiFyre.exe`: - `.github/workflows/main.yml`: CI/CD build pipeline ### Include Directories -- `./include/`: Common headers (`Common.h`, `ndisapi.h`) -- `./ndisapi/`: NDIS API implementation +- `./external/ndisapi/`: Git submodule of [wiresock/ndisapi](https://github.com/wiresock/ndisapi) (Windows Packet Filter user-mode API). `include/` holds `Common.h` and `ndisapi.h`; `ndisapi/` holds the implementation. Run `git submodule update --init` after cloning. +- `./ndisapi.lib/`: ProxiFyre's static-library project that builds the submodule sources with the solution's CRT settings - `./netlib/`: Network utility C++ classes ## Common Tasks @@ -228,7 +228,7 @@ Create this file in the same directory as `ProxiFyre.exe`: ```bash # Root directory listing ls -la -# Output includes the engine, managed UI, native launcher, tests, MSI, bundle, both setup helpers, socksify, ndisapi.lib, include, netlib, scripts, docs, README.md, and socksify.sln +# Output includes the engine, managed UI, native launcher, tests, MSI, bundle, both setup helpers, socksify, ndisapi.lib, external (ndisapi submodule), netlib, scripts, docs, README.md, and socksify.sln # Key configuration files find . -name "*.json" -o -name "*.config" -o -name "packages.config" @@ -247,7 +247,7 @@ find . -name "*.cs" # Find C++ files find . -name "*.cpp" -o -name "*.h" -# Output: socksify/ and ndisapi/ directories contain C++ implementation +# Output: socksify/, netlib/ and the external/ndisapi/ submodule contain C++ implementation ``` ## Limitations diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index cb92767..23b7f7d 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -26,6 +26,7 @@ jobs: uses: actions/checkout@v7 with: persist-credentials: false + submodules: true - name: Add msbuild to PATH uses: microsoft/setup-msbuild@v3 diff --git a/.github/workflows/native-tests.yml b/.github/workflows/native-tests.yml index e557ea7..e97d9f2 100644 --- a/.github/workflows/native-tests.yml +++ b/.github/workflows/native-tests.yml @@ -21,6 +21,7 @@ jobs: uses: actions/checkout@v7 with: persist-credentials: false + submodules: true - name: Install compiler and test dependencies run: | @@ -46,6 +47,7 @@ jobs: uses: actions/checkout@v7 with: persist-credentials: false + submodules: true - name: Add msbuild to PATH uses: microsoft/setup-msbuild@v3 diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..d7fe683 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "external/ndisapi"] + path = external/ndisapi + url = https://github.com/wiresock/ndisapi.git diff --git a/README.md b/README.md index ef4c0a8..0349c8b 100644 --- a/README.md +++ b/README.md @@ -137,6 +137,8 @@ Set `socks5Transport` to `"TLS"` to protect the SOCKS5 TCP connection and UDP `A Development requires Visual Studio 2022 with the C++ and .NET desktop workloads, the v143 toolset, the .NET Framework 4.7.2 targeting pack, NuGet CLI, PowerShell 7, a .NET SDK, and the repository's vcpkg dependencies. +The Windows Packet Filter user-mode API (`ndisapi`) is the [`wiresock/ndisapi`](https://github.com/wiresock/ndisapi) repository, included as a Git submodule in `external/ndisapi`. Clone with `git clone --recurse-submodules`, or run `git submodule update --init` in an existing clone. GitHub's "Download ZIP" source archives do not include it. + The exact restore, Release build, test, and packaging commands are maintained in [docs/gui.md#build-and-test](docs/gui.md#build-and-test) and [docs/installer.md#building-installers](docs/installer.md#building-installers). The authoritative project version is `ProxiFyreReleaseVersion` in [Directory.Build.props](Directory.Build.props). ## License diff --git a/docs/gui.md b/docs/gui.md index 5c018a2..ec7ad79 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -89,6 +89,7 @@ Prerequisites are Visual Studio 2022 with the .NET Framework and C++ desktop wor From a Visual Studio developer shell: ```powershell +git submodule update --init # external/ndisapi (Windows Packet Filter API) nuget restore ProxiFyre.Configuration\packages.config -PackagesDirectory packages -NonInteractive nuget restore ProxiFyre\packages.config -PackagesDirectory packages -NonInteractive nuget restore ProxiFyre.Tests\packages.config -PackagesDirectory packages -NonInteractive diff --git a/docs/installer.md b/docs/installer.md index c46b4d2..9524950 100644 --- a/docs/installer.md +++ b/docs/installer.md @@ -231,6 +231,7 @@ Build prerequisites are Visual Studio 2022 with the C++ desktop and .NET Framewo From a Visual Studio developer shell: ```powershell +git submodule update --init # external/ndisapi (Windows Packet Filter API) nuget restore .\ProxiFyre.Configuration\packages.config -PackagesDirectory .\packages -NonInteractive nuget restore .\ProxiFyre\packages.config -PackagesDirectory .\packages -NonInteractive nuget restore .\ProxiFyre.Tests\packages.config -PackagesDirectory .\packages -NonInteractive diff --git a/external/ndisapi b/external/ndisapi new file mode 160000 index 0000000..fc03ee7 --- /dev/null +++ b/external/ndisapi @@ -0,0 +1 @@ +Subproject commit fc03ee7b42775cf3b109edd71d291fde0577c8ae diff --git a/include/Common.h b/include/Common.h deleted file mode 100644 index eb8c2c8..0000000 --- a/include/Common.h +++ /dev/null @@ -1,1011 +0,0 @@ -/**************************************************************************/ -/* Copyright (c) 2000-2024 NT KERNEL. */ -/* All Rights Reserved. */ -/* https://www.ntkernel.com */ -/* ndisrd@ntkernel.com */ -/* */ -/* Module Name: common.h */ -/* */ -/* Abstract: Definitions common to kernel-mode driver and Win32 app. */ -/* */ -/* Environment: */ -/* User mode, Kernel mode */ -/* */ -/* Description: This header file contains definitions and data structures */ -/* that are common to both the kernel-mode driver and the */ -/* Win32 application. This includes constants, structure */ -/* definitions, and function prototypes. */ -/* */ -/**************************************************************************/ - -#ifndef COMMON_H -#define COMMON_H - -#ifdef _WINDOWS -#include // Compiling Win32 Applications Or DLL's -#endif // _WINDOWS - -// The following definitions are used to customize the driver build -// In you would like to redefine these for the custom build do that in the user_settings.h file -#ifdef USER_NAMES -#include "user_settings.h" -#else - -// Define NDISRD name once in both ASCII and Unicode formats -#define NDISRD_NAME_A "NDISRD" -#define NDISRD_NAME_U L"NDISRD" - -// Define lowercase NDISRD name for registry paths -#define NDISRD_NAME_LOWER_A "ndisrd" -#define NDISRD_NAME_LOWER_U L"ndisrd" - -// FILTER_FRIENDLY_NAME is the friendly name of the NDISRD filter -#define FILTER_FRIENDLY_NAME L"WinpkFilter NDIS LightWeight Filter" - -// FILTER_UNIQUE_NAME is the unique name (GUID) of the NDISRD filter -#define FILTER_UNIQUE_NAME L"{CD75C963-E19F-4139-BC3B-14019EF72F19}" - -#endif // USER_NAMES - -#ifndef ANY_SIZE -#define ANY_SIZE 1 -#endif - -// NDISRD_VERSION is the version number of the NDISRD driver -#define NDISRD_VERSION 0x06013000 - -// NDISRD_MAJOR_VERSION is the major version number of the NDISRD driver -#define NDISRD_MAJOR_VERSION 0x0003 - -// NDISRD_MINOR_VERSION is the minor version number of the NDISRD driver -#define NDISRD_MINOR_VERSION 0x0601 - -// DRIVER_NAME_A is the ASCII name of the NDISRD driver -#define DRIVER_NAME_A NDISRD_NAME_A - -// DRIVER_NAME_U is the Unicode name of the NDISRD driver -#define DRIVER_NAME_U NDISRD_NAME_U - -// DEVICE_NAME is the device name of the NDISRD driver in the device namespace -#define DEVICE_PREFIX L"\\Device\\" -#define DEVICE_NAME DEVICE_PREFIX NDISRD_NAME_U - -// SYMLINK_NAME is the symbolic link name of the NDISRD driver in the DOS namespace -#define SYMLINK_PREFIX L"\\DosDevices\\" -#define SYMLINK_NAME SYMLINK_PREFIX NDISRD_NAME_U - -// WIN9X_REG_PARAM is the registry path for the NDISRD driver parameters on Windows 9x systems -#define WIN9X_REG_BASE "System\\CurrentControlSet\\Services\\VxD\\" -#define WIN9X_REG_PARAM WIN9X_REG_BASE NDISRD_NAME_LOWER_A "\\Parameters" - -// WINNT_REG_PARAM is the registry path for the NDISRD driver parameters on Windows NT systems -#define WINNT_REG_BASE TEXT("SYSTEM\\CurrentControlSet\\Services\\") -#define WINNT_REG_PARAM WINNT_REG_BASE TEXT(NDISRD_NAME_LOWER_A) TEXT("\\Parameters") - -// FILTER_SERVICE_NAME is the service name of the NDISRD filter -#define FILTER_SERVICE_NAME NDISRD_NAME_U - -// Some size constants -#define ADAPTER_NAME_SIZE 256 // Maximum size of the adapter name -#define ADAPTER_LIST_SIZE 32 // Maximum number of adapters in the list -#define ETHER_ADDR_LENGTH 6 // Length of the Ethernet address - -#ifdef JUMBO_FRAME_SUPPORTED -#define MAX_ETHER_FRAME 9014 // Maximum size of the Ethernet frame when Jumbo Frames are supported -#else -#define MAX_ETHER_FRAME 1514 // Maximum size of the Ethernet frame when Jumbo Frames are not supported -#endif - -// Adapter flags -#define MSTCP_FLAG_SENT_TUNNEL 0x00000001 // Flag to receive packets sent by MSTCP -#define MSTCP_FLAG_RECV_TUNNEL 0x00000002 // Flag to receive packets instead of MSTCP -#define MSTCP_FLAG_SENT_LISTEN 0x00000004 // Flag to receive packets sent by MSTCP, original ones delivered to the network -#define MSTCP_FLAG_RECV_LISTEN 0x00000008 // Flag to receive packets received by MSTCP - -#define MSTCP_FLAG_FILTER_DIRECT 0x00000010 // Flag to filter packets in promiscuous mode. - // In promiscuous mode, TCP/IP stack receives all packets in the ethernet segment. - // To prevent this, set this flag. - // All packets with destination MAC different from FF-FF-FF-FF-FF-FF and - // network interface current MAC will be blocked - -// By default, loopback packets are passed to original MSTCP handlers without processing. -// To change this behavior, use the flags below -#define MSTCP_FLAG_LOOPBACK_FILTER 0x00000020 // Flag to pass loopback packet for processing -#define MSTCP_FLAG_LOOPBACK_BLOCK 0x00000040 // Flag to silently drop loopback packets. - // This flag is recommended for usage in combination with promiscuous mode - -// Device flags for intermediate buffer -#define PACKET_FLAG_ON_SEND 0x00000001 // Flag to indicate packet is on send -#define PACKET_FLAG_ON_RECEIVE 0x00000002 // Flag to indicate packet is on receive - -// Specify Structure Packing -#pragma pack(push,1) - -/** - * @brief TCP_AdapterList structure is used for requesting information about currently bound TCPIP adapters. - * - * @param m_nAdapterCount This field stores the number of adapters. - * @param m_szAdapterNameList This is an array of adapter names. The size of the array is defined by the ADAPTER_LIST_SIZE constant, - * and each name is a string of characters with a maximum length defined by the ADAPTER_NAME_SIZE constant. - * @param m_nAdapterHandle This is an array of adapter handles. These handles are key for any adapter relative operation. - * @param m_nAdapterMediumList This is a list of adapter mediums. Each medium is represented as an unsigned integer. - * @param m_czCurrentAddress This is an array of current (configured) Ethernet addresses. Each address is represented as an array of bytes - * with a length defined by the ETHER_ADDR_LENGTH constant. - * @param m_usMTU This is an array of the current MTU (Maximum Transmission Unit) for each adapter. Each MTU is represented as an unsigned short. - */ -typedef struct _TCP_AdapterList -{ - DWORD m_nAdapterCount; - unsigned char m_szAdapterNameList[ADAPTER_LIST_SIZE][ADAPTER_NAME_SIZE]; - HANDLE m_nAdapterHandle[ADAPTER_LIST_SIZE]; - unsigned int m_nAdapterMediumList[ADAPTER_LIST_SIZE]; - unsigned char m_czCurrentAddress[ADAPTER_LIST_SIZE][ETHER_ADDR_LENGTH]; - unsigned short m_usMTU[ADAPTER_LIST_SIZE]; -} TCP_AdapterList, * PTCP_AdapterList; - -/** - * @brief TCP_AdapterList_WOW64 structure is similar to TCP_AdapterList, but it's used in a WOW64 environment. - * WOW64 is a subsystem of the Windows operating system capable of running 32-bit applications and is included on all 64-bit versions of Windows. - * In the TCP_AdapterList_WOW64 structure, the m_nAdapterHandle field is an array of ULARGE_INTEGER to accommodate the larger pointer size - * in a 64-bit environment. - * - * @param m_nAdapterCount This field stores the number of adapters. - * @param m_szAdapterNameList This is an array of adapter names. The size of the array is defined by the ADAPTER_LIST_SIZE constant, - * and each name is a string of characters with a maximum length defined by the ADAPTER_NAME_SIZE constant. - * @param m_nAdapterHandle This is an array of adapter handles. These handles are key for any adapter relative operation. - * @param m_nAdapterMediumList This is a list of adapter mediums. Each medium is represented as an unsigned integer. - * @param m_czCurrentAddress This is an array of current (configured) Ethernet addresses. Each address is represented as an array of bytes - * with a length defined by the ETHER_ADDR_LENGTH constant. - * @param m_usMTU This is an array of the current MTU (Maximum Transmission Unit) for each adapter. Each MTU is represented as an unsigned short. - */ -typedef struct _TCP_AdapterList_WOW64 -{ - DWORD m_nAdapterCount; - unsigned char m_szAdapterNameList[ADAPTER_LIST_SIZE][ADAPTER_NAME_SIZE]; - ULARGE_INTEGER m_nAdapterHandle[ADAPTER_LIST_SIZE]; - unsigned int m_nAdapterMediumList[ADAPTER_LIST_SIZE]; - unsigned char m_czCurrentAddress[ADAPTER_LIST_SIZE][ETHER_ADDR_LENGTH]; - unsigned short m_usMTU[ADAPTER_LIST_SIZE]; -} TCP_AdapterList_WOW64, * PTCP_AdapterList_WOW64; - -/** - * @brief INTERMEDIATE_BUFFER structure is used for storing packet data and related information. - * - * @param m_hAdapter/m_qLink This is a union of two fields. m_hAdapter is a handle to the adapter. m_qLink is a link to the next packet in the queue. - * @param m_dwDeviceFlags This field stores device-specific flags. These flags can be used to indicate whether the packet is on send or receive. - * @param m_Length This field stores the length of the packet. - * @param m_Flags This field stores NDIS_PACKET flags. These flags provide information about the packet, such as whether it's a loopback - * packet or a broadcast packet. - * @param m_8021q This field stores 802.1q information. 802.1q is a networking standard that supports virtual LANs (VLANs) on an Ethernet network. - * @param m_FilterID This field stores the filter ID. This can be used to identify the filter that the packet passed through. - * @param m_Reserved This field is reserved for future use. - * @param m_IBuffer This field is a buffer that contains the packet data. The size of the buffer is defined by the MAX_ETHER_FRAME constant. - */ -typedef struct _INTERMEDIATE_BUFFER -{ - union { - HANDLE m_hAdapter; - LIST_ENTRY m_qLink; - }; - DWORD m_dwDeviceFlags; - DWORD m_Length; - DWORD m_Flags; // NDIS_PACKET flags - DWORD m_8021q; // 802.1q info - DWORD m_FilterID; - DWORD m_Reserved[4]; - UCHAR m_IBuffer[MAX_ETHER_FRAME]; -} INTERMEDIATE_BUFFER, * PINTERMEDIATE_BUFFER; - -/** - * @brief INTERMEDIATE_BUFFER_WOW64 structure is similar to INTERMEDIATE_BUFFER, but it's used in a WOW64 environment. - * WOW64 is a subsystem of the Windows operating system capable of running 32-bit applications and is included on all 64-bit versions of Windows. - * In the INTERMEDIATE_BUFFER_WOW64 structure, the m_hAdapter and m_qLink fields are arrays of two handles to accommodate the larger pointer - * size in a 64-bit environment. - * - * @param m_hAdapter/m_qLink This is a union of two fields. m_hAdapter is a handle to the adapter. m_qLink is a link to the next packet in the queue. - * @param m_dwDeviceFlags This field stores device-specific flags. These flags can be used to indicate whether the packet is on send or receive. - * @param m_Length This field stores the length of the packet. - * @param m_Flags This field stores NDIS_PACKET flags. These flags provide information about the packet, such as whether it's a loopback packet - * or a broadcast packet. - * @param m_8021q This field stores 802.1q information. 802.1q is a networking standard that supports virtual LANs (VLANs) on an Ethernet network. - * @param m_FilterID This field stores the filter ID. This can be used to identify the filter that the packet passed through. - * @param m_Reserved This field is reserved for future use. - * @param m_IBuffer This field is a buffer that contains the packet data. The size of the buffer is defined by the MAX_ETHER_FRAME constant. - */ -typedef struct _INTERMEDIATE_BUFFER_WOW64 -{ - union { - HANDLE m_hAdapter[2]; - LIST_ENTRY m_qLink[2]; - }; - DWORD m_dwDeviceFlags; - DWORD m_Length; - DWORD m_Flags; // NDIS_PACKET flags - DWORD m_8021q; // 802.1q tag - DWORD m_FilterID; - DWORD m_Reserved[4]; - UCHAR m_IBuffer[MAX_ETHER_FRAME]; -} INTERMEDIATE_BUFFER_WOW64, * PINTERMEDIATE_BUFFER_WOW64; - -/** - * @brief NDISRD_ETH_Packet structure is a container for INTERMEDIATE_BUFFER pointer. - * This structure can be extended in future versions. - * - * @param Buffer This field is a pointer to an INTERMEDIATE_BUFFER structure that contains the packet data and related information. - */ -typedef struct _NDISRD_ETH_Packet -{ - PINTERMEDIATE_BUFFER Buffer; -} NDISRD_ETH_Packet, * PNDISRD_ETH_Packet; - -/** - * @brief NDISRD_ETH_Packet_WOW64 structure is similar to NDISRD_ETH_Packet, but it's used in a WOW64 environment. - * WOW64 is a subsystem of the Windows operating system capable of running 32-bit applications and is included on all 64-bit versions of Windows. - * - * @param Buffer This field is a ULARGE_INTEGER that contains the address of an INTERMEDIATE_BUFFER structure that contains the packet data - * and related information. - */ -typedef struct _NDISRD_ETH_Packet_WOW64 -{ - ULARGE_INTEGER Buffer; -} NDISRD_ETH_Packet_WOW64, * PNDISRD_ETH_Packet_WOW64; - -/** - * @brief ETH_REQUEST structure is used for both reading a single packet from the driver and sending packets to the driver. - * - * @param hAdapterHandle This field is a handle to the adapter. It's used to identify the adapter that the packet is being read from or sent to. - * @param EthPacket This field is an NDISRD_ETH_Packet structure that contains the packet data and related information. When reading, this - * structure will be filled with the packet data retrieved from the driver. When sending, this structure should be filled with the packet data to be sent. - */ -typedef struct _ETH_REQUEST -{ - HANDLE hAdapterHandle; - NDISRD_ETH_Packet EthPacket; -} ETH_REQUEST, * PETH_REQUEST; - -/** - * @brief ETH_REQUEST_WOW64 structure is similar to ETH_REQUEST, but it's used in a WOW64 environment. - * WOW64 is a subsystem of the Windows operating system capable of running 32-bit applications and is included on all 64-bit versions of Windows. - * In the ETH_REQUEST_WOW64 structure, the hAdapterHandle field is a ULARGE_INTEGER and the EthPacket field is an NDISRD_ETH_Packet_WOW64 structure - * to accommodate the larger pointer size in a 64-bit environment. - * - * @param hAdapterHandle This field is a ULARGE_INTEGER that represents a handle to the adapter. It's used to identify the adapter that the packet - * is being read from or sent to. - * @param EthPacket This field is an NDISRD_ETH_Packet_WOW64 structure that contains the packet data and related information. When reading, this - * structure will be filled with the packet data retrieved from the driver. When sending, this structure should be filled with the packet data to be sent. - */ -typedef struct _ETH_REQUEST_WOW64 -{ - ULARGE_INTEGER hAdapterHandle; - NDISRD_ETH_Packet_WOW64 EthPacket; -} ETH_REQUEST_WOW64, * PETH_REQUEST_WOW64; -/** - * @brief ETH_M_REQUEST structure is used for both reading multiple packets from the driver and sending multiple packets to the driver. - * - * @param hAdapterHandle This field is a handle to the adapter. It's used to identify the adapter that the packets are being read from or sent to. - * @param dwPacketsNumber This field stores the number of packets. - * @param dwPacketsSuccess This field stores the number of successfully processed packets. - * @param EthPacket This is an array of NDISRD_ETH_Packet structures that contain the packet data and related information. When reading, these - * structures will be filled with the packet data retrieved from the driver. When sending, these structures should be filled with the packet data - * to be sent. - */ -typedef struct _ETH_M_REQUEST -{ - HANDLE hAdapterHandle; - unsigned dwPacketsNumber; - unsigned dwPacketsSuccess; - NDISRD_ETH_Packet EthPacket[ANY_SIZE]; -} ETH_M_REQUEST, * PETH_M_REQUEST; - -/** - * @brief ETH_M_REQUEST_WOW64 structure is similar to ETH_M_REQUEST, but it's used in a WOW64 environment. - * WOW64 is a subsystem of the Windows operating system capable of running 32-bit applications and is included on all 64-bit versions of Windows. - * In the ETH_M_REQUEST_WOW64 structure, the hAdapterHandle field is a ULARGE_INTEGER and the EthPacket field is an array of NDISRD_ETH_Packet_WOW64 - * structures to accommodate the larger pointer size in a 64-bit environment. - * - * @param hAdapterHandle This field is a ULARGE_INTEGER that represents a handle to the adapter. It's used to identify the adapter that the packets - * are being read from or sent to. - * @param dwPacketsNumber This field stores the number of packets. - * @param dwPacketsSuccess This field stores the number of successfully processed packets. - * @param EthPacket This is an array of NDISRD_ETH_Packet_WOW64 structures that contain the packet data and related information. When reading, - * these structures will be filled with the packet data retrieved from the driver. When sending, these structures should be filled with the packet - * data to be sent. - */ -typedef struct _ETH_M_REQUEST_WOW64 -{ - ULARGE_INTEGER hAdapterHandle; - unsigned dwPacketsNumber; - unsigned dwPacketsSuccess; - NDISRD_ETH_Packet_WOW64 EthPacket[ANY_SIZE]; -} ETH_M_REQUEST_WOW64, * PETH_M_REQUEST_WOW64; - -/** - * @brief ADAPTER_MODE structure is used for setting the working mode of the network adapter. - * - * @param hAdapterHandle This field is a handle to the adapter. It's used to identify the adapter that the mode is being set for. - * @param dwFlags This field stores the mode flags. These flags determine the working mode of the adapter. The flags can be a combination of - * the following values: MSTCP_FLAG_SENT_TUNNEL, MSTCP_FLAG_RECV_TUNNEL, MSTCP_FLAG_SENT_LISTEN, MSTCP_FLAG_RECV_LISTEN, MSTCP_FLAG_FILTER_DIRECT, - * MSTCP_FLAG_TUNNEL, MSTCP_FLAG_LISTEN, and MSTCP_FLAG_FILTER. - */ -typedef struct _ADAPTER_MODE -{ - HANDLE hAdapterHandle; - DWORD dwFlags; -} ADAPTER_MODE, * PADAPTER_MODE; - -/** - * @brief ADAPTER_MODE_WOW64 structure is similar to ADAPTER_MODE, but it's used in a WOW64 environment. - * WOW64 is a subsystem of the Windows operating system capable of running 32-bit applications and is included on all 64-bit versions of Windows. - * In the ADAPTER_MODE_WOW64 structure, the hAdapterHandle field is a ULARGE_INTEGER to accommodate the larger pointer size in a 64-bit environment. - * - * @param hAdapterHandle This field is a ULARGE_INTEGER that represents a handle to the adapter. It's used to identify the adapter that the mode - * is being set for. - * @param dwFlags This field stores the mode flags. These flags determine the working mode of the adapter. The flags can be a combination of the - * following values: MSTCP_FLAG_SENT_TUNNEL, MSTCP_FLAG_RECV_TUNNEL, MSTCP_FLAG_SENT_LISTEN, MSTCP_FLAG_RECV_LISTEN, MSTCP_FLAG_FILTER_DIRECT, - * MSTCP_FLAG_TUNNEL, MSTCP_FLAG_LISTEN, and MSTCP_FLAG_FILTER. - */ -typedef struct _ADAPTER_MODE_WOW64 -{ - ULARGE_INTEGER hAdapterHandle; - DWORD dwFlags; -} ADAPTER_MODE_WOW64, * PADAPTER_MODE_WOW64; - -/** - * @brief ADAPTER_EVENT structure is used for setting up the event which driver sets once having packet in the queue for the processing. - * - * @param hAdapterHandle This field is a handle to the adapter. It's used to identify the adapter that the event is being set for. - * @param hEvent This field is a handle to the event that will be signaled when a packet is received. - */ -typedef struct _ADAPTER_EVENT -{ - HANDLE hAdapterHandle; - HANDLE hEvent; -} ADAPTER_EVENT, * PADAPTER_EVENT; - -/** - * @brief ADAPTER_EVENT_WOW64 structure is similar to ADAPTER_EVENT, but it's used in a WOW64 environment. - * WOW64 is a subsystem of the Windows operating system capable of running 32-bit applications and is included on all 64-bit versions of Windows. - * In the ADAPTER_EVENT_WOW64 structure, the hAdapterHandle and hEvent fields are ULARGE_INTEGER to accommodate the larger pointer size in a - * 64-bit environment. - * - * @param hAdapterHandle This field is a ULARGE_INTEGER that represents a handle to the adapter. It's used to identify the adapter that the - * event is being set for. - * @param hEvent This field is a ULARGE_INTEGER that represents a handle to the event that will be signaled when a packet is received. - */ -typedef struct _ADAPTER_EVENT_WOW64 -{ - ULARGE_INTEGER hAdapterHandle; - ULARGE_INTEGER hEvent; -} ADAPTER_EVENT_WOW64, * PADAPTER_EVENT_WOW64; - -/** - * @brief PACKET_OID_DATA structure is used for making query or set requests on the underlying network adapter driver. - * - * @param hAdapterHandle This field is a handle to the adapter. It's used to identify the adapter that the request is being made on. - * @param Oid This field stores the OID (Object Identifier) of the request. The OID is a code that identifies the network parameter that - * is being queried or set. - * @param Length This field stores the length of the data being queried or set. - * @param Data This is an array of bytes that contains the data being queried or set. The size of the array is defined by the ANY_SIZE constant. - */ -typedef struct _PACKET_OID_DATA -{ - HANDLE hAdapterHandle; - DWORD Oid; - DWORD Length; - UCHAR Data[ANY_SIZE]; -} PACKET_OID_DATA, * PPACKET_OID_DATA; - -/** - * @brief PACKET_OID_DATA_WOW64 structure is similar to PACKET_OID_DATA, but it's used in a WOW64 environment. - * WOW64 is a subsystem of the Windows operating system capable of running 32-bit applications and is included on all 64-bit versions of Windows. - * In the PACKET_OID_DATA_WOW64 structure, the hAdapterHandle field is a ULARGE_INTEGER to accommodate the larger pointer size in a - * 64-bit environment. - * - * @param hAdapterHandle This field is a ULARGE_INTEGER that represents a handle to the adapter. It's used to identify the adapter that - * the request is being made on. - * @param Oid This field stores the OID (Object Identifier) of the request. The OID is a code that identifies the network parameter that - * is being queried or set. - * @param Length This field stores the length of the data being queried or set. - * @param Data This is an array of bytes that contains the data being queried or set. The size of the array is defined by the ANY_SIZE constant. - */ -typedef struct _PACKET_OID_DATA_WOW64 -{ - ULARGE_INTEGER hAdapterHandle; - DWORD Oid; - DWORD Length; - UCHAR Data[ANY_SIZE]; -} PACKET_OID_DATA_WOW64, * PPACKET_OID_DATA_WOW64; - - -/** - * @brief RAS_LINK_INFO structure is used to provide information about a RAS (Remote Access Service) link. - * - * @param LinkSpeed This field stores the link speed in units of 100 bps. Zero indicates no change from the speed returned when the protocol - * called NdisRequest with OID_GEN_LINK_SPEED. - * @param MaximumTotalSize This field stores the maximum number of bytes per packet that the protocol can send over the network. Zero indicates - * no change from the value returned when the protocol called NdisRequest with OID_GEN_MAXIMUM_TOTAL_SIZE. - * @param RemoteAddress This field stores the remote address for the link in Ethernet-style format. NDISWAN supplies this value. - * @param LocalAddress This field stores the local address for the link in Ethernet-style format. - * @param ProtocolBufferLength This field specifies the number of bytes in the buffer at ProtocolBuffer. - * @param ProtocolBuffer This field is a buffer containing protocol-specific information supplied by a higher-level component that makes - * connections through NDISWAN to the appropriate protocol(s). Maximum observed size is 600 bytes on Windows Vista, 1200 on Windows 10. - */ -typedef struct _RAS_LINK_INFO -{ -#define RAS_LINK_BUFFER_LENGTH 2048 - DWORD LinkSpeed; - DWORD MaximumTotalSize; - UCHAR RemoteAddress[ETHER_ADDR_LENGTH]; - UCHAR LocalAddress[ETHER_ADDR_LENGTH]; - DWORD ProtocolBufferLength; - UCHAR ProtocolBuffer[RAS_LINK_BUFFER_LENGTH]; -} RAS_LINK_INFO, * PRAS_LINK_INFO; - -/** - * @brief RAS_LINKS structure is used to store an array of RAS_LINK_INFO structures. - * - * @param nNumberOfLinks This field stores the number of RAS_LINK_INFO structures in the RasLinks array. - * @param RasLinks This is an array of RAS_LINK_INFO structures. - */ -typedef struct _RAS_LINKS -{ -#define RAS_LINKS_MAX 256 - DWORD nNumberOfLinks; - RAS_LINK_INFO RasLinks[RAS_LINKS_MAX]; -} RAS_LINKS, * PRAS_LINKS; - -/********************************************************************************** - Static packet filter definitions -***********************************************************************************/ - -/** - * @brief ETH_802_3_FILTER structure is used to set the Ethernet 802.3 filter for the network adapter. - * - * @param m_ValidFields This field stores the valid fields flags. These flags determine which fields in the structure are valid. The flags - * can be a combination of the following values: ETH_802_3_SRC_ADDRESS, ETH_802_3_DEST_ADDRESS, ETH_802_3_PROTOCOL. - * @param m_SrcAddress This field stores the source address for the filter. It is an array of bytes representing the MAC address. - * @param m_DestAddress This field stores the destination address for the filter. It is an array of bytes representing the MAC address. - * @param m_Protocol This field stores the protocol for the filter. It is a 16-bit value representing the EtherType of the protocol. - */ -typedef struct _ETH_802_3_FILTER -{ -#define ETH_802_3_SRC_ADDRESS 0x00000001 -#define ETH_802_3_DEST_ADDRESS 0x00000002 -#define ETH_802_3_PROTOCOL 0x00000004 - DWORD m_ValidFields; // Specifies which of the fields below contain valid values and should be matched against the packet - unsigned char m_SrcAddress[ETHER_ADDR_LENGTH]; // Source MAC address - unsigned char m_DestAddress[ETHER_ADDR_LENGTH]; // Destination MAC address - unsigned short m_Protocol; // EtherType - unsigned short Padding; -} ETH_802_3_FILTER, * PETH_802_3_FILTER; - -/** - * @brief IP_SUBNET_V4 structure is used to represent an IPv4 subnet. - * - * @param m_Ip This field stores the IPv4 address expressed as an DWORD. - * @param m_IpMask This field stores the IPv4 subnet mask expressed as an DWORD. - */ -typedef struct _IP_SUBNET_V4 -{ - DWORD m_Ip; // IPv4 address expressed as DWORD - DWORD m_IpMask; // IPv4 mask expressed as DWORD -} IP_SUBNET_V4, * PIP_SUBNET_V4; - -/** - * @brief IP_RANGE_V4 structure is used to represent a range of IPv4 addresses. - * - * @param m_StartIp This field stores the starting IPv4 address of the range expressed as an DWORD. - * @param m_EndIp This field stores the ending IPv4 address of the range expressed as an DWORD. - */ -typedef struct _IP_RANGE_V4 -{ - DWORD m_StartIp; // Start of IPv4 address range expressed as DWORD - DWORD m_EndIp; // End of IPv4 address range expressed as DWORD -} IP_RANGE_V4, * PIP_RANGE_V4; - -/** - * @brief IP_ADDRESS_V4 structure is used to represent an IPv4 address which can be either a subnet or a range. - * - * @param m_AddressType This field specifies the type of the IPv4 address. It can be either IP_SUBNET_V4_TYPE or IP_RANGE_V4_TYPE. - * @param m_IpSubnet This field is an IP_SUBNET_V4 structure that represents an IPv4 subnet. - * @param m_IpRange This field is an IP_RANGE_V4 structure that represents a range of IPv4 addresses. - */ -typedef struct _IP_ADDRESS_V4 -{ -#define IP_SUBNET_V4_TYPE 0x00000001 -#define IP_RANGE_V4_TYPE 0x00000002 - DWORD m_AddressType; // Specifies which of the IP v4 address types is used below - union - { - IP_SUBNET_V4 m_IpSubnet; - IP_RANGE_V4 m_IpRange; - }; -} IP_ADDRESS_V4, * PIP_ADDRESS_V4; - -/** - * @brief IP_V4_FILTER structure is used to set the IPv4 filter for the network adapter. - * - * @param m_ValidFields This field stores the valid fields flags. These flags determine which fields in the structure are valid. The flags - * can be a combination of the following values: IP_V4_FILTER_SRC_ADDRESS, IP_V4_FILTER_DEST_ADDRESS, IP_V4_FILTER_PROTOCOL. - * @param m_SrcAddress This field is an IP_ADDRESS_V4 structure that stores the source address for the filter. - * @param m_DestAddress This field is an IP_ADDRESS_V4 structure that stores the destination address for the filter. - * @param m_Protocol This field stores the protocol for the filter. It is an unsigned char representing the protocol number. - */ -typedef struct _IP_V4_FILTER -{ -#define IP_V4_FILTER_SRC_ADDRESS 0x00000001 -#define IP_V4_FILTER_DEST_ADDRESS 0x00000002 -#define IP_V4_FILTER_PROTOCOL 0x00000004 - DWORD m_ValidFields; // Specifies which of the fields below contain valid values and should be matched against the packet - IP_ADDRESS_V4 m_SrcAddress; // IP v4 source address - IP_ADDRESS_V4 m_DestAddress; // IP v4 destination address - unsigned char m_Protocol; // Specifies next protocol - unsigned char Padding[3]; -} IP_V4_FILTER, * PIP_V4_FILTER; - -/** - * @brief IP_SUBNET_V6 structure is used to represent an IPv6 subnet. - * - * @param m_Ip This field stores the IPv6 address expressed as an IN6_ADDR structure. - * @param m_IpMask This field stores the IPv6 subnet mask expressed as an IN6_ADDR structure. - */ -typedef struct _IP_SUBNET_V6 -{ - IN6_ADDR m_Ip; // IPv6 address - IN6_ADDR m_IpMask; // IPv6 mask -} IP_SUBNET_V6, * PIP_SUBNET_V6; - -/** - * @brief IP_RANGE_V6 structure is used to represent a range of IPv6 addresses. - * - * @param m_StartIp This field stores the starting IPv6 address of the range expressed as an IN6_ADDR structure. - * @param m_EndIp This field stores the ending IPv6 address of the range expressed as an IN6_ADDR structure. - */ -typedef struct _IP_RANGE_V6 -{ - IN6_ADDR m_StartIp; // Start of IPv6 address range - IN6_ADDR m_EndIp; // End of IPv6 address range -} IP_RANGE_V6, * PIP_RANGE_V6; - -/** - * @brief IP_ADDRESS_V6 structure is used to represent an IPv6 address which can be either a subnet or a range. - * - * @param m_AddressType This field specifies the type of the IPv6 address. It can be either IP_SUBNET_V6_TYPE or IP_RANGE_V6_TYPE. - * @param m_IpSubnet This field is an IP_SUBNET_V6 structure that represents an IPv6 subnet. - * @param m_IpRange This field is an IP_RANGE_V6 structure that represents a range of IPv6 addresses. - */ -typedef struct _IP_ADDRESS_V6 -{ -#define IP_SUBNET_V6_TYPE 0x00000001 -#define IP_RANGE_V6_TYPE 0x00000002 - DWORD m_AddressType; // Specifies which of the IP v6 address types is used below - union - { - IP_SUBNET_V6 m_IpSubnet; - IP_RANGE_V6 m_IpRange; - }; -} IP_ADDRESS_V6, * PIP_ADDRESS_V6; - -/** - * @brief IP_V6_FILTER structure is used to set the IPv6 filter for the network adapter. - * - * @param m_ValidFields This field stores the valid fields flags. These flags determine which fields in the structure are valid. The flags - * can be a combination of the following values: IP_V6_FILTER_SRC_ADDRESS, IP_V6_FILTER_DEST_ADDRESS, IP_V6_FILTER_PROTOCOL. - * @param m_SrcAddress This field is an IP_ADDRESS_V6 structure that stores the source address for the filter. - * @param m_DestAddress This field is an IP_ADDRESS_V6 structure that stores the destination address for the filter. - * @param m_Protocol This field stores the protocol for the filter. It is an unsigned char representing the protocol number. - */ -typedef struct _IP_V6_FILTER -{ -#define IP_V6_FILTER_SRC_ADDRESS 0x00000001 -#define IP_V6_FILTER_DEST_ADDRESS 0x00000002 -#define IP_V6_FILTER_PROTOCOL 0x00000004 - DWORD m_ValidFields; // Specifies which of the fields below contain valid values and should be matched against the packet - IP_ADDRESS_V6 m_SrcAddress; // IP v6 source address - IP_ADDRESS_V6 m_DestAddress; // IP v6 destination address - unsigned char m_Protocol; // Specifies next protocol - unsigned char Padding[3]; -} IP_V6_FILTER, * PIP_V6_FILTER; - -/** - * @brief PORT_RANGE structure is used to represent a range of ports. - * - * @param m_StartRange This field stores the starting port of the range. It is an unsigned short. The port is specified in host byte order. - * @param m_EndRange This field stores the ending port of the range. It is also an unsigned short. The port is specified in host byte order. - */ -typedef struct _PORT_RANGE -{ - unsigned short m_StartRange; // Starting port of the range in host byte order - unsigned short m_EndRange; // Ending port of the range in host byte order -} PORT_RANGE, * PPORT_RANGE; - -/** - * @brief TCPUDP_FILTER structure is used to set the TCP/UDP filter for the network adapter. - * - * @param m_ValidFields This field stores the valid fields flags. These flags determine which fields in the structure are valid. The flags - * can be a combination of the following values: TCPUDP_SRC_PORT, TCPUDP_DEST_PORT, TCPUDP_TCP_FLAGS. - * @param m_SourcePort This field is a PORT_RANGE structure that stores the source port range for the filter. - * @param m_DestPort This field is a PORT_RANGE structure that stores the destination port range for the filter. - * @param m_TCPFlags This field stores the TCP flags for the filter. It is an unsigned char representing the TCP flags combination. - */ -typedef struct _TCPUDP_FILTER -{ -#define TCPUDP_SRC_PORT 0x00000001 -#define TCPUDP_DEST_PORT 0x00000002 -#define TCPUDP_TCP_FLAGS 0x00000004 - DWORD m_ValidFields; // Specifies which of the fields below contain valid values and should be matched against the packet - PORT_RANGE m_SourcePort; // Source port - PORT_RANGE m_DestPort; // Destination port - unsigned char m_TCPFlags; // TCP flags combination - unsigned char Padding[3]; -} TCPUDP_FILTER, * PTCPUDP_FILTER; - -/** - * @brief BYTE_RANGE structure is used to represent a range of bytes. - * - * @param m_StartRange This field stores the starting byte of the range. It is an unsigned char. - * @param m_EndRange This field stores the ending byte of the range. It is also an unsigned char. - */ -typedef struct _BYTE_RANGE -{ - unsigned char m_StartRange; // Starting byte of the range - unsigned char m_EndRange; // Ending byte of the range -} BYTE_RANGE, * PBYTE_RANGE; - -/** - * @brief ICMP_FILTER structure is used to set the ICMP filter for the network adapter. - * - * @param m_ValidFields This field stores the valid fields flags. These flags determine which fields in the structure are valid. The flags - * can be a combination of the following values: ICMP_TYPE, ICMP_CODE. - * @param m_TypeRange This field is a BYTE_RANGE structure that stores the ICMP Type range for the filter. - * @param m_CodeRange This field is a BYTE_RANGE structure that stores the ICMP Code range for the filter. - */ -typedef struct _ICMP_FILTER -{ -#define ICMP_TYPE 0x00000001 -#define ICMP_CODE 0x00000002 - DWORD m_ValidFields; // Specifies which of the fields below contain valid values and should be matched against the packet - BYTE_RANGE m_TypeRange; // ICMP Type range - BYTE_RANGE m_CodeRange; // ICMP Code range -} ICMP_FILTER, * PICMP_FILTER; - -/** - * @brief DATA_LINK_LAYER_FILTER structure is used to set the data link layer filter for the network adapter. - * - * @param m_dwUnionSelector This field stores the valid fields flags. These flags determine which fields in the structure are valid. The flags - * can be a combination of the following values: ETH_802_3. - * @param m_Eth8023Filter This field is an ETH_802_3_FILTER structure that stores the Ethernet 802.3 filter. - */ -typedef struct _DATA_LINK_LAYER_FILTER -{ -#define ETH_802_3 0x00000001 - DWORD m_dwUnionSelector; // Specifies which of the fields below contain valid values and should be matched against the packet - union - { - ETH_802_3_FILTER m_Eth8023Filter; // Ethernet 802.3 filter - }; -} DATA_LINK_LAYER_FILTER, * PDATA_LINK_LAYER_FILTER; - -/** - * @brief NETWORK_LAYER_FILTER structure is used to set the network layer filter for the network adapter. - * - * @param m_dwUnionSelector This field stores the valid fields flags. These flags determine which fields in the structure are valid. The flags - * can be a combination of the following values: IPV4, IPV6. - * @param m_IPv4 This field is an IP_V4_FILTER structure that stores the IPv4 filter. - * @param m_IPv6 This field is an IP_V6_FILTER structure that stores the IPv6 filter. - */ -typedef struct _NETWORK_LAYER_FILTER -{ -#define IPV4 0x00000001 -#define IPV6 0x00000002 - DWORD m_dwUnionSelector; // Specifies which of the fields below contain valid values and should be matched against the packet - union - { - IP_V4_FILTER m_IPv4; // IPv4 filter - IP_V6_FILTER m_IPv6; // IPv6 filter - }; -} NETWORK_LAYER_FILTER, * PNETWORK_LAYER_FILTER; - -/** - * @brief TRANSPORT_LAYER_FILTER structure is used to set the transport layer filter for the network adapter. - * - * @param m_dwUnionSelector This field stores the valid fields flags. These flags determine which fields in the structure are valid. The flags - * can be a combination of the following values: TCPUDP, ICMP. - * @param m_TcpUdp This field is a TCPUDP_FILTER structure that stores the TCP/UDP filter. - * @param m_Icmp This field is an ICMP_FILTER structure that stores the ICMP filter. - */ -typedef struct _TRANSPORT_LAYER_FILTER -{ -#define TCPUDP 0x00000001 -#define ICMP 0x00000002 - DWORD m_dwUnionSelector; // Specifies which of the fields below contain valid values and should be matched against the packet - union - { - TCPUDP_FILTER m_TcpUdp; // TCP/UDP filter - ICMP_FILTER m_Icmp; // ICMP filter - }; -} TRANSPORT_LAYER_FILTER, * PTRANSPORT_LAYER_FILTER; - -/** - * @brief STATIC_FILTER structure is used to define a static filter for the network adapter. - * - * @param m_Adapter This field is a handle to the adapter. It's used to identify the adapter that the filter is associated with. - * @param m_dwDirectionFlags This field stores direction flags. These flags can be used to indicate whether the filter applies to sent packets, - * received packets, or both. - * @param m_FilterAction This field specifies the action to be taken when the filter conditions are met. It can be one of the following values: - * FILTER_PACKET_PASS, FILTER_PACKET_DROP, FILTER_PACKET_REDIRECT, FILTER_PACKET_PASS_RDR, FILTER_PACKET_DROP_RDR. - * @param m_ValidFields This field stores the valid fields flags. These flags determine which fields in the structure are valid. The flags can - * be a combination of the following values: DATA_LINK_LAYER_VALID, NETWORK_LAYER_VALID, TRANSPORT_LAYER_VALID. - * @param m_LastReset This field stores the time of the last counters reset in seconds passed since 1 Jan 1980. - * @param m_PacketsIn This field stores the number of incoming packets that passed through this filter. - * @param m_BytesIn This field stores the number of incoming bytes that passed through this filter. - * @param m_PacketsOut This field stores the number of outgoing packets that passed through this filter. - * @param m_BytesOut This field stores the number of outgoing bytes that passed through this filter. - * @param m_DataLinkFilter This field is a DATA_LINK_LAYER_FILTER structure that stores the data link layer filter. - * @param m_NetworkFilter This field is a NETWORK_LAYER_FILTER structure that stores the network layer filter. - * @param m_TransportFilter This field is a TRANSPORT_LAYER_FILTER structure that stores the transport layer filter. - */ -typedef struct _STATIC_FILTER -{ -#define FILTER_PACKET_PASS 0x00000001 // Pass packet if it matches the filter -#define FILTER_PACKET_DROP 0x00000002 // Drop packet if it matches the filter -#define FILTER_PACKET_REDIRECT 0x00000003 // Redirect packet to WinpkFilter client application -#define FILTER_PACKET_PASS_RDR 0x00000004 // Redirect packet to WinpkFilter client application and pass over network (listen mode) -#define FILTER_PACKET_DROP_RDR 0x00000005 // Redirect packet to WinpkFilter client application and drop it, e.g. log but remove from the flow (listen mode) - -#define DATA_LINK_LAYER_VALID 0x00000001 // Match packet against data link layer filter -#define NETWORK_LAYER_VALID 0x00000002 // Match packet against network layer filter -#define TRANSPORT_LAYER_VALID 0x00000004 // Match packet against transport layer filter - - ULARGE_INTEGER m_Adapter; // Adapter handle extended to 64 bit size for structure compatibility across x64 and x86 - DWORD m_dwDirectionFlags; // PACKET_FLAG_ON_SEND or/and PACKET_FLAG_ON_RECEIVE - DWORD m_FilterAction; // FILTER_PACKET_XXX - DWORD m_ValidFields; // Specifies which of the fields below contain valid values and should be matched against the packet - - // Statistics for the filter - DWORD m_LastReset; // Time of the last counters reset (in seconds passed since 1 Jan 1980) - ULARGE_INTEGER m_PacketsIn; // Incoming packets passed through this filter - ULARGE_INTEGER m_BytesIn; // Incoming bytes passed through this filter - ULARGE_INTEGER m_PacketsOut; // Outgoing packets passed through this filter - ULARGE_INTEGER m_BytesOut; // Outgoing bytes passed through this filter - - DATA_LINK_LAYER_FILTER m_DataLinkFilter; - NETWORK_LAYER_FILTER m_NetworkFilter; - TRANSPORT_LAYER_FILTER m_TransportFilter; -} STATIC_FILTER, * PSTATIC_FILTER; - -/** - * @brief Defines a table of static filters to be applied on network traffic. - * - * This structure is used to hold a collection of static filters that determine how network packets are processed. - * Each filter in the table can specify actions like pass, drop, or redirect packets based on various criteria such as - * source and destination IP addresses, port numbers, and protocol types. The table size is dynamic, allowing for - * a variable number of filters to be defined based on the needs of the application. - * - * @param m_TableSize The number of STATIC_FILTER entries in the table. This determines the number of filters - * currently defined and active for processing network packets. - * @param Padding Reserved for future use, ensuring proper alignment of the structure in memory. - * @param m_StaticFilters An array of STATIC_FILTER structures, each defining a specific filter with its own - * set of criteria and actions. The size of this array is determined by m_TableSize. - */ -typedef struct _STATIC_FILTER_TABLE -{ - DWORD m_TableSize; // number of STATIC_FILTER entries - DWORD Padding; - STATIC_FILTER m_StaticFilters[ANY_SIZE]; -} STATIC_FILTER_TABLE, * PSTATIC_FILTER_TABLE; - -/** - * @brief Structure to define a static filter with a specific insertion position. - * - * This structure combines a STATIC_FILTER with a position value to specify where in the filter list the static filter should be inserted. - * The position determines the order of filter application, with lower values indicating higher priority. This allows for precise control - * over the packet filtering process, enabling the insertion of filters at specific points in the filter chain. - * - * @param m_Position The position in the filter list where the new filter should be inserted. Filters are processed in ascending order based - * on this value. - * @param m_StaticFilter The STATIC_FILTER structure that defines the filter criteria and actions. This includes details such as the direction - * of traffic to filter, the protocol to filter, and the action to take when a packet matches the filter criteria. - */ -typedef struct _STATIC_FILTER_WITH_POSITION -{ - unsigned long m_Position; // position to insert new filter - STATIC_FILTER m_StaticFilter; -} STATIC_FILTER_WITH_POSITION, * PSTATIC_FILTER_WITH_POSITION; - -/********************************************************************************** - Fast I/O structures definitions -***********************************************************************************/ - -/** - * @brief FAST_IO_WRITE_UNION structure is used to store the number of packets and the write-in-progress flag in a union. - * - * @param union_ This is a union of two fields. The split field is a structure that contains the number_of_packets and write_in_progress_flag fields. - * The join field is an DWORD that can store the combined value of the two fields in the split structure. - */ -typedef struct _FAST_IO_WRITE_UNION { - union { - struct { - USHORT number_of_packets; - USHORT write_in_progress_flag; - } split; - DWORD join; - } union_; -}FAST_IO_WRITE_UNION, * PFAST_IO_WRITE_UNION; - -/** - * @brief FAST_IO_SECTION_HEADER structure is used to store the fast I/O write union and the read in progress flag. - * - * @param fast_io_write_union This field is a FAST_IO_WRITE_UNION structure that stores the number of packets and the write-in-progress flag. - * @param read_in_progress_flag This field is an DWORD that stores the read in progress flag. - */ -typedef struct _FAST_IO_SECTION_HEADER { - FAST_IO_WRITE_UNION fast_io_write_union; - DWORD read_in_progress_flag; -} FAST_IO_SECTION_HEADER, * PFAST_IO_SECTION_HEADER; - -/** - * @brief FAST_IO_SECTION structure is used to store the fast I/O section header and the fast I/O packets. - * - * @param fast_io_header This field is a volatile FAST_IO_SECTION_HEADER structure that stores the fast I/O write union and the - * read-in-progress flag. - * @param fast_io_packets This field is an array of INTERMEDIATE_BUFFER structures that store the fast I/O packets. The size of the array - * is defined by the ANY_SIZE constant. - */ -typedef struct _FAST_IO_SECTION -{ - volatile FAST_IO_SECTION_HEADER fast_io_header; - INTERMEDIATE_BUFFER fast_io_packets[ANY_SIZE]; -} FAST_IO_SECTION, * PFAST_IO_SECTION; - -/** - * @brief INITIALIZE_FAST_IO_PARAMS structure is used to store the header pointer and the data size for initializing fast I/O. - * - * @param header_ptr This field is a pointer to a FAST_IO_SECTION structure that stores the fast I/O section header and the fast I/O packets. - * @param data_size This field is an DWORD that stores the data size. - */ -typedef struct _INITIALIZE_FAST_IO_PARAMS -{ - PFAST_IO_SECTION header_ptr; - DWORD data_size; -}INITIALIZE_FAST_IO_PARAMS, * PINITIALIZE_FAST_IO_PARAMS; - -/********************************************************************************** - Unsorted Read/Send packets -***********************************************************************************/ - -/** - * @brief UNSORTED_READ_SEND_REQUEST structure is used for storing an array of packets for reading or sending. - * - * @param packets This field is a pointer to an array of PINTERMEDIATE_BUFFER structures. Each PINTERMEDIATE_BUFFER structure contains the - * packet data and related information. - * @param packets_num This field stores the number of packets in the array. - */ -typedef struct _UNSORTED_READ_SEND_REQUEST -{ - PINTERMEDIATE_BUFFER* packets; - DWORD packets_num; -} UNSORTED_READ_SEND_REQUEST, * PUNSORTED_READ_SEND_REQUEST; - -// Restore Default Structure Packing -#pragma pack(pop) - -/********************************************************************************** - Standard IOCTL Codes For NDIS Packet Redirector Driver -***********************************************************************************/ - -#define FILE_DEVICE_NDISRD 0x00008300 -#define NDISRD_IOCTL_INDEX 0x830 - -#define IOCTL_NDISRD_GET_VERSION\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_GET_TCPIP_INTERFACES\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+1, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SEND_PACKET_TO_ADAPTER\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+2, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SEND_PACKET_TO_MSTCP\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+3, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_READ_PACKET\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+4, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SET_ADAPTER_MODE\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+5, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_FLUSH_ADAPTER_QUEUE\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+6, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SET_EVENT\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+7, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_NDIS_SET_REQUEST\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+8, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_NDIS_GET_REQUEST\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+9, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SET_WAN_EVENT\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+10, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SET_ADAPTER_EVENT\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+11, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_ADAPTER_QUEUE_SIZE\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+12, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_GET_ADAPTER_MODE\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+13, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SET_PACKET_FILTERS\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+14, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_RESET_PACKET_FILTERS\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+15, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_GET_PACKET_FILTERS_TABLESIZE\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+16, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_GET_PACKET_FILTERS\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+17, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_GET_PACKET_FILTERS_RESET_STATS\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+18, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_GET_RAS_LINKS\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+19, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SEND_PACKETS_TO_ADAPTER\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+20, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SEND_PACKETS_TO_MSTCP\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+21, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_READ_PACKETS\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+22, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SET_ADAPTER_HWFILTER_EVENT\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+23, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_INITIALIZE_FAST_IO\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+24, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_READ_PACKETS_UNSORTED\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+25, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SEND_PACKET_TO_ADAPTER_UNSORTED\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+26, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SEND_PACKET_TO_MSTCP_UNSORTED\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+27, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_ADD_SECOND_FAST_IO_SECTION\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+28, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_QUERY_IB_POOL_SIZE\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+29, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_ADD_PACKET_FILTER_FRONT\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+30, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_ADD_PACKET_FILTER_BACK\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+31, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_REMOVE_FILTER_BY_INDEX\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+32, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_GET_ADP_FILTERS_LIST\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+33, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_INSERT_FILTER_BY_INDEX\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+34, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SET_FILTER_CACHE_STATE\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+35, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#define IOCTL_NDISRD_SET_FRAGMENT_CACHE_STATE\ - CTL_CODE(FILE_DEVICE_NDISRD, NDISRD_IOCTL_INDEX+36, METHOD_BUFFERED, FILE_ANY_ACCESS) - -#endif // COMMON_H \ No newline at end of file diff --git a/include/ndisapi.h b/include/ndisapi.h deleted file mode 100644 index 75b7872..0000000 --- a/include/ndisapi.h +++ /dev/null @@ -1,387 +0,0 @@ -/*************************************************************************/ -/* Copyright (c) 2000-2024 NT KERNEL. */ -/* All Rights Reserved. */ -/* https://www.ntkernel.com */ -/* ndisrd@ntkernel.com */ -/* */ -/* Module Name: ndisapi.h */ -/* */ -/* Description: API exported C++ class and C API declarations */ -/* */ -/* Environment: */ -/* User mode */ -/* */ -/*************************************************************************/ -#pragma once - -#ifdef _LIB // must be defined when linking static library version of ndisapi.dll -#define NDISAPI_API -#else -// The following ifdef block is the standard way of creating macros which make exporting -// from a DLL simpler. All files within this DLL are compiled with the NDISAPI_EXPORTS -// symbol defined on the command line. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see -// NDISAPI_API functions as being imported from a DLL, whereas this DLL sees symbols -// defined with this macro as being exported. -#ifdef NDISAPI_EXPORTS -#define NDISAPI_API __declspec(dllexport) -#else -#define NDISAPI_API __declspec(dllimport) -#endif //NDISAPI_EXPORTS -#endif //_LIB - -#if _MSC_VER >= 1700 -#ifdef _USING_V110_SDK71_ -#define _USE_LEGACY_VERSION_INFO -#endif //_USING_V110_SDK71_ -#endif // _MSC_VER - -#if _MSC_VER < 1700 -#define _USE_LEGACY_VERSION_INFO -#endif //_MSC_VER - -#ifndef _USE_LEGACY_VERSION_INFO // Use VersionHelpers for 2012 and later toolsets only -#include -#endif // _USE_LEGACY_VERSION_INFO - -enum -{ - FILE_NAME_SIZE = 1000 -}; - -typedef BOOL(__stdcall* IsWow64ProcessPtr)(HANDLE hProcess, PBOOL Wow64Process); - -/** - * @struct CVersionInfo - * @brief An extension of the OSVERSIONINFO structure for retrieving and - * comparing operating system version information. - * - * This structure provides a set of functions to check whether the current - * operating system version is equal to or greater than a specific version, - * such as Windows XP, Windows 7, or Windows 10. - * - * Usage: - * CVersionInfo versionInfo; - * if (versionInfo.IsWindows7OrGreater()) { - * // Code for Windows 7 or later - * } - */ -struct NDISAPI_API CVersionInfo : private OSVERSIONINFO -{ -#ifdef _USE_LEGACY_VERSION_INFO - /** - * @brief Constructor that initializes the OSVERSIONINFO structure. - */ - CVersionInfo() - { - dwOSVersionInfoSize = sizeof(OSVERSIONINFO); - ::GetVersionEx(this); - } - - /** - * @brief Checks if the operating system is Windows Vista or greater. - * @return TRUE if Windows Vista or greater, FALSE otherwise. - */ - BOOL IsWindowsVistaOrGreater() { return (dwMajorVersion >= 6); } - - /** - * @brief Checks if the operating system is Windows 7 or greater. - * @return TRUE if Windows 7 or greater, FALSE otherwise. - */ - BOOL IsWindows7OrGreater() { return (dwMajorVersion > 6) || ((dwMajorVersion == 6) && (dwMinorVersion > 0)); } - - /** - * @brief Checks if the operating system is Windows XP or greater. - * @return TRUE if Windows XP or greater, FALSE otherwise. - */ - BOOL IsWindowsXPOrGreater() { return ((dwMajorVersion == 5) && (dwMinorVersion >= 1)) || (dwMajorVersion > 5); } - - /** - * @brief Checks if the operating system is Windows 10 or greater. - * @return TRUE if Windows 10 or greater, FALSE otherwise. - */ - BOOL IsWindows10OrGreater() { return (dwMajorVersion >= 10); } - - /** - * @brief Checks if the operating system is of the Windows NT platform. - * @return TRUE if Windows NT platform, FALSE otherwise. - */ - BOOL IsWindowsNTPlatform() { return (dwPlatformId == VER_PLATFORM_WIN32_NT); } -#else - /** - * @brief Static function to check if the operating system is Windows Vista or greater. - * @return TRUE if Windows Vista or greater, FALSE otherwise. - */ - static BOOL IsWindowsVistaOrGreater() { return ::IsWindowsVistaOrGreater(); } - - /** - * @brief Static function to check if the operating system is Windows XP or greater. - * @return TRUE if Windows XP or greater, FALSE otherwise. - */ - static BOOL IsWindowsXPOrGreater() { return ::IsWindowsXPOrGreater(); } - - /** - * @brief Static function to check if the operating system is Windows 7 or greater. - * @return TRUE if Windows 7 or greater, FALSE otherwise. - */ - static BOOL IsWindows7OrGreater() { return ::IsWindows7OrGreater(); } - - /** - * @brief Static function to check if the operating system is Windows 10 or greater. - * @return TRUE if Windows 10 or greater, FALSE otherwise. - */ - static BOOL IsWindows10OrGreater() { return ::IsWindowsVersionOrGreater(10, 0, 0); } - - /** - * @brief Static function to check if the operating system is of the Windows NT platform. - * @return TRUE if Windows NT platform, FALSE otherwise. - */ - static BOOL IsWindowsNTPlatform() { return IsWindowsXPOrGreater(); } -#endif // _MSC_VER >= 1700 -}; - -class NDISAPI_API CNdisApi -{ - class CWow64Helper; - -public: - CNdisApi(const TCHAR* pszFileName = _T(DRIVER_NAME_A)); - virtual ~CNdisApi(); - -#if _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - CNdisApi(const CNdisApi& other) = delete; - CNdisApi(CNdisApi&& other) = delete; - CNdisApi& operator=(const CNdisApi& other) = delete; - CNdisApi& operator=(CNdisApi&& other) = delete; -#endif // _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - -private: - // Private member functions - BOOL SetPacketFilterCacheState(BOOL bState) const; - BOOL SetPacketFragmentCacheState(BOOL bState) const; - // Private static functions - static BOOL IsNdiswanInterface(LPCSTR adapterName, LPCSTR ndiswanName); - -public: - // Driver services - BOOL DeviceIoControl(DWORD dwService, void* BuffIn, int SizeIn, void* BuffOut, int SizeOut, LPDWORD SizeRet = NULL, LPOVERLAPPED povlp = NULL) const; - ULONG GetVersion() const; - BOOL GetTcpipBoundAdaptersInfo(PTCP_AdapterList pAdapters) const; - BOOL SendPacketToMstcp(PETH_REQUEST pPacket) const; - BOOL SendPacketToAdapter(PETH_REQUEST pPacket) const; - BOOL ReadPacket(PETH_REQUEST pPacket) const; - BOOL SendPacketsToMstcp(PETH_M_REQUEST pPackets) const; - BOOL SendPacketsToAdapter(PETH_M_REQUEST pPackets) const; - BOOL ReadPackets(PETH_M_REQUEST pPackets) const; - BOOL SetAdapterMode(PADAPTER_MODE pMode) const; - BOOL GetAdapterMode(PADAPTER_MODE pMode) const; - BOOL FlushAdapterPacketQueue(HANDLE hAdapter) const; - BOOL GetAdapterPacketQueueSize(HANDLE hAdapter, PDWORD pdwSize) const; - BOOL SetPacketEvent(HANDLE hAdapter, HANDLE hWin32Event) const; - BOOL SetWANEvent(HANDLE hWin32Event) const; - BOOL SetAdapterListChangeEvent(HANDLE hWin32Event) const; - BOOL NdisrdRequest(PPACKET_OID_DATA OidData, BOOL Set) const; - BOOL GetRasLinks(HANDLE hAdapter, PRAS_LINKS pLinks) const; - BOOL SetHwPacketFilter(HANDLE hAdapter, DWORD Filter) const; - BOOL GetHwPacketFilter(HANDLE hAdapter, PDWORD pFilter) const; - BOOL SetHwPacketFilterEvent(HANDLE hAdapter, HANDLE hWin32Event) const; - BOOL SetPacketFilterTable(PSTATIC_FILTER_TABLE pFilterList) const; - BOOL AddStaticFilterFront(PSTATIC_FILTER pFilter) const; - BOOL AddStaticFilterBack(PSTATIC_FILTER pFilter) const; - BOOL InsertStaticFilter(PSTATIC_FILTER pFilter, unsigned long Position) const; - BOOL RemoveStaticFilter(DWORD dwFilterId) const; - BOOL ResetPacketFilterTable() const; - BOOL GetPacketFilterTableSize(PDWORD pdwTableSize) const; - BOOL GetPacketFilterTable(PSTATIC_FILTER_TABLE pFilterList) const; - BOOL GetPacketFilterTableResetStats(PSTATIC_FILTER_TABLE pFilterList) const; - BOOL EnablePacketFilterCache() const; - BOOL DisablePacketFilterCache() const; - BOOL EnablePacketFragmentCache() const; - BOOL DisablePacketFragmentCache() const; - BOOL IsDriverLoaded() const; - BOOL InitializeFastIo(PFAST_IO_SECTION pFastIo, DWORD dwSize) const; - BOOL AddSecondaryFastIo(PFAST_IO_SECTION pFastIo, DWORD dwSize) const; - BOOL ReadPacketsUnsorted(PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketsSuccess) const; - BOOL SendPacketsToAdaptersUnsorted(PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketSuccess) const; - BOOL SendPacketsToMstcpUnsorted(PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketSuccess) const; - BOOL GetIntermediateBufferPoolSize(PDWORD pdwSize) const; - DWORD GetBytesReturned() const; - - // Static helper routines - - static BOOL SetMTUDecrement(DWORD dwMTUDecrement); - static DWORD GetMTUDecrement(); - - static BOOL SetAdaptersStartupMode(DWORD dwStartupMode); - static DWORD GetAdaptersStartupMode(); - - static BOOL SetPoolSize(DWORD dwPoolSize); - static DWORD GetPoolSize(); - - static BOOL IsNdiswanIp(LPCSTR adapterName); - static BOOL IsNdiswanIpv6(LPCSTR adapterName); - static BOOL IsNdiswanBh(LPCSTR adapterName); - - static BOOL - ConvertWindowsNTAdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength - ); - - static BOOL - ConvertWindows2000AdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength - ); - - static BOOL - ConvertWindows9xAdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength - ); - - static void - RecalculateIPChecksum( - PINTERMEDIATE_BUFFER pPacket - ); - - static void - RecalculateICMPChecksum( - PINTERMEDIATE_BUFFER pPacket - ); - - static void - RecalculateTCPChecksum( - PINTERMEDIATE_BUFFER pPacket - ); - - static void - RecalculateUDPChecksum( - PINTERMEDIATE_BUFFER pPacket - ); - - static BOOL IsWindowsVistaOrLater() - { - return ms_Version.IsWindowsVistaOrGreater(); - } - - static BOOL IsWindows7OrLater() - { - return ms_Version.IsWindows7OrGreater(); - } - -private: - // Private member variables - mutable OVERLAPPED m_ovlp; - mutable DWORD m_BytesReturned; - - HANDLE m_hFileHandle; - BOOL m_bIsLoadSuccessfully; - - IsWow64ProcessPtr m_pfnIsWow64Process; - BOOL m_bIsWow64Process; - CWow64Helper& m_Wow64Helper; - - static CVersionInfo ms_Version; -}; - -extern "C" -{ - HANDLE __stdcall OpenFilterDriver(const TCHAR* pszFileName = _T(DRIVER_NAME_A)); - VOID __stdcall CloseFilterDriver(HANDLE hOpen); - DWORD __stdcall GetDriverVersion(HANDLE hOpen); - BOOL __stdcall GetTcpipBoundAdaptersInfo(HANDLE hOpen, PTCP_AdapterList pAdapters); - BOOL __stdcall SendPacketToMstcp(HANDLE hOpen, PETH_REQUEST pPacket); - BOOL __stdcall SendPacketToAdapter(HANDLE hOpen, PETH_REQUEST pPacket); - BOOL __stdcall ReadPacket(HANDLE hOpen, PETH_REQUEST pPacket); - BOOL __stdcall SendPacketsToMstcp(HANDLE hOpen, PETH_M_REQUEST pPackets); - BOOL __stdcall SendPacketsToAdapter(HANDLE hOpen, PETH_M_REQUEST pPackets); - BOOL __stdcall ReadPackets(HANDLE hOpen, PETH_M_REQUEST pPackets); - BOOL __stdcall SetAdapterMode(HANDLE hOpen, PADAPTER_MODE pMode); - BOOL __stdcall GetAdapterMode(HANDLE hOpen, PADAPTER_MODE pMode); - BOOL __stdcall FlushAdapterPacketQueue(HANDLE hOpen, HANDLE hAdapter); - BOOL __stdcall GetAdapterPacketQueueSize(HANDLE hOpen, HANDLE hAdapter, PDWORD pdwSize); - BOOL __stdcall SetPacketEvent(HANDLE hOpen, HANDLE hAdapter, HANDLE hWin32Event); - BOOL __stdcall SetWANEvent(HANDLE hOpen, HANDLE hWin32Event); - BOOL __stdcall SetAdapterListChangeEvent(HANDLE hOpen, HANDLE hWin32Event); - BOOL __stdcall NdisrdRequest(HANDLE hOpen, PPACKET_OID_DATA OidData, BOOL Set); - BOOL __stdcall GetRasLinks(HANDLE hOpen, HANDLE hAdapter, PRAS_LINKS pLinks); - BOOL __stdcall SetHwPacketFilter(HANDLE hOpen, HANDLE hAdapter, DWORD Filter); - BOOL __stdcall GetHwPacketFilter(HANDLE hOpen, HANDLE hAdapter, PDWORD pFilter); - BOOL __stdcall SetHwPacketFilterEvent(HANDLE hOpen, HANDLE hAdapter, HANDLE hWin32Event); - BOOL __stdcall SetPacketFilterTable(HANDLE hOpen, PSTATIC_FILTER_TABLE pFilterList); - BOOL __stdcall AddStaticFilterFront(HANDLE hOpen, PSTATIC_FILTER pFilter); - BOOL __stdcall AddStaticFilterBack(HANDLE hOpen, PSTATIC_FILTER pFilter); - BOOL __stdcall InsertStaticFilter(HANDLE hOpen, PSTATIC_FILTER pFilter, unsigned long Position); - BOOL __stdcall RemoveStaticFilter(HANDLE hOpen, DWORD dwFilterId); - BOOL __stdcall ResetPacketFilterTable(HANDLE hOpen); - BOOL __stdcall GetPacketFilterTableSize(HANDLE hOpen, PDWORD pdwTableSize); - BOOL __stdcall GetPacketFilterTable(HANDLE hOpen, PSTATIC_FILTER_TABLE pFilterList); - BOOL __stdcall GetPacketFilterTableResetStats(HANDLE hOpen, PSTATIC_FILTER_TABLE pFilterList); - BOOL __stdcall EnablePacketFilterCache(HANDLE hOpen); - BOOL __stdcall DisablePacketFilterCache(HANDLE hOpen); - BOOL __stdcall EnablePacketFragmentCache(HANDLE hOpen); - BOOL __stdcall DisablePacketFragmentCache(HANDLE hOpen); - BOOL __stdcall SetMTUDecrement(DWORD dwMTUDecrement); - DWORD __stdcall GetMTUDecrement(); - BOOL __stdcall SetAdaptersStartupMode(DWORD dwStartupMode); - DWORD __stdcall GetAdaptersStartupMode(); - BOOL __stdcall SetPoolSize(DWORD dwPoolSize); - DWORD __stdcall GetPoolSize(); - BOOL __stdcall IsDriverLoaded(HANDLE hOpen); - BOOL __stdcall InitializeFastIo(HANDLE hOpen, PFAST_IO_SECTION pFastIo, DWORD dwSize); - BOOL __stdcall AddSecondaryFastIo(HANDLE hOpen, PFAST_IO_SECTION pFastIo, DWORD dwSize); - BOOL __stdcall ReadPacketsUnsorted(HANDLE hOpen, PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketsSuccess); - BOOL __stdcall SendPacketsToAdaptersUnsorted(HANDLE hOpen, PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketSuccess); - BOOL __stdcall SendPacketsToMstcpUnsorted(HANDLE hOpen, PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketSuccess); - BOOL __stdcall GetIntermediateBufferPoolSize(HANDLE hOpen, PDWORD pdwSize); - DWORD __stdcall GetBytesReturned(HANDLE hOpen); - - BOOL __stdcall IsNdiswanIp(LPCSTR adapterName); - BOOL __stdcall IsNdiswanIpv6(LPCSTR adapterName); - BOOL __stdcall IsNdiswanBh(LPCSTR adapterName); - - BOOL __stdcall - ConvertWindowsNTAdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength - ); - - BOOL __stdcall - ConvertWindows2000AdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength - ); - - BOOL __stdcall - ConvertWindows9xAdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength - ); - - void __stdcall - RecalculateIPChecksum( - PINTERMEDIATE_BUFFER pPacket - ); - - void __stdcall - RecalculateICMPChecksum( - PINTERMEDIATE_BUFFER pPacket - ); - - void __stdcall - RecalculateTCPChecksum( - PINTERMEDIATE_BUFFER pPacket - ); - - void __stdcall - RecalculateUDPChecksum( - PINTERMEDIATE_BUFFER pPacket - ); -} \ No newline at end of file diff --git a/ndisapi.lib/ndisapilib.vcxproj b/ndisapi.lib/ndisapilib.vcxproj index 3db26e5..79f466a 100644 --- a/ndisapi.lib/ndisapilib.vcxproj +++ b/ndisapi.lib/ndisapilib.vcxproj @@ -248,18 +248,18 @@ - - - - - - + + + + + + - + - + diff --git a/ndisapi.lib/ndisapilib.vcxproj.filters b/ndisapi.lib/ndisapilib.vcxproj.filters index 2328a95..72b427e 100644 --- a/ndisapi.lib/ndisapilib.vcxproj.filters +++ b/ndisapi.lib/ndisapilib.vcxproj.filters @@ -15,32 +15,32 @@ - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Header Files - + Source Files - + Resource Files diff --git a/ndisapi/inet_checksum.h b/ndisapi/inet_checksum.h deleted file mode 100644 index 3ab0ebe..0000000 --- a/ndisapi/inet_checksum.h +++ /dev/null @@ -1,148 +0,0 @@ -/*************************************************************************/ -/* Copyright (c) 2000-2026 NT KERNEL. */ -/* All Rights Reserved. */ -/* https://www.ntkernel.com */ -/* ndisrd@ntkernel.com */ -/* */ -/* Module Name: inet_checksum.h */ -/* */ -/* Description: Wide (RFC 1071) Internet checksum accumulation */ -/* */ -/* Environment: */ -/* User mode */ -/* */ -/*************************************************************************/ - -#pragma once - -// This header is compiled by every project that builds ndisapi.cpp, including -// the legacy VC6/VS2012 ones (ndisapi.vc6/ndisapi.dsp), so it cannot assume -// C++11. arrived with VS2010 (_MSC_VER 1600) and `noexcept` with -// VS2015 (1900); older MSVC gets typedefs onto the compiler's built-in -// __int64 and an empty noexcept macro. The body itself avoids everything VC6 -// chokes on: no `ull` literal suffixes, no per-loop redeclaration of the -// index variable. -// -// INET_CHECKSUM_FORCE_LEGACY_COMPAT exists so a modern compiler can be forced -// down the legacy branch, which is how that branch is compile- and -// correctness-tested without a VC6 installation. It changes types and -// spelling only, never values. -// in both branches: sum16_be's signature uses unqualified size_t, -// and only the C header is guaranteed to place it in the global namespace -- -// / promise std::size_t, with global injection unspecified. -#include - -#if (defined(_MSC_VER) && _MSC_VER < 1600) || defined(INET_CHECKSUM_FORCE_LEGACY_COMPAT) -#include -#define INET_CHECKSUM_MEMCPY ::memcpy -namespace inet_checksum -{ - typedef unsigned __int64 sum_uint64; - typedef unsigned int sum_uint32; - typedef unsigned short sum_uint16; -} -#else -#include -#include -#define INET_CHECKSUM_MEMCPY ::std::memcpy -namespace inet_checksum -{ - typedef ::std::uint64_t sum_uint64; - typedef ::std::uint32_t sum_uint32; - typedef ::std::uint16_t sum_uint16; -} -#endif - -#if (defined(_MSC_VER) && _MSC_VER < 1900) || defined(INET_CHECKSUM_FORCE_LEGACY_COMPAT) -#define INET_CHECKSUM_NOEXCEPT -#else -#define INET_CHECKSUM_NOEXCEPT noexcept -#endif - -namespace inet_checksum -{ - /// - /// 16-bit one's-complement sum (NOT complemented) of a byte span, in the - /// big-endian word domain, i.e. exactly the value the byte-pair loop - /// sum += (buff[i] << 8) | buff[i + 1] accumulates and folds. - /// Callers add their pseudo-header words to it, fold, and complement, - /// unchanged. - /// - /// - /// The Internet checksum is byte-order independent up to one byte swap of - /// the folded result (RFC 1071 section 2(B)), so the hot loop accumulates - /// native little-endian 32-bit words and only the final 16 bits are - /// swapped. The invariant this rests on: for every span and every length - /// parity, folding the little-endian sum and swapping equals folding the - /// big-endian byte-pair sum (with a zero pad byte for odd lengths), and - /// the 0x0000-versus-0xFFFF folding boundary cannot diverge because a - /// folded sum is zero only for an all-zero argument in both formulations. - /// Any change here must keep a differential test against the byte-pair - /// formulation green across odd/even lengths and all start alignments. - /// - /// Accumulating 32-bit loads into 64-bit accumulators needs no carry - /// handling at all -- a 64-bit accumulator absorbs 2^32 such additions, - /// and an IPv4 payload is bounded far below that -- so the loop is - /// portable across x86, x64 and ARM64 with no intrinsics. Four - /// independent accumulators break the dependency chain that made the - /// byte-pair loop front-end bound; measured on one out-of-order x64 core, - /// the cost drops from 1.1-1.7 cycles/byte to roughly 0.21-0.26. - /// - /// An ODD length is handled with a masked tail load. The byte-pair loop - /// instead wrote a zero pad byte into the packet buffer one past the - /// payload before reading it back; this function never writes anywhere. - /// - /// Start of the span. No alignment requirement. - /// Span length in bytes. Zero yields zero. - /// The folded, uncomplemented sum, in [0x0000, 0xFFFF]. - inline sum_uint16 sum16_be(const unsigned char* data, const size_t length) INET_CHECKSUM_NOEXCEPT - { - sum_uint64 s0 = 0, s1 = 0, s2 = 0, s3 = 0; - size_t i = 0; - - for (; i + 16 <= length; i += 16) - { - sum_uint32 w0, w1, w2, w3; - INET_CHECKSUM_MEMCPY(&w0, data + i, 4); - INET_CHECKSUM_MEMCPY(&w1, data + i + 4, 4); - INET_CHECKSUM_MEMCPY(&w2, data + i + 8, 4); - INET_CHECKSUM_MEMCPY(&w3, data + i + 12, 4); - s0 += w0; - s1 += w1; - s2 += w2; - s3 += w3; - } - - for (; i + 4 <= length; i += 4) - { - sum_uint32 w; - INET_CHECKSUM_MEMCPY(&w, data + i, 4); - s0 += w; - } - - // Masked tail: up to three bytes. The 4-byte blocks above end on an - // even offset, so within this final word the byte at relative offset r - // belongs at little-endian lane r -- which is precisely what building - // the word with shifts 0/8/16 produces. Never reads past `length`. - if (i < length) - { - sum_uint32 w = 0; - unsigned int shift = 0; - for (; i < length; ++i, shift += 8) - w |= static_cast(data[i]) << shift; - s0 += w; - } - - sum_uint64 sum = s0 + s1 + s2 + s3; - while (sum >> 32) - sum = (sum & 0xFFFFFFFFu) + (sum >> 32); - - sum_uint32 folded = static_cast(sum); - while (folded >> 16) - folded = (folded & 0xFFFF) + (folded >> 16); - - // Swap into the big-endian word domain the callers accumulate - // pseudo-header words in. - return static_cast(((folded & 0xFF) << 8) | (folded >> 8)); - } -} diff --git a/ndisapi/iphlp.h b/ndisapi/iphlp.h deleted file mode 100644 index 2799147..0000000 --- a/ndisapi/iphlp.h +++ /dev/null @@ -1,220 +0,0 @@ -//*************************************************************************/ -/* Copyright (c) 2000-2024 NT KERNEL. */ -/* All Rights Reserved. */ -/* https://www.ntkernel.com */ -/* ndisrd@ntkernel.com */ -/* Module Name: iphlp.h */ -/* */ -/* Abstract: IP helper definitions */ -/* */ -/* Environment: */ -/* User mode, Kernel mode */ -/* */ -/*************************************************************************/ - -#ifndef __IPHLP_H__ -#define __IPHLP_H__ - -#pragma pack(1) - -/////////////////////////////////////////////////////////////////////////// -// packet structures -/////////////////////////////////////////////////////////////////////////// -typedef long n_long; -typedef short n_short; -typedef long n_time; -typedef unsigned short u_short; -typedef unsigned long u_long; -typedef unsigned char u_char; -typedef struct in_addr IN_ADDR, *PIN_ADDR; - -#define ETH_ALEN 6 /* Octets in one ethernet addr */ -#define ETHER_HEADER_LENGTH 14 /* Ethernet header length */ - -#define ETH_P_ARP 0x0806 /* Address Resolution packet */ -#define ARPHRD_ETHER 0x01 -#define ARPOP_REQUEST 0x01 -#define ARPOP_REPLY 0x02 - -#define ETH_P_IP 0x0800 /* Internet Protocol packet */ -#define ETH_P_IP_NET 0x0008 /* Internet Protocol packet network order*/ -#define ETH_P_RARP 0x8035 /* Reverse Addr Res packet */ -#define ETH_P_ARP 0x0806 /* Address Resolution packet */ - -#define ETH_P_IPV6 0x86dd /* Internet Protocol V6 packet */ -#define ETH_P_IPV6_NET 0xdd86 /* Internet Protocol V6 packet network order*/ - -/* - * Protocols - */ -#define IPPROTO_IP 0 /* dummy for IP */ -#define IPPROTO_ICMP 1 /* control message protocol */ -#define IPPROTO_IGMP 2 /* group management protocol */ -#define IPPROTO_GGP 3 /* gateway^2 (deprecated) */ -#define IPPROTO_TCP 6 /* tcp */ -#define IPPROTO_PUP 12 /* pup */ -#define IPPROTO_UDP 17 /* user datagram protocol */ -#define IPPROTO_IDP 22 /* xns idp */ -#define IPPROTO_ND 77 /* UNOFFICIAL net disk proto */ - -#define IPPROTO_RAW 255 /* raw IP packet */ -#define IPPROTO_MAX 256 - -// Ethernet Header -typedef struct ether_header -{ - unsigned char h_dest[ETH_ALEN]; /* destination eth addr */ - unsigned char h_source[ETH_ALEN]; /* source ether addr */ - unsigned short h_proto; /* packet type ID field */ -} ether_header, *ether_header_ptr; - -typedef struct arphdr -{ - unsigned short ar_hrd; /* format of hardware address */ - unsigned short ar_pro; /* format of protocol address */ - unsigned char ar_hln; /* length of hardware address */ - unsigned char ar_pln; /* length of protocol address */ - unsigned short ar_op; /* ARP opcode (command) */ -} arphdr, *arphdr_ptr; - -typedef struct ether_arp -{ - struct arphdr ea_hdr; /* fixed-size header */ - u_char arp_sha[ETH_ALEN]; /* sender hardware address */ - u_char arp_spa[4]; /* sender protocol address */ - u_char arp_tha[ETH_ALEN]; /* target hardware address */ - u_char arp_tpa[4]; /* target protocol address */ -} ether_arp, *ether_arp_ptr; - -#define arp_hrd ea_hdr.ar_hrd -#define arp_pro ea_hdr.ar_pro -#define arp_hln ea_hdr.ar_hln -#define arp_pln ea_hdr.ar_pln -#define arp_op ea_hdr.ar_op - -/* IP Header in Little Endian */ -typedef struct iphdr -{ - u_char ip_hl:4, /* header length */ - ip_v:4; /* version */ - u_char ip_tos; /* type of service */ - u_short ip_len; /* total length */ - u_short ip_id; /* identification */ - u_short ip_off; /* fragment offset field */ -#define IP_DF 0x4000 /* dont fragment flag */ -#define IP_MF 0x2000 /* more fragments flag */ - u_char ip_ttl; /* time to live */ - u_char ip_p; /* protocol */ - u_short ip_sum; /* checksum */ - struct in_addr ip_src,ip_dst; /* source and dest address */ -} iphdr, *iphdr_ptr; -///////////////////////////////////////////////////////////////////////// -/* UDP header */ -typedef struct udphdr -{ - u_short th_sport; /* source port */ - u_short th_dport; /* destination port */ - u_short length; /* data length */ - u_short th_sum; /* checksum */ -} udphdr, *udphdr_ptr; -///////////////////////////////////////////////////////////////////////// -typedef u_long tcp_seq; - -// TCP header. Per RFC 793, September, 1981. In Little Endian -typedef struct tcphdr { - u_short th_sport; /* source port */ - u_short th_dport; /* destination port */ - tcp_seq th_seq; /* sequence number */ - tcp_seq th_ack; /* acknowledgement number */ - u_char th_x2:4, /* (unused) */ - th_off:4; /* data offset */ -#define TCP_NO_OPTIONS 0x05 - u_char th_flags; -#define TH_FIN 0x01 -#define TH_SYN 0x02 -#define TH_RST 0x04 -#define TH_PSH 0x08 -#define TH_ACK 0x10 -#define TH_URG 0x20 - u_short th_win; /* window */ - u_short th_sum; /* checksum */ - u_short th_urp; /* urgent pointer */ -} tcphdr, *tcphdr_ptr; - -typedef struct pseudo_header -{ - struct in_addr source_address; - struct in_addr dest_address; - unsigned char placeholder; - unsigned char protocol; - unsigned short tcp_length; - -}pseudo_header, *pseudo_header_ptr; - -///////////////////////////////////////////////////////////////////////// - -// -// Protocols for IPv6 -// -#define IPPROTO_HOPOPTS 0 // Hop by hop header for v6 -#define IPPROTO_IPV6 41 // IPv6 encapsulated in IP -#define IPPROTO_ROUTING 43 // Routing header for IPv6 -#define IPPROTO_FRAGMENT 44 // Fragment header for IPv6 -#define IPPROTO_ICMPV6 58 // ICMP for IPv6 -#define IPPROTO_NONE 59 // No next header for IPv6 -#define IPPROTO_DSTOPTS 60 // Destinations options - -// -// IPv6 header format -// -typedef struct ipv6hdr -{ - unsigned int ip6_flow; // 4 bits = version #, - // 8 bits = Trafic class, - // 20 bits = flow label - unsigned short ip6_len; // Payload length - unsigned char ip6_next; // Next Header - unsigned char ip6_hops; // Hop Limit - IN6_ADDR ip6_src; // Source Address - IN6_ADDR ip6_dst; // Destination Address -} ipv6hdr, *ipv6hdr_ptr; - -// -// IPv6 extension header format -// -typedef struct ipv6ext { - unsigned char ip6_next; // Next Header - unsigned char ip6_len; // number of bytes in this header - unsigned char ip6_data[2]; // optional data -}ipv6ext, *ipv6ext_ptr; - -typedef struct ipv6ext_frag -{ - unsigned char ip6_next; // next header - unsigned char ip6_reserved; // reserved field - unsigned short ip6_offlg; // offset, reserved, and flag - unsigned int ip6_ident; // identification -}ipv6ext_frag, *ipv6ext_frag_ptr; - -typedef struct mss_tcp_options { -#define MSS_TYPE 0x02 -#define SACK_TYPE 0x04 - u_char mss_type; - u_char mss_option_length; - u_short mss_value; -}mss_tcp_options, *mss_tcp_options_ptr; - -// -// ICMP header -// -typedef struct icmphdr { - unsigned char type; // ICMP packet type - unsigned char code; // Type sub code - unsigned short checksum; - unsigned short id; - unsigned short seq; -}icmphdr, *icmphdr_ptr; - -#pragma pack() - -#endif // __IPHLP_H__ \ No newline at end of file diff --git a/ndisapi/ndisapi.cpp b/ndisapi/ndisapi.cpp deleted file mode 100644 index aa92292..0000000 --- a/ndisapi/ndisapi.cpp +++ /dev/null @@ -1,4430 +0,0 @@ -/*************************************************************************/ -/* Copyright (c) 2000-2024 NT KERNEL. */ -/* All Rights Reserved. */ -/* https://www.ntkernel.com */ -/* ndisrd@ntkernel.com */ -/* */ -/* Module Name: ndisapi.cpp */ -/* */ -/* Description: API exported C++ class and C API definitions */ -/* */ -/* Environment: */ -/* User mode */ -/* */ -/*************************************************************************/ - -#include "precomp.h" -#include "inet_checksum.h" - -#if _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) -#include -#include -#endif // _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - -#define DEVICE_NDISWANIP "\\DEVICE\\NDISWANIP" -#define USER_NDISWANIP "WAN Network Interface (IP)" -#define DEVICE_NDISWANBH "\\DEVICE\\NDISWANBH" -#define USER_NDISWANBH "WAN Network Interface (BH)" -#define DEVICE_NDISWANIPV6 "\\DEVICE\\NDISWANIPV6" -#define USER_NDISWANIPV6 "WAN Network Interface (IPv6)" -#define REGSTR_COMPONENTID_NDISWANIP "ms_ndiswanip" -#define REGSTR_COMPONENTID_NDISWANIPV6 "ms_ndiswanipv6" -#define REGSTR_COMPONENTID_NDISWANBH "ms_ndiswanbh" -#define REGSTR_VAL_CONNECTION "\\Connection" -#define REGSTR_VAL_NAME "Name" -#define REGSTR_VAL_SERVICE_NAME "ServiceName" -#define REGSTR_VAL_DRIVER_DESC "DriverDesc" -#define REGSTR_VAL_TITLE "Title" - -#define REGSTR_NETWORK_CONTROL_KEY "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" -#define REGSTR_NETWORK_CARDS TEXT("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\NetworkCards") -#define REGSTR_MSTCP_CLASS_NET "SYSTEM\\CurrentControlSet\\Services\\Class\\Net\\" -#define REGSTR_NETWORK_CONTROL_CLASS TEXT("SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}") - -#define OID_GEN_CURRENT_PACKET_FILTER 0x0001010E - -// OS version information -CVersionInfo CNdisApi::ms_Version; - -/** - * @class CNdisApi::CWow64Helper - * @brief A helper class to manage conversion of handles between 32-bit and 64-bit applications in WOW64 mode. - * - * This class is designed as a singleton and provides methods for updating handle mappings and converting - * handles between 32-bit and 64-bit representations. It is useful when a 32-bit application interacts with - * a 64-bit driver on a 64-bit operating system. - * - * Usage: - * auto& wow64Helper = CNdisApi::CWow64Helper::getInstance(); - * unsigned int handle32 = wow64Helper.From64to32Handle(handle64); - */ -class CNdisApi::CWow64Helper -{ -public: -#if _MSC_VER < 1800 || defined(_USING_V110_SDK71_) - /** - * @brief Destructor that releases the Win32 mutex. - */ - ~CWow64Helper() - { - ::CloseHandle(m_hWin32Mutex); - } -#endif //_MSC_VER < 1800 || defined(_USING_V110_SDK71_) - - /** - * @brief Returns a reference to the singleton instance of CWow64Helper. - * @return A reference to the singleton instance. - */ - static CWow64Helper& getInstance() - { - static CWow64Helper instance; // Guaranteed to be destroyed. - // Instantiated on first use. - return instance; - } - -#if _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - CWow64Helper(const CWow64Helper& other) = delete; - CWow64Helper& operator=(const CWow64Helper& other) = delete; - CWow64Helper(CWow64Helper&& other) = delete; - CWow64Helper& operator=(CWow64Helper&& other) = delete; - ~CWow64Helper() = default; -#endif // _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - - /** - * @brief Updates the handle mappings based on the provided TCP_AdapterList_WOW64. - * @param adapterListWow64 A reference to the TCP_AdapterList_WOW64 structure. - */ - void Update(const TCP_AdapterList_WOW64& adapterListWow64); - - /** - * @brief Converts a 32-bit handle to its 64-bit equivalent. - * @param handle The 32-bit handle to convert. - * @return The corresponding 64-bit handle. - */ - ULONGLONG From32to64Handle(const unsigned int handle) - { -#if _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - std::shared_lock lock(m_SharedLock); -#else - InternalLock(); -#endif // _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - - const ULONGLONG result = m_Handle32to64[handle]; - -#if _MSC_VER < 1800 || defined(_USING_V110_SDK71_) - InternalUnlock(); -#endif //_MSC_VER < 1800 || defined(_USING_V110_SDK71_) - - return result; - } - - /** - * @brief Converts a 64-bit handle to its 32-bit equivalent. - * @param handle The 64-bit handle to convert. - * @return The corresponding 32-bit handle. - */ - unsigned int From64to32Handle(const ULONGLONG handle) - { - unsigned int result = 0; - -#if _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - std::shared_lock lock(m_SharedLock); -#else - InternalLock(); -#endif // _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - - for (unsigned int i = 1; i < ADAPTER_LIST_SIZE + 1; ++i) - { - if (m_Handle32to64[i] == handle) - { - result = i; - break; - } - } - -#if _MSC_VER < 1800 || defined(_USING_V110_SDK71_) - InternalUnlock(); -#endif //_MSC_VER < 1800 || defined(_USING_V110_SDK71_) - return result; - } - -private: -#if _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - CWow64Helper() = default; -#else - CWow64Helper() : m_hWin32Mutex(::CreateMutex(NULL, FALSE, NULL)) - { - memset((void*)m_Handle32to64, 0, sizeof(m_Handle32to64)); - } - - // Synchronize an access to m_Handle32to64 using Win32 mutex - DWORD InternalLock() { return ::WaitForSingleObject(m_hWin32Mutex, INFINITE); } - void InternalUnlock() { ::ReleaseMutex(m_hWin32Mutex); } - - CWow64Helper(CWow64Helper const&); // Don't Implement - CWow64Helper& operator=(CWow64Helper const&); // Don't implement -#endif // _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - -#if _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - std::shared_mutex m_SharedLock; - ULONGLONG m_Handle32to64[ADAPTER_LIST_SIZE + 1]{}; -#else - HANDLE m_hWin32Mutex; - ULONGLONG m_Handle32to64[ADAPTER_LIST_SIZE + 1]; -#endif //_MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) -}; - -/** - * @brief Updates the handle mappings based on the provided TCP_AdapterList_WOW64. - * - * This method updates the internal handle mapping table to ensure it reflects the current state - * of the adapter list in the system. This should be called whenever the adapter list changes. - * - * @param adapterListWow64 A reference to the TCP_AdapterList_WOW64 structure containing the - * current adapter handles. - */ -void CNdisApi::CWow64Helper::Update(const TCP_AdapterList_WOW64& adapterListWow64) -{ -#if _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - std::unique_lock _lock(m_SharedLock); -#else - InternalLock(); -#endif // _MSC_VER >= 1800 && !defined(_USING_V110_SDK71_) - - if (m_Handle32to64[0] == 0) - { - // First call to GetTcpipBoundAdaptersInfo, initialize m_Handle32to64 - m_Handle32to64[0] = (-1); - - for (unsigned i = 0; i < adapterListWow64.m_nAdapterCount; ++i) - { - m_Handle32to64[i + 1] = adapterListWow64.m_nAdapterHandle[i].QuadPart; - } - } - else - { - for (unsigned i = 0; i < adapterListWow64.m_nAdapterCount; ++i) - { - // Check if we already have adapterListWow64.m_nAdapterHandle[i] adapter in the translation table - bool bAlreadyExists = false; - - for (unsigned j = 1; j < ADAPTER_LIST_SIZE + 1; ++j) - { - if (m_Handle32to64[j] == adapterListWow64.m_nAdapterHandle[i].QuadPart) - { - bAlreadyExists = true; - break; - } - } - - if (!bAlreadyExists) - { - // This is a new interface, not present in the table - // Search through the table for the first entry which can be replaced - - unsigned pos = 0; - - for (unsigned j = 1; j < ADAPTER_LIST_SIZE + 1; ++j) - { - for (unsigned k = 0; k < adapterListWow64.m_nAdapterCount; ++k) - { - if (m_Handle32to64[j] == adapterListWow64.m_nAdapterHandle[k].QuadPart) - break; - - // We are at the last element and m_Handle32to64[j] is not found - if (k == (adapterListWow64.m_nAdapterCount - 1)) - { - pos = j; - } - - if (pos) - break; - } - } - - if (pos) - { - m_Handle32to64[pos] = adapterListWow64.m_nAdapterHandle[i].QuadPart; - } - } - } - } - -#if _MSC_VER < 1800 || defined(_USING_V110_SDK71_) - InternalUnlock(); -#endif //_MSC_VER < 1800 || defined(_USING_V110_SDK71_) -} - -/** - * @brief CNdisApi constructor that opens the specified driver file and initializes internal structures. - * - * This constructor attempts to open the driver file specified by pszFileName, and initializes internal - * structures including the OVERLAPPED structure and the CWow64Helper instance. It also checks if the - * process is running in WOW64 mode and initializes handle mapping if necessary. - * - * @param pszFileName A const TCHAR pointer to the name of the driver file to be opened. - */ -CNdisApi::CNdisApi(const TCHAR* pszFileName) : - m_ovlp(), - m_pfnIsWow64Process(NULL), - m_Wow64Helper(CWow64Helper::getInstance()) -{ - TCHAR pszFullName[FILE_NAME_SIZE]; - - // Format full file name -#if _MSC_VER >= 1700 - _tcscpy_s(pszFullName, FILE_NAME_SIZE, _T("\\\\.\\")); - _tcscat_s(pszFullName, FILE_NAME_SIZE, pszFileName); -#else - _tcscpy(pszFullName, _T("\\\\.\\")); - _tcscat(pszFullName, pszFileName); -#endif //_MSC_VER >= 1700 - - m_bIsLoadSuccessfully = FALSE; - - // We open driver for overlapped I/O, though none of current driver services are processed asynchronously - m_hFileHandle = ::CreateFile(pszFullName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, - FILE_FLAG_OVERLAPPED, 0); - - // If driver is opened successfully we initialize our OVERLAPPED structure - if (m_hFileHandle == INVALID_HANDLE_VALUE) - { - m_ovlp.hEvent = 0; - } - else - { - m_ovlp.hEvent = CreateEvent(0, TRUE, FALSE, NULL); - if (m_ovlp.hEvent) - { - m_bIsLoadSuccessfully = TRUE; - } - } - - m_BytesReturned = 0; - - // - // Check if we are running in WOW64 - // - m_bIsWow64Process = FALSE; - - if (ms_Version.IsWindowsXPOrGreater()) - { - const HMODULE hKernel32 = ::GetModuleHandle(TEXT("kernel32.dll")); - if (hKernel32) - { - m_pfnIsWow64Process = reinterpret_cast(::GetProcAddress(hKernel32, "IsWow64Process")); - if (m_pfnIsWow64Process) - { - m_pfnIsWow64Process(GetCurrentProcess(), &m_bIsWow64Process); - } - } - } - - if (m_bIsWow64Process) - { - // Initialize CWow64Helper::m_Handle32to64 - TCP_AdapterList AdaptersList = { 0 }; // NOLINT(clang-diagnostic-missing-field-initializers) - GetTcpipBoundAdaptersInfo(&AdaptersList); - } -} - -/** - * @brief CNdisApi destructor that closes the driver file handle and the event handle of the OVERLAPPED structure. - * - * This destructor ensures that the driver file handle and the event handle associated with the - * OVERLAPPED structure are properly closed when the CNdisApi instance is destroyed. - */ -CNdisApi::~CNdisApi() -{ - if (m_hFileHandle != INVALID_HANDLE_VALUE) - { - ::CloseHandle(m_hFileHandle); - } - - if (m_ovlp.hEvent) - { - ::CloseHandle(m_ovlp.hEvent); - } -} - -/** - * @brief Sends a control code directly to the NDISAPI driver. - * - * @param dwService The control code for the operation. - * @param BuffIn A pointer to the input buffer that contains the data required to perform the operation. - * @param SizeIn The size of the input buffer, in bytes. - * @param BuffOut A pointer to the output buffer that is to receive the data returned by the operation. - * @param SizeOut The size of the output buffer, in bytes. - * @param SizeRet A pointer to a variable that receives the size of the data stored in the output buffer, in bytes. - * @param povlp A pointer to an OVERLAPPED structure. Use NULL for synchronous operation. - * @return BOOL Returns TRUE if the operation completes successfully, FALSE otherwise. - * - * This function sends a control code to the NDISAPI driver, either in a synchronous or asynchronous manner, - * depending on the value of the 'povlp' parameter. - */ -BOOL CNdisApi::DeviceIoControl(DWORD dwService, void* BuffIn, int SizeIn, void* BuffOut, int SizeOut, LPDWORD SizeRet, LPOVERLAPPED povlp) const -{ - BOOL Ret = 0; - - // Supports overlapped and non-overlapped IO - - if (!SizeRet) SizeRet = &m_BytesReturned; - - if (m_hFileHandle != INVALID_HANDLE_VALUE) - { - if (povlp == NULL) - Ret = ::DeviceIoControl(m_hFileHandle, dwService, BuffIn, SizeIn, BuffOut, SizeOut, SizeRet, &m_ovlp); - else - Ret = ::DeviceIoControl(m_hFileHandle, dwService, BuffIn, SizeIn, BuffOut, SizeOut, SizeRet, povlp); - - } - - return Ret; -} - -/** - * @brief Retrieves the NDISAPI driver version. - * - * @return ULONG Returns the NDISAPI driver version if successful, or 0xFFFFFFFF if unsuccessful. - * - * This function retrieves the version number of the NDISAPI driver by sending an IOCTL_NDISRD_GET_VERSION control code - * to the driver using DeviceIoControl. - */ -ULONG CNdisApi::GetVersion() const -{ - ULONG nDriverAPIVersion = 0xFFFFFFFF; - - DeviceIoControl( - IOCTL_NDISRD_GET_VERSION, - &nDriverAPIVersion, - sizeof(ULONG), - &nDriverAPIVersion, - sizeof(ULONG), - NULL, // Bytes Returned - NULL - ); - - return nDriverAPIVersion; -} - -/** - * @brief Retrieves the list of TCPIP-bound adapters. - * - * @param pAdapters Pointer to a TCP_AdapterList structure that receives the adapter list. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function retrieves the list of network adapters available to Windows Packet Filter by sending an - * IOCTL_NDISRD_GET_TCPIP_INTERFACES control code to the NDISAPI driver using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function retrieves the 64-bit adapter - * handles and converts them to 32-bit handles using the Wow64Helper. - */ -BOOL CNdisApi::GetTcpipBoundAdaptersInfo(PTCP_AdapterList pAdapters) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - TCP_AdapterList_WOW64 adaptersList = { 0 }; // NOLINT(clang-diagnostic-missing-field-initializers) - - if (m_bIsWow64Process) - { - // In case of WOW64 process pass our own structure to driver - bIOResult = DeviceIoControl( - IOCTL_NDISRD_GET_TCPIP_INTERFACES, - &adaptersList, - sizeof(TCP_AdapterList_WOW64), - &adaptersList, - sizeof(TCP_AdapterList_WOW64), - NULL, // Bytes Returned - NULL - ); - - if (bIOResult) - { - // Update WOW64 handle conversion helper - m_Wow64Helper.Update(adaptersList); - - // Zero-initialize - ZeroMemory(pAdapters, sizeof(TCP_AdapterList)); - - // Simply copy all the fields except adapters handles - pAdapters->m_nAdapterCount = adaptersList.m_nAdapterCount; - memmove(pAdapters->m_szAdapterNameList, adaptersList.m_szAdapterNameList, sizeof(pAdapters->m_szAdapterNameList)); - memmove(pAdapters->m_nAdapterMediumList, adaptersList.m_nAdapterMediumList, sizeof(pAdapters->m_nAdapterMediumList)); - memmove(pAdapters->m_czCurrentAddress, adaptersList.m_czCurrentAddress, sizeof(pAdapters->m_czCurrentAddress)); - memmove(pAdapters->m_usMTU, adaptersList.m_usMTU, sizeof(pAdapters->m_usMTU)); - - // Convert 64 bit handles to 32 bit ones - for (size_t i = 0; i < pAdapters->m_nAdapterCount; ++i) - { - pAdapters->m_nAdapterHandle[i] = reinterpret_cast(m_Wow64Helper.From64to32Handle( - adaptersList.m_nAdapterHandle[i].QuadPart)); - } - } - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_GET_TCPIP_INTERFACES, - pAdapters, - sizeof(TCP_AdapterList), - pAdapters, - sizeof(TCP_AdapterList), - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sends a packet to the Microsoft TCP/IP stack. - * - * @param pPacket Pointer to an ETH_REQUEST structure that contains the packet to be sent. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sends a packet to the Microsoft TCP/IP stack by sending an IOCTL_NDISRD_SEND_PACKET_TO_MSTCP - * control code to the NDISAPI driver using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function converts the adapter handle - * and buffer pointer using the Wow64Helper before sending the IOCTL. - */ -BOOL CNdisApi::SendPacketToMstcp(PETH_REQUEST pPacket) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ETH_REQUEST_WOW64 EthRequest; - INTERMEDIATE_BUFFER_WOW64 Buffer; - - // Initialize INTERMEDIATE_BUFFER_WOW64 - Buffer.m_dwDeviceFlags = pPacket->EthPacket.Buffer->m_dwDeviceFlags; - Buffer.m_Flags = pPacket->EthPacket.Buffer->m_Flags; - Buffer.m_8021q = pPacket->EthPacket.Buffer->m_8021q; - Buffer.m_FilterID = pPacket->EthPacket.Buffer->m_FilterID; - memmove(Buffer.m_Reserved, pPacket->EthPacket.Buffer->m_Reserved, sizeof(ULONG) * 4); - Buffer.m_Length = pPacket->EthPacket.Buffer->m_Length; - memmove(Buffer.m_IBuffer, pPacket->EthPacket.Buffer->m_IBuffer, Buffer.m_Length); - - // Initialize ETH_REQUEST_WOW64 - EthRequest.hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)pPacket->hAdapterHandle); - EthRequest.EthPacket.Buffer.HighPart = 0; - EthRequest.EthPacket.Buffer.LowPart = (ULONG_PTR)&Buffer; - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKET_TO_MSTCP, - &EthRequest, - sizeof(ETH_REQUEST_WOW64), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKET_TO_MSTCP, - pPacket, - sizeof(ETH_REQUEST), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sends a packet to the network adapter. - * - * @param pPacket Pointer to an ETH_REQUEST structure that contains the packet to be sent. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sends a packet to the network adapter by sending an IOCTL_NDISRD_SEND_PACKET_TO_ADAPTER - * control code to the NDISAPI driver using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function converts the adapter handle - * and buffer pointer using the Wow64Helper before sending the IOCTL. - */ -BOOL CNdisApi::SendPacketToAdapter(PETH_REQUEST pPacket) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ETH_REQUEST_WOW64 EthRequest; - INTERMEDIATE_BUFFER_WOW64 Buffer; - - // Initialize INTERMEDIATE_BUFFER_WOW64 - Buffer.m_dwDeviceFlags = pPacket->EthPacket.Buffer->m_dwDeviceFlags; - Buffer.m_Flags = pPacket->EthPacket.Buffer->m_Flags; - Buffer.m_8021q = pPacket->EthPacket.Buffer->m_8021q; - Buffer.m_FilterID = pPacket->EthPacket.Buffer->m_FilterID; - memmove(Buffer.m_Reserved, pPacket->EthPacket.Buffer->m_Reserved, sizeof(ULONG) * 4); - Buffer.m_Length = pPacket->EthPacket.Buffer->m_Length; - memmove(Buffer.m_IBuffer, pPacket->EthPacket.Buffer->m_IBuffer, Buffer.m_Length); - - // Initialize ETH_REQUEST_WOW64 - EthRequest.hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)pPacket->hAdapterHandle); - EthRequest.EthPacket.Buffer.HighPart = 0; - EthRequest.EthPacket.Buffer.LowPart = (ULONG_PTR)&Buffer; - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKET_TO_ADAPTER, - &EthRequest, - sizeof(ETH_REQUEST_WOW64), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKET_TO_ADAPTER, - pPacket, - sizeof(ETH_REQUEST), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Reads a packet from the Windows Packet Filter driver. - * - * @param pPacket Pointer to an ETH_REQUEST structure that will receive the read packet. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function reads a packet from the NDISAPI driver by sending an IOCTL_NDISRD_READ_PACKET - * control code to the NDISAPI driver using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function converts the adapter handle - * and buffer pointer using the Wow64Helper before sending the IOCTL, and copies the resulting packet from - * INTERMEDIATE_BUFFER_WOW64 to INTERMEDIATE_BUFFER. - */ -BOOL CNdisApi::ReadPacket(PETH_REQUEST pPacket) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ETH_REQUEST_WOW64 EthRequest; - INTERMEDIATE_BUFFER_WOW64 Buffer; - - // Initialize ETH_REQUEST_WOW64 - EthRequest.hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)pPacket->hAdapterHandle); - EthRequest.EthPacket.Buffer.HighPart = 0; - EthRequest.EthPacket.Buffer.LowPart = (ULONG_PTR)&Buffer; - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_READ_PACKET, - &EthRequest, - sizeof(ETH_REQUEST_WOW64), - &EthRequest, - sizeof(ETH_REQUEST_WOW64), - NULL, // Bytes Returned - NULL - ); - - if (bIOResult) - { - // Copy the resulting packet from INTERMEDIATE_BUFFER_WOW64 to INTERMEDIATE_BUFFER - pPacket->EthPacket.Buffer->m_dwDeviceFlags = Buffer.m_dwDeviceFlags; - pPacket->EthPacket.Buffer->m_Flags = Buffer.m_Flags; - pPacket->EthPacket.Buffer->m_8021q = Buffer.m_8021q; - pPacket->EthPacket.Buffer->m_FilterID = Buffer.m_FilterID; - memmove(pPacket->EthPacket.Buffer->m_Reserved, Buffer.m_Reserved, sizeof(ULONG) * 4); - pPacket->EthPacket.Buffer->m_Length = Buffer.m_Length; - memmove(pPacket->EthPacket.Buffer->m_IBuffer, Buffer.m_IBuffer, Buffer.m_Length); - } - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_READ_PACKET, - pPacket, - sizeof(ETH_REQUEST), - pPacket, - sizeof(ETH_REQUEST), - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sends multiple packets to the MSTCP (TCP/IP stack) from the Windows Packet Filter driver. - * - * @param pPackets Pointer to an ETH_M_REQUEST structure containing an array of packets to be sent. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sends multiple packets to the MSTCP (TCP/IP stack) from the Windows Packet Filter driver - * by sending an IOCTL_NDISRD_SEND_PACKETS_TO_MSTCP control code to the Windows Packet Filter driver - * using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function converts the adapter handle - * and buffer pointer using the Wow64Helper before sending the IOCTL. It also allocates and initializes - * ETH_M_REQUEST_WOW64 and INTERMEDIATE_BUFFER_WOW64 structures for the IOCTL call. - */ -BOOL CNdisApi::SendPacketsToMstcp(PETH_M_REQUEST pPackets) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - PINTERMEDIATE_BUFFER_WOW64 Buffers; - - const PETH_M_REQUEST_WOW64 pEthRequest = static_cast(malloc( - sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1))); - Buffers = static_cast(malloc(pPackets->dwPacketsNumber * sizeof(INTERMEDIATE_BUFFER_WOW64))); - - if (Buffers && pEthRequest) - { - memset(pEthRequest, 0, sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1)); - memset(Buffers, 0, pPackets->dwPacketsNumber * sizeof(INTERMEDIATE_BUFFER_WOW64)); - pEthRequest->hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle(reinterpret_cast(pPackets->hAdapterHandle)); - pEthRequest->dwPacketsNumber = pPackets->dwPacketsNumber; - - for (unsigned i = 0; i < pPackets->dwPacketsNumber; ++i) - { - // Initialize INTERMEDIATE_BUFFER_WOW64 - Buffers[i].m_dwDeviceFlags = pPackets->EthPacket[i].Buffer->m_dwDeviceFlags; - Buffers[i].m_Flags = pPackets->EthPacket[i].Buffer->m_Flags; - Buffers[i].m_8021q = pPackets->EthPacket[i].Buffer->m_8021q; - Buffers[i].m_FilterID = pPackets->EthPacket[i].Buffer->m_FilterID; - memmove(Buffers[i].m_Reserved, pPackets->EthPacket[i].Buffer->m_Reserved, sizeof(ULONG) * 4); - Buffers[i].m_Length = pPackets->EthPacket[i].Buffer->m_Length; - memmove(Buffers[i].m_IBuffer, pPackets->EthPacket[i].Buffer->m_IBuffer, Buffers[i].m_Length); - - // Initialize ETH_REQUEST_WOW64 - pEthRequest->EthPacket[i].Buffer.HighPart = 0; - pEthRequest->EthPacket[i].Buffer.LowPart = reinterpret_cast(&Buffers[i]); - } - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKETS_TO_MSTCP, - pEthRequest, - sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - free(Buffers); - free(pEthRequest); - } - else - { - if (Buffers) - free(Buffers); - - if (pEthRequest) - free(pEthRequest); - - return FALSE; - } - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKETS_TO_MSTCP, - pPackets, - sizeof(ETH_M_REQUEST) + sizeof(NDISRD_ETH_Packet) * (pPackets->dwPacketsNumber - 1), // NOLINT(bugprone-narrowing-conversions, cppcoreguidelines-narrowing-conversions) - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sends multiple packets to the network adapter from the Windows Packet Filter driver. - * - * @param pPackets Pointer to an ETH_M_REQUEST structure containing an array of packets to be sent. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sends multiple packets to the network adapter from the Windows Packet Filter driver - * by sending an IOCTL_NDISRD_SEND_PACKETS_TO_ADAPTER control code to the Windows Packet Filter driver - * using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function converts the adapter handle - * and buffer pointer using the Wow64Helper before sending the IOCTL. It also allocates and initializes - * ETH_M_REQUEST_WOW64 and INTERMEDIATE_BUFFER_WOW64 structures for the IOCTL call. - */ -BOOL CNdisApi::SendPacketsToAdapter(PETH_M_REQUEST pPackets) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - PINTERMEDIATE_BUFFER_WOW64 Buffers; - - const PETH_M_REQUEST_WOW64 pEthRequest = static_cast(malloc( - sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1))); - Buffers = static_cast(malloc(pPackets->dwPacketsNumber * sizeof(INTERMEDIATE_BUFFER_WOW64))); - - if (Buffers && pEthRequest) - { - memset(pEthRequest, 0, sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1)); - memset(Buffers, 0, pPackets->dwPacketsNumber * sizeof(INTERMEDIATE_BUFFER_WOW64)); - pEthRequest->hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle(reinterpret_cast(pPackets->hAdapterHandle)); - pEthRequest->dwPacketsNumber = pPackets->dwPacketsNumber; - - for (unsigned i = 0; i < pPackets->dwPacketsNumber; ++i) - { - // Initialize INTERMEDIATE_BUFFER_WOW64 - Buffers[i].m_dwDeviceFlags = pPackets->EthPacket[i].Buffer->m_dwDeviceFlags; - Buffers[i].m_Flags = pPackets->EthPacket[i].Buffer->m_Flags; - Buffers[i].m_8021q = pPackets->EthPacket[i].Buffer->m_8021q; - Buffers[i].m_FilterID = pPackets->EthPacket[i].Buffer->m_FilterID; - memmove(Buffers[i].m_Reserved, pPackets->EthPacket[i].Buffer->m_Reserved, sizeof(ULONG) * 4); - Buffers[i].m_Length = pPackets->EthPacket[i].Buffer->m_Length; - memmove(Buffers[i].m_IBuffer, pPackets->EthPacket[i].Buffer->m_IBuffer, Buffers[i].m_Length); - - // Initialize ETH_REQUEST_WOW64 - pEthRequest->EthPacket[i].Buffer.HighPart = 0; - pEthRequest->EthPacket[i].Buffer.LowPart = reinterpret_cast(&Buffers[i]); - } - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKETS_TO_ADAPTER, - pEthRequest, - sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - free(Buffers); - free(pEthRequest); - } - else - { - if (Buffers) - free(Buffers); - - if (pEthRequest) - free(pEthRequest); - - return FALSE; - } - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKETS_TO_ADAPTER, - pPackets, - sizeof(ETH_M_REQUEST) + sizeof(NDISRD_ETH_Packet) * (pPackets->dwPacketsNumber - 1), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Reads multiple packets from the network adapter through the Windows Packet Filter driver. - * - * @param pPackets Pointer to an ETH_M_REQUEST structure containing an array of packets to be read. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function reads multiple packets from the network adapter through the Windows Packet Filter - * driver by sending an IOCTL_NDISRD_READ_PACKETS control code to the Windows Packet Filter driver - * using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function allocates and initializes - * ETH_M_REQUEST_WOW64 and INTERMEDIATE_BUFFER_WOW64 structures for the IOCTL call. It also converts the adapter - * handle and buffer pointer using the Wow64Helper before sending the IOCTL. - */ -BOOL CNdisApi::ReadPackets(PETH_M_REQUEST pPackets) const -{ - BOOL bIOResult = FALSE; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - PETH_M_REQUEST_WOW64 pEthRequest = (PETH_M_REQUEST_WOW64)malloc(sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1)); - - if (!pEthRequest) - return bIOResult; - - PINTERMEDIATE_BUFFER_WOW64 Buffers = (PINTERMEDIATE_BUFFER_WOW64)malloc(pPackets->dwPacketsNumber * sizeof(INTERMEDIATE_BUFFER_WOW64)); - - if (!Buffers) - { - if (pEthRequest) - free(pEthRequest); - - return bIOResult; - } - - memset(pEthRequest, 0, sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1)); - memset(Buffers, 0, pPackets->dwPacketsNumber * sizeof(INTERMEDIATE_BUFFER_WOW64)); - - if (Buffers && pEthRequest) - { - pEthRequest->hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)pPackets->hAdapterHandle); - pEthRequest->dwPacketsNumber = pPackets->dwPacketsNumber; - - for (unsigned i = 0; i < pPackets->dwPacketsNumber; ++i) - { - // Initialize ETH_REQUEST_WOW64 - pEthRequest->EthPacket[i].Buffer.HighPart = 0; - pEthRequest->EthPacket[i].Buffer.LowPart = (ULONG_PTR)&Buffers[i]; - } - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_READ_PACKETS, - pEthRequest, - sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1), - pEthRequest, - sizeof(ETH_M_REQUEST_WOW64) + sizeof(NDISRD_ETH_Packet_WOW64) * (pPackets->dwPacketsNumber - 1), - NULL, // Bytes Returned - NULL - ); - - if (bIOResult) - { - pPackets->dwPacketsSuccess = pEthRequest->dwPacketsSuccess; - - for (unsigned i = 0; i < pEthRequest->dwPacketsSuccess; ++i) - { - // Copy back - pPackets->EthPacket[i].Buffer->m_dwDeviceFlags = Buffers[i].m_dwDeviceFlags; - pPackets->EthPacket[i].Buffer->m_Flags = Buffers[i].m_Flags; - pPackets->EthPacket[i].Buffer->m_8021q = Buffers[i].m_8021q; - pPackets->EthPacket[i].Buffer->m_FilterID = Buffers[i].m_FilterID; - memmove(pPackets->EthPacket[i].Buffer->m_Reserved, Buffers[i].m_Reserved, sizeof(ULONG) * 4); - pPackets->EthPacket[i].Buffer->m_Length = Buffers[i].m_Length; - memmove(pPackets->EthPacket[i].Buffer->m_IBuffer, Buffers[i].m_IBuffer, Buffers[i].m_Length); - } - } - - free(Buffers); - free(pEthRequest); - } - else - { - if (Buffers) - free(Buffers); - - if (pEthRequest) - free(pEthRequest); - - return FALSE; - } - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_READ_PACKETS, - pPackets, - sizeof(ETH_M_REQUEST) + sizeof(NDISRD_ETH_Packet) * (pPackets->dwPacketsNumber - 1), - pPackets, - sizeof(ETH_M_REQUEST) + sizeof(NDISRD_ETH_Packet) * (pPackets->dwPacketsNumber - 1), - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sets the filter mode of the network adapter for the Windows Packet Filter driver. - * - * @param pMode Pointer to an ADAPTER_MODE structure containing the adapter handle and the flags for the desired mode. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sets the filter mode of the network adapter for the Windows Packet Filter driver by sending an - * IOCTL_NDISRD_SET_ADAPTER_MODE control code to the Windows Packet Filter driver using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function initializes an - * ADAPTER_MODE_WOW64 structure with the mode flags and the converted adapter handle using Wow64Helper - * before sending the IOCTL. - */ -BOOL CNdisApi::SetAdapterMode(PADAPTER_MODE pMode) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ADAPTER_MODE_WOW64 AdapterMode; - AdapterMode.dwFlags = pMode->dwFlags; - AdapterMode.hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle(reinterpret_cast(pMode->hAdapterHandle)); - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_ADAPTER_MODE, - &AdapterMode, - sizeof(ADAPTER_MODE_WOW64), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_ADAPTER_MODE, - pMode, - sizeof(ADAPTER_MODE), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Retrieves the filter mode of the network adapter for the Windows Packet Filter driver. - * - * @param pMode Pointer to an ADAPTER_MODE structure containing the adapter handle. On success, the structure will be updated with the adapter mode flags. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function retrieves the filter mode of the network adapter for the Windows Packet Filter driver by sending an - * IOCTL_NDISRD_GET_ADAPTER_MODE control code to the Windows Packet Filter driver using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function initializes an - * ADAPTER_MODE_WOW64 structure with the converted adapter handle using Wow64Helper before sending the IOCTL. - * If the operation is successful, the mode flags are copied back to the input ADAPTER_MODE structure. - */ -BOOL CNdisApi::GetAdapterMode(PADAPTER_MODE pMode) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ADAPTER_MODE_WOW64 AdapterMode; - AdapterMode.hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)pMode->hAdapterHandle); - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_GET_ADAPTER_MODE, - &AdapterMode, - sizeof(ADAPTER_MODE_WOW64), - &AdapterMode, - sizeof(ADAPTER_MODE_WOW64), - NULL, // Bytes Returned - NULL - ); - - if (bIOResult) - pMode->dwFlags = AdapterMode.dwFlags; - - } - else -#endif // _WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_GET_ADAPTER_MODE, - pMode, - sizeof(ADAPTER_MODE), - pMode, - sizeof(ADAPTER_MODE), - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Flushes the packet queue of the specified network adapter. - * - * @param hAdapter The handle of the network adapter. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function flushes the packet queue of the specified network adapter by sending an - * IOCTL_NDISRD_FLUSH_ADAPTER_QUEUE control code to the Windows Packet Filter driver using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function converts the adapter handle using Wow64Helper - * before sending the IOCTL. - */ -BOOL CNdisApi::FlushAdapterPacketQueue(HANDLE hAdapter) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ULARGE_INTEGER h64Adapter; - h64Adapter.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)hAdapter); - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_FLUSH_ADAPTER_QUEUE, - &h64Adapter, - sizeof(ULARGE_INTEGER), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_FLUSH_ADAPTER_QUEUE, - &hAdapter, - sizeof(HANDLE), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Retrieves the size of the packet queue for the specified network adapter. - * - * @param hAdapter The handle of the network adapter. - * @param pdwSize Pointer to a DWORD variable that receives the packet queue size. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function retrieves the size of the packet queue for the specified network adapter by sending an - * IOCTL_NDISRD_ADAPTER_QUEUE_SIZE control code to the Windows Packet Filter driver using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function converts the adapter handle using Wow64Helper - * before sending the IOCTL. - */ -BOOL CNdisApi::GetAdapterPacketQueueSize(HANDLE hAdapter, PDWORD pdwSize) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ULARGE_INTEGER h64Adapter; - h64Adapter.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)hAdapter); - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_ADAPTER_QUEUE_SIZE, - &h64Adapter, - sizeof(ULARGE_INTEGER), - pdwSize, - sizeof(DWORD), - NULL, // Bytes Returned - NULL - ); - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_ADAPTER_QUEUE_SIZE, - &hAdapter, - sizeof(HANDLE), - pdwSize, - sizeof(DWORD), - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sets a Win32 event to be signaled when a packet arrives at the specified network adapter. - * - * @param hAdapter The handle of the network adapter. - * @param hWin32Event The handle of the Win32 event to be signaled when a packet arrives. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sets a Win32 event to be signaled when a packet arrives at the specified network adapter by - * sending an IOCTL_NDISRD_SET_EVENT control code to the Windows Packet Filter driver using DeviceIoControl. - * - * The function converts the event handle to a Ring0 event handle for Windows NT platforms, and to a VxD event handle - * for Windows 9x/ME platforms. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function initializes an ADAPTER_EVENT_WOW64 - * structure with the converted adapter and event handles using Wow64Helper before sending the IOCTL. - */ -BOOL CNdisApi::SetPacketEvent(HANDLE hAdapter, HANDLE hWin32Event) const -{ - HANDLE hRing0Event; - ADAPTER_EVENT AdapterEvent; - - AdapterEvent.hAdapterHandle = hAdapter; - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT - hRing0Event = hWin32Event; - } - else - { - // Windows 9x/ME - const HINSTANCE hKernel32Dll = LoadLibrary(TEXT("kernel32.dll")); - - if (!hKernel32Dll) - return FALSE; - - HANDLE(WINAPI * pfOpenVxDHandle)(HANDLE) = reinterpret_cast(GetProcAddress( - hKernel32Dll, "OpenVxDHandle")); - - if (!pfOpenVxDHandle) - { - FreeLibrary(hKernel32Dll); - return FALSE; - } - - if (hWin32Event) - hRing0Event = pfOpenVxDHandle(hWin32Event); - else - hRing0Event = NULL; - - FreeLibrary(hKernel32Dll); - } - - AdapterEvent.hEvent = hRing0Event; - - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ADAPTER_EVENT_WOW64 AdapterEvent64; - AdapterEvent64.hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)AdapterEvent.hAdapterHandle); - AdapterEvent64.hEvent.HighPart = 0; - AdapterEvent64.hEvent.LowPart = (ULONG_PTR)AdapterEvent.hEvent; - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_EVENT, - &AdapterEvent64, - sizeof(ADAPTER_EVENT_WOW64), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_EVENT, - &AdapterEvent, - sizeof(ADAPTER_EVENT), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sets a Win32 event to be signaled when a NDISWAN adapter connect/disconnect occurs. - * - * @param hWin32Event The handle of the Win32 event to be signaled when a NDISWAN adapter connect/disconnect occurs. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sets a Win32 event to be signaled when a NDISWAN adapter connect/disconnect occurs by sending an - * IOCTL_NDISRD_SET_WAN_EVENT control code to the Windows Packet Filter driver using DeviceIoControl. - * - * The function converts the event handle to a Ring0 event handle for Windows NT platforms, and to a VxD event handle - * for Windows 9x/ME platforms. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function initializes an ULARGE_INTEGER - * structure with the converted event handle before sending the IOCTL. - */ -BOOL CNdisApi::SetWANEvent(HANDLE hWin32Event) const -{ - HANDLE hRing0Event; - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT - hRing0Event = hWin32Event; - } - else - { - // Windows 9x/ME - const HINSTANCE hKernel32Dll = LoadLibrary(TEXT("kernel32.dll")); - - if (!hKernel32Dll) - return FALSE; - - HANDLE(WINAPI * pfOpenVxDHandle)(HANDLE) = reinterpret_cast(GetProcAddress(hKernel32Dll, "OpenVxDHandle")); - - if (!pfOpenVxDHandle) - return FALSE; - - if (hWin32Event) - hRing0Event = pfOpenVxDHandle(hWin32Event); - else - hRing0Event = NULL; - - FreeLibrary(hKernel32Dll); - } - - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ULARGE_INTEGER ulRing0Event; - ulRing0Event.HighPart = 0; - ulRing0Event.LowPart = (ULONG_PTR)hRing0Event; - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_WAN_EVENT, - &ulRing0Event, - sizeof(ULARGE_INTEGER), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_WAN_EVENT, - &hRing0Event, - sizeof(HANDLE), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sets a Win32 event to be signaled when a network adapter list change occurs. - * - * @param hWin32Event The handle of the Win32 event to be signaled when a network adapter list change occurs. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sets a Win32 event to be signaled when a network adapter list change occurs by sending an - * IOCTL_NDISRD_SET_ADAPTER_EVENT control code to the Windows Packet Filter driver using DeviceIoControl. - * - * The function converts the event handle to a Ring0 event handle for Windows NT platforms, and to a VxD event handle - * for Windows 9x/ME platforms. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function initializes an ULARGE_INTEGER - * structure with the converted event handle before sending the IOCTL. - */ -BOOL CNdisApi::SetAdapterListChangeEvent(HANDLE hWin32Event) const -{ - HANDLE hRing0Event; - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT - hRing0Event = hWin32Event; - } - else - { - // Windows 9x/ME - const HINSTANCE hKernel32Dll = LoadLibrary(TEXT("kernel32.dll")); - - if (!hKernel32Dll) - return FALSE; - - HANDLE(WINAPI * pfOpenVxDHandle)(HANDLE) = reinterpret_cast(GetProcAddress(hKernel32Dll, "OpenVxDHandle")); - - if (!pfOpenVxDHandle) - return FALSE; - - if (hWin32Event) - hRing0Event = pfOpenVxDHandle(hWin32Event); - else - hRing0Event = NULL; - - FreeLibrary(hKernel32Dll); - } - - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ULARGE_INTEGER ulRing0Event; - ulRing0Event.HighPart = 0; - ulRing0Event.LowPart = (ULONG_PTR)hRing0Event; - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_ADAPTER_EVENT, - &ulRing0Event, - sizeof(ULARGE_INTEGER), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_ADAPTER_EVENT, - &hRing0Event, - sizeof(HANDLE), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sends an NDIS request to the network adapter through the Windows Packet Filter driver. - * - * @param OidData A pointer to the PACKET_OID_DATA structure that contains the NDIS request data. - * @param Set A boolean value that indicates whether the request is a set (TRUE) or get (FALSE) operation. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sends an NDIS request to the network adapter through the Windows Packet Filter driver - * using DeviceIoControl. - * The request can be either a set or a get operation, depending on the value of the Set parameter. - * The function uses an OVERLAPPED structure to handle asynchronous I/O operations. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function allocates and initializes - * a PACKET_OID_DATA_WOW64 structure with the original PACKET_OID_DATA structure's data, and sends the IOCTL - * using the PACKET_OID_DATA_WOW64 structure. - * - * If the operation is not successful, the function returns FALSE. - */ -BOOL CNdisApi::NdisrdRequest(PPACKET_OID_DATA OidData, BOOL Set) const -{ - OVERLAPPED Overlap; - const DWORD dwLength = OidData->Length; - - Overlap.Offset = 0; - Overlap.OffsetHigh = 0; - Overlap.hEvent = CreateEvent( - NULL, - FALSE, - FALSE, - NULL - ); - - if (Overlap.hEvent == NULL) - { - return FALSE; - } - - if (!ResetEvent(Overlap.hEvent)) - { - ::CloseHandle(Overlap.hEvent); - return FALSE; - } - - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - PPACKET_OID_DATA_WOW64 OidData64 = (PPACKET_OID_DATA_WOW64)malloc(sizeof(PACKET_OID_DATA_WOW64) + OidData->Length - 1); - if (OidData64) - { - OidData64->hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)OidData->hAdapterHandle); - OidData64->Oid = OidData->Oid; - OidData64->Length = OidData->Length; - if (Set) - memmove(OidData64->Data, OidData->Data, OidData->Length); - - bIOResult = DeviceIoControl( - (DWORD)Set ? IOCTL_NDISRD_NDIS_SET_REQUEST : IOCTL_NDISRD_NDIS_GET_REQUEST, - OidData64, - sizeof(PACKET_OID_DATA_WOW64) - 1 + OidData->Length, - OidData64, - sizeof(PACKET_OID_DATA_WOW64) - 1 + OidData->Length, - NULL, // Bytes Returned - &Overlap - ); - - if ((!bIOResult) && (ERROR_IO_PENDING == GetLastError())) - { - WaitForSingleObject(Overlap.hEvent, INFINITE); - - if (!Set) - { - memmove(OidData->Data, OidData64->Data, OidData64->Length); - OidData->Length = OidData64->Length; - } - } - else - if (!bIOResult) - { - ::CloseHandle(Overlap.hEvent); - free(OidData64); - return FALSE; - } - - free(OidData64); - } - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - static_cast(Set) ? IOCTL_NDISRD_NDIS_SET_REQUEST : IOCTL_NDISRD_NDIS_GET_REQUEST, - OidData, - sizeof(PACKET_OID_DATA) - 1 + OidData->Length, - OidData, - sizeof(PACKET_OID_DATA) - 1 + OidData->Length, - NULL, // Bytes Returned - &Overlap - ); - - if ((!bIOResult) && (ERROR_IO_PENDING == GetLastError())) - WaitForSingleObject(Overlap.hEvent, INFINITE); - else - if (!bIOResult) - { - ::CloseHandle(Overlap.hEvent); - return FALSE; - } - } - - ::CloseHandle(Overlap.hEvent); - - if (dwLength == OidData->Length) - return TRUE; - - return FALSE; -} - -/** - * @brief Retrieves the RAS links associated with a network adapter. - * - * @param hAdapter A handle to the network adapter for which the RAS links are to be retrieved. - * @param pLinks A pointer to a RAS_LINKS structure that will receive the RAS links information. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function retrieves the RAS links associated with a network adapter by sending an - * IOCTL_NDISRD_GET_RAS_LINKS control code to the Windows Packet Filter driver using DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function initializes an - * ULARGE_INTEGER structure with the adapter handle before sending the IOCTL. - */ -BOOL CNdisApi::GetRasLinks(HANDLE hAdapter, PRAS_LINKS pLinks) const -{ - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ULARGE_INTEGER h64Adapter; - h64Adapter.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)hAdapter); - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_GET_RAS_LINKS, - &h64Adapter, - sizeof(ULARGE_INTEGER), - pLinks, - sizeof(RAS_LINKS), - NULL, // Bytes Returned - NULL - ); - } - else -#endif // _WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_GET_RAS_LINKS, - &hAdapter, - sizeof(HANDLE), - pLinks, - sizeof(RAS_LINKS), - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sets the hardware packet filter for the network adapter. - * - * @param hAdapter The handle of the network adapter. - * @param Filter The packet filter bitmask to be set. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sets the hardware packet filter for the network adapter by sending an NDIS set request - * with OID_GEN_CURRENT_PACKET_FILTER. It uses the CNdisApi::NdisrdRequest function to send the request. - * - * The function allocates memory for the PACKET_OID_DATA structure, initializes it with the provided - * filter bitmask, and sends the set request. After the operation, the memory for PACKET_OID_DATA is freed. - */ -BOOL CNdisApi::SetHwPacketFilter(HANDLE hAdapter, const DWORD Filter) const -{ - BOOL bRet = FALSE; - const PPACKET_OID_DATA pPacket = static_cast(malloc(sizeof(PACKET_OID_DATA) + sizeof(DWORD) - 1)); - - if (pPacket) - { - pPacket->Length = sizeof(DWORD); - pPacket->Oid = OID_GEN_CURRENT_PACKET_FILTER; - pPacket->hAdapterHandle = hAdapter; - - *reinterpret_cast(pPacket->Data) = Filter; - bRet = NdisrdRequest(pPacket, TRUE); - - free(pPacket); - } - - return bRet; -} - -/** - * @brief Gets the hardware packet filter for the network adapter. - * - * @param hAdapter The handle of the network adapter. - * @param pFilter A pointer to a DWORD variable that will receive the current packet filter bitmask. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function retrieves the hardware packet filter for the network adapter by sending an NDIS get request - * with OID_GEN_CURRENT_PACKET_FILTER. It uses the CNdisApi::NdisrdRequest function to send the request. - * - * The function allocates memory for the PACKET_OID_DATA structure, initializes it, and sends the get request. - * If the operation is successful, the function copies the retrieved packet filter bitmask to the pFilter - * parameter. After the operation, the memory for PACKET_OID_DATA is freed. - */ -BOOL CNdisApi::GetHwPacketFilter(HANDLE hAdapter, PDWORD pFilter) const -{ - BOOL bRet = FALSE; - - const PPACKET_OID_DATA pPacket = static_cast(malloc(sizeof(PACKET_OID_DATA) + sizeof(DWORD) - 1)); - - if (pPacket) - { - pPacket->Length = sizeof(DWORD); - pPacket->Oid = OID_GEN_CURRENT_PACKET_FILTER; - pPacket->hAdapterHandle = hAdapter; - - if (NdisrdRequest(pPacket, FALSE)) - { - *pFilter = *reinterpret_cast(pPacket->Data); - - bRet = TRUE; - } - - free(pPacket); - } - return bRet; -} - -/** - * @brief Sets the hardware packet filter change event for the network adapter. - * - * @param hAdapter The handle of the network adapter. - * @param hWin32Event The Win32 event handle to be signaled when a hardware filter on the adapter changes. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sets the hardware packet filter change event for the network adapter. The specified event will - * be signaled when a hardware filter on the adapter changes. It uses DeviceIoControl - * with the IOCTL_NDISRD_SET_ADAPTER_HWFILTER_EVENT code to perform the operation. - * - * The function first checks if the operating system is Windows NT or Windows 9x/ME. On Windows NT, the - * ring 0 event is set to the provided Win32 event. On Windows 9x/ME, the function loads the kernel32.dll - * library, resolves the OpenVxDHandle function, and calls it to obtain a ring 0 event from the provided - * Win32 event. The function then initializes an ADAPTER_EVENT structure and sends the IOCTL using - * DeviceIoControl. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function initializes an - * ADAPTER_EVENT_WOW64 structure with the original ADAPTER_EVENT structure's data, and sends the IOCTL - * using the ADAPTER_EVENT_WOW64 structure. - */ -BOOL CNdisApi::SetHwPacketFilterEvent(HANDLE hAdapter, HANDLE hWin32Event) const -{ - HANDLE hRing0Event; - ADAPTER_EVENT AdapterEvent; - - AdapterEvent.hAdapterHandle = hAdapter; - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT - hRing0Event = hWin32Event; - } - else - { - // Windows 9x/ME - const HINSTANCE hKernel32Dll = LoadLibrary(TEXT("kernel32.dll")); - - if (!hKernel32Dll) - return FALSE; - - HANDLE(WINAPI * pfOpenVxDHandle)(HANDLE) = reinterpret_cast(GetProcAddress(hKernel32Dll, "OpenVxDHandle")); - - if (!pfOpenVxDHandle) - return FALSE; - - if (hWin32Event) - hRing0Event = pfOpenVxDHandle(hWin32Event); - else - hRing0Event = NULL; - - FreeLibrary(hKernel32Dll); - } - - AdapterEvent.hEvent = hRing0Event; - - BOOL bIOResult; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - ADAPTER_EVENT_WOW64 AdapterEvent64; - AdapterEvent64.hAdapterHandle.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)AdapterEvent.hAdapterHandle); - AdapterEvent64.hEvent.HighPart = 0; - AdapterEvent64.hEvent.LowPart = (ULONG_PTR)AdapterEvent.hEvent; - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_ADAPTER_HWFILTER_EVENT, - &AdapterEvent64, - sizeof(ADAPTER_EVENT_WOW64), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - else -#endif //_WIN64 - { - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_ADAPTER_HWFILTER_EVENT, - &AdapterEvent, - sizeof(ADAPTER_EVENT), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - } - - return bIOResult; -} - -/** - * @brief Sets the static packet filter table for the Windows Packet Filter driver. - * - * @param pFilterList A pointer to the STATIC_FILTER_TABLE structure containing the packet filter rules. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sets the static packet filter table for the Windows Packet Filter driver. The table - * contains a list of packet filter rules that determine which packets should be processed by the driver, - * e.g. passed, dropped or redirected to user-mode application for further processing. - * It uses DeviceIoControl with the IOCTL_NDISRD_SET_PACKET_FILTERS code to perform the operation. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function iterates through the - * filter list and updates the adapter handle values using the From32to64Handle method from the WOW64 helper - * before passing the filter list to the driver. - */ -BOOL CNdisApi::SetPacketFilterTable(PSTATIC_FILTER_TABLE pFilterList) const -{ - BOOL bIOResult = FALSE; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - // Adapter handle values in the table contain values which are not valid for the driver - // and we need to pre-process filter table before passing it to the driver - - for (unsigned i = 0; i < pFilterList->m_TableSize; ++i) - { - if (pFilterList->m_StaticFilters[i].m_Adapter.QuadPart) - pFilterList->m_StaticFilters[i].m_Adapter.QuadPart = - m_Wow64Helper.From32to64Handle((unsigned)pFilterList->m_StaticFilters[i].m_Adapter.LowPart); - } - } -#endif //_WIN64 - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_SET_PACKET_FILTERS, - pFilterList, - sizeof(STATIC_FILTER_TABLE) + (pFilterList->m_TableSize - ANY_SIZE) * sizeof(STATIC_FILTER), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Adds a static filter to the front of the filter list in the Windows Packet Filter driver. - * - * @param pFilter A pointer to the STATIC_FILTER structure containing the filter to be added. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function adds a static filter to the front of the filter list in the Windows Packet Filter driver. - * The filter determines how packets are processed by the driver, e.g., passed, dropped, or redirected - * to user-mode application for further processing. It uses DeviceIoControl with the - * IOCTL_NDISRD_ADD_PACKET_FILTER_FRONT code to perform the operation. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function updates the adapter - * handle value in the filter using the From32to64Handle method from the WOW64 helper before passing - * the filter to the driver. - */ -BOOL CNdisApi::AddStaticFilterFront(PSTATIC_FILTER pFilter) const -{ - BOOL bIOResult = FALSE; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - // Adapter handle values in the filter contain values which are not valid for the driver - // and we need to pre-process filter before passing it to the driver - - if (pFilter->m_Adapter.QuadPart) - pFilter->m_Adapter.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)pFilter->m_Adapter.LowPart); - } -#endif //_WIN64 - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_ADD_PACKET_FILTER_FRONT, - pFilter, - sizeof(STATIC_FILTER), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Adds a static filter to the end of the filter chain. - * - * This method appends a static filter to the end of the existing filter chain for packet processing. - * In a 32-bit process on a 64-bit system, it converts the adapter handle from 32-bit to 64-bit using - * the WOW64 helper before passing the filter to the driver. This ensures compatibility across different - * system architectures. The filter is defined by the PSTATIC_FILTER structure, which includes details - * such as the filter action, direction, and conditions. - * - * @param pFilter Pointer to the STATIC_FILTER structure that defines the filter to be added. - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL CNdisApi::AddStaticFilterBack(PSTATIC_FILTER pFilter) const -{ - BOOL bIOResult = FALSE; - -#ifndef _WIN64 - if (m_bIsWow64Process) - { - // Adapter handle values in the filter contain values which are not valid for the driver - // and we need to pre-process filter before passing it to the driver - - if (pFilter->m_Adapter.QuadPart) - pFilter->m_Adapter.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)pFilter->m_Adapter.LowPart); - } -#endif //_WIN64 - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_ADD_PACKET_FILTER_BACK, - pFilter, - sizeof(STATIC_FILTER), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Inserts a static filter at a specified position in the filter chain. - * - * This method inserts a static filter into the filter chain at the specified position. The position - * determines the order in which filters are applied, with lower values indicating higher priority. - * In a 32-bit process on a 64-bit system, it converts the adapter handle from 32-bit to 64-bit using - * the WOW64 helper before passing the filter to the driver. This ensures compatibility across different - * system architectures. The filter is defined by the PSTATIC_FILTER structure, which includes details - * such as the filter action, direction, and conditions. - * - * @param pFilter Pointer to the STATIC_FILTER structure that defines the filter to be inserted. - * @param Position The position in the filter chain where the filter should be inserted. - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL CNdisApi::InsertStaticFilter(PSTATIC_FILTER pFilter, unsigned long Position) const -{ - BOOL bIOResult = FALSE; - -#ifndef _WIN64 - if (m_bIsWow64Process) { - // Adapter handle values in the filter contain values which are not valid for the driver - // and we need to pre-process filter before passing it to the driver - - if (pFilter->m_Adapter.QuadPart) - pFilter->m_Adapter.QuadPart = m_Wow64Helper.From32to64Handle((unsigned)pFilter->m_Adapter.LowPart); - } -#endif //_WIN64 - - STATIC_FILTER_WITH_POSITION DriverData; - DriverData.m_StaticFilter = *pFilter; - DriverData.m_Position = Position; - - bIOResult = DeviceIoControl( - IOCTL_NDISRD_INSERT_FILTER_BY_INDEX, - &DriverData, - sizeof(STATIC_FILTER_WITH_POSITION), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Removes a static filter by its unique identifier. - * - * This method removes a previously added static filter from the filter chain based on its unique identifier. - * The identifier is a DWORD value that uniquely identifies the filter to be removed. This operation directly - * communicates with the driver using the IOCTL_NDISRD_REMOVE_FILTER_BY_INDEX control code to perform the removal. - * If the operation is successful, the filter is no longer applied to the network packets. - * - * @param dwFilterId The unique identifier of the filter to be removed. - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL CNdisApi::RemoveStaticFilter(DWORD dwFilterId) const -{ - BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_REMOVE_FILTER_BY_INDEX, - &dwFilterId, - sizeof(DWORD), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Resets the static packet filter table for the Windows Packet Filter driver. - * - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function resets the static packet filter table for the Windows Packet Filter driver, - * effectively removing all the packet filter rules previously set. - * It uses DeviceIoControl with the IOCTL_NDISRD_RESET_PACKET_FILTERS code to perform the operation. - */ -BOOL CNdisApi::ResetPacketFilterTable() const -{ - const BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_RESET_PACKET_FILTERS, - NULL, - 0, - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Retrieves the size of the currently loaded static packet filter table from the Windows Packet Filter driver. - * - * @param pdwTableSize A pointer to a DWORD variable that receives the size of the packet filter table. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function retrieves the size of the static packet filter table from the Windows Packet Filter driver. - * The table contains a list of packet filter rules that determine which packets should be processed by the driver. - * It uses DeviceIoControl with the IOCTL_NDISRD_GET_PACKET_FILTERS_TABLESIZE code to perform the operation. - */ -BOOL CNdisApi::GetPacketFilterTableSize(PDWORD pdwTableSize) const -{ - const BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_GET_PACKET_FILTERS_TABLESIZE, - NULL, - 0, - pdwTableSize, - sizeof(DWORD), - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Retrieves the static packet filter table from the Windows Packet Filter driver. - * - * @param pFilterList A pointer to the STATIC_FILTER_TABLE structure that receives the packet filter rules. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function retrieves the static packet filter table from the Windows Packet Filter driver. The table - * contains a list of packet filter rules that determine which packets should be processed by the driver, - * e.g. passed, dropped or redirected to user-mode application for further processing. - * It uses DeviceIoControl with the IOCTL_NDISRD_GET_PACKET_FILTERS code to perform the operation. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function iterates through the - * filter list and updates the adapter handle values using the From64to32Handle method from the WOW64 helper - * after receiving the filter list from the driver. - */ -BOOL CNdisApi::GetPacketFilterTable(PSTATIC_FILTER_TABLE pFilterList) const -{ - BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_GET_PACKET_FILTERS, - NULL, - 0, - pFilterList, - sizeof(STATIC_FILTER_TABLE) + (pFilterList->m_TableSize - ANY_SIZE) * sizeof(STATIC_FILTER), - NULL, // Bytes Returned - NULL - ); -#ifndef _WIN64 - if (bIOResult && m_bIsWow64Process) - { - // Adapter handle values in the table contain values which are not valid for the client - // and we need to post-process filter table before passing it to the client - - for (unsigned i = 0; i < pFilterList->m_TableSize; ++i) - { - pFilterList->m_StaticFilters[i].m_Adapter.QuadPart = - m_Wow64Helper.From64to32Handle(pFilterList->m_StaticFilters[i].m_Adapter.QuadPart); - } - } -#endif //_WIN64 - - return bIOResult; -} - -/** - * @brief Retrieves the static packet filter table and resets statistics for the Windows Packet Filter driver. - * - * @param pFilterList A pointer to the STATIC_FILTER_TABLE structure that receives the packet filter rules. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function retrieves the static packet filter table from the Windows Packet Filter driver and resets - * the packet filtering statistics. The table contains a list of packet filter rules that determine which - * packets should be processed by the driver, e.g. passed, dropped or redirected to user-mode application - * for further processing. It uses DeviceIoControl with the IOCTL_NDISRD_GET_PACKET_FILTERS_RESET_STATS code - * to perform the operation. - * - * For 32-bit processes running on a 64-bit operating system (WOW64), the function iterates through the - * filter list and updates the adapter handle values using the From64to32Handle method from the WOW64 helper - * after receiving the filter list from the driver. - */ -BOOL CNdisApi::GetPacketFilterTableResetStats(PSTATIC_FILTER_TABLE pFilterList) const -{ - BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_GET_PACKET_FILTERS_RESET_STATS, - NULL, - 0, - pFilterList, - sizeof(STATIC_FILTER_TABLE) + (pFilterList->m_TableSize - ANY_SIZE) * sizeof(STATIC_FILTER), - NULL, // Bytes Returned - NULL - ); - -#ifndef _WIN64 - if (bIOResult && m_bIsWow64Process) - { - // Adapter handle values in the table contain values which are not valid for the client - // and we need to post-process filter table before passing it to the client - - for (unsigned i = 0; i < pFilterList->m_TableSize; ++i) - { - pFilterList->m_StaticFilters[i].m_Adapter.QuadPart = - m_Wow64Helper.From64to32Handle(pFilterList->m_StaticFilters[i].m_Adapter.QuadPart); - } - } -#endif //_WIN64 - - return bIOResult; -} - -/** - * @brief Sets the state of the packet filter cache. - * - * This method enables or disables the packet filter cache based on the provided state. The packet filter cache - * is used to temporarily store packet filter information to improve performance. Enabling the cache can lead to - * faster packet processing, while disabling it may be useful for debugging or in scenarios where the most up-to-date - * filter information is required. The state is set by sending the IOCTL_NDISRD_SET_FILTER_CACHE_STATE control code - * to the driver. - * - * @param dwState The desired state of the packet filter cache. TRUE to enable, FALSE to disable. - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL CNdisApi::SetPacketFilterCacheState(BOOL bState) const -{ - DWORD dwState = static_cast(bState); - - return DeviceIoControl( - IOCTL_NDISRD_SET_FILTER_CACHE_STATE, - &dwState, - sizeof(DWORD), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); -} - -/** - * @brief Sets the state of the packet fragment cache. - * - * This function enables or disables the packet fragment cache. The packet fragment cache is used to improve - * performance by caching packet fragments. Enabling the cache can improve packet processing speed, while - * disabling it may be useful for debugging or in scenarios where caching is not desirable. - * - * @param bState A BOOL value where TRUE enables the cache and FALSE disables it. - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL CNdisApi::SetPacketFragmentCacheState(BOOL bState) const -{ - DWORD dwState = static_cast(bState); - - return DeviceIoControl( - IOCTL_NDISRD_SET_FRAGMENT_CACHE_STATE, - &dwState, - sizeof(DWORD), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); -} - -/** - * @brief Enables the packet filter cache. - * - * This method enables the packet filter cache, which is used to temporarily store packet filter information - * to improve performance. Enabling the cache can lead to faster packet processing. The cache is enabled by - * setting its state to TRUE using the SetPacketFilterCacheState method. - * - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL CNdisApi::EnablePacketFilterCache() const -{ - return SetPacketFilterCacheState(TRUE); -} - -/** - * @brief Disables the packet filter cache. - * - * This method disables the packet filter cache. Disabling the cache may be useful for debugging or in scenarios - * where the most up-to-date filter information is required. The cache is disabled by setting its state to FALSE - * using the SetPacketFilterCacheState method. - * - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL CNdisApi::DisablePacketFilterCache() const -{ - return SetPacketFilterCacheState(FALSE); -} - -/** - * @brief Enables the packet fragment cache. - * - * This function enables the packet fragment cache by calling SetPacketFragmentCacheState with TRUE. - * Enabling the cache can improve performance by caching packet fragments, which can be beneficial - * for packet processing speed. - * - * @return TRUE if the cache was successfully enabled, FALSE otherwise. - */ -BOOL CNdisApi::EnablePacketFragmentCache() const -{ - return SetPacketFragmentCacheState(TRUE); -} - -/** - * @brief Disables the packet fragment cache. - * - * This function disables the packet fragment cache by calling SetPacketFragmentCacheState with FALSE. - * Disabling the cache may be useful for debugging or in scenarios where caching is not desirable. - * - * @return TRUE if the cache was successfully disabled, FALSE otherwise. - */ -BOOL CNdisApi::DisablePacketFragmentCache() const -{ - return SetPacketFragmentCacheState(FALSE); -} - -/** - * @brief Checks if the Windows Packet Filter driver is loaded successfully. - * - * @return BOOL Returns TRUE if the driver is loaded successfully, or FALSE otherwise. - * - * This function checks if the Windows Packet Filter driver is loaded successfully during the - * initialization of the CNdisApi object. If the driver is not loaded, the CNdisApi object - * will not be able to perform operations on the driver. - */ -BOOL CNdisApi::IsDriverLoaded() const -{ - return m_bIsLoadSuccessfully; -} - -/** - * @brief Initializes the Fast I/O shared memory section. - * - * @param pFastIo Pointer to user allocated memory to be used as a shared section. - * @param dwSize Size in bytes of allocated memory. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function initializes the Fast I/O shared memory section for the Windows Packet Filter driver. - * Fast I/O provides a more efficient way to transfer data between user mode and kernel mode, - * improving the performance of packet processing. It is supported only for Windows Vista and later, - * and not available in WOW64 mode. - * - * The function uses DeviceIoControl with the IOCTL_NDISRD_INITIALIZE_FAST_IO code to perform the operation. - */ -BOOL CNdisApi::InitializeFastIo(PFAST_IO_SECTION pFastIo, DWORD dwSize) const -{ - // Only supported for Vista and later. Can't be used in WOW64 mode. - if (!IsWindowsVistaOrLater() || m_bIsWow64Process || (dwSize < sizeof(FAST_IO_SECTION))) - return FALSE; - - INITIALIZE_FAST_IO_PARAMS params = { pFastIo, dwSize }; - - const BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_INITIALIZE_FAST_IO, - ¶ms, - sizeof(INITIALIZE_FAST_IO_PARAMS), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Adds a secondary Fast I/O shared memory section. - * - * @param pFastIo Pointer to user allocated memory to be used as a shared section. - * @param dwSize Size in bytes of allocated memory. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function adds a secondary Fast I/O shared memory section for the Windows Packet Filter driver. - * Fast I/O provides a more efficient way to transfer data between user mode and kernel mode, - * improving the performance of packet processing. It is supported only for Windows Vista and later, - * and not available in WOW64 mode. - * - * The function uses DeviceIoControl with the IOCTL_NDISRD_ADD_SECOND_FAST_IO_SECTION code to - * perform the operation. - */ -BOOL CNdisApi::AddSecondaryFastIo(PFAST_IO_SECTION pFastIo, DWORD dwSize) const -{ - // Only supported for Vista and later. Can't be used in WOW64 mode. - if (!IsWindowsVistaOrLater() || m_bIsWow64Process || (dwSize < sizeof(FAST_IO_SECTION))) - return FALSE; - - INITIALIZE_FAST_IO_PARAMS params = { pFastIo, dwSize }; - - const BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_ADD_SECOND_FAST_IO_SECTION, - ¶ms, - sizeof(INITIALIZE_FAST_IO_PARAMS), - NULL, - 0, - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Reads a bunch of packets from the driver packet queues without sorting by network adapter. - * - * @param Packets Array of INTERMEDIATE_BUFFER pointers. - * @param dwPacketsNum Number of packets in the array above. The associated adapter handle will be stored - * in the INTERMEDIATE_BUFFER.m_hAdapter field. - * @param pdwPacketsSuccess Pointer to store the number of packets successfully read from the driver. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function reads a bunch of packets from the driver packet queues without sorting by network adapter. - * The associated adapter handle will be stored in the INTERMEDIATE_BUFFER.m_hAdapter field. - * The function is not available in WOW64 mode. - * - * The function uses DeviceIoControl with the IOCTL_NDISRD_READ_PACKETS_UNSORTED code to perform the operation. - */ -BOOL CNdisApi::ReadPacketsUnsorted(PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketsSuccess) const -{ - if (m_bIsWow64Process) - return FALSE; - - UNSORTED_READ_SEND_REQUEST request = { Packets, dwPacketsNum }; - - const BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_READ_PACKETS_UNSORTED, - &request, - sizeof(UNSORTED_READ_SEND_REQUEST), - &request, - sizeof(UNSORTED_READ_SEND_REQUEST), - NULL, // Bytes Returned - NULL - ); - - *pdwPacketsSuccess = request.packets_num; - - return bIOResult; -} - -/** - * @brief Sends a bunch of packets to the network adapters. - * - * @param Packets Array of INTERMEDIATE_BUFFER pointers. The target adapter handle should be set - * in the INTERMEDIATE_BUFFER.m_hAdapter field. - * @param dwPacketsNum Number of packets in the array above. - * @param pdwPacketSuccess Pointer to store the number of packets successfully sent to the adapters. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sends a bunch of packets to the network adapters. The target adapter handle - * should be set in the INTERMEDIATE_BUFFER.m_hAdapter field. The function is not available in WOW64 mode. - * - * The function uses DeviceIoControl with the IOCTL_NDISRD_SEND_PACKET_TO_ADAPTER_UNSORTED code to perform the operation. - */ -BOOL CNdisApi::SendPacketsToAdaptersUnsorted(PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketSuccess) const -{ - if (m_bIsWow64Process) - return FALSE; - - UNSORTED_READ_SEND_REQUEST request = { Packets, dwPacketsNum }; - - const BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKET_TO_ADAPTER_UNSORTED, - &request, - sizeof(UNSORTED_READ_SEND_REQUEST), - &request, - sizeof(UNSORTED_READ_SEND_REQUEST), - NULL, // Bytes Returned - NULL - ); - - *pdwPacketSuccess = request.packets_num; - - return bIOResult; -} - -/** - * @brief Indicates a bunch of packets to the MSTCP (and other upper layer network protocols). - * - * @param Packets Array of INTERMEDIATE_BUFFER pointers. The associated adapter handle should be stored - * in the INTERMEDIATE_BUFFER.m_hAdapter field. - * @param dwPacketsNum Number of packets in the array above. - * @param pdwPacketSuccess Pointer to store the number of packets successfully sent to the MSTCP. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function Indicates a bunch of packets to the MSTCP (and other upper layer network protocols). - * The associated adapter handle is stored in the INTERMEDIATE_BUFFER.m_hAdapter field. The function is not available in WOW64 mode. - * - * The function uses DeviceIoControl with the IOCTL_NDISRD_SEND_PACKET_TO_MSTCP_UNSORTED code to perform the operation. - */ -BOOL CNdisApi::SendPacketsToMstcpUnsorted(PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketSuccess) const -{ - if (m_bIsWow64Process) - return FALSE; - - UNSORTED_READ_SEND_REQUEST request = { Packets, dwPacketsNum }; - - const BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_SEND_PACKET_TO_MSTCP_UNSORTED, - &request, - sizeof(UNSORTED_READ_SEND_REQUEST), - &request, - sizeof(UNSORTED_READ_SEND_REQUEST), - NULL, // Bytes Returned - NULL - ); - - *pdwPacketSuccess = request.packets_num; - - return bIOResult; -} - -/** - * @brief Retrieves the effective size of the Windows Packet Filter internal intermediate buffer pool. - * - * @param pdwSize Pointer to store the size of the intermediate buffer pool. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function retrieves the size of the intermediate buffer pool used by the driver. - * It uses DeviceIoControl with the IOCTL_NDISRD_QUERY_IB_POOL_SIZE code to perform the operation. - */ -BOOL CNdisApi::GetIntermediateBufferPoolSize(PDWORD pdwSize) const -{ - const BOOL bIOResult = DeviceIoControl( - IOCTL_NDISRD_QUERY_IB_POOL_SIZE, - pdwSize, - sizeof(DWORD), - pdwSize, - sizeof(DWORD), - NULL, // Bytes Returned - NULL - ); - - return bIOResult; -} - -/** - * @brief Retrieves the number of bytes returned by the last DeviceIoControl operation. - * - * @return DWORD The number of bytes returned by the last DeviceIoControl operation. - * - * This function returns the number of bytes returned by the last DeviceIoControl operation - * performed by the CNdisApi instance. This can be useful for obtaining additional information - * about the result of the operation. - */ -DWORD CNdisApi::GetBytesReturned() const -{ - return m_BytesReturned; -} - -/** - * @brief Sets the system wide MTU decrement value in the system registry. - * - * @param dwMTUDecrement The MTU decrement value to be set. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sets the MTU decrement value in the system registry. The MTU decrement value - * is used by the Windows Packet Filter driver to decrease the maximum transmission unit (MTU) - * size for network packets. - * - * For Windows NT/2000/XP, the registry key is created under HKEY_LOCAL_MACHINE with the path - * defined in WINNT_REG_PARAM. For Windows 9x/ME, the registry key is created under - * HKEY_LOCAL_MACHINE with the path defined in WIN9X_REG_PARAM. - */ -BOOL CNdisApi::SetMTUDecrement(const DWORD dwMTUDecrement) -{ - HKEY hKey; - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT, 2000 or XP - if (ERROR_SUCCESS == RegCreateKey(HKEY_LOCAL_MACHINE, WINNT_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegSetValueEx(hKey, TEXT("MTUDecrement"), 0, REG_DWORD, reinterpret_cast(&dwMTUDecrement), sizeof(DWORD))) - { - RegCloseKey(hKey); - return TRUE; - } - - RegCloseKey(hKey); - return FALSE; - } - return FALSE; - } - - // Windows 9x/ME - if (ERROR_SUCCESS == RegCreateKeyA(HKEY_LOCAL_MACHINE, WIN9X_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegSetValueEx(hKey, TEXT("MTUDecrement"), 0, REG_DWORD, (CONST BYTE*) & dwMTUDecrement, sizeof(DWORD))) - { - RegCloseKey(hKey); - return TRUE; - } - - RegCloseKey(hKey); - return FALSE; - } - return FALSE; -} - -/** - * @brief Retrieves the MTU decrement value from the system registry. - * - * @return DWORD Returns the MTU decrement value if the operation is successful, or 0 otherwise. - * - * This function retrieves the MTU decrement value from the system registry. The MTU decrement value - * is used by the Windows Packet Filter driver to decrease the maximum transmission unit (MTU) - * size for network packets. - * - * For Windows NT/2000/XP, the registry key is read from HKEY_LOCAL_MACHINE with the path - * defined in WINNT_REG_PARAM. For Windows 9x/ME, the registry key is read from - * HKEY_LOCAL_MACHINE with the path defined in WIN9X_REG_PARAM. - */ -DWORD CNdisApi::GetMTUDecrement() -{ - HKEY hKey; - DWORD dwMTUDecrement; - DWORD dwSize = sizeof(DWORD); - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT, 2000 or XP - if (ERROR_SUCCESS == RegCreateKey(HKEY_LOCAL_MACHINE, WINNT_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegQueryValueEx(hKey, TEXT("MTUDecrement"), 0, NULL, reinterpret_cast(&dwMTUDecrement), &dwSize)) - { - RegCloseKey(hKey); - return dwMTUDecrement; - } - - RegCloseKey(hKey); - return 0; - } - return 0; - } - - // Windows 9x/ME - if (ERROR_SUCCESS == RegCreateKeyA(HKEY_LOCAL_MACHINE, WIN9X_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegQueryValueEx(hKey, TEXT("MTUDecrement"), 0, NULL, reinterpret_cast(&dwMTUDecrement), &dwSize)) - { - RegCloseKey(hKey); - return dwMTUDecrement; - } - - RegCloseKey(hKey); - return 0; - } - return 0; -} - -/** - * @brief Sets the startup filter mode for the network adapters. - * - * @param dwStartupMode A combination of flags that determine the startup mode. - * @return BOOL Returns TRUE if the operation is successful, or FALSE otherwise. - * - * This function sets the startup filter mode for network adapters in the system registry. The startup mode - * determines the initial state of the network adapters when the Windows Packet Filter driver is - * loaded. - * - * The dwStartupMode parameter must be a combination of the XXX_LISTEN or XXX_TUNNEL flags: - * - MSTCP_FLAG_SENT_TUNNEL: Queue all packets sent from MSTCP to the network interface. The original packet is dropped. - * - MSTCP_FLAG_RECV_TUNNEL: Queue all packets indicated by the network interface to MSTCP. The original packet is dropped. - * - MSTCP_FLAG_SENT_LISTEN: Queue all packets sent from MSTCP to the network interface. The original packet goes ahead. - * - MSTCP_FLAG_RECV_LISTEN: Queue all packets indicated by the network interface to MSTCP. The original packet goes ahead. - * - MSTCP_FLAG_FILTER_DIRECT: In promiscuous mode, TCP/IP stack receives all packets in the Ethernet segment and replies with various ICMP packets. To prevent this, set this flag. All packets with destination MAC different from FF-FF-FF-FF-FF-FF and the network interface's current MAC will never reach MSTCP. - * - * By default, loopback packets are passed to the original MSTCP handlers without processing. To change this behavior, use these additional flags: - * - MSTCP_FLAG_LOOPBACK_FILTER: Pass loopback packets for processing by the helper driver routines (redirected to user-mode if requested). - * - MSTCP_FLAG_LOOPBACK_BLOCK: Silently drop loopback packets. This flag is recommended for usage with promiscuous mode to avoid multiple processing of one packet. - * - * Remarks: - * This routine sets the default mode to be applied to each adapter when it appears in the system. It can be useful when you need to prevent a network interface from starting operation before your application has started. Note that this API call requires a system reboot to take effect. - */ -BOOL CNdisApi::SetAdaptersStartupMode(const DWORD dwStartupMode) -{ - HKEY hKey; - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT, 2000 or XP - if (ERROR_SUCCESS == RegCreateKey(HKEY_LOCAL_MACHINE, WINNT_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegSetValueEx(hKey, TEXT("StartupMode"), 0, REG_DWORD, reinterpret_cast(&dwStartupMode), sizeof(DWORD))) - { - RegCloseKey(hKey); - return TRUE; - } - - RegCloseKey(hKey); - return FALSE; - } - return FALSE; - } - - // Windows 9x/ME - if (ERROR_SUCCESS == RegCreateKeyA(HKEY_LOCAL_MACHINE, WIN9X_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegSetValueEx(hKey, TEXT("StartupMode"), 0, REG_DWORD, reinterpret_cast(&dwStartupMode), sizeof(DWORD))) - { - RegCloseKey(hKey); - return TRUE; - } - - RegCloseKey(hKey); - return FALSE; - } - return FALSE; -} - -/** - * @brief Retrieves the network adapters' startup filter mode from the system registry. - * - * @return DWORD The current startup mode for network adapters. - * - * This function retrieves the startup filter mode for network adapters stored in the system registry. - * The startup mode determines the initial state of network adapters when the Windows Packet Filter - * driver is loaded. - * - * The returned value is a combination of the XXX_LISTEN or XXX_TUNNEL flags. See the - * SetAdaptersStartupMode() function documentation for more information about these flags. - */ -DWORD CNdisApi::GetAdaptersStartupMode() -{ - HKEY hKey; - DWORD dwStartupMode; - DWORD dwSize = sizeof(DWORD); - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT, 2000 or XP - if (ERROR_SUCCESS == RegCreateKey(HKEY_LOCAL_MACHINE, WINNT_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegQueryValueEx(hKey, TEXT("StartupMode"), 0, NULL, reinterpret_cast(&dwStartupMode), &dwSize)) - { - RegCloseKey(hKey); - return dwStartupMode; - } - - RegCloseKey(hKey); - return 0; - } - return 0; - } - - // Windows 9x/ME - if (ERROR_SUCCESS == RegCreateKeyA(HKEY_LOCAL_MACHINE, WIN9X_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegQueryValueEx(hKey, TEXT("StartupMode"), 0, NULL, reinterpret_cast(&dwStartupMode), &dwSize)) - { - RegCloseKey(hKey); - return dwStartupMode; - } - - RegCloseKey(hKey); - return 0; - } - return 0; -} - -/** - * @brief Sets the pool size multiplier for Windows Packet Filter driver in the Windows registry. - * - * This function creates or modifies the PoolSize value in the registry based on the - * given value. The appropriate registry key is selected depending on the - * Windows platform (NT/2000/XP or 9x/ME). The resulting internal packet pool size - * will be equal to 2048 (512 for Windows version before Vista) * PoolSize packets. The maximum - * effective PoolSize is 10. - * - * @param dwPoolSize The desired pool size multiplier to be set in the registry. - * @return BOOL Returns TRUE if the pool size multiplier is successfully set, FALSE otherwise. - */ -BOOL CNdisApi::SetPoolSize(const DWORD dwPoolSize) -{ - HKEY hKey; - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT, 2000 or XP - if (ERROR_SUCCESS == RegCreateKey(HKEY_LOCAL_MACHINE, WINNT_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegSetValueEx(hKey, TEXT("PoolSize"), 0, REG_DWORD, reinterpret_cast(&dwPoolSize), sizeof(DWORD))) - { - RegCloseKey(hKey); - return TRUE; - } - - RegCloseKey(hKey); - return FALSE; - } - return FALSE; - } - - // Windows 9x/ME - if (ERROR_SUCCESS == RegCreateKeyA(HKEY_LOCAL_MACHINE, WIN9X_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegSetValueEx(hKey, TEXT("PoolSize"), 0, REG_DWORD, reinterpret_cast(&dwPoolSize), sizeof(DWORD))) - { - RegCloseKey(hKey); - return TRUE; - } - - RegCloseKey(hKey); - return FALSE; - } - return FALSE; -} - -/** - * @brief Retrieves the pool size multiplier for the Windows Packet Filter driver from the Windows registry. - * - * This function queries the registry for the PoolSize value and returns it. - * The appropriate registry key is used depending on the Windows platform - * (NT/2000/XP or 9x/ME). The internal packet pool size is determined by - * 2048 * PoolSize packets. The maximum effective PoolSize is 10. - * - * @return DWORD The pool size multiplier retrieved from the registry, or 0 if the value is not found or an error occurs. - */ -DWORD CNdisApi::GetPoolSize() -{ - HKEY hKey; - DWORD dwStartupMode; - DWORD dwSize = sizeof(DWORD); - - if (ms_Version.IsWindowsNTPlatform()) - { - // Windows NT, 2000 or XP - if (ERROR_SUCCESS == RegCreateKey(HKEY_LOCAL_MACHINE, WINNT_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegQueryValueEx(hKey, TEXT("PoolSize"), 0, NULL, reinterpret_cast(&dwStartupMode), &dwSize)) - { - RegCloseKey(hKey); - return dwStartupMode; - } - - RegCloseKey(hKey); - return 0; - } - return 0; - } - - // Windows 9x/ME - if (ERROR_SUCCESS == RegCreateKeyA(HKEY_LOCAL_MACHINE, WIN9X_REG_PARAM, &hKey)) - { - if (ERROR_SUCCESS == RegQueryValueEx(hKey, TEXT("PoolSize"), 0, NULL, reinterpret_cast(&dwStartupMode), &dwSize)) - { - RegCloseKey(hKey); - return dwStartupMode; - } - - RegCloseKey(hKey); - return 0; - } - return 0; -} - -/** - * @brief Determines if the given adapter is an NDISWAN interface with the specified component ID. - * - * This function enumerates all subkeys of the registry key - * HKLM\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318} - * and checks for the component ID value matching the provided ndiswanName. - * If a match is found, it grabs the linkage subkey and the export string - * to verify if the adapter name matches. The function works for both - * Windows 7 and Windows 10. - * - * Possible component ID values: - * - ms_ndiswanip - * - ms_ndiswanipv6 - * - ms_ndiswanbh - * - * @param adapterName The adapter name to check. - * @param ndiswanName The NDISWAN component ID to look for. - * @return BOOL Returns TRUE if the adapter is an NDISWAN interface with the specified component ID, FALSE otherwise. - */ -BOOL CNdisApi::IsNdiswanInterface(LPCSTR adapterName, LPCSTR ndiswanName) -{ - HKEY TargetKey = NULL; - HKEY ConnectionKey = NULL; - HKEY LinkageKey = NULL; - int i = 0; - TCHAR Buffer[MAX_PATH] = { 0 }; - char TempBuffer[MAX_PATH] = { 0 }; - DWORD BufferLength = MAX_PATH; - DWORD TempBufferLength = MAX_PATH; - DWORD RegType = 0; - BOOL isNdiswanInterface = FALSE; - - LONG lStatus = RegOpenKeyEx(HKEY_LOCAL_MACHINE, REGSTR_NETWORK_CONTROL_CLASS, 0, KEY_READ, &TargetKey); - - if (lStatus == ERROR_SUCCESS) - { - while (!isNdiswanInterface && ERROR_NO_MORE_ITEMS != RegEnumKeyEx(TargetKey, i, Buffer, &BufferLength, 0, 0, 0, 0)) - { - lStatus = RegOpenKeyEx(TargetKey, Buffer, 0, KEY_READ, &ConnectionKey); - if (lStatus == ERROR_SUCCESS) - { - lStatus = RegQueryValueExA(ConnectionKey, "ComponentId", 0, &RegType, reinterpret_cast(TempBuffer), &TempBufferLength); - TempBufferLength = MAX_PATH; - - if (lStatus == ERROR_SUCCESS && 0 == _stricmp(TempBuffer, ndiswanName)) - { - lStatus = RegOpenKeyEx(ConnectionKey, TEXT("Linkage"), 0, KEY_READ, &LinkageKey); - if (lStatus == ERROR_SUCCESS) - { - lStatus = RegQueryValueExA(LinkageKey, "Export", 0, &RegType, reinterpret_cast(TempBuffer), &TempBufferLength); - TempBufferLength = MAX_PATH; - - if (lStatus == ERROR_SUCCESS && 0 == _stricmp(TempBuffer, adapterName)) - { - isNdiswanInterface = TRUE; - } - RegCloseKey(LinkageKey); - } - } - RegCloseKey(ConnectionKey); - } - ++i; - BufferLength = MAX_PATH; - } - RegCloseKey(TargetKey); - } - - return isNdiswanInterface; -} - -/** - * @brief Determines if the given adapter is an NDISWANIP interface. - * - * This function checks if the adapter name matches the internal name for - * NDISWANIP on systems prior to Windows 10. On Windows 10 and later systems, - * it calls the IsNdiswanInterface function to check if the adapter is an - * NDISWAN interface with the specified component ID (REGSTR_COMPONENTID_NDISWANIP). - * - * @param adapterName The adapter name to check. - * @return BOOL Returns TRUE if the adapter is an NDISWANIP interface, FALSE otherwise. - */ -BOOL CNdisApi::IsNdiswanIp(LPCSTR adapterName) -{ - // Before Windows 10, NDISWANIP can be identified by the internal name - if (!ms_Version.IsWindows10OrGreater() /* before Windows 10 */) - { - if (_stricmp(adapterName, DEVICE_NDISWANIP) == 0) - { - return TRUE; - } - } - - return IsNdiswanInterface(adapterName, REGSTR_COMPONENTID_NDISWANIP); -} - -/** - * @brief Determines if the given adapter is an NDISWANIPV6 interface. - * - * This function checks if the adapter name matches the internal name for - * NDISWANIPV6 on systems prior to Windows 10. On Windows 10 and later systems, - * it calls the IsNdiswanInterface function to check if the adapter is an - * NDISWAN interface with the specified component ID (REGSTR_COMPONENTID_NDISWANIPV6). - * - * @param adapterName The adapter name to check. - * @return BOOL Returns TRUE if the adapter is an NDISWANIPV6 interface, FALSE otherwise. - */ -BOOL CNdisApi::IsNdiswanIpv6(LPCSTR adapterName) -{ - // Before Windows 10, NDISWANIPV6 can be identified by the internal name - if (!ms_Version.IsWindows10OrGreater() /* before Windows 10 */) - { - if (_stricmp(adapterName, DEVICE_NDISWANIPV6) == 0) - { - return TRUE; - } - } - - return IsNdiswanInterface(adapterName, REGSTR_COMPONENTID_NDISWANIPV6); -} - -/** - * @brief Determines if the given adapter is an NDISWANBH interface. - * - * This function checks if the adapter name matches the internal name for - * NDISWANBH on systems prior to Windows 10. On Windows 10 and later systems, - * it calls the IsNdiswanInterface function to check if the adapter is an - * NDISWAN interface with the specified component ID (REGSTR_COMPONENTID_NDISWANBH). - * - * @param adapterName The adapter name to check. - * @return BOOL Returns TRUE if the adapter is an NDISWANBH interface, FALSE otherwise. - */ -BOOL CNdisApi::IsNdiswanBh(LPCSTR adapterName) -{ - // Before Windows 10, NDISWANBH can be identified by the internal name - if (!ms_Version.IsWindows10OrGreater() /* before Windows 10 */) - { - if (_stricmp(adapterName, DEVICE_NDISWANBH) == 0) - { - return TRUE; - } - } - - return IsNdiswanInterface(adapterName, REGSTR_COMPONENTID_NDISWANBH); -} - -/** - * @brief Converts an adapter's internal name to a user-friendly name on Windows NT 4.0. - * - * This function searches the registry to find the corresponding user-friendly name - * for the specified adapter name on Windows NT 4.0 systems. It locates the adapter - * by comparing the service name with the adapter name and retrieves the user-friendly - * name from the registry. - * - * @param szAdapterName The adapter name to convert. - * @param szUserFriendlyName A buffer to store the user-friendly name. - * @param dwUserFriendlyNameLength The length of the buffer for the user-friendly name. - * @return BOOL Returns TRUE if the conversion is successful, FALSE otherwise. - */ -BOOL CNdisApi::ConvertWindowsNTAdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength -) -{ - HKEY hKeyAdapters, hKeyAdapter; - DWORD dwType, dwIndex = 0; - FILETIME time; - char szSubKey[MAX_PATH * 2], szServiceName[MAX_PATH * 2]; - DWORD dwSubKeyLength = MAX_PATH * 2; - DWORD dwServiceNameLength = MAX_PATH * 2; - BOOL bRet = TRUE; - - LONG lResult = RegOpenKeyEx( - HKEY_LOCAL_MACHINE, - REGSTR_NETWORK_CARDS, - 0, - KEY_READ, - &hKeyAdapters - ); - - if (lResult == ERROR_SUCCESS) - { - // Enumerate bound interfaces - while (RegEnumKeyExA(hKeyAdapters, dwIndex, szSubKey, &dwSubKeyLength, NULL, NULL, NULL, &time) == ERROR_SUCCESS) - { - // Subkey retrieved, open subkey - lResult = RegOpenKeyExA( - hKeyAdapters, - szSubKey, - 0, - KEY_READ, - &hKeyAdapter - ); - - if (lResult == ERROR_SUCCESS) - { - lResult = RegQueryValueExA(hKeyAdapter, REGSTR_VAL_SERVICE_NAME, NULL, &dwType, reinterpret_cast(szServiceName), &dwServiceNameLength); - if (lResult == ERROR_SUCCESS) - { - if (_stricmp(szServiceName, &szAdapterName[strlen("\\Device\\")]) == 0) - { - lResult = RegQueryValueExA(hKeyAdapter, REGSTR_VAL_TITLE, 0, &dwType, reinterpret_cast(szUserFriendlyName), &dwUserFriendlyNameLength); - - RegCloseKey(hKeyAdapter); - RegCloseKey(hKeyAdapters); - - if (lResult == ERROR_SUCCESS) - { - return TRUE; - } - return FALSE; - } - } - else - { - bRet = FALSE; - } - RegCloseKey(hKeyAdapter); - dwServiceNameLength = MAX_PATH * 2; - } - else - { - bRet = FALSE; - } - - dwIndex++; - dwSubKeyLength = MAX_PATH; - } - - RegCloseKey(hKeyAdapters); - - } - else - { - bRet = FALSE; - } - - return bRet; -} - -/** - * @brief Converts an adapter's internal name to a user-friendly name on Windows 2000 and later. - * - * This function identifies NDISWAN adapters (IP, BH, and IPv6) and retrieves the - * corresponding user-friendly name for the specified adapter name on Windows 2000 (and later) systems. - * For other adapters, it searches the registry for the appropriate user-friendly name. - * - * @param szAdapterName The Windows 2000 (and later) adapter name to convert. - * @param szUserFriendlyName A buffer to store the user-friendly name. - * @param dwUserFriendlyNameLength The length of the buffer for the user-friendly name. - * @return BOOL Returns TRUE if the conversion is successful, FALSE otherwise. - */ -BOOL CNdisApi::ConvertWindows2000AdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength -) -{ - HKEY hKey; - char szFriendlyNameKey[MAX_PATH * 2]; - DWORD dwType; - -#if _MSC_VER >= 1700 - if (IsNdiswanIp(szAdapterName)) - { - strcpy_s(szUserFriendlyName, dwUserFriendlyNameLength, USER_NDISWANIP); - return TRUE; - } - - if (IsNdiswanBh(szAdapterName)) - { - strcpy_s(szUserFriendlyName, dwUserFriendlyNameLength, USER_NDISWANBH); - return TRUE; - } - - if (IsNdiswanIpv6(szAdapterName)) - { - strcpy_s(szUserFriendlyName, dwUserFriendlyNameLength, USER_NDISWANIPV6); - return TRUE; - } - - strcpy_s(szFriendlyNameKey, MAX_PATH * 2, REGSTR_NETWORK_CONTROL_KEY); - strcpy_s(static_cast(szFriendlyNameKey) + strlen(szFriendlyNameKey), MAX_PATH * 2 - strlen(szFriendlyNameKey), &szAdapterName[strlen("\\Device\\")]); - strcpy_s(static_cast(szFriendlyNameKey) + strlen(szFriendlyNameKey), MAX_PATH * 2 - strlen(szFriendlyNameKey), REGSTR_VAL_CONNECTION); -#else - if (IsNdiswanIp(szAdapterName)) - { - strcpy(szUserFriendlyName, USER_NDISWANIP); - return TRUE; - } - - if (IsNdiswanBh(szAdapterName)) - { - strcpy(szUserFriendlyName, USER_NDISWANBH); - return TRUE; - } - - if (IsNdiswanIpv6(szAdapterName)) - { - strcpy(szUserFriendlyName, USER_NDISWANIPV6); - return TRUE; - } - - strcpy(szFriendlyNameKey, REGSTR_NETWORK_CONTROL_KEY); - strcpy(static_cast(szFriendlyNameKey) + strlen(szFriendlyNameKey), &szAdapterName[strlen("\\Device\\")]); - strcpy(static_cast(szFriendlyNameKey) + strlen(szFriendlyNameKey), REGSTR_VAL_CONNECTION); - -#endif //_MSC_VER >= 1700 - - LONG lResult = RegOpenKeyExA( - HKEY_LOCAL_MACHINE, - szFriendlyNameKey, - 0, - KEY_READ, - &hKey - ); - - if (lResult == ERROR_SUCCESS) - { - lResult = RegQueryValueExA(hKey, REGSTR_VAL_NAME, 0, &dwType, reinterpret_cast(szUserFriendlyName), &dwUserFriendlyNameLength); - - RegCloseKey(hKey); - - if (lResult == ERROR_SUCCESS) - return TRUE; - } - - return FALSE; -} - -/** - * @brief Converts the given Windows 9x adapter name to a user-friendly name. - * - * This function retrieves the user-friendly name for the specified adapter name on - * Windows 9x systems by searching the registry. - * - * @param szAdapterName The Windows 9x adapter name to convert. - * @param szUserFriendlyName A buffer to store the user-friendly name. - * @param dwUserFriendlyNameLength The length of the buffer for the user-friendly name. - * @return BOOL Returns TRUE if the conversion is successful, FALSE otherwise. - */ -BOOL -CNdisApi::ConvertWindows9xAdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength -) -{ - HKEY hKey; - char szFriendlyNameKey[MAX_PATH * 2]; - DWORD dwType; - BOOL bRet = FALSE; - -#if _MSC_VER >= 1700 - strcpy_s(szFriendlyNameKey, MAX_PATH * 2, REGSTR_MSTCP_CLASS_NET); - strcpy_s(static_cast(szFriendlyNameKey) + strlen(szFriendlyNameKey), MAX_PATH * 2 - strlen(szFriendlyNameKey), szAdapterName); -#else - strcpy(szFriendlyNameKey, REGSTR_MSTCP_CLASS_NET); - strcpy((PCHAR)szFriendlyNameKey + strlen(szFriendlyNameKey), szAdapterName); -#endif //_MSC_VER >= 1700 - - LONG lResult = RegOpenKeyExA( - HKEY_LOCAL_MACHINE, - szFriendlyNameKey, - 0, - KEY_READ, - &hKey - ); - - if (lResult == ERROR_SUCCESS) - { - lResult = RegQueryValueExA(hKey, REGSTR_VAL_DRIVER_DESC, 0, &dwType, reinterpret_cast(szUserFriendlyName), &dwUserFriendlyNameLength); - if (lResult == ERROR_SUCCESS) - { - bRet = TRUE; - } - RegCloseKey(hKey); - } - - return bRet; -} - -/** - * @brief Recalculates the IPv4 checksum of a given packet. - * - * @param pPacket Pointer to the packet's INTERMEDIATE_BUFFER structure. - * - * This function recalculates the IP checksum for the given packet. The IP checksum - * is a 16-bit value used to verify the integrity of the IP header in an IP packet. - * The checksum must be recalculated if any changes are made to the IP header. - * This function should be called after modifying any field in the IP header - * to ensure the packet's integrity. - */ -void CNdisApi::RecalculateIPChecksum(PINTERMEDIATE_BUFFER pPacket) -{ - unsigned int sum = 0; - - // Get a pointer to the IP header within the packet - const iphdr_ptr pIpHeader = reinterpret_cast(&pPacket->m_IBuffer[sizeof(ether_header)]); - - // Initialize checksum to zero - pIpHeader->ip_sum = 0; - const PUCHAR buff = reinterpret_cast(pIpHeader); - - // Wide one's-complement sum over the header; bit-identical to the former - // byte-pair loop (see inet_checksum.h). - sum = inet_checksum::sum16_be(buff, pIpHeader->ip_hl * sizeof(DWORD)); - - // Keep only the last 16 bits of the 32-bit calculated sum and add the carries - while (sum >> 16) - sum = (sum & 0xFFFF) + (sum >> 16); - - // Take the one's complement of sum - sum = ~sum; - - // Store the recalculated checksum in the IP header - pIpHeader->ip_sum = htons(static_cast(sum)); -} - -/** - * @brief Recalculates the ICMPv4 checksum of a given packet. - * - * @param pPacket Pointer to the packet's INTERMEDIATE_BUFFER structure. - */ -void CNdisApi::RecalculateICMPChecksum(PINTERMEDIATE_BUFFER pPacket) -{ - unsigned int sum = 0; - icmphdr_ptr pIcmpHeader; - const iphdr_ptr pIpHeader = reinterpret_cast(&pPacket->m_IBuffer[sizeof(ether_header)]); - - // Sanity check - if (pIpHeader->ip_p == IPPROTO_ICMP) - { - pIcmpHeader = reinterpret_cast(reinterpret_cast(pIpHeader) + sizeof(DWORD) * pIpHeader->ip_hl); - } - else - return; - - const DWORD dwIpHeaderLen = static_cast(pIpHeader->ip_hl) * 4; - const DWORD dwIpPacketLen = ntohs(pIpHeader->ip_len); - - // Validate the lengths before the unsigned subtraction below, exactly as the - // TCP and UDP siblings do. A packet whose IP total-length field is smaller - // than its IP + ICMP headers would otherwise underflow dwIcmpLen to a huge - // value and the checksum would read far past m_IBuffer. This function was - // the one of the four that never received the guard. - if (dwIpHeaderLen < sizeof(iphdr) || - dwIpPacketLen < dwIpHeaderLen + sizeof(icmphdr) || - static_cast(sizeof(ether_header)) + dwIpPacketLen > pPacket->m_Length) - { - return; - } - - const DWORD dwIcmpLen = dwIpPacketLen - dwIpHeaderLen; - - const PUCHAR buff = reinterpret_cast(pIcmpHeader); - pIcmpHeader->checksum = 0; - - // Wide one's-complement sum; bit-identical to the former byte-pair loop and, - // unlike it, needs no zero pad byte written into the packet buffer for odd - // lengths (see inet_checksum.h). - sum = inet_checksum::sum16_be(buff, dwIcmpLen); - - // Keep only the last 16 bits of the 32-bit calculated sum and add the carries - while (sum >> 16) - sum = (sum & 0xFFFF) + (sum >> 16); - - // Take the one's complement of sum - sum = ~sum; - - pIcmpHeader->checksum = ntohs(static_cast(sum)); -} - -/** - * @brief Recalculates the TCP checksum of a given IPv4 packet. - * - * @param pPacket Pointer to the packet's INTERMEDIATE_BUFFER structure. - */ -void CNdisApi::RecalculateTCPChecksum(PINTERMEDIATE_BUFFER pPacket) -{ - tcphdr_ptr pTcpHeader; - unsigned int sum = 0; - - const iphdr_ptr pIpHeader = reinterpret_cast(&pPacket->m_IBuffer[sizeof(ether_header)]); - - // Sanity check - if (pIpHeader->ip_p == IPPROTO_TCP) - { - pTcpHeader = reinterpret_cast(reinterpret_cast(pIpHeader) + sizeof(DWORD) * pIpHeader->ip_hl); - } - else - return; - - const DWORD dwIpHeaderLen = static_cast(pIpHeader->ip_hl) * 4; - const DWORD dwIpPacketLen = ntohs(pIpHeader->ip_len); - - // Validate the lengths before the unsigned subtraction below. A packet whose - // IP total-length field is smaller than its IP + TCP headers would otherwise - // underflow dwTcpLen to a huge value, and the checksum loop would then read far - // past m_IBuffer (EXCEPTION_ACCESS_VIOLATION). The usual trigger is TCP/UDP - // segmentation offload, which can present outbound segments with ip_len == 0 - // (the NIC fills in the real length later). The third condition additionally - // requires the whole L4 payload to lie within the captured frame, so an - // over-stated ip_len cannot over-read here or over-write the padding byte below. - if (dwIpHeaderLen < sizeof(iphdr) || - dwIpPacketLen < dwIpHeaderLen + sizeof(tcphdr) || - static_cast(sizeof(ether_header)) + dwIpPacketLen > pPacket->m_Length) - { - return; - } - - const DWORD dwTcpLen = dwIpPacketLen - dwIpHeaderLen; - - const PUCHAR buff = reinterpret_cast(pTcpHeader); - pTcpHeader->th_sum = 0; - - // Wide one's-complement sum over the TCP segment; bit-identical to the - // former byte-pair loop and, unlike it, needs no zero pad byte written into - // the packet buffer for odd lengths (see inet_checksum.h). - sum = inet_checksum::sum16_be(buff, dwTcpLen); - - // Add the TCP pseudo header which contains: - // the IP source and destination addresses - sum = sum + ntohs(pIpHeader->ip_src.S_un.S_un_w.s_w1) + ntohs(pIpHeader->ip_src.S_un.S_un_w.s_w2); - sum = sum + ntohs(pIpHeader->ip_dst.S_un.S_un_w.s_w1) + ntohs(pIpHeader->ip_dst.S_un.S_un_w.s_w2); - - // The protocol number and the length of the TCP packet - sum = sum + IPPROTO_TCP + static_cast(dwTcpLen); - - // Keep only the last 16 bits of the 32-bit calculated sum and add the carries - while (sum >> 16) - sum = (sum & 0xFFFF) + (sum >> 16); - - // Take the one's complement of sum - sum = ~sum; - - pTcpHeader->th_sum = htons(static_cast(sum)); -} - -/** - * @brief Recalculates the UDP checksum for a given IPv4 packet. - * @param pPacket The packet for which the UDP checksum needs to be recalculated. - * - * This function recalculates the UDP checksum for a packet by considering the pseudo-header, - * which includes the IP source and destination addresses, protocol number, and the length of - * the UDP packet. The calculated checksum is stored in the UDP header of the packet. - */ -void CNdisApi::RecalculateUDPChecksum(PINTERMEDIATE_BUFFER pPacket) { - unsigned int sum = 0; - - const iphdr_ptr pIpHeader = reinterpret_cast(&pPacket->m_IBuffer[sizeof(ether_header)]); - - // Sanity check: Ensure the packet is a UDP packet - if (pIpHeader->ip_p != IPPROTO_UDP) { - return; - } - - const udphdr_ptr pUdpHeader = reinterpret_cast(reinterpret_cast(pIpHeader) + sizeof(DWORD) * pIpHeader - ->ip_hl); - - const DWORD dwIpHeaderLen = static_cast(pIpHeader->ip_hl) * 4; - const DWORD dwIpPacketLen = ntohs(pIpHeader->ip_len); - - // Validate the lengths before the unsigned subtraction below. A packet whose - // IP total-length field is smaller than its IP + UDP headers would otherwise - // underflow dwUdpLen to a huge value, and the checksum loop would then read far - // past m_IBuffer (EXCEPTION_ACCESS_VIOLATION). The usual trigger is TCP/UDP - // segmentation offload, which can present outbound segments with ip_len == 0 - // (the NIC fills in the real length later). The third condition additionally - // requires the whole L4 payload to lie within the captured frame, so an - // over-stated ip_len cannot over-read here or over-write the padding byte below. - if (dwIpHeaderLen < sizeof(iphdr) || - dwIpPacketLen < dwIpHeaderLen + sizeof(udphdr) || - static_cast(sizeof(ether_header)) + dwIpPacketLen > pPacket->m_Length) { - return; - } - - const DWORD dwUdpLen = dwIpPacketLen - dwIpHeaderLen; - - const PUCHAR buff = reinterpret_cast(pUdpHeader); - pUdpHeader->th_sum = 0; - - // Wide one's-complement sum over the UDP datagram; bit-identical to the - // former byte-pair loop and, unlike it, needs no zero pad byte written into - // the packet buffer for odd lengths (see inet_checksum.h). - sum = inet_checksum::sum16_be(buff, dwUdpLen); - - // Add the UDP pseudo-header to the sum - sum = sum + ntohs(pIpHeader->ip_src.S_un.S_un_w.s_w1) + ntohs(pIpHeader->ip_src.S_un.S_un_w.s_w2); - sum = sum + ntohs(pIpHeader->ip_dst.S_un.S_un_w.s_w1) + ntohs(pIpHeader->ip_dst.S_un.S_un_w.s_w2); - sum = sum + IPPROTO_UDP + static_cast(dwUdpLen); - - // Keep only the last 16 bits of the calculated sum and add the carries - while (sum >> 16) { - sum = (sum & 0xFFFF) + (sum >> 16); - } - - // Take the one's complement of sum - sum = ~sum; - - // Store the recalculated checksum in the UDP header - pUdpHeader->th_sum = ntohs(static_cast(sum)); -} - -/** - * @brief Opens the filter driver with the specified file name. - * @param pszFileName The file name of the filter driver to be opened. - * @return A handle to the opened filter driver, represented as a CNdisApi object. - * - * This function creates a new CNdisApi object with the given file name and returns its handle. - * The handle can be used to perform operations with the opened filter driver. - */ -HANDLE __stdcall OpenFilterDriver(const TCHAR* pszFileName) { - return new CNdisApi(pszFileName); -} - -/** - * @brief Closes the filter driver associated with the given handle. - * @param hOpen The handle to the filter driver to be closed. - * - * This function deallocates the CNdisApi object associated with the provided handle, - * effectively closing the filter driver. - */ -VOID __stdcall CloseFilterDriver(HANDLE hOpen) { - delete static_cast(hOpen); -} - -/** - * @brief Retrieves the version of the filter driver associated with the given handle. - * @param hOpen The handle to the filter driver for which the version is requested. - * @return The version of the filter driver as a DWORD, or 0 if the handle is invalid. - * - * This function retrieves the version of the filter driver associated with the provided handle - * by calling the GetVersion() method of the CNdisApi object. - */ -DWORD __stdcall GetDriverVersion(HANDLE hOpen) { - if (!hOpen) { - return 0; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetVersion(); -} - -/** - * @brief Retrieves information about the TCP/IP bound adapters using the given filter driver handle. - * @param hOpen The handle to the filter driver for which the TCP/IP bound adapters information is requested. - * @param pAdapters A pointer to a TCP_AdapterList structure that receives the information about the adapters. - * @return TRUE if the information is successfully retrieved, or FALSE if the handle is invalid or the operation fails. - * - * This function retrieves information about the TCP/IP bound adapters associated with the provided filter driver handle - * by calling the GetTcpipBoundAdaptersInfo() method of the CNdisApi object. - */ -BOOL __stdcall GetTcpipBoundAdaptersInfo(HANDLE hOpen, PTCP_AdapterList pAdapters) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetTcpipBoundAdaptersInfo(pAdapters); -} - -/** - * @brief Sends a packet to the Microsoft TCP/IP stack using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param pPacket A pointer to an ETH_REQUEST structure containing the packet to be sent. - * @return TRUE if the packet is successfully sent, or FALSE if the handle is invalid or the operation fails. - * - * This function sends a packet to the Microsoft TCP/IP stack using the provided filter driver handle - * by calling the SendPacketToMstcp() method of the CNdisApi object. - */ -BOOL __stdcall SendPacketToMstcp(HANDLE hOpen, PETH_REQUEST pPacket) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SendPacketToMstcp(pPacket); -} - -/** - * @brief Sends a packet to the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param pPacket A pointer to an ETH_REQUEST structure containing the packet to be sent. - * @return TRUE if the packet is successfully sent, or FALSE if the handle is invalid or the operation fails. - * - * This function sends a packet to the network adapter using the provided filter driver handle - * by calling the SendPacketToAdapter() method of the CNdisApi object. - */ -BOOL __stdcall SendPacketToAdapter(HANDLE hOpen, PETH_REQUEST pPacket) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SendPacketToAdapter(pPacket); -} - -/** - * @brief Reads a packet from the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver from which the packet is to be read. - * @param pPacket A pointer to an ETH_REQUEST structure that receives the packet information. - * @return TRUE if the packet is successfully read, or FALSE if the handle is invalid or the operation fails. - * - * This function reads a packet from the network adapter using the provided filter driver handle - * by calling the ReadPacket() method of the CNdisApi object. - */ -BOOL __stdcall ReadPacket(HANDLE hOpen, PETH_REQUEST pPacket) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->ReadPacket(pPacket); -} - -/** - * @brief Sends multiple packets to the Microsoft TCP/IP stack using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param pPackets A pointer to an ETH_M_REQUEST structure containing the packets to be sent. - * @return TRUE if the packets are successfully sent, or FALSE if the handle is invalid or the operation fails. - * - * This function sends multiple packets to the Microsoft TCP/IP stack using the provided filter driver handle - * by calling the SendPacketsToMstcp() method of the CNdisApi object. - */ -BOOL __stdcall SendPacketsToMstcp(HANDLE hOpen, PETH_M_REQUEST pPackets) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SendPacketsToMstcp(pPackets); -} - -/** - * @brief Sends multiple packets to the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param pPackets A pointer to an ETH_M_REQUEST structure containing the packets to be sent. - * @return TRUE if the packets are successfully sent, or FALSE if the handle is invalid or the operation fails. - * - * This function sends multiple packets to the network adapter using the provided filter driver handle - * by calling the SendPacketsToAdapter() method of the CNdisApi object. - */ -BOOL __stdcall SendPacketsToAdapter(HANDLE hOpen, PETH_M_REQUEST pPackets) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SendPacketsToAdapter(pPackets); -} - -/** - * @brief Reads multiple packets from the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver from which the packets are to be read. - * @param pPackets A pointer to an ETH_M_REQUEST structure that receives the packet information. - * @return TRUE if the packets are successfully read, or FALSE if the handle is invalid or the operation fails. - * - * This function reads multiple packets from the network adapter using the provided filter driver handle - * by calling the ReadPackets() method of the CNdisApi object. - */ -BOOL __stdcall ReadPackets(HANDLE hOpen, PETH_M_REQUEST pPackets) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->ReadPackets(pPackets); -} - -/** - * @brief Sets the filter mode of the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param pMode A pointer to an ADAPTER_MODE structure containing the adapter handle and new filter mode settings. - * @return TRUE if the mode is successfully set, or FALSE if the handle is invalid or the operation fails. - * - * This function sets the filter mode of the network adapter using the provided filter driver handle - * by calling the SetAdapterMode() method of the CNdisApi object. - */ -BOOL __stdcall SetAdapterMode(HANDLE hOpen, PADAPTER_MODE pMode) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SetAdapterMode(pMode); -} - -/** - * @brief Retrieves the filter mode of the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param pMode A pointer to an ADAPTER_MODE structure containing the adapter handle that receives the mode settings. - * @return TRUE if the mode is successfully retrieved, or FALSE if the handle is invalid or the operation fails. - * - * This function retrieves the operating mode of the network adapter using the provided filter driver handle - * by calling the GetAdapterMode() method of the CNdisApi object. - */ -BOOL __stdcall GetAdapterMode(HANDLE hOpen, PADAPTER_MODE pMode) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetAdapterMode(pMode); -} - -/** - * @brief Flushes the packet queue of the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param hAdapter The handle to the network adapter whose packet queue is to be flushed. - * @return TRUE if the packet queue is successfully flushed, or FALSE if the handle is invalid or the operation fails. - * - * This function flushes the packet queue of the network adapter using the provided filter driver handle - * by calling the FlushAdapterPacketQueue() method of the CNdisApi object. - */ -BOOL __stdcall FlushAdapterPacketQueue(HANDLE hOpen, HANDLE hAdapter) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->FlushAdapterPacketQueue(hAdapter); -} - -/** - * @brief Retrieves the packet queue size of the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param hAdapter The handle to the network adapter whose packet queue size is to be retrieved. - * @param pdwSize A pointer to a DWORD variable that receives the size of the packet queue. - * @return TRUE if the packet queue size is successfully retrieved, or FALSE if the handle is invalid or the operation fails. - * - * This function retrieves the packet queue size of the network adapter usingh the provided filter driver handle - * by calling the GetAdapterPacketQueueSize() method of the CNdisApi object. - */ -BOOL __stdcall GetAdapterPacketQueueSize(HANDLE hOpen, HANDLE hAdapter, PDWORD pdwSize) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetAdapterPacketQueueSize(hAdapter, pdwSize); -} - -/** - * @brief Associates a Win32 event with the packet queue of the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param hAdapter The handle to the network adapter whose packet queue is to be associated with the event. - * @param hWin32Event The handle to a Win32 event to be associated with the packet queue. - * @return TRUE if the event is successfully set, or FALSE if the handle is invalid or the operation fails. - * - * This function associates a Win32 event with the packet queue of the network adapter using the provided filter driver handle - * by calling the SetPacketEvent() method of the CNdisApi object. - */ -BOOL __stdcall SetPacketEvent(HANDLE hOpen, HANDLE hAdapter, HANDLE hWin32Event) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SetPacketEvent(hAdapter, hWin32Event); -} - -/** - * @brief Associates a Win32 event with the WAN connect/disconnect events of the network adapters using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param hWin32Event The handle to a Win32 event to be associated with the WAN connect/disconnect events. - * @return TRUE if the event is successfully set, or FALSE if the handle is invalid or the operation fails. - * - * This function associates a Win32 event with the WAN events of the network adapters using the provided filter driver handle - * by calling the SetWANEvent() method of the CNdisApi object. - */ -BOOL __stdcall SetWANEvent(HANDLE hOpen, HANDLE hWin32Event) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SetWANEvent(hWin32Event); -} - -/** - * @brief Associates a Win32 event with the network adapter list change events for the given filter driver handle. - * @param hOpen The handle to the filter driver for which the adapter list change event is to be set. - * @param hWin32Event The handle to a Win32 event to be associated with the adapter list change events. - * @return TRUE if the event is successfully set, or FALSE if the handle is invalid or the operation fails. - * - * This function associates a Win32 event with the network adapter list change events associated with the provided filter driver handle - * by calling the SetAdapterListChangeEvent() method of the CNdisApi object. - */ -BOOL __stdcall SetAdapterListChangeEvent(HANDLE hOpen, HANDLE hWin32Event) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SetAdapterListChangeEvent(hWin32Event); -} - -/** - * @brief Sends an OID request to the filter driver associated with the given handle. - * @param hOpen The handle to the filter driver. - * @param OidData A pointer to a PACKET_OID_DATA structure containing the OID data and adapter handle associated with OID request. - * @param Set A boolean value specifying whether the request is a set (TRUE) or query (FALSE) operation. - * @return TRUE if the OID request is successfully sent, or FALSE if the handle is invalid or the operation fails. - * - * This function sends an OID request to the filter driver associated with the provided handle - * by calling the NdisrdRequest() method of the CNdisApi object. - */ -BOOL __stdcall NdisrdRequest(HANDLE hOpen, PPACKET_OID_DATA OidData, BOOL Set) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->NdisrdRequest(OidData, Set); -} - -/** - * @brief Retrieves RAS links information for the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param hAdapter The handle to the network adapter whose RAS links information is to be retrieved. - * @param pLinks A pointer to a RAS_LINKS structure that receives the RAS links information. - * @return TRUE if the RAS links information is successfully retrieved, or FALSE if the handle is invalid or the operation fails. - * - * This function retrieves RAS links information for the network adapter using the provided filter driver handle - * by calling the GetRasLinks() method of the CNdisApi object. - */ -BOOL __stdcall GetRasLinks(HANDLE hOpen, HANDLE hAdapter, PRAS_LINKS pLinks) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetRasLinks(hAdapter, pLinks); -} - -/** - * @brief Sets the hardware packet filter for the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param hAdapter The handle to the network adapter whose hardware packet filter is to be set. - * @param Filter A DWORD value specifying the hardware packet filter to be set. - * @return TRUE if the hardware packet filter is successfully set, or FALSE if the handle is invalid or the operation fails. - * - * This function sets the hardware packet filter for the network adapter using the provided filter driver handle - * by calling the SetHwPacketFilter() method of the CNdisApi object. - */ -BOOL __stdcall SetHwPacketFilter(HANDLE hOpen, HANDLE hAdapter, DWORD Filter) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SetHwPacketFilter(hAdapter, Filter); -} - -/** - * @brief Retrieves the hardware packet filter for the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param hAdapter The handle to the network adapter whose hardware packet filter is to be retrieved. - * @param pFilter A pointer to a DWORD variable that receives the hardware packet filter value. - * @return TRUE if the hardware packet filter is successfully retrieved, or FALSE if the handle is invalid or the operation fails. - * - * This function retrieves the hardware packet filter for the network adapter using the provided filter driver handle - * by calling the GetHwPacketFilter() method of the CNdisApi object. - */ -BOOL __stdcall GetHwPacketFilter(HANDLE hOpen, HANDLE hAdapter, PDWORD pFilter) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetHwPacketFilter(hAdapter, pFilter); -} - -/** - * @brief Sets a hardware packet filter change event for the network adapter using the given filter driver handle. - * @param hOpen The handle to the filter driver. - * @param hAdapter The handle to the network adapter whose hardware packet filter change event is to be set. - * @param hWin32Event The Win32 event to be associated with the hardware packet filter event. - * @return TRUE if the hardware packet filter event is successfully set, or FALSE if the handle is invalid or the operation fails. - * - * This function sets a hardware packet filter event for the network adapter using the provided filter driver handle - * by calling the SetHwPacketFilterEvent() method of the CNdisApi object. - */ -BOOL __stdcall SetHwPacketFilterEvent(HANDLE hOpen, HANDLE hAdapter, HANDLE hWin32Event) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SetHwPacketFilterEvent(hAdapter, hWin32Event); -} - -/** - * @brief Sets the packet filter table for the filter driver associated with the given handle. - * @param hOpen The handle to the filter driver for which the packet filter table is to be set. - * @param pFilterList A pointer to a STATIC_FILTER_TABLE structure containing the packet filter rules to be applied. - * @return TRUE if the packet filter table is successfully set, or FALSE if the handle is invalid or the operation fails. - * - * This function sets the packet filter table for the filter driver associated with the provided handle - * by calling the SetPacketFilterTable() method of the CNdisApi object. - */ -BOOL __stdcall SetPacketFilterTable(HANDLE hOpen, PSTATIC_FILTER_TABLE pFilterList) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SetPacketFilterTable(pFilterList); -} - -/** - * @brief Adds a static filter to the beginning of the filter list. - * - * This function adds a new static filter to the front of the filter list managed by the NDISAPI driver. - * The filter is specified by the pFilter parameter. This operation is only successful if the handle to the - * driver (hOpen) is valid. - * - * @param hOpen Handle to the NDISAPI driver. - * @param pFilter Pointer to the STATIC_FILTER structure that defines the filter to be added. - * @return TRUE if the filter was successfully added, FALSE otherwise. - */ -BOOL __stdcall AddStaticFilterFront(HANDLE hOpen, PSTATIC_FILTER pFilter) -{ - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->AddStaticFilterFront(pFilter); -} - -/** - * @brief Adds a static filter to the end of the filter list. - * - * This function adds a new static filter to the back of the filter list managed by the NDISAPI driver. - * The filter is specified by the pFilter parameter. This operation is only successful if the handle to the - * driver (hOpen) is valid. - * - * @param hOpen Handle to the NDISAPI driver. - * @param pFilter Pointer to the STATIC_FILTER structure that defines the filter to be added. - * @return TRUE if the filter was successfully added, FALSE otherwise. - */ -BOOL __stdcall AddStaticFilterBack(HANDLE hOpen, PSTATIC_FILTER pFilter) -{ - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->AddStaticFilterBack(pFilter); -} - -/** - * @brief Inserts a static filter at a specified position in the filter list. - * - * This function inserts a new static filter at the specified position in the filter list managed by the NDISAPI driver. - * The position is zero-based. The filter is specified by the pFilter parameter. This operation is only successful if - * the handle to the driver (hOpen) is valid. - * - * @param hOpen Handle to the NDISAPI driver. - * @param pFilter Pointer to the STATIC_FILTER structure that defines the filter to be inserted. - * @param Position The zero-based position at which to insert the new filter. - * @return TRUE if the filter was successfully inserted, FALSE otherwise. - */ -BOOL __stdcall InsertStaticFilter(HANDLE hOpen, PSTATIC_FILTER pFilter, unsigned long Position) { - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->InsertStaticFilter(pFilter, Position); -} - -/** - * @brief Removes a static filter from the filter list by its unique identifier. - * - * This function removes a static filter from the filter list managed by the NDISAPI driver. The filter to be removed - * is identified by its unique identifier (dwFilterId). This operation is only successful if the handle to the driver - * (hOpen) is valid. - * - * @param hOpen Handle to the NDISAPI driver. - * @param dwFilterId The unique identifier of the filter to be removed. - * @return TRUE if the filter was successfully removed, FALSE otherwise. - */ -BOOL __stdcall RemoveStaticFilter(HANDLE hOpen, DWORD dwFilterId) -{ - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->RemoveStaticFilter(dwFilterId); -} - -/** - * @brief Resets the packet filter table for the filter driver associated with the given handle. - * @param hOpen The handle to the filter driver for which the packet filter table is to be reset. - * @return TRUE if the packet filter table is successfully reset, or FALSE if the handle is invalid or the operation fails. - * - * This function resets the packet filter table for the filter driver associated with the provided handle - * by calling the ResetPacketFilterTable() method of the CNdisApi object. - */ -BOOL __stdcall ResetPacketFilterTable(HANDLE hOpen) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->ResetPacketFilterTable(); -} - -/** - * @brief Retrieves the packet filter table size for the filter driver associated with the given handle. - * @param hOpen The handle to the filter driver for which the packet filter table size is to be retrieved. - * @param pdwTableSize A pointer to a DWORD variable that receives the size of the packet filter table. - * @return TRUE if the packet filter table size is successfully retrieved, or FALSE if the handle is invalid or the operation fails. - * - * This function retrieves the packet filter table size for the filter driver associated with the provided handle - * by calling the GetPacketFilterTableSize() method of the CNdisApi object. - */ -BOOL __stdcall GetPacketFilterTableSize(HANDLE hOpen, PDWORD pdwTableSize) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetPacketFilterTableSize(pdwTableSize); -} - -/** - * @brief Retrieves the packet filter table for the filter driver associated with the given handle. - * @param hOpen The handle to the filter driver for which the packet filter table is to be retrieved. - * @param pFilterList A pointer to a STATIC_FILTER_TABLE structure that receives the packet filter rules. - * @return TRUE if the packet filter table is successfully retrieved, or FALSE if the handle is invalid or the operation fails. - * - * This function retrieves the packet filter table for the filter driver associated with the provided handle - * by calling the GetPacketFilterTable() method of the CNdisApi object. - */ -BOOL __stdcall GetPacketFilterTable(HANDLE hOpen, PSTATIC_FILTER_TABLE pFilterList) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetPacketFilterTable(pFilterList); -} - -/** - * @brief Retrieves the packet filter table with reset statistics for the filter driver associated with the given handle. - * @param hOpen The handle to the filter driver for which the packet filter table with reset statistics is to be retrieved. - * @param pFilterList A pointer to a STATIC_FILTER_TABLE structure that receives the packet filter rules with reset statistics. - * @return TRUE if the packet filter table with reset statistics is successfully retrieved, or FALSE if the handle is invalid or the operation fails. - * - * This function retrieves the packet filter table with reset statistics for the filter driver associated with the provided handle - * by calling the GetPacketFilterTableResetStats() method of the CNdisApi object. - */ -BOOL __stdcall GetPacketFilterTableResetStats(HANDLE hOpen, PSTATIC_FILTER_TABLE pFilterList) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetPacketFilterTableResetStats(pFilterList); -} - -/** - * @brief Enables the packet filter cache. - * - * This function enables the packet filter cache for the filter driver associated with the given handle. - * The packet filter cache is used to improve performance by caching packet filters. Enabling the cache - * can improve packet processing speed, while disabling it may be useful for debugging or in scenarios - * where caching is not desirable. - * - * @param hOpen A handle to the open object for which the packet filter cache will be enabled. - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL __stdcall EnablePacketFilterCache(HANDLE hOpen) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->EnablePacketFilterCache(); -} - -/** - * @brief Disables the packet filter cache. - * - * This function disables the packet filter cache for the filter driver associated with the given handle. - * Disabling the cache may be useful for debugging or in scenarios where caching is not desirable. - * - * @param hOpen A handle to the open object for which the packet filter cache will be disabled. - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL __stdcall DisablePacketFilterCache(HANDLE hOpen) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->DisablePacketFilterCache(); -} - -/** - * @brief Enables the packet fragment cache. - * - * This function enables the packet fragment cache for the filter driver associated with the given handle. - * The packet fragment cache is used to improve performance by caching packet fragments. Enabling the cache - * can improve packet processing speed, while disabling it may be useful for debugging or in scenarios where - * caching is not desirable. - * - * @param hOpen A handle to the open object for which the packet fragment cache will be enabled. - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL __stdcall EnablePacketFragmentCache(HANDLE hOpen) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->EnablePacketFragmentCache(); -} - -/** - * @brief Disables the packet fragment cache. - * - * This function disables the packet fragment cache for the filter driver associated with the given handle. - * Disabling the cache may be useful for debugging or in scenarios where caching is not desirable. - * - * @param hOpen A handle to the open object for which the packet fragment cache will be disabled. - * @return TRUE if the operation was successful, FALSE otherwise. - */ -BOOL __stdcall DisablePacketFragmentCache(HANDLE hOpen) { - if (!hOpen) { - return FALSE; - } - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->DisablePacketFragmentCache(); -} - -/** - * @brief Sets the MTU decrement value. - * @param dwMTUDecrement The value to decrement the MTU by. - * @return TRUE if the MTU decrement is successfully set, or FALSE if the operation fails. - * - * This function sets the MTU decrement value by calling the SetMTUDecrement() method of the CNdisApi class. - */ -BOOL __stdcall SetMTUDecrement(DWORD dwMTUDecrement) { - return CNdisApi::SetMTUDecrement(dwMTUDecrement); -} - -/** - * @brief Retrieves the current MTU decrement value. - * @return The current MTU decrement value. - * - * This function retrieves the current MTU decrement value by calling the GetMTUDecrement() method of the CNdisApi class. - */ -DWORD __stdcall GetMTUDecrement() { - return CNdisApi::GetMTUDecrement(); -} - -/** - * @brief Sets the startup filter mode for network adapters. - * @param dwStartupMode The startup filter mode value to be set. - * @return TRUE if the adapter's startup filter mode is successfully set, or FALSE if the operation fails. - * - * This function sets the startup mode for network adapters by calling the SetAdaptersStartupMode() method of the CNdisApi class. - */ -BOOL __stdcall SetAdaptersStartupMode(DWORD dwStartupMode) { - return CNdisApi::SetAdaptersStartupMode(dwStartupMode); -} - -/** - * @brief Retrieves the current startup filter mode for network adapters. - * @return The current startup filter mode value. - * - * This function retrieves the current startup filter mode for network adapters by calling the GetAdaptersStartupMode() method of the CNdisApi class. - */ -DWORD __stdcall GetAdaptersStartupMode() { - return CNdisApi::GetAdaptersStartupMode(); -} - -/** - * @brief Sets the intermediate buffer pool size multiplier for Windows Packet Filter driver in the Windows registry. - * @param dwPoolSize The desired pool size multiplier to be set in the registry. - * @return TRUE if the pool size is successfully set, or FALSE if the operation fails. - * - * This function sets the pool size multiplier for Windows Packet Filter driver by calling the SetPoolSize() - * method of the CNdisApi class. - */ -BOOL __stdcall SetPoolSize(DWORD dwPoolSize) { - return CNdisApi::SetPoolSize(dwPoolSize); -} - -/** - * @brief Retrieves the pool size multiplier for the Windows Packet Filter driver from the Windows registry. - * - * This function gets the pool size multiplier for Windows Packet Filter driver by calling the SetPoolSize() - * method of the CNdisApi class. - * - * @return DWORD The pool size multiplier retrieved from the registry, or 0 if the value is not found or an error occurs. - */ -DWORD __stdcall GetPoolSize() -{ - return CNdisApi::GetPoolSize(); -} - -/** - * @brief Checks if the Windows Packet Filter driver is loaded. - * @param hOpen The handle to the CNdisApi instance. - * @return TRUE if the driver is loaded, or FALSE if the driver is not loaded or the handle is invalid. - * - * This function checks if the driver is loaded by calling the IsDriverLoaded() method of the CNdisApi class. - * It returns FALSE if the handle provided is invalid. - */ -BOOL __stdcall IsDriverLoaded(HANDLE hOpen) { - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->IsDriverLoaded(); -} - -/** - * @brief This function initializes the Fast I/O shared memory section for the Windows Packet Filter driver. - * @param hOpen The handle to the CNdisApi instance. - * @param pFastIo Pointer to a FAST_IO_SECTION structure that holds the Fast I/O section information. - * @param dwSize The size of the FAST_IO_SECTION structure. - * @return TRUE if the Fast I/O section is successfully initialized, or FALSE if the operation fails or the handle is invalid. - * - * This function initializes the Fast I/O section by calling the InitializeFastIo() method of the CNdisApi class. - * It returns FALSE if the handle provided is invalid. - */ -BOOL __stdcall InitializeFastIo(HANDLE hOpen, PFAST_IO_SECTION pFastIo, DWORD dwSize) { - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->InitializeFastIo(pFastIo, dwSize); -} - -/** - * @brief This function adds a secondary Fast I/O shared memory section for the Windows Packet Filter driver. - * @param hOpen The handle to the CNdisApi instance. - * @param pFastIo Pointer to a FAST_IO_SECTION structure that holds the secondary Fast I/O section information. - * @param dwSize The size of the FAST_IO_SECTION structure. - * @return TRUE if the secondary Fast I/O section is successfully added, or FALSE if the operation fails or the handle is invalid. - * - * This function adds a secondary Fast I/O section by calling the AddSecondaryFastIo() method of the CNdisApi class. - * It returns FALSE if the handle provided is invalid. - */ -BOOL __stdcall AddSecondaryFastIo(HANDLE hOpen, PFAST_IO_SECTION pFastIo, DWORD dwSize) { - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->AddSecondaryFastIo(pFastIo, dwSize); -} - -/** - * @brief Reads a bunch of packets from the driver packet queues without sorting. - * @param hOpen The handle to the CNdisApi instance. - * @param Packets Pointer to an array of PINTERMEDIATE_BUFFER pointers that will receive the packet data. - * The associated adapter handle will be stored in the INTERMEDIATE_BUFFER.m_hAdapter field. - * @param dwPacketsNum The number of packets to read. - * @param pdwPacketsSuccess Pointer to a DWORD that will receive the number of successfully read packets. - * @return TRUE if the function is successful, or FALSE if the operation fails or the handle is invalid. - * - * This function reads unsorted packets by calling the ReadPacketsUnsorted() method of the CNdisApi class. - * It returns FALSE if the handle provided is invalid.The function is not available in WOW64 mode. - */ -BOOL __stdcall ReadPacketsUnsorted(HANDLE hOpen, PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketsSuccess) { - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->ReadPacketsUnsorted(Packets, dwPacketsNum, pdwPacketsSuccess); -} - -/** - * @brief Sends a bunch of packets to the network adapters. - * @param hOpen The handle to the CNdisApi instance. - * @param Packets Pointer to an array of PINTERMEDIATE_BUFFER pointers containing the packet data to send. The target - * adapter handle should be set in the INTERMEDIATE_BUFFER.m_hAdapter field. - * @param dwPacketsNum The number of packets to send. - * @param pdwPacketSuccess Pointer to a DWORD that will receive the number of successfully sent packets. - * @return TRUE if the function is successful, or FALSE if the operation fails or the handle is invalid. - * - * This function sends unsorted packets to the network adapters by calling the SendPacketsToAdaptersUnsorted() method of - * the CNdisApi class. It returns FALSE if the handle provided is invalid. - */ -BOOL __stdcall SendPacketsToAdaptersUnsorted(HANDLE hOpen, PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketSuccess) { - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SendPacketsToAdaptersUnsorted(Packets, dwPacketsNum, pdwPacketSuccess); -} - -/** - * @brief Sends unsorted packets to the MSTCP (and other upper layer network protocols) using the CNdisApi instance. - * @param hOpen The handle to the CNdisApi instance. - * @param Packets Pointer to an array of PINTERMEDIATE_BUFFER pointers containing the packet data to send. The associated - * adapter handle should be stored in the INTERMEDIATE_BUFFER.m_hAdapter field. - * @param dwPacketsNum The number of packets to send. - * @param pdwPacketSuccess Pointer to a DWORD that will receive the number of successfully sent packets. - * @return TRUE if the function is successful, or FALSE if the operation fails or the handle is invalid. - * - * This function sends unsorted packets to the MSTCP (and other upper layer network protocols) by calling - * the SendPacketsToMstcpUnsorted() method of the CNdisApi class. It returns FALSE if the handle provided is invalid. - */ -BOOL __stdcall SendPacketsToMstcpUnsorted(HANDLE hOpen, PINTERMEDIATE_BUFFER* Packets, DWORD dwPacketsNum, PDWORD pdwPacketSuccess) { - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->SendPacketsToMstcpUnsorted(Packets, dwPacketsNum, pdwPacketSuccess); -} - -/** - * @brief Retrieves the effective size of the Windows Packet Filter internal intermediate buffer pool using the CNdisApi instance. - * @param hOpen The handle to the CNdisApi instance. - * @param pdwSize Pointer to a DWORD that will receive the size of the intermediate buffer pool. - * @return TRUE if the function is successful, or FALSE if the operation fails or the handle is invalid. - * - * This function retrieves the size of the intermediate buffer pool used by the driver by calling the GetIntermediateBufferPoolSize() - * method of the CNdisApi class. It returns FALSE if the handle provided is invalid. - */ -BOOL __stdcall GetIntermediateBufferPoolSize(HANDLE hOpen, PDWORD pdwSize) { - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetIntermediateBufferPoolSize(pdwSize); -} - -/** - * @brief Retrieves the number of bytes returned by the last operation that used an IOCTL code requiring a returned byte count using the CNdisApi instance. - * @param hOpen The handle to the CNdisApi instance. - * @return The number of bytes returned by the last operation if the function is successful, or FALSE if the handle is invalid. - * - * This function retrieves the number of bytes returned by the last operation that used an IOCTL code requiring a returned byte count. - * It returns FALSE if the handle provided is invalid. - */ -DWORD __stdcall GetBytesReturned(HANDLE hOpen) { - if (!hOpen) - return FALSE; - - const CNdisApi* pApi = static_cast(hOpen); - - return pApi->GetBytesReturned(); -} - -/** - * @brief Determines if the given adapter is an NDISWANIP interface. - * - * @param adapterName The adapter name to check. - * @return BOOL Returns TRUE if the adapter is an NDISWANIP interface, or FALSE otherwise. - * - * This function checks if the adapter name matches the internal name for - * NDISWANIP on systems prior to Windows 10. On Windows 10 and later systems, - * it calls the IsNdiswanInterface function to check if the adapter is an - * NDISWAN interface with the specified component ID (REGSTR_COMPONENTID_NDISWANIP). - */ -BOOL __stdcall IsNdiswanIp(LPCSTR adapterName) { - return CNdisApi::IsNdiswanIp(adapterName); -} - -/** - * @brief Determines if the given adapter is an NDISWANIPV6 interface. - * - * @param adapterName The adapter name to check. - * @return BOOL Returns TRUE if the adapter is an NDISWANIPV6 interface, or FALSE otherwise. - * - * This function checks if the adapter name matches the internal name for - * NDISWANIPV6 on systems prior to Windows 10. On Windows 10 and later systems, - * it calls the IsNdiswanInterface function to check if the adapter is an - * NDISWAN interface with the specified component ID (REGSTR_COMPONENTID_NDISWANIPV6). - */ -BOOL __stdcall IsNdiswanIpv6(LPCSTR adapterName) { - return CNdisApi::IsNdiswanIpv6(adapterName); -} - -/** - * @brief Determines if the given adapter is an NDISWANBH interface. - * - * @param adapterName The adapter name to check. - * @return BOOL Returns TRUE if the adapter is an NDISWANBH interface, or FALSE otherwise. - * - * This function checks if the adapter name matches the internal name for - * NDISWANBH on systems prior to Windows 10. On Windows 10 and later systems, - * it calls the IsNdiswanInterface function to check if the adapter is an - * NDISWAN interface with the specified component ID (REGSTR_COMPONENTID_NDISWANBH). - */ -BOOL __stdcall IsNdiswanBh(LPCSTR adapterName) { - return CNdisApi::IsNdiswanBh(adapterName); -} - -/** - * @brief Converts an adapter's internal name to a user-friendly name on Windows NT 4.0. - * - * @param szAdapterName The internal adapter name to convert. - * @param szUserFriendlyName A pointer to a buffer to store the resulting user-friendly name. - * @param dwUserFriendlyNameLength The length of the buffer pointed to by szUserFriendlyName. - * @return BOOL Returns TRUE if the conversion is successful, or FALSE otherwise. - * - * This function converts an adapter's internal name to a user-friendly name - * that is easier to understand. The user-friendly name is stored in the buffer - * pointed to by szUserFriendlyName. The function returns TRUE if the conversion is - * successful and FALSE otherwise. The length of the buffer is specified by the - * dwUserFriendlyNameLength parameter. - */ -BOOL -__stdcall -ConvertWindowsNTAdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength -) -{ - return CNdisApi::ConvertWindowsNTAdapterName( - szAdapterName, - szUserFriendlyName, - dwUserFriendlyNameLength - ); -} - -/** - * @brief Converts an adapter's internal name to a user-friendly name on Windows 2000 and later. - * - * @param szAdapterName The internal adapter name to convert. - * @param szUserFriendlyName A pointer to a buffer to store the resulting user-friendly name. - * @param dwUserFriendlyNameLength The length of the buffer pointed to by szUserFriendlyName. - * @return BOOL Returns TRUE if the conversion is successful, or FALSE otherwise. - * - * This function converts an adapter's internal name to a user-friendly name - * that is easier to understand. The user-friendly name is stored in the buffer - * pointed to by szUserFriendlyName. The function returns TRUE if the conversion is - * successful and FALSE otherwise. The length of the buffer is specified by the - * dwUserFriendlyNameLength parameter. - */ -BOOL -__stdcall -ConvertWindows2000AdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength -) -{ - return CNdisApi::ConvertWindows2000AdapterName( - szAdapterName, - szUserFriendlyName, - dwUserFriendlyNameLength - ); -} - -/** - * @brief Converts an adapter's internal name to a user-friendly name on Windows 95/98/ME. - * - * @param szAdapterName The internal adapter name to convert. - * @param szUserFriendlyName A pointer to a buffer to store the resulting user-friendly name. - * @param dwUserFriendlyNameLength The length of the buffer pointed to by szUserFriendlyName. - * @return BOOL Returns TRUE if the conversion is successful, or FALSE otherwise. - * - * This function converts an adapter's internal name to a user-friendly name - * that is easier to understand. The user-friendly name is stored in the buffer - * pointed to by szUserFriendlyName. The function returns TRUE if the conversion is - * successful and FALSE otherwise. The length of the buffer is specified by the - * dwUserFriendlyNameLength parameter. - */ -BOOL -__stdcall -ConvertWindows9xAdapterName( - LPCSTR szAdapterName, - LPSTR szUserFriendlyName, - DWORD dwUserFriendlyNameLength -) -{ - return CNdisApi::ConvertWindows9xAdapterName( - szAdapterName, - szUserFriendlyName, - dwUserFriendlyNameLength - ); -} - -/** - * @brief Recalculates the IPv4 checksum of a given packet. - * - * @param pPacket Pointer to the packet's INTERMEDIATE_BUFFER structure. - * - * This function recalculates the IP checksum for the given packet. The IP checksum - * is a 16-bit value used to verify the integrity of the IP header in an IP packet. - * The checksum must be recalculated if any changes are made to the IP header. - * This function should be called after modifying any field in the IP header - * to ensure the packet's integrity. - */ -void -__stdcall -RecalculateIPChecksum( - PINTERMEDIATE_BUFFER pPacket -) -{ - CNdisApi::RecalculateIPChecksum(pPacket); -} - -/** - * @brief Recalculates the ICMPv4 checksum of a given packet. - * - * @param pPacket Pointer to the packet's INTERMEDIATE_BUFFER structure. - */ -void -__stdcall -RecalculateICMPChecksum( - PINTERMEDIATE_BUFFER pPacket -) -{ - CNdisApi::RecalculateICMPChecksum(pPacket); -} - -/** - * @brief Recalculates the TCP checksum of a given IPv4 packet. - * - * @param pPacket Pointer to the packet's INTERMEDIATE_BUFFER structure. - */ -void -__stdcall -RecalculateTCPChecksum( - PINTERMEDIATE_BUFFER pPacket -) -{ - CNdisApi::RecalculateTCPChecksum(pPacket); -} - -/** - * @brief Recalculates the UDP checksum for a given IPv4 packet. - * @param pPacket The packet for which the UDP checksum needs to be recalculated. - * - * This function recalculates the UDP checksum for a packet by considering the pseudo-header, - * which includes the IP source and destination addresses, protocol number, and the length of - * the UDP packet. The calculated checksum is stored in the UDP header of the packet. - */ -void -__stdcall -RecalculateUDPChecksum( - PINTERMEDIATE_BUFFER pPacket -) -{ - CNdisApi::RecalculateUDPChecksum(pPacket); -} - diff --git a/ndisapi/ndisapi.rc b/ndisapi/ndisapi.rc deleted file mode 100644 index 700e929..0000000 --- a/ndisapi/ndisapi.rc +++ /dev/null @@ -1,100 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// English (United States) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) -LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US -#pragma code_page(1252) - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 3,6,1,1 - PRODUCTVERSION 3,6,1,1 - FILEFLAGSMASK 0x3fL -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x40004L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "040004b0" - BEGIN - VALUE "CompanyName", "NT KERNEL" - VALUE "FileDescription", "Windows Packet Filter user interface library" - VALUE "FileVersion", "3.6.1.1" - VALUE "InternalName", "ndisapi.dll" - VALUE "LegalCopyright", "Copyright © NT KERNEL 2000-2024" - VALUE "OriginalFilename", "ndisapi.dll" - VALUE "ProductName", "Windows Packet Filter Kit" - VALUE "ProductVersion", "3.6.1.1" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x400, 1200 - END -END - -#endif // English (United States) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/ndisapi/precomp.h b/ndisapi/precomp.h deleted file mode 100644 index 005117e..0000000 --- a/ndisapi/precomp.h +++ /dev/null @@ -1,46 +0,0 @@ -/*************************************************************************/ -/* Copyright (c) 2000-2024 NT KERNEL. */ -/* All Rights Reserved. */ -/* https://www.ntkernel.com */ -/* ndisrd@ntkernel.com */ -/* */ -/* Module Name: precomp.h */ -/* */ -/* Description: Cumulative include header */ -/* */ -/* Environment: */ -/* User mode */ -/* */ -/*************************************************************************/ - -#pragma once - -#include -#include -#include -#include - -#include - -#ifdef CYGWIN_BUILD -#include // For strcasecmp -#include // For strcpy, strcat -#include // For wcscpy, wcscat -#define _stricmp strcasecmp -#ifdef UNICODE -// Define _tcscpy, etc. for Unicode under non-Windows -#define _tcscpy wcscpy -#define _tcscat wcscat -#define TCHAR wchar_t -// ... other wide character (wchar_t) functions as needed ... -#else -// Define _tcscpy, etc. for non-Unicode under non-Windows -#define _tcscpy strcpy -#define _tcscat strcat -// ... other single-byte (char) functions as needed ... -#endif // UNICODE -#endif // CYGWIN_BUILD - -#include "../include/common.h" -#include "../include/ndisapi.h" -#include "iphlp.h" diff --git a/ndisapi/resource.h b/ndisapi/resource.h deleted file mode 100644 index b53a79e..0000000 --- a/ndisapi/resource.h +++ /dev/null @@ -1,15 +0,0 @@ -//{{NO_DEPENDENCIES}} -// Microsoft Visual C++ generated include file. -// Used by ndisapi.rc -// - -// Next default values for new objects -// -#ifdef APSTUDIO_INVOKED -#ifndef APSTUDIO_READONLY_SYMBOLS -#define _APS_NEXT_RESOURCE_VALUE 101 -#define _APS_NEXT_COMMAND_VALUE 40001 -#define _APS_NEXT_CONTROL_VALUE 1001 -#define _APS_NEXT_SYMED_VALUE 101 -#endif -#endif diff --git a/netlib/README.md b/netlib/README.md index 8a12320..3c21e44 100644 --- a/netlib/README.md +++ b/netlib/README.md @@ -109,5 +109,6 @@ CXX=clang++ netlib/test/portable/run-portable-tests.sh router's DNS handlers do, and checks every rewritten field, the SOCKS5 UDP header sent to the relay, the restored answer source, and independently verified checksums. `winshim/` supplies the few Windows SDK declarations those headers need, and the script extracts the product - `CNdisApi` checksum routines verbatim from `ndisapi/ndisapi.cpp`. The Windows Packet Filter + `CNdisApi` checksum routines verbatim from `external/ndisapi/ndisapi/ndisapi.cpp` (the + `wiresock/ndisapi` submodule, which must be checked out). The Windows Packet Filter driver, sockets, and the router class itself are not involved. diff --git a/netlib/test/portable/run-portable-tests.sh b/netlib/test/portable/run-portable-tests.sh index f505d01..2c3f331 100755 --- a/netlib/test/portable/run-portable-tests.sh +++ b/netlib/test/portable/run-portable-tests.sh @@ -7,7 +7,7 @@ # * ../proxy/dns_routing_policy_test.cpp - also part of the Windows netlib-tests project # * dns_packet_redirect_test.cpp - portable only: compiles the production # tcp_local_redirect.h / socks5_udp_local_redirect.h against winshim/ and the product -# CNdisApi checksum routines extracted verbatim from ndisapi/ndisapi.cpp +# CNdisApi checksum routines extracted verbatim from external/ndisapi/ndisapi/ndisapi.cpp # # Usage: netlib/test/portable/run-portable-tests.sh [extra gtest arguments] # Requires: a C++20 compiler (CXX, default g++), GoogleTest, and the Microsoft GSL headers. @@ -28,15 +28,20 @@ if [[ "${SANITIZE:-0}" == "1" ]]; then fi # Product checksum routines, extracted verbatim so the packet tests verify the shipped code. +ndisapi_cpp="$repo/external/ndisapi/ndisapi/ndisapi.cpp" +if [[ ! -f "$ndisapi_cpp" ]]; then + echo "external/ndisapi is not checked out; run: git submodule update --init" >&2 + exit 1 +fi checksums="$out/ndisapi_checksums.cpp" { - echo '// Generated by run-portable-tests.sh from ndisapi/ndisapi.cpp. Do not edit.' + echo '// Generated by run-portable-tests.sh from external/ndisapi/ndisapi/ndisapi.cpp. Do not edit.' echo '#include "winshim/packet_env.h"' awk '/^void CNdisApi::Recalculate(IP|TCP|UDP)Checksum\(/{p=1} p{print} p&&/^}/{p=0; print ""}' \ - "$repo/ndisapi/ndisapi.cpp" + "$ndisapi_cpp" } > "$checksums" if [[ "$(grep -c '^void CNdisApi::Recalculate' "$checksums")" != "3" ]]; then - echo "Failed to extract the CNdisApi checksum routines from ndisapi/ndisapi.cpp" >&2 + echo "Failed to extract the CNdisApi checksum routines from external/ndisapi/ndisapi/ndisapi.cpp" >&2 exit 1 fi diff --git a/netlib/test/portable/winshim/packet_env.h b/netlib/test/portable/winshim/packet_env.h index 2399eea..8954403 100644 --- a/netlib/test/portable/winshim/packet_env.h +++ b/netlib/test/portable/winshim/packet_env.h @@ -3,7 +3,7 @@ #pragma once #include "winshim.h" -#include "../../../../include/Common.h" +#include "../../../../external/ndisapi/include/Common.h" // iphlp.h declares tcp_seq as u_long, which is 32-bit on Windows but 64-bit on LP64 hosts (and // the host C library already declares its own u_long). Give iphlp.h a private u_long with the // Windows (LLP64) width so tcphdr has its on-wire size. @@ -11,7 +11,7 @@ #define long int #include "../../../src/iphlp.h" #undef long -#include "../../../../ndisapi/inet_checksum.h" +#include "../../../../external/ndisapi/ndisapi/inet_checksum.h" #include "../../../src/tools/generic.h" #include "../../../src/log/log.h" #include "../../../src/net/ip_address.h" diff --git a/socksify/unmanaged.h b/socksify/unmanaged.h index 0e45541..e625472 100644 --- a/socksify/unmanaged.h +++ b/socksify/unmanaged.h @@ -35,8 +35,8 @@ #include #include -#include "../include/common.h" -#include "../include/ndisapi.h" +#include "../external/ndisapi/include/Common.h" +#include "../external/ndisapi/include/ndisapi.h" #include "../netlib/src/tools/generic.h" #include "../netlib/src/tools/strings.h" #include "../netlib/src/log/log.h" From 84df0b49c837bd85124af2935daafead832be4b1 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 16:24:38 +0000 Subject: [PATCH 32/62] refactor: move the SOCKS5 UDP ASSOCIATE client steps into a shared helper Connecting the control connection, negotiating authentication and UDP ASSOCIATE (optionally over TLS), and creating the UDP socket connected to the relay move verbatim from socks5_local_udp_proxy_server into socks5_udp_association_client, so the DNS proxy's shared association can use the same code. The per-source-port UDP proxy server now delegates to it; its behavior is unchanged. --- .../src/proxy/socks5_local_udp_proxy_server.h | 727 +---------------- netlib/src/proxy/socks5_udp_association.h | 770 ++++++++++++++++++ socksify/socksify.vcxproj | 1 + socksify/socksify.vcxproj.filters | 3 + socksify/unmanaged.h | 1 + 5 files changed, 789 insertions(+), 713 deletions(-) create mode 100644 netlib/src/proxy/socks5_udp_association.h diff --git a/netlib/src/proxy/socks5_local_udp_proxy_server.h b/netlib/src/proxy/socks5_local_udp_proxy_server.h index ec2155e..e1c9aaa 100644 --- a/netlib/src/proxy/socks5_local_udp_proxy_server.h +++ b/netlib/src/proxy/socks5_local_udp_proxy_server.h @@ -89,10 +89,11 @@ namespace proxy * UDP ASSOCIATE, before the relay socket is created or sends anything. * * The relay socket is connected to this endpoint and sends nothing else. Apart from the - * local listener's replies, which the router handles as listener replies before any DNS - * decision, it is the only ProxiFyre UDP traffic to a SOCKS5 server's address. The router - * uses it to know whether any of its own UDP traffic that can reach the DNS recursion - * guard can be addressed to port 53. + * local listeners' replies, which the router handles as listener replies before any DNS + * decision, these relay sockets and the DNS relay's (socks5_dns_udp_relay.h, which reports + * its relay endpoints the same way) are the only ProxiFyre UDP traffic to a SOCKS5 + * server's address. The router uses them to know whether any of its own UDP traffic that + * can reach the DNS recursion guard can be addressed to port 53. */ using relay_endpoint_observed_t = void(const net::ip_endpoint&); @@ -251,6 +252,9 @@ namespace proxy */ uint16_t proxy_port_; + /** SOCKS5 control connection, UDP ASSOCIATE and relay socket setup. */ + socks5_udp_association_client association_; + /** Set when a completed server receive could not be re-armed synchronously. */ std::atomic_bool server_receive_rearm_needed_{ false }; @@ -261,32 +265,6 @@ namespace proxy */ std::atomic_bool end_server_{ true }; // set to true on proxy termination - void tune_udp_socket_buffers(const SOCKET socket, const char* const socket_name) const noexcept - { - const auto set_buffer = [this, socket, socket_name](const int option, const char* const option_name) - { - int requested_size = udp_socket_buffer_size; - if (setsockopt(socket, SOL_SOCKET, option, - reinterpret_cast(&requested_size), sizeof(requested_size)) == SOCKET_ERROR) - { - NETLIB_WARNING("{}: failed to set {} to {} bytes: {}", - socket_name, option_name, requested_size, WSAGetLastError()); - return; - } - - int actual_size = 0; - int actual_size_len = static_cast(sizeof(actual_size)); - if (getsockopt(socket, SOL_SOCKET, option, - reinterpret_cast(&actual_size), &actual_size_len) == 0) - { - NETLIB_DEBUG("{}: {} is {} bytes", socket_name, option_name, actual_size); - } - }; - - set_buffer(SO_RCVBUF, "SO_RCVBUF"); - set_buffer(SO_SNDBUF, "SO_SNDBUF"); - } - [[nodiscard]] std::optional> local_endpoint_from( const SOCKADDR_STORAGE& sender) const { @@ -544,7 +522,8 @@ namespace proxy query_remote_peer_(query_remote_peer_fn), commit_remote_peer_(commit_remote_peer_fn), relay_endpoint_observed_(relay_endpoint_observed_fn), - proxy_port_(proxy_port) + proxy_port_(proxy_port), + association_(log_level, logger::log_stream_) { if (!create_server_socket()) { @@ -1090,7 +1069,7 @@ namespace proxy } } - tune_udp_socket_buffers(server_socket_, "local UDP proxy server socket"); + association_.tune_udp_socket_buffers(server_socket_, "local UDP proxy server socket"); if constexpr (address_type_t::af_type == AF_INET) { @@ -1158,574 +1137,6 @@ namespace proxy return true; } - /** - * @brief Establishes a TCP connection to the specified SOCKS5 proxy server. - * - * This method creates a non-blocking TCP socket (IPv4 or IPv6 depending on address_type_t::af_type), - * binds it to a local ephemeral port, and connects it to the given SOCKS5 proxy server address and port. - * On failure, the socket is closed and INVALID_SOCKET is returned. - * - * @param socks_server_address The address of the SOCKS5 proxy server to connect to. - * @param socks_server_port The port of the SOCKS5 proxy server. - * @return A connected TCP SOCKET handle, or INVALID_SOCKET on failure. - */ - SOCKET connect_to_socks5_proxy(address_type_t socks_server_address, const uint16_t socks_server_port) - { - auto socks_tcp_socket = WSASocket(address_type_t::af_type, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, - WSA_FLAG_OVERLAPPED); - - if (socks_tcp_socket == INVALID_SOCKET) - { - return INVALID_SOCKET; - } - - // Set socket timeouts to prevent indefinite blocking in recv/send calls - // This prevents deadlock where IOCP worker holds lock_ while blocked on network I/O - constexpr DWORD timeout_ms = 5000; // 5 second timeout - if (setsockopt(socks_tcp_socket, SOL_SOCKET, SO_RCVTIMEO, - reinterpret_cast(&timeout_ms), sizeof(timeout_ms)) == SOCKET_ERROR) - { - NETLIB_WARNING("Failed to set socket receive timeout: {}", WSAGetLastError()); - closesocket(socks_tcp_socket); - return INVALID_SOCKET; - } - - if (setsockopt(socks_tcp_socket, SOL_SOCKET, SO_SNDTIMEO, - reinterpret_cast(&timeout_ms), sizeof(timeout_ms)) == SOCKET_ERROR) - { - NETLIB_WARNING("Failed to set socket send timeout: {}", WSAGetLastError()); - closesocket(socks_tcp_socket); - return INVALID_SOCKET; - } - - if constexpr (address_type_t::af_type == AF_INET) - { - sockaddr_in sa_local{}; - sa_local.sin_family = address_type_t::af_type; - sa_local.sin_port = htons(0); - sa_local.sin_addr.s_addr = htonl(INADDR_ANY); - - if (const auto status = bind(socks_tcp_socket, reinterpret_cast(&sa_local), sizeof(sa_local)) - ; status == SOCKET_ERROR) - { - closesocket(socks_tcp_socket); - return INVALID_SOCKET; - } - } - else - { - // Allow this AF_INET6 upstream control socket to reach IPv4 SOCKS5 - // servers via IPv4-mapped addresses (e.g. ::ffff:127.0.0.1) by - // clearing IPV6_V6ONLY so the dual-stack socket accepts both families. - DWORD v6_only = 0; - if (setsockopt(socks_tcp_socket, IPPROTO_IPV6, IPV6_V6ONLY, - reinterpret_cast(&v6_only), sizeof(v6_only)) == SOCKET_ERROR) - { - NETLIB_WARNING("Failed to clear IPV6_V6ONLY on SOCKS5 control socket: {}", WSAGetLastError()); - } - - sockaddr_in6 sa_local{}; - sa_local.sin6_family = address_type_t::af_type; - sa_local.sin6_port = htons(0); - sa_local.sin6_addr = in6addr_any; - - if (const auto status = bind(socks_tcp_socket, reinterpret_cast(&sa_local), sizeof(sa_local)) - ; status == SOCKET_ERROR) - { - closesocket(socks_tcp_socket); - return INVALID_SOCKET; - } - } - - // connect to server - if constexpr (address_type_t::af_type == AF_INET) - { - sockaddr_in sa_service{}; - sa_service.sin_family = address_type_t::af_type; - sa_service.sin_addr = socks_server_address; - sa_service.sin_port = htons(socks_server_port); - - if (!connect_with_timeout(socks_tcp_socket, reinterpret_cast(&sa_service), - sizeof(sa_service), 5000)) - { - closesocket(socks_tcp_socket); - return INVALID_SOCKET; - } - } - else - { - sockaddr_in6 sa_service{}; - sa_service.sin6_family = address_type_t::af_type; - sa_service.sin6_addr = socks_server_address; - sa_service.sin6_port = htons(socks_server_port); - - if (!connect_with_timeout(socks_tcp_socket, reinterpret_cast(&sa_service), - sizeof(sa_service), 5000)) - { - closesocket(socks_tcp_socket); - return INVALID_SOCKET; - } - } - - return socks_tcp_socket; - } - - /** - * @brief Connects a socket with a bounded timeout. - * - * A plain blocking connect() is not bounded by SO_*TIMEO and can hang for the OS - * default TCP connect timeout (~21s) on a black-holed SOCKS5 server while this thread - * holds the server lock, stalling all UDP relay. This switches the socket to - * non-blocking, issues the connect, and waits with select() up to timeout_ms, then - * restores blocking mode for the subsequent SO_*TIMEO-bounded send/recv. - * - * @return true if the connection completed within the timeout, false otherwise. - */ - static bool connect_with_timeout(const SOCKET s, const sockaddr* const addr, const int addr_len, - const DWORD timeout_ms) noexcept - { - u_long non_blocking = 1; - if (ioctlsocket(s, FIONBIO, &non_blocking) == SOCKET_ERROR) - return false; - - auto succeeded = false; - if (connect(s, addr, addr_len) == 0) - { - succeeded = true; - } - else if (WSAGetLastError() == WSAEWOULDBLOCK) - { - fd_set write_set; - FD_ZERO(&write_set); - FD_SET(s, &write_set); - fd_set error_set; - FD_ZERO(&error_set); - FD_SET(s, &error_set); - - timeval tv; - tv.tv_sec = static_cast(timeout_ms / 1000); - tv.tv_usec = static_cast((timeout_ms % 1000) * 1000); - - if (const auto sel = select(0, nullptr, &write_set, &error_set, &tv); - sel > 0 && FD_ISSET(s, &write_set)) - { - auto so_error = 0; - auto len = static_cast(sizeof(so_error)); - if (getsockopt(s, SOL_SOCKET, SO_ERROR, reinterpret_cast(&so_error), &len) == 0 && - so_error == 0) - { - succeeded = true; - } - } - } - - // Restore blocking mode for the subsequent SO_*TIMEO-bounded send/recv. If the - // socket connected but cannot be put back into blocking mode, fail the connect so - // the caller closes it rather than issuing blocking send/recv on a still-non-blocking - // socket (which would spuriously return WSAEWOULDBLOCK and break negotiation). - u_long blocking = 0; - if (ioctlsocket(s, FIONBIO, &blocking) == SOCKET_ERROR) - return false; - return succeeded; - } - - /** - * @brief Performs SOCKS5 negotiation and sends the UDP ASSOCIATE command. - * - * This method negotiates authentication with the SOCKS5 proxy server over the provided TCP socket, - * using either "NO AUTHENTICATION REQUIRED" or "USERNAME/PASSWORD" (RFC 1929) as needed. - * If authentication succeeds, it sends a UDP ASSOCIATE command to the proxy and retrieves the - * UDP relay endpoint assigned by the proxy for relaying UDP packets. - * - * @param socks_tcp_socket The connected TCP socket to the SOCKS5 proxy server. - * @param negotiate_ctx Unique pointer to the negotiation context, containing optional credentials. - * @return The UDP relay endpoint assigned by the SOCKS5 proxy, or std::nullopt on failure. - */ - [[nodiscard]] std::optional> associate_to_socks5_proxy( - const SOCKET socks_tcp_socket, - const address_type_t socks_server_address, - std::unique_ptr& - negotiate_ctx) const - { - using namespace std::string_literals; - - socks5_ident_req<2> ident_req{}; - socks5_ident_resp ident_resp{}; - - auto socks5_ident_req_size = sizeof(ident_req); - - ident_req.methods[0] = 0x0; // RFC 1928: X'00' NO AUTHENTICATION REQUIRED - ident_req.methods[1] = 0x2; // RFC 1928: X'02' USERNAME/PASSWORD - - // Don't suggest username/password option if not provided - if (!negotiate_ctx->socks5_username.has_value()) - { - ident_req.number_of_methods = 1; - socks5_ident_req_size = sizeof(socks5_ident_req<1>); - } - - std::unique_ptr tls_stream; - if (negotiate_ctx->upstream_options.is_tls()) - { - tls_stream = std::make_unique( - socks_tcp_socket, - negotiate_ctx->upstream_options.tls); - if (!tls_stream->handshake()) - { - NETLIB_INFO( - "[SOCKS5TLS]: associate_to_socks5_proxy: TLS handshake failed: {}", - tls_stream->last_error()); - return {}; - } - } - - auto control_socket_error = 0; - const auto send_all_raw = [socks_tcp_socket, &control_socket_error]( - const void* const buffer, const int len) -> bool - { - control_socket_error = 0; - auto* bytes = static_cast(buffer); - int sent_total = 0; - while (sent_total < len) - { - const auto sent = send(socks_tcp_socket, bytes + sent_total, len - sent_total, 0); - if (sent == SOCKET_ERROR) - { - control_socket_error = WSAGetLastError(); - return false; - } - if (sent == 0) - { - control_socket_error = WSAECONNRESET; - return false; - } - sent_total += sent; - } - return true; - }; - - // Blocking read of exactly 'len' bytes (recv() may return short reads on a - // stream socket); returns false on error or premature close. - const auto recv_exact_raw = [&control_socket_error]( - const SOCKET s, void* const buffer, const int len) -> bool - { - control_socket_error = 0; - // Bound the TOTAL time spent assembling these bytes, not just each recv(). - // SO_RCVTIMEO is a per-call timeout, so a server that drips one byte just - // under it could otherwise keep this loop alive for timeout * byte-count. - constexpr DWORD total_timeout_ms = 5000; - - DWORD original_timeout = total_timeout_ms; - int original_timeout_size = static_cast(sizeof(original_timeout)); - getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, - reinterpret_cast(&original_timeout), &original_timeout_size); - - const auto restore_timeout = [s, original_timeout] // NOLINT(clang-diagnostic-padded) - { - setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, - reinterpret_cast(&original_timeout), sizeof(original_timeout)); - }; - - auto* const bytes = static_cast(buffer); - const auto deadline = GetTickCount64() + total_timeout_ms; - int received = 0; - while (received < len) - { - const auto now = GetTickCount64(); - if (now >= deadline) - { - control_socket_error = WSAETIMEDOUT; - restore_timeout(); - return false; - } - - auto remaining_ms = static_cast(deadline - now); - if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, - reinterpret_cast(&remaining_ms), sizeof(remaining_ms)) == SOCKET_ERROR) - { - control_socket_error = WSAGetLastError(); - restore_timeout(); - return false; - } - - const auto n = recv(s, bytes + received, len - received, 0); - if (n == SOCKET_ERROR) - { - control_socket_error = WSAGetLastError(); - restore_timeout(); - return false; - } - if (n == 0) - { - control_socket_error = WSAECONNRESET; - restore_timeout(); - return false; - } - received += n; - } - - restore_timeout(); - return true; - }; - - const auto send_control = [&tls_stream, &send_all_raw](const void* const buffer, const int len) -> bool - { - return tls_stream ? tls_stream->send_all(buffer, len) : send_all_raw(buffer, len); - }; - - const auto recv_control = [&tls_stream, socks_tcp_socket, &recv_exact_raw](void* const buffer, const int len) -> bool - { - return tls_stream ? tls_stream->recv_exact(buffer, len) : recv_exact_raw(socks_tcp_socket, buffer, len); - }; - - const auto control_error = [&tls_stream, &control_socket_error] - { - return tls_stream - ? tls_stream->last_error() - : std::to_string(control_socket_error); - }; - - if (!send_control(reinterpret_cast(&ident_req), - static_cast(socks5_ident_req_size))) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Failed to send socks5_ident_req: {}", - control_error()); - return {}; - } - - if (!recv_control(reinterpret_cast(&ident_resp), sizeof(ident_resp))) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Failed to receive socks5_ident_resp: {}", - control_error()); - return {}; - } - - if ((ident_resp.version != socks5_protocol_version) || - (ident_resp.method != 0x00 && ident_resp.method != 0x02)) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: SOCKS5 selected an unsupported authentication method"); - return {}; - } - - if (ident_resp.method == 0x2) - { - if (!negotiate_ctx->socks5_username.has_value()) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: RFC 1928: X'02' USERNAME/PASSWORD is chosen but USERNAME is not provided"); - return {}; - } - - if (negotiate_ctx->socks5_username.value().length() > socks5_username_max_length || - negotiate_ctx->socks5_username.value().length() < 1) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: RFC 1928: X'02' USERNAME/PASSWORD is chosen but USERNAME exceeds maximum possible length"); - return {}; - } - - if (!negotiate_ctx->socks5_password.has_value()) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: RFC 1928: X'02' USERNAME/PASSWORD is chosen but PASSWORD is not provided"); - return {}; - } - - if (negotiate_ctx->socks5_password.value().length() > socks5_username_max_length || - negotiate_ctx->socks5_password.value().length() < 1) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: RFC 1928: X'02' USERNAME/PASSWORD is chosen but PASSWORD exceeds maximum possible length"); - return {}; - } - - const socks5_username_auth auth_req( - negotiate_ctx->socks5_username.value(), - negotiate_ctx->socks5_password.value() - ); - - if (!send_control(reinterpret_cast(&auth_req), - 3 + static_cast(negotiate_ctx->socks5_username.value().length()) + - static_cast(negotiate_ctx->socks5_password.value().length()))) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Failed to send socks5_username_auth: {}", - control_error()); - return {}; - } - - if (!recv_control(reinterpret_cast(&ident_resp), sizeof(ident_resp))) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Failed to receive socks5_ident_resp: {}", - control_error()); - return {}; - } - - if (ident_resp.version != socks5_username_auth_version || ident_resp.method != 0x00) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: USERNAME/PASSWORD authentication has failed!"); - return {}; - } - - NETLIB_DEBUG( - "[SOCKS5]: associate_to_socks5_proxy: USERNAME/PASSWORD authentication SUCCESS"); - } - - // Build the UDP ASSOCIATE request. DST.ADDR/DST.PORT only advertise the - // address the client expects to send datagrams from; we advertise the - // unspecified address. The ATYP must match the family actually used on the - // wire: the IPv6 proxy instance reaches the (IPv4) SOCKS5 server through an - // IPv4-mapped upstream, so an IPv4-only server would reject an ATYP=4 request. - // Send ATYP=1 with a zero IPv4 address whenever the upstream is IPv4 or - // IPv4-mapped, and ATYP=4 only for a genuine IPv6 upstream. - unsigned char associate_req_buf[4 + sizeof(in6_addr) + sizeof(unsigned short)]{}; - associate_req_buf[0] = 5; // VER - associate_req_buf[1] = 3; // CMD = UDP ASSOCIATE - associate_req_buf[2] = 0; // RSV - int associate_req_len; - if constexpr (address_type_t::af_type == AF_INET) - { - associate_req_buf[3] = 1; // ATYP = IPv4 - associate_req_len = 4 + 4 + static_cast(sizeof(unsigned short)); - } - else - { - if (IN6_IS_ADDR_V4MAPPED(static_cast(&socks_server_address))) - { - associate_req_buf[3] = 1; // ATYP = IPv4 (IPv4-mapped upstream) - associate_req_len = 4 + 4 + static_cast(sizeof(unsigned short)); - } - else - { - associate_req_buf[3] = 4; // ATYP = IPv6 (genuine IPv6 upstream) - associate_req_len = 4 + static_cast(sizeof(in6_addr)) + static_cast(sizeof(unsigned short)); - } - } - if (!send_control(reinterpret_cast(associate_req_buf), associate_req_len)) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Failed to send SOCKS5 ASSOCIATE request: {}", - control_error()); - return {}; - } - - // Read and validate the SOCKS5 UDP ASSOCIATE reply. The reply's BND.ADDR - // family (ATYP) is selected by the SERVER and is independent of the address - // family this proxy instance uses: an IPv6 proxy instance reaches the - // configured (IPv4) SOCKS5 server through an IPv4-mapped upstream, so the - // server typically replies with ATYP=1 and a 4-byte BND.ADDR. Parsing the - // reply as a fixed-size socks5_resp (which has a 16-byte - // BND.ADDR for IPv6) would then read BND.PORT from the wrong offset and - // hand back a bogus relay port. Parse the 4-byte reply prefix, then read - // exactly the bytes implied by the returned ATYP and take BND.PORT from the - // correct position so the relay port is family-agnostic and correct. - - // Fixed 4-byte reply prefix: VER, REP, RSV, ATYP. - struct socks5_resp_prefix - { - unsigned char version; - unsigned char reply; - unsigned char reserved; - unsigned char address_type; - } resp_prefix{}; - - if (!recv_control(&resp_prefix, sizeof(resp_prefix))) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Failed to receive SOCKS5 ASSOCIATE reply header: {}", - control_error()); - return {}; - } - - if ((resp_prefix.version != socks5_protocol_version) || - (resp_prefix.reply != 0) || - (resp_prefix.reserved != 0)) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: SOCKS5 ASSOCIATE has failed"); - return {}; - } - - // Determine BND.ADDR length from the server-selected ATYP. For ATYP=3 - // (domain) the first byte carries the name length. - int bnd_addr_len; - switch (resp_prefix.address_type) - { - case 1: // IPv4 - bnd_addr_len = 4; - break; - case 4: // IPv6 - bnd_addr_len = 16; - break; - case 3: // domain name - { - unsigned char domain_len = 0; - if (!recv_control(&domain_len, sizeof(domain_len))) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Failed to receive BND.ADDR domain length: {}", - control_error()); - return {}; - } - if (domain_len == 0) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Empty BND.ADDR domain in ASSOCIATE reply"); - return {}; - } - bnd_addr_len = domain_len; - } - break; - default: - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Unexpected BND.ADDR type {} in ASSOCIATE reply", - resp_prefix.address_type); - return {}; - } - - // Read BND.ADDR followed by the 2-byte BND.PORT. The buffer is sized for the - // largest possible BND.ADDR (a 255-byte domain) plus the port. - unsigned char bnd_addr_and_port[255 + sizeof(unsigned short)]{}; - if (!recv_control(bnd_addr_and_port, - bnd_addr_len + static_cast(sizeof(unsigned short)))) - { - NETLIB_INFO( - "[SOCKS5]: associate_to_socks5_proxy: Failed to receive BND.ADDR/BND.PORT: {}", - control_error()); - return {}; - } - - // BND.PORT immediately follows BND.ADDR, in network byte order. Assembling - // the two big-endian bytes directly yields the host-order port value. - const auto bind_port = static_cast( - (static_cast(bnd_addr_and_port[bnd_addr_len]) << 8) | - static_cast(bnd_addr_and_port[bnd_addr_len + 1])); - - // The UDP relay endpoint is, in every deployment ProxiFyre supports, the same - // host as the SOCKS5 server we connected the control socket to. Servers - // frequently report a BND.ADDR that is only meaningful from their own vantage - // point (0.0.0.0, 127.0.0.1, or an internal/NAT address), so honoring it - // verbatim can aim the relay at an address the client cannot reach -- and it - // would also turn a server-supplied address into a connect() target. We - // therefore relay to the address we already reached over the control - // connection (socks_server_address -- the IPv4-mapped upstream for the IPv6 - // instance) and take only BND.PORT from the reply. BND.PORT was parsed at the - // family-correct offset above, so the relay port is correct regardless of the - // ATYP the server selected, and no blocking DNS lookup is needed for an - // ATYP=3 (domain) reply. - NETLIB_DEBUG( - "[SOCKS5]: associate_to_socks5_proxy: SOCKS5 ASSOCIATE SUCCESS endpoint: {}:{}", - socks_server_address, - bind_port); - - return net::ip_endpoint{ socks_server_address, bind_port }; - } - /** * @brief Establishes a UDP relay session to a remote host through a SOCKS5 proxy. * @@ -1789,7 +1200,7 @@ namespace proxy // tearing down published sessions. Every early return below re-acquires lock_. lock.unlock(); - auto socks5_tcp_socket = connect_to_socks5_proxy(remote_address, remote_port); + auto socks5_tcp_socket = association_.connect_to_socks5_proxy(remote_address, remote_port); if (socks5_tcp_socket == INVALID_SOCKET) { NETLIB_DEBUG( @@ -1803,7 +1214,7 @@ namespace proxy std::optional> udp_endpoint; try { - udp_endpoint = associate_to_socks5_proxy(socks5_tcp_socket, remote_address, negotiate_ctx); + udp_endpoint = association_.associate_to_socks5_proxy(socks5_tcp_socket, remote_address, negotiate_ctx); } catch (...) { @@ -1833,124 +1244,14 @@ namespace proxy if (relay_endpoint_observed_) relay_endpoint_observed_(*udp_endpoint); - auto remote_socket = WSASocket(address_type_t::af_type, SOCK_DGRAM, IPPROTO_UDP, nullptr, 0, - WSA_FLAG_OVERLAPPED); - + const auto remote_socket = association_.create_relay_socket(*udp_endpoint); if (remote_socket == INVALID_SOCKET) { - NETLIB_DEBUG( - "connect_to_remote_host: Failed to create UDP socket: {}", - WSAGetLastError()); closesocket(socks5_tcp_socket); lock.lock(); return false; } - tune_udp_socket_buffers(remote_socket, "SOCKS5 UDP relay socket"); - - // Suppress spurious WSAECONNRESET on the relay socket too (see create_server_socket): - // an ICMP port-unreachable from the SOCKS5 UDP relay must not kill this relay's reads. - { - BOOL new_behavior = FALSE; - DWORD bytes_returned = 0; - if (WSAIoctl(remote_socket, SIO_UDP_CONNRESET, &new_behavior, sizeof(new_behavior), - nullptr, 0, &bytes_returned, nullptr, nullptr) == SOCKET_ERROR) - { - NETLIB_WARNING("connect_to_remote_host: failed to disable SIO_UDP_CONNRESET on relay socket: {}", - WSAGetLastError()); - } - } - - if constexpr (address_type_t::af_type == AF_INET) - { - sockaddr_in sa_local{}; - sa_local.sin_family = address_type_t::af_type; - sa_local.sin_port = htons(0); - sa_local.sin_addr.s_addr = htonl(INADDR_ANY); - - if (const auto status = bind(remote_socket, reinterpret_cast(&sa_local), sizeof(sa_local)); - status == SOCKET_ERROR) - { - closesocket(remote_socket); - closesocket(socks5_tcp_socket); - NETLIB_DEBUG( - "connect_to_remote_host: Failed to bind UDP socket: {}", - WSAGetLastError()); - lock.lock(); - return false; - } - } - else - { - // Dual-stack the AF_INET6 UDP relay socket so it can reach an IPv4 - // SOCKS5 server's UDP relay endpoint via its IPv4-mapped address - // (the relay address mirrors the configured control address). - DWORD v6_only = 0; - if (setsockopt(remote_socket, IPPROTO_IPV6, IPV6_V6ONLY, - reinterpret_cast(&v6_only), sizeof(v6_only)) == SOCKET_ERROR) - { - NETLIB_WARNING("connect_to_remote_host: Failed to clear IPV6_V6ONLY on UDP relay socket: {}", - WSAGetLastError()); - } - - sockaddr_in6 sa_local{}; - sa_local.sin6_family = address_type_t::af_type; - sa_local.sin6_port = htons(0); - sa_local.sin6_addr = in6addr_any; - - if (const auto status = bind(remote_socket, reinterpret_cast(&sa_local), sizeof(sa_local)); - status == SOCKET_ERROR) - { - closesocket(remote_socket); - closesocket(socks5_tcp_socket); - NETLIB_DEBUG( - "connect_to_remote_host: Failed to bind UDP socket: {}", - WSAGetLastError()); - lock.lock(); - return false; - } - } - - // connect to server - if constexpr (address_type_t::af_type == AF_INET) - { - sockaddr_in sa_service{}; - sa_service.sin_family = address_type_t::af_type; - sa_service.sin_addr = udp_endpoint->ip; - sa_service.sin_port = htons(udp_endpoint->port); - - if (connect(remote_socket, reinterpret_cast(&sa_service), sizeof(sa_service)) == - SOCKET_ERROR) - { - closesocket(remote_socket); - closesocket(socks5_tcp_socket); - NETLIB_DEBUG( - "connect_to_remote_host: Failed to connect UDP socket: {}", - WSAGetLastError()); - lock.lock(); - return false; - } - } - else - { - sockaddr_in6 sa_service{}; - sa_service.sin6_family = address_type_t::af_type; - sa_service.sin6_addr = udp_endpoint->ip; - sa_service.sin6_port = htons(udp_endpoint->port); - - if (connect(remote_socket, reinterpret_cast(&sa_service), sizeof(sa_service)) == - SOCKET_ERROR) - { - closesocket(remote_socket); - closesocket(socks5_tcp_socket); - NETLIB_DEBUG( - "connect_to_remote_host: Failed to connect UDP socket: {}", - WSAGetLastError()); - lock.lock(); - return false; - } - } - // Re-acquire lock_ to publish the session (see the lock.unlock() above). From here on // proxy_sockets_ and the server members are accessed under the lock again. lock.lock(); diff --git a/netlib/src/proxy/socks5_udp_association.h b/netlib/src/proxy/socks5_udp_association.h new file mode 100644 index 0000000..0610829 --- /dev/null +++ b/netlib/src/proxy/socks5_udp_association.h @@ -0,0 +1,770 @@ +#pragma once + +// SOCKS5 UDP ASSOCIATE client steps shared by the per-source-port UDP proxy server +// (socks5_local_udp_proxy_server.h) and the DNS proxy's shared association +// (socks5_dns_udp_relay.h): connecting the control connection, negotiating authentication and +// UDP ASSOCIATE (optionally over TLS), and creating the UDP socket connected to the relay. + +// SIO_UDP_CONNRESET normally comes from , but this header-only file relies on the +// project's master include order and the macro is not reliably visible here across SDKs. Provide +// the standard fallback definition; _WSAIOW/IOC_VENDOR are from , which is always +// included ahead of this file. +#ifndef SIO_UDP_CONNRESET +#define SIO_UDP_CONNRESET _WSAIOW(IOC_VENDOR, 12) +#endif + +namespace proxy +{ + /** + * @brief Blocking SOCKS5 UDP ASSOCIATE client. + * + * Every step is bounded by timeouts (connect, per-call SO_*TIMEO and an overall receive + * deadline), so callers run it on a worker thread without holding locks. + * + * @tparam AddressT net::ip_address_v4 or net::ip_address_v6: the family of the control and + * relay sockets. The IPv6 instance reaches an IPv4 SOCKS5 server through IPv4-mapped + * addresses. + */ + template + class socks5_udp_association_client : public netlib::log::logger> + { + public: + using log_level = netlib::log::log_level; + using logger = netlib::log::logger; + using address_type_t = AddressT; + using negotiate_context_t = socks5_negotiate_context; + + /** + * @brief Requested UDP socket buffer size for QUIC-sized bursts. + * + * Browser QUIC can emit many ~1200 byte datagrams immediately. The first + * datagram for a local UDP source port may need to establish a SOCKS5 TCP + * control connection and complete UDP ASSOCIATE before it can be forwarded; + * while that happens, the local UDP proxy socket relies on the kernel + * receive buffer to hold the rest of the burst. + */ + constexpr static int udp_socket_buffer_size = 4 * 1024 * 1024; + + explicit socks5_udp_association_client(const log_level log_level = log_level::error, + std::shared_ptr log_stream = nullptr) + : logger(log_level, std::move(log_stream)) + { + } + + void tune_udp_socket_buffers(const SOCKET socket, const char* const socket_name) const noexcept + { + const auto set_buffer = [this, socket, socket_name](const int option, const char* const option_name) + { + int requested_size = udp_socket_buffer_size; + if (setsockopt(socket, SOL_SOCKET, option, + reinterpret_cast(&requested_size), sizeof(requested_size)) == SOCKET_ERROR) + { + NETLIB_WARNING("{}: failed to set {} to {} bytes: {}", + socket_name, option_name, requested_size, WSAGetLastError()); + return; + } + + int actual_size = 0; + int actual_size_len = static_cast(sizeof(actual_size)); + if (getsockopt(socket, SOL_SOCKET, option, + reinterpret_cast(&actual_size), &actual_size_len) == 0) + { + NETLIB_DEBUG("{}: {} is {} bytes", socket_name, option_name, actual_size); + } + }; + + set_buffer(SO_RCVBUF, "SO_RCVBUF"); + set_buffer(SO_SNDBUF, "SO_SNDBUF"); + } + + /** + * @brief Establishes a TCP connection to the specified SOCKS5 proxy server. + * + * This method creates a non-blocking TCP socket (IPv4 or IPv6 depending on address_type_t::af_type), + * binds it to a local ephemeral port, and connects it to the given SOCKS5 proxy server address and port. + * On failure, the socket is closed and INVALID_SOCKET is returned. + * + * @param socks_server_address The address of the SOCKS5 proxy server to connect to. + * @param socks_server_port The port of the SOCKS5 proxy server. + * @return A connected TCP SOCKET handle, or INVALID_SOCKET on failure. + */ + SOCKET connect_to_socks5_proxy(address_type_t socks_server_address, const uint16_t socks_server_port) + { + auto socks_tcp_socket = WSASocket(address_type_t::af_type, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, + WSA_FLAG_OVERLAPPED); + + if (socks_tcp_socket == INVALID_SOCKET) + { + return INVALID_SOCKET; + } + + // Set socket timeouts to prevent indefinite blocking in recv/send calls + // This prevents deadlock where IOCP worker holds lock_ while blocked on network I/O + constexpr DWORD timeout_ms = 5000; // 5 second timeout + if (setsockopt(socks_tcp_socket, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast(&timeout_ms), sizeof(timeout_ms)) == SOCKET_ERROR) + { + NETLIB_WARNING("Failed to set socket receive timeout: {}", WSAGetLastError()); + closesocket(socks_tcp_socket); + return INVALID_SOCKET; + } + + if (setsockopt(socks_tcp_socket, SOL_SOCKET, SO_SNDTIMEO, + reinterpret_cast(&timeout_ms), sizeof(timeout_ms)) == SOCKET_ERROR) + { + NETLIB_WARNING("Failed to set socket send timeout: {}", WSAGetLastError()); + closesocket(socks_tcp_socket); + return INVALID_SOCKET; + } + + if constexpr (address_type_t::af_type == AF_INET) + { + sockaddr_in sa_local{}; + sa_local.sin_family = address_type_t::af_type; + sa_local.sin_port = htons(0); + sa_local.sin_addr.s_addr = htonl(INADDR_ANY); + + if (const auto status = bind(socks_tcp_socket, reinterpret_cast(&sa_local), sizeof(sa_local)) + ; status == SOCKET_ERROR) + { + closesocket(socks_tcp_socket); + return INVALID_SOCKET; + } + } + else + { + // Allow this AF_INET6 upstream control socket to reach IPv4 SOCKS5 + // servers via IPv4-mapped addresses (e.g. ::ffff:127.0.0.1) by + // clearing IPV6_V6ONLY so the dual-stack socket accepts both families. + DWORD v6_only = 0; + if (setsockopt(socks_tcp_socket, IPPROTO_IPV6, IPV6_V6ONLY, + reinterpret_cast(&v6_only), sizeof(v6_only)) == SOCKET_ERROR) + { + NETLIB_WARNING("Failed to clear IPV6_V6ONLY on SOCKS5 control socket: {}", WSAGetLastError()); + } + + sockaddr_in6 sa_local{}; + sa_local.sin6_family = address_type_t::af_type; + sa_local.sin6_port = htons(0); + sa_local.sin6_addr = in6addr_any; + + if (const auto status = bind(socks_tcp_socket, reinterpret_cast(&sa_local), sizeof(sa_local)) + ; status == SOCKET_ERROR) + { + closesocket(socks_tcp_socket); + return INVALID_SOCKET; + } + } + + // connect to server + if constexpr (address_type_t::af_type == AF_INET) + { + sockaddr_in sa_service{}; + sa_service.sin_family = address_type_t::af_type; + sa_service.sin_addr = socks_server_address; + sa_service.sin_port = htons(socks_server_port); + + if (!connect_with_timeout(socks_tcp_socket, reinterpret_cast(&sa_service), + sizeof(sa_service), 5000)) + { + closesocket(socks_tcp_socket); + return INVALID_SOCKET; + } + } + else + { + sockaddr_in6 sa_service{}; + sa_service.sin6_family = address_type_t::af_type; + sa_service.sin6_addr = socks_server_address; + sa_service.sin6_port = htons(socks_server_port); + + if (!connect_with_timeout(socks_tcp_socket, reinterpret_cast(&sa_service), + sizeof(sa_service), 5000)) + { + closesocket(socks_tcp_socket); + return INVALID_SOCKET; + } + } + + return socks_tcp_socket; + } + + /** + * @brief Connects a socket with a bounded timeout. + * + * A plain blocking connect() is not bounded by SO_*TIMEO and can hang for the OS + * default TCP connect timeout (~21s) on a black-holed SOCKS5 server while this thread + * holds the server lock, stalling all UDP relay. This switches the socket to + * non-blocking, issues the connect, and waits with select() up to timeout_ms, then + * restores blocking mode for the subsequent SO_*TIMEO-bounded send/recv. + * + * @return true if the connection completed within the timeout, false otherwise. + */ + static bool connect_with_timeout(const SOCKET s, const sockaddr* const addr, const int addr_len, + const DWORD timeout_ms) noexcept + { + u_long non_blocking = 1; + if (ioctlsocket(s, FIONBIO, &non_blocking) == SOCKET_ERROR) + return false; + + auto succeeded = false; + if (connect(s, addr, addr_len) == 0) + { + succeeded = true; + } + else if (WSAGetLastError() == WSAEWOULDBLOCK) + { + fd_set write_set; + FD_ZERO(&write_set); + FD_SET(s, &write_set); + fd_set error_set; + FD_ZERO(&error_set); + FD_SET(s, &error_set); + + timeval tv; + tv.tv_sec = static_cast(timeout_ms / 1000); + tv.tv_usec = static_cast((timeout_ms % 1000) * 1000); + + if (const auto sel = select(0, nullptr, &write_set, &error_set, &tv); + sel > 0 && FD_ISSET(s, &write_set)) + { + auto so_error = 0; + auto len = static_cast(sizeof(so_error)); + if (getsockopt(s, SOL_SOCKET, SO_ERROR, reinterpret_cast(&so_error), &len) == 0 && + so_error == 0) + { + succeeded = true; + } + } + } + + // Restore blocking mode for the subsequent SO_*TIMEO-bounded send/recv. If the + // socket connected but cannot be put back into blocking mode, fail the connect so + // the caller closes it rather than issuing blocking send/recv on a still-non-blocking + // socket (which would spuriously return WSAEWOULDBLOCK and break negotiation). + u_long blocking = 0; + if (ioctlsocket(s, FIONBIO, &blocking) == SOCKET_ERROR) + return false; + return succeeded; + } + + /** + * @brief Performs SOCKS5 negotiation and sends the UDP ASSOCIATE command. + * + * This method negotiates authentication with the SOCKS5 proxy server over the provided TCP socket, + * using either "NO AUTHENTICATION REQUIRED" or "USERNAME/PASSWORD" (RFC 1929) as needed. + * If authentication succeeds, it sends a UDP ASSOCIATE command to the proxy and retrieves the + * UDP relay endpoint assigned by the proxy for relaying UDP packets. + * + * @param socks_tcp_socket The connected TCP socket to the SOCKS5 proxy server. + * @param negotiate_ctx Unique pointer to the negotiation context, containing optional credentials. + * @return The UDP relay endpoint assigned by the SOCKS5 proxy, or std::nullopt on failure. + */ + [[nodiscard]] std::optional> associate_to_socks5_proxy( + const SOCKET socks_tcp_socket, + const address_type_t socks_server_address, + std::unique_ptr& + negotiate_ctx) const + { + using namespace std::string_literals; + + socks5_ident_req<2> ident_req{}; + socks5_ident_resp ident_resp{}; + + auto socks5_ident_req_size = sizeof(ident_req); + + ident_req.methods[0] = 0x0; // RFC 1928: X'00' NO AUTHENTICATION REQUIRED + ident_req.methods[1] = 0x2; // RFC 1928: X'02' USERNAME/PASSWORD + + // Don't suggest username/password option if not provided + if (!negotiate_ctx->socks5_username.has_value()) + { + ident_req.number_of_methods = 1; + socks5_ident_req_size = sizeof(socks5_ident_req<1>); + } + + std::unique_ptr tls_stream; + if (negotiate_ctx->upstream_options.is_tls()) + { + tls_stream = std::make_unique( + socks_tcp_socket, + negotiate_ctx->upstream_options.tls); + if (!tls_stream->handshake()) + { + NETLIB_INFO( + "[SOCKS5TLS]: associate_to_socks5_proxy: TLS handshake failed: {}", + tls_stream->last_error()); + return {}; + } + } + + auto control_socket_error = 0; + const auto send_all_raw = [socks_tcp_socket, &control_socket_error]( + const void* const buffer, const int len) -> bool + { + control_socket_error = 0; + auto* bytes = static_cast(buffer); + int sent_total = 0; + while (sent_total < len) + { + const auto sent = send(socks_tcp_socket, bytes + sent_total, len - sent_total, 0); + if (sent == SOCKET_ERROR) + { + control_socket_error = WSAGetLastError(); + return false; + } + if (sent == 0) + { + control_socket_error = WSAECONNRESET; + return false; + } + sent_total += sent; + } + return true; + }; + + // Blocking read of exactly 'len' bytes (recv() may return short reads on a + // stream socket); returns false on error or premature close. + const auto recv_exact_raw = [&control_socket_error]( + const SOCKET s, void* const buffer, const int len) -> bool + { + control_socket_error = 0; + // Bound the TOTAL time spent assembling these bytes, not just each recv(). + // SO_RCVTIMEO is a per-call timeout, so a server that drips one byte just + // under it could otherwise keep this loop alive for timeout * byte-count. + constexpr DWORD total_timeout_ms = 5000; + + DWORD original_timeout = total_timeout_ms; + int original_timeout_size = static_cast(sizeof(original_timeout)); + getsockopt(s, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast(&original_timeout), &original_timeout_size); + + const auto restore_timeout = [s, original_timeout] // NOLINT(clang-diagnostic-padded) + { + setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast(&original_timeout), sizeof(original_timeout)); + }; + + auto* const bytes = static_cast(buffer); + const auto deadline = GetTickCount64() + total_timeout_ms; + int received = 0; + while (received < len) + { + const auto now = GetTickCount64(); + if (now >= deadline) + { + control_socket_error = WSAETIMEDOUT; + restore_timeout(); + return false; + } + + auto remaining_ms = static_cast(deadline - now); + if (setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, + reinterpret_cast(&remaining_ms), sizeof(remaining_ms)) == SOCKET_ERROR) + { + control_socket_error = WSAGetLastError(); + restore_timeout(); + return false; + } + + const auto n = recv(s, bytes + received, len - received, 0); + if (n == SOCKET_ERROR) + { + control_socket_error = WSAGetLastError(); + restore_timeout(); + return false; + } + if (n == 0) + { + control_socket_error = WSAECONNRESET; + restore_timeout(); + return false; + } + received += n; + } + + restore_timeout(); + return true; + }; + + const auto send_control = [&tls_stream, &send_all_raw](const void* const buffer, const int len) -> bool + { + return tls_stream ? tls_stream->send_all(buffer, len) : send_all_raw(buffer, len); + }; + + const auto recv_control = [&tls_stream, socks_tcp_socket, &recv_exact_raw](void* const buffer, const int len) -> bool + { + return tls_stream ? tls_stream->recv_exact(buffer, len) : recv_exact_raw(socks_tcp_socket, buffer, len); + }; + + const auto control_error = [&tls_stream, &control_socket_error] + { + return tls_stream + ? tls_stream->last_error() + : std::to_string(control_socket_error); + }; + + if (!send_control(reinterpret_cast(&ident_req), + static_cast(socks5_ident_req_size))) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Failed to send socks5_ident_req: {}", + control_error()); + return {}; + } + + if (!recv_control(reinterpret_cast(&ident_resp), sizeof(ident_resp))) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Failed to receive socks5_ident_resp: {}", + control_error()); + return {}; + } + + if ((ident_resp.version != socks5_protocol_version) || + (ident_resp.method != 0x00 && ident_resp.method != 0x02)) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: SOCKS5 selected an unsupported authentication method"); + return {}; + } + + if (ident_resp.method == 0x2) + { + if (!negotiate_ctx->socks5_username.has_value()) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: RFC 1928: X'02' USERNAME/PASSWORD is chosen but USERNAME is not provided"); + return {}; + } + + if (negotiate_ctx->socks5_username.value().length() > socks5_username_max_length || + negotiate_ctx->socks5_username.value().length() < 1) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: RFC 1928: X'02' USERNAME/PASSWORD is chosen but USERNAME exceeds maximum possible length"); + return {}; + } + + if (!negotiate_ctx->socks5_password.has_value()) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: RFC 1928: X'02' USERNAME/PASSWORD is chosen but PASSWORD is not provided"); + return {}; + } + + if (negotiate_ctx->socks5_password.value().length() > socks5_username_max_length || + negotiate_ctx->socks5_password.value().length() < 1) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: RFC 1928: X'02' USERNAME/PASSWORD is chosen but PASSWORD exceeds maximum possible length"); + return {}; + } + + const socks5_username_auth auth_req( + negotiate_ctx->socks5_username.value(), + negotiate_ctx->socks5_password.value() + ); + + if (!send_control(reinterpret_cast(&auth_req), + 3 + static_cast(negotiate_ctx->socks5_username.value().length()) + + static_cast(negotiate_ctx->socks5_password.value().length()))) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Failed to send socks5_username_auth: {}", + control_error()); + return {}; + } + + if (!recv_control(reinterpret_cast(&ident_resp), sizeof(ident_resp))) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Failed to receive socks5_ident_resp: {}", + control_error()); + return {}; + } + + if (ident_resp.version != socks5_username_auth_version || ident_resp.method != 0x00) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: USERNAME/PASSWORD authentication has failed!"); + return {}; + } + + NETLIB_DEBUG( + "[SOCKS5]: associate_to_socks5_proxy: USERNAME/PASSWORD authentication SUCCESS"); + } + + // Build the UDP ASSOCIATE request. DST.ADDR/DST.PORT only advertise the + // address the client expects to send datagrams from; we advertise the + // unspecified address. The ATYP must match the family actually used on the + // wire: the IPv6 proxy instance reaches the (IPv4) SOCKS5 server through an + // IPv4-mapped upstream, so an IPv4-only server would reject an ATYP=4 request. + // Send ATYP=1 with a zero IPv4 address whenever the upstream is IPv4 or + // IPv4-mapped, and ATYP=4 only for a genuine IPv6 upstream. + unsigned char associate_req_buf[4 + sizeof(in6_addr) + sizeof(unsigned short)]{}; + associate_req_buf[0] = 5; // VER + associate_req_buf[1] = 3; // CMD = UDP ASSOCIATE + associate_req_buf[2] = 0; // RSV + int associate_req_len; + if constexpr (address_type_t::af_type == AF_INET) + { + associate_req_buf[3] = 1; // ATYP = IPv4 + associate_req_len = 4 + 4 + static_cast(sizeof(unsigned short)); + } + else + { + if (IN6_IS_ADDR_V4MAPPED(static_cast(&socks_server_address))) + { + associate_req_buf[3] = 1; // ATYP = IPv4 (IPv4-mapped upstream) + associate_req_len = 4 + 4 + static_cast(sizeof(unsigned short)); + } + else + { + associate_req_buf[3] = 4; // ATYP = IPv6 (genuine IPv6 upstream) + associate_req_len = 4 + static_cast(sizeof(in6_addr)) + static_cast(sizeof(unsigned short)); + } + } + if (!send_control(reinterpret_cast(associate_req_buf), associate_req_len)) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Failed to send SOCKS5 ASSOCIATE request: {}", + control_error()); + return {}; + } + + // Read and validate the SOCKS5 UDP ASSOCIATE reply. The reply's BND.ADDR + // family (ATYP) is selected by the SERVER and is independent of the address + // family this proxy instance uses: an IPv6 proxy instance reaches the + // configured (IPv4) SOCKS5 server through an IPv4-mapped upstream, so the + // server typically replies with ATYP=1 and a 4-byte BND.ADDR. Parsing the + // reply as a fixed-size socks5_resp (which has a 16-byte + // BND.ADDR for IPv6) would then read BND.PORT from the wrong offset and + // hand back a bogus relay port. Parse the 4-byte reply prefix, then read + // exactly the bytes implied by the returned ATYP and take BND.PORT from the + // correct position so the relay port is family-agnostic and correct. + + // Fixed 4-byte reply prefix: VER, REP, RSV, ATYP. + struct socks5_resp_prefix + { + unsigned char version; + unsigned char reply; + unsigned char reserved; + unsigned char address_type; + } resp_prefix{}; + + if (!recv_control(&resp_prefix, sizeof(resp_prefix))) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Failed to receive SOCKS5 ASSOCIATE reply header: {}", + control_error()); + return {}; + } + + if ((resp_prefix.version != socks5_protocol_version) || + (resp_prefix.reply != 0) || + (resp_prefix.reserved != 0)) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: SOCKS5 ASSOCIATE has failed"); + return {}; + } + + // Determine BND.ADDR length from the server-selected ATYP. For ATYP=3 + // (domain) the first byte carries the name length. + int bnd_addr_len; + switch (resp_prefix.address_type) + { + case 1: // IPv4 + bnd_addr_len = 4; + break; + case 4: // IPv6 + bnd_addr_len = 16; + break; + case 3: // domain name + { + unsigned char domain_len = 0; + if (!recv_control(&domain_len, sizeof(domain_len))) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Failed to receive BND.ADDR domain length: {}", + control_error()); + return {}; + } + if (domain_len == 0) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Empty BND.ADDR domain in ASSOCIATE reply"); + return {}; + } + bnd_addr_len = domain_len; + } + break; + default: + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Unexpected BND.ADDR type {} in ASSOCIATE reply", + resp_prefix.address_type); + return {}; + } + + // Read BND.ADDR followed by the 2-byte BND.PORT. The buffer is sized for the + // largest possible BND.ADDR (a 255-byte domain) plus the port. + unsigned char bnd_addr_and_port[255 + sizeof(unsigned short)]{}; + if (!recv_control(bnd_addr_and_port, + bnd_addr_len + static_cast(sizeof(unsigned short)))) + { + NETLIB_INFO( + "[SOCKS5]: associate_to_socks5_proxy: Failed to receive BND.ADDR/BND.PORT: {}", + control_error()); + return {}; + } + + // BND.PORT immediately follows BND.ADDR, in network byte order. Assembling + // the two big-endian bytes directly yields the host-order port value. + const auto bind_port = static_cast( + (static_cast(bnd_addr_and_port[bnd_addr_len]) << 8) | + static_cast(bnd_addr_and_port[bnd_addr_len + 1])); + + // The UDP relay endpoint is, in every deployment ProxiFyre supports, the same + // host as the SOCKS5 server we connected the control socket to. Servers + // frequently report a BND.ADDR that is only meaningful from their own vantage + // point (0.0.0.0, 127.0.0.1, or an internal/NAT address), so honoring it + // verbatim can aim the relay at an address the client cannot reach -- and it + // would also turn a server-supplied address into a connect() target. We + // therefore relay to the address we already reached over the control + // connection (socks_server_address -- the IPv4-mapped upstream for the IPv6 + // instance) and take only BND.PORT from the reply. BND.PORT was parsed at the + // family-correct offset above, so the relay port is correct regardless of the + // ATYP the server selected, and no blocking DNS lookup is needed for an + // ATYP=3 (domain) reply. + NETLIB_DEBUG( + "[SOCKS5]: associate_to_socks5_proxy: SOCKS5 ASSOCIATE SUCCESS endpoint: {}:{}", + socks_server_address, + bind_port); + + return net::ip_endpoint{ socks_server_address, bind_port }; + } + + /** + * @brief Creates a UDP socket connected to the SOCKS5 UDP relay endpoint @p udp_endpoint. + * + * The socket is bound to an ephemeral port, has SIO_UDP_CONNRESET disabled so an ICMP + * port-unreachable cannot break its reads, and (for the IPv6 instance) is dual-stack so + * it can reach an IPv4 relay through its IPv4-mapped address. + * + * @return The connected socket, or INVALID_SOCKET on failure. + */ + SOCKET create_relay_socket(const net::ip_endpoint& udp_endpoint) + { + auto remote_socket = WSASocket(address_type_t::af_type, SOCK_DGRAM, IPPROTO_UDP, nullptr, 0, + WSA_FLAG_OVERLAPPED); + + if (remote_socket == INVALID_SOCKET) + { + NETLIB_DEBUG( + "create_relay_socket: Failed to create UDP socket: {}", + WSAGetLastError()); + return INVALID_SOCKET; + } + + tune_udp_socket_buffers(remote_socket, "SOCKS5 UDP relay socket"); + + // Suppress spurious WSAECONNRESET on the relay socket: + // an ICMP port-unreachable from the SOCKS5 UDP relay must not kill this relay's reads. + { + BOOL new_behavior = FALSE; + DWORD bytes_returned = 0; + if (WSAIoctl(remote_socket, SIO_UDP_CONNRESET, &new_behavior, sizeof(new_behavior), + nullptr, 0, &bytes_returned, nullptr, nullptr) == SOCKET_ERROR) + { + NETLIB_WARNING("create_relay_socket: failed to disable SIO_UDP_CONNRESET on relay socket: {}", + WSAGetLastError()); + } + } + + if constexpr (address_type_t::af_type == AF_INET) + { + sockaddr_in sa_local{}; + sa_local.sin_family = address_type_t::af_type; + sa_local.sin_port = htons(0); + sa_local.sin_addr.s_addr = htonl(INADDR_ANY); + + if (const auto status = bind(remote_socket, reinterpret_cast(&sa_local), sizeof(sa_local)); + status == SOCKET_ERROR) + { + closesocket(remote_socket); + NETLIB_DEBUG( + "create_relay_socket: Failed to bind UDP socket: {}", + WSAGetLastError()); + return INVALID_SOCKET; + } + } + else + { + // Dual-stack the AF_INET6 UDP relay socket so it can reach an IPv4 + // SOCKS5 server's UDP relay endpoint via its IPv4-mapped address + // (the relay address mirrors the configured control address). + DWORD v6_only = 0; + if (setsockopt(remote_socket, IPPROTO_IPV6, IPV6_V6ONLY, + reinterpret_cast(&v6_only), sizeof(v6_only)) == SOCKET_ERROR) + { + NETLIB_WARNING("create_relay_socket: Failed to clear IPV6_V6ONLY on UDP relay socket: {}", + WSAGetLastError()); + } + + sockaddr_in6 sa_local{}; + sa_local.sin6_family = address_type_t::af_type; + sa_local.sin6_port = htons(0); + sa_local.sin6_addr = in6addr_any; + + if (const auto status = bind(remote_socket, reinterpret_cast(&sa_local), sizeof(sa_local)); + status == SOCKET_ERROR) + { + closesocket(remote_socket); + NETLIB_DEBUG( + "create_relay_socket: Failed to bind UDP socket: {}", + WSAGetLastError()); + return INVALID_SOCKET; + } + } + + // connect to server + if constexpr (address_type_t::af_type == AF_INET) + { + sockaddr_in sa_service{}; + sa_service.sin_family = address_type_t::af_type; + sa_service.sin_addr = udp_endpoint.ip; + sa_service.sin_port = htons(udp_endpoint.port); + + if (connect(remote_socket, reinterpret_cast(&sa_service), sizeof(sa_service)) == + SOCKET_ERROR) + { + closesocket(remote_socket); + NETLIB_DEBUG( + "create_relay_socket: Failed to connect UDP socket: {}", + WSAGetLastError()); + return INVALID_SOCKET; + } + } + else + { + sockaddr_in6 sa_service{}; + sa_service.sin6_family = address_type_t::af_type; + sa_service.sin6_addr = udp_endpoint.ip; + sa_service.sin6_port = htons(udp_endpoint.port); + + if (connect(remote_socket, reinterpret_cast(&sa_service), sizeof(sa_service)) == + SOCKET_ERROR) + { + closesocket(remote_socket); + NETLIB_DEBUG( + "create_relay_socket: Failed to connect UDP socket: {}", + WSAGetLastError()); + return INVALID_SOCKET; + } + } + + return remote_socket; + } + }; +} diff --git a/socksify/socksify.vcxproj b/socksify/socksify.vcxproj index efcc49d..85fbf3c 100644 --- a/socksify/socksify.vcxproj +++ b/socksify/socksify.vcxproj @@ -269,6 +269,7 @@ + diff --git a/socksify/socksify.vcxproj.filters b/socksify/socksify.vcxproj.filters index 23cba15..082679f 100644 --- a/socksify/socksify.vcxproj.filters +++ b/socksify/socksify.vcxproj.filters @@ -144,6 +144,9 @@ Header Files\netlib\proxy + + Header Files\netlib\proxy + Header Files\netlib\proxy diff --git a/socksify/unmanaged.h b/socksify/unmanaged.h index e625472..1169059 100644 --- a/socksify/unmanaged.h +++ b/socksify/unmanaged.h @@ -69,6 +69,7 @@ #include "../netlib/src/proxy/socks5_tcp_proxy_socket.h" #include "../netlib/src/proxy/tcp_proxy_server.h" #include "../netlib/src/proxy/socks5_udp_proxy_socket.h" +#include "../netlib/src/proxy/socks5_udp_association.h" #include "../netlib/src/proxy/socks5_local_udp_proxy_server.h" #include "../netlib/src/iphelper/network_adapter_info.h" #include "../netlib/src/iphelper/process_lookup.h" From 26406e04bfebe7bbc4ba821dc40eda524fd73965 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 16:24:45 +0000 Subject: [PATCH 33/62] feat: share one SOCKS5 UDP association for all UDP DNS Proxy mode previously sent each DNS query through the per-source-port UDP proxy, so almost every query opened its own SOCKS5 control connection and UDP ASSOCIATE (plus a TLS handshake with TLS transport) and kept it for five minutes idle. UDP DNS now goes to a dedicated DNS relay per address family (socks5_dns_udp_relay.h) with one control connection and one UDP association shared by every query. Each query's message ID is replaced by a unique, randomly chosen relay ID; the answer carrying it is returned to the client socket with its original ID and a SOCKS5 header naming the server the client queried, whatever source or address family the relay reported. Answers that match no query in flight are dropped. The association opens on the first query and is reopened after its control connection closes, its relay socket fails, or queries stop being answered, with a backoff from 1 to 30 s after failed attempts. DNS is never sent directly meanwhile. TCP DNS keeps using CONNECT. The relay accepts datagrams only from source ports the router just redirected, and reports its relay endpoints to the recursion guard like the UDP proxy. Because the relay now names the queried server itself, the per-client-port answer tracker and the redirect's source override (including its handling of other-family relay headers) are removed; the redirect's answer path is back to main. A UDP datagram too short for a DNS header is dropped with its own block reason. Bookkeeping is portable and tested (dns_udp_multiplexer.h); the packet tests drive the real redirect through the relay's listener step. --- netlib-tests/netlib-tests.vcxproj | 1 + netlib-tests/pch.h | 1 + .../src/ndisapi/socks5_udp_local_redirect.h | 120 +-- netlib/src/proxy/dns_routing_policy.h | 386 +--------- netlib/src/proxy/dns_udp_multiplexer.h | 340 +++++++++ netlib/src/proxy/socks5_dns_udp_relay.h | 704 ++++++++++++++++++ netlib/src/proxy/socks_local_router.h | 309 +++++--- .../portable/dns_packet_redirect_test.cpp | 546 +++++++------- netlib/test/portable/run-portable-tests.sh | 2 + netlib/test/portable/winshim/packet_env.h | 1 + netlib/test/portable/winshim/winshim.h | 4 +- netlib/test/proxy/dns_routing_policy_test.cpp | 232 +----- .../test/proxy/dns_udp_multiplexer_test.cpp | 346 +++++++++ socksify/socksify.vcxproj | 2 + socksify/socksify.vcxproj.filters | 6 + socksify/unmanaged.h | 1 + 16 files changed, 1903 insertions(+), 1098 deletions(-) create mode 100644 netlib/src/proxy/dns_udp_multiplexer.h create mode 100644 netlib/src/proxy/socks5_dns_udp_relay.h create mode 100644 netlib/test/proxy/dns_udp_multiplexer_test.cpp diff --git a/netlib-tests/netlib-tests.vcxproj b/netlib-tests/netlib-tests.vcxproj index 390b9cb..a3a3b0b 100644 --- a/netlib-tests/netlib-tests.vcxproj +++ b/netlib-tests/netlib-tests.vcxproj @@ -112,6 +112,7 @@ + diff --git a/netlib-tests/pch.h b/netlib-tests/pch.h index 515be95..ebedafc 100644 --- a/netlib-tests/pch.h +++ b/netlib-tests/pch.h @@ -58,5 +58,6 @@ #include "../netlib/src/iphelper/process_lookup.h" #include "../netlib/src/proxy/process_routing_policy.h" #include "../netlib/src/proxy/dns_routing_policy.h" +#include "../netlib/src/proxy/dns_udp_multiplexer.h" #endif // PCH_H diff --git a/netlib/src/ndisapi/socks5_udp_local_redirect.h b/netlib/src/ndisapi/socks5_udp_local_redirect.h index f0a7d23..1f75086 100644 --- a/netlib/src/ndisapi/socks5_udp_local_redirect.h +++ b/netlib/src/ndisapi/socks5_udp_local_redirect.h @@ -264,8 +264,7 @@ namespace ndisapi * @param port Destination port to forward the packet to (network byte order). If 0, uses proxy_port_. * @param socks_destination Optional destination (port in host byte order) written to the * SOCKS5 UDP header instead of the packet's own destination. The IP header still - * records the original destination, so the response can be restored to it. Used - * for the DNS server override. + * records the original destination. Used for the DNS server override. * @return True if the packet was translated, false otherwise. */ bool process_client_to_server_packet(INTERMEDIATE_BUFFER& packet, uint16_t port = 0, @@ -475,39 +474,6 @@ namespace ndisapi return false; } - /** - * @brief Size of the SOCKS5 UDP header to strip from a relayed datagram, or 0 when the - * datagram must not be translated. - * - * The relay's header normally has this redirect's address family (ATYP 1 for IPv4, 4 for - * IPv6). A header of the other family is rejected: parsing a mismatched layout would hand - * the client a garbage source endpoint. When the caller supplies the source to present - * (@p source_supplied), the header's own address is not used, so a header of the other - * family is accepted and stripped by its real size. - * - * @param udp_payload The UDP payload: the SOCKS5 UDP header followed by the data. - * @param captured Captured bytes available at @p udp_payload. - */ - [[nodiscard]] static std::size_t relay_header_size(const uint8_t* udp_payload, const std::size_t captured, - const bool source_supplied) noexcept - { - constexpr std::size_t prefix_size = 4; // RSV (2), FRAG (1), ATYP (1) - if (captured < prefix_size) - return 0; - - constexpr uint8_t own_address_type = std::is_same_v> ? 1 : 4; - const auto address_type = udp_payload[3]; - if (address_type == own_address_type) - return sizeof(proxy::socks5_udp_header); - if (!source_supplied) - return 0; - if (address_type == 1) - return sizeof(proxy::socks5_udp_header); - if (address_type == 4) - return sizeof(proxy::socks5_udp_header); - return 0; - } - /** * @brief Processes an S2C packet, restoring the original client source port and remote peer. * @@ -515,15 +481,9 @@ namespace ndisapi * addresses and ports as needed. * * @param packet S2C network packet. - * @param source_override Optional source endpoint (port in host byte order) presented to - * the client instead of the one in the relay's SOCKS5 UDP header. Used to restore - * the server a DNS client originally queried. Because the header's own address is - * then not used, a header of the other address family is accepted and stripped by - * its real size; without it such a header is rejected. * @return True if the packet was translated, false otherwise. */ - bool process_server_to_client_packet(INTERMEDIATE_BUFFER& packet, - const std::optional>& source_override = std::nullopt) + bool process_server_to_client_packet(INTERMEDIATE_BUFFER& packet) { if constexpr (auto* const eth_header = reinterpret_cast(packet.m_IBuffer); std::is_same_v< net::ip_address_v4, std::decay_t>) @@ -555,30 +515,27 @@ namespace ndisapi // the received datagram. Without these guards a short/forged length makes // udp_payload_size - socks5_header_size underflow into a huge value and the // memmove writes far out of bounds. Mirrors the IPv6 detach guards. + constexpr auto socks5_header_size = sizeof(proxy::socks5_udp_header); const auto* const packet_end = packet.m_IBuffer + packet.m_Length; const auto* const udp_header_bytes = reinterpret_cast(udp_header); - if (udp_header_bytes > packet_end || - static_cast(packet_end - udp_header_bytes) < sizeof(udphdr)) - { - return false; - } - - // The SOCKS5 UDP header to strip: this relay's family (ATYP 1), or, only when the - // caller supplies the source to present, the other family's (relay_header_size()). - // A mismatched header is otherwise rejected, before any mutation. const auto udp_length = ntohs(udp_header->length); - const auto captured_udp_size = static_cast(packet_end - udp_header_bytes); - const auto socks5_header_size = relay_header_size(reinterpret_cast(udp_header + 1), - captured_udp_size - sizeof(udphdr), source_override.has_value()); - if (socks5_header_size == 0 || + if (udp_header_bytes > packet_end || + static_cast(packet_end - udp_header_bytes) < sizeof(udphdr) || udp_length < sizeof(udphdr) + socks5_header_size || - udp_length > captured_udp_size || + udp_length > static_cast(packet_end - udp_header_bytes) || packet.m_Length < socks5_header_size || ntohs(ip_header->ip_len) < socks5_header_size) { return false; } + // Reject a reply whose SOCKS5 UDP header ATYP doesn't match this relay's family + // (IPv4 = 1): parsing a mismatched layout (e.g. a 16-byte IPv6 address as IPv4) + // would hand the client a spoofed/garbage source endpoint. The bounds check above + // guarantees the SOCKS5 header is fully captured. Done before any mutation. + if (reinterpret_cast*>(udp_header + 1)->address_type != 1) + return false; + NETLIB_DEBUG( "S2C: {}:{} -> {}:{}", std::string{ T{ip_header->ip_src} }, @@ -595,24 +552,16 @@ namespace ndisapi auto* udp_payload = reinterpret_cast(udp_header + 1); auto* socks5_udp_header_ptr = reinterpret_cast*>(udp_payload); - if (source_override) - { - ip_header->ip_src = source_override->ip; - udp_header->th_sport = htons(source_override->port); - } - else - { - ip_header->ip_src = socks5_udp_header_ptr->dest_address; - udp_header->th_sport = socks5_udp_header_ptr->dest_port; - } + ip_header->ip_src = socks5_udp_header_ptr->dest_address; + udp_header->th_sport = socks5_udp_header_ptr->dest_port; const auto udp_payload_size = static_cast(udp_length - sizeof(udphdr)); memmove(udp_payload, udp_payload + socks5_header_size, udp_payload_size - socks5_header_size); - packet.m_Length -= static_cast(socks5_header_size); - ip_header->ip_len = htons(static_cast(ntohs(ip_header->ip_len) - socks5_header_size)); - udp_header->length = htons(static_cast(ntohs(udp_header->length) - socks5_header_size)); + packet.m_Length -= sizeof(proxy::socks5_udp_header); + ip_header->ip_len = htons(ntohs(ip_header->ip_len) - sizeof(proxy::socks5_udp_header)); + udp_header->length = htons(ntohs(udp_header->length) - sizeof(proxy::socks5_udp_header)); CNdisApi::RecalculateUDPChecksum(&packet); CNdisApi::RecalculateIPChecksum(&packet); @@ -657,6 +606,7 @@ namespace ndisapi ntohs(udp_header->th_dport)); // Remove SOCK5 UDP header here + constexpr auto socks5_header_size = sizeof(proxy::socks5_udp_header); const auto* const packet_end = packet.m_IBuffer + packet.m_Length; const auto* const udp_header_bytes = reinterpret_cast(udp_header); if (udp_header_bytes > packet_end || @@ -665,15 +615,9 @@ namespace ndisapi return false; } - // The SOCKS5 UDP header to strip: this relay's family (ATYP 4), or, only when the - // caller supplies the source to present, the other family's (relay_header_size()). - // A mismatched header is otherwise rejected, before any mutation. const auto udp_length = ntohs(udp_header->length); const auto captured_udp_size = static_cast(packet_end - udp_header_bytes); - const auto socks5_header_size = relay_header_size(reinterpret_cast(udp_header + 1), - captured_udp_size - sizeof(udphdr), source_override.has_value()); - if (socks5_header_size == 0 || - udp_length < sizeof(udphdr) + socks5_header_size || + if (udp_length < sizeof(udphdr) + socks5_header_size || udp_length > captured_udp_size || packet.m_Length < socks5_header_size || ntohs(ip_header->ip6_len) < socks5_header_size) @@ -684,30 +628,28 @@ namespace ndisapi auto* udp_payload = reinterpret_cast(udp_header + 1); auto* socks5_udp_header_ptr = reinterpret_cast*>(udp_payload); + // Reject a reply whose SOCKS5 UDP header ATYP doesn't match this relay's family + // (IPv6 = 4); see the IPv4 path. The bounds check above guarantees the header is + // fully captured. Done before any mutation. + if (socks5_udp_header_ptr->address_type != 4) + return false; + // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); // Swap IP addresses std::swap(ip_header->ip6_dst, ip_header->ip6_src); - if (source_override) - { - ip_header->ip6_src = source_override->ip; - udp_header->th_sport = htons(source_override->port); - } - else - { - ip_header->ip6_src = socks5_udp_header_ptr->dest_address; - udp_header->th_sport = socks5_udp_header_ptr->dest_port; - } + ip_header->ip6_src = socks5_udp_header_ptr->dest_address; + udp_header->th_sport = socks5_udp_header_ptr->dest_port; const auto udp_payload_size = static_cast(udp_length - sizeof(udphdr)); memmove(udp_payload, udp_payload + socks5_header_size, udp_payload_size - socks5_header_size); - packet.m_Length -= static_cast(socks5_header_size); - ip_header->ip6_len = htons(static_cast(ntohs(ip_header->ip6_len) - socks5_header_size)); - udp_header->length = htons(static_cast(ntohs(udp_header->length) - socks5_header_size)); + packet.m_Length -= socks5_header_size; + ip_header->ip6_len = htons(ntohs(ip_header->ip6_len) - socks5_header_size); + udp_header->length = htons(ntohs(udp_header->length) - socks5_header_size); // Recalculate checksum net::ipv6_helper::recalculate_tcp_udp_checksum(&packet); diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index edb1d75..0ac12d2 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -3,22 +3,18 @@ // Global DNS routing policy used by socks_local_router's packet handlers. // // Everything in this header is deliberately free of Windows, driver, and socket types so the -// routing decisions, the DNS server override syntax, and the UDP response-origin bookkeeping +// routing decisions, the DNS server override syntax, and the parsing the DNS relay relies on // can be unit tested on any platform without the Windows Packet Filter driver. The router // supplies already-parsed packet fields and the state of the selected proxy; these helpers // return what to do with the packet. #include -#include #include #include -#include #include -#include #include #include #include -#include #include #include @@ -60,6 +56,7 @@ namespace proxy ///< or a TCP segment of a connection opened before ProxiFyre started) upstream_sender_unknown, ///< addressed to a SOCKS5 server, and its sender could not be resolved fragmented, ///< the first fragment of a fragmented datagram addressed to port 53 + not_dns_message, ///< a UDP datagram too short for a DNS header: it cannot be relayed count }; @@ -131,10 +128,11 @@ namespace proxy * ProxiFyre's TCP traffic to a SOCKS5 server goes to its configured port, so for TCP the * destination match (address and port 53) already implies a server configured on port 53. * The only ProxiFyre UDP traffic to a SOCKS5 server's address that can reach the recursion - * guard goes to the relay endpoint returned by UDP ASSOCIATE (the local listener's replies, - * which can also be addressed to a SOCKS5 host, are handled as listener replies before any - * DNS decision), so for UDP the packet can be ProxiFyre's own only if a server has returned - * a relay on port 53. Otherwise it cannot be, and it follows the DNS policy + * guard goes to relay endpoints returned by UDP ASSOCIATE, for the per-port UDP proxy and + * for the DNS relay's shared association alike (the local listeners' replies, which can also + * be addressed to a SOCKS5 host, are handled as listener replies before any DNS decision), + * so for UDP the packet can be ProxiFyre's own only if a server has returned a relay on + * port 53. Otherwise it cannot be, and it follows the DNS policy * with no sender lookup and no deferral, which also removes any dependence on the cached * connection table. * @@ -213,10 +211,12 @@ namespace proxy return "the DNS server override belongs to the other address family"; case dns_block_reason::redirect_failed: return "the packet could not be redirected to the DNS proxy (fragmented, oversized, " - "not a DNS message, or part of a TCP connection opened before ProxiFyre started)"; + "or part of a TCP connection opened before ProxiFyre started)"; case dns_block_reason::fragmented: return "the datagram is fragmented and cannot be redirected through the DNS proxy; only its first " "fragment, which carries the port, is dropped"; + case dns_block_reason::not_dns_message: + return "the UDP datagram is too short to be a DNS message, so the DNS proxy cannot relay it"; case dns_block_reason::upstream_sender_unknown: return "the packet is addressed to a configured SOCKS5 server and its sending process could not be " "resolved, so it cannot be identified as ProxiFyre's own traffic"; @@ -638,257 +638,6 @@ namespace proxy return static_cast((static_cast(payload[0]) << 8) | payload[1]); } - /** - * @brief Remembers, for UDP DNS queries redirected to the DNS proxy, which server the - * application originally addressed. - * - * The requesting resolver only accepts an answer from the server it queried, but the SOCKS5 - * relay may report another source: always when a server override is configured (it answers - * from the override server), and for some relays even without one. Each redirected query - * records (client source port, DNS message ID) -> original server endpoint; - * the response carrying the same client port and message ID is restored to that endpoint - * before it is delivered. Entries expire after @p ttl and the table is bounded, so it cannot - * grow without limit under a flood of queries. Entries are not consumed by a lookup so that - * duplicate answers to a retransmitted query are restored consistently. - * - * Thread-safe. - * - * @tparam Endpoint Original server endpoint type (copyable). - */ - template - class dns_udp_origin_tracker - { - public: - using clock = std::chrono::steady_clock; - - explicit dns_udp_origin_tracker(const std::chrono::seconds ttl = std::chrono::seconds{ 30 }, - const std::size_t capacity = 8192) noexcept - : ttl_(ttl), capacity_(std::max(capacity, 1)) - { - } - - /** - * @brief Records the original server of a query sent from @p client_port with - * @p message_id. Re-remembering a key refreshes its time. - * - * Runs on the packet thread, so it costs amortized O(1) even when the table is full of - * live entries: expired and then oldest entries are found at the front of an - * insertion-ordered queue instead of by scanning the table. - */ - void remember(const uint16_t client_port, const uint16_t message_id, const Endpoint& original, - const clock::time_point now = clock::now()) - { - std::scoped_lock lock(lock_); - const auto key = make_key(client_port, message_id); - - if (const auto it = entries_.find(key); it != entries_.end()) - { - // The key's earlier queue record becomes stale; it is skipped when it reaches - // the front. - it->second = entry{ now, original }; - order_.push_back({ key, now }); - compact_if_needed_locked(); - return; - } - - if (entries_.size() >= capacity_) - { - expire_front_locked(now); - if (entries_.size() >= capacity_) - evict_oldest_locked(); - } - - entries_.emplace(key, entry{ now, original }); - order_.push_back({ key, now }); - compact_if_needed_locked(); - } - - /// Returns the original server for a response to @p client_port with @p message_id. - [[nodiscard]] std::optional resolve(const uint16_t client_port, const uint16_t message_id, - const clock::time_point now = clock::now()) - { - std::scoped_lock lock(lock_); - const auto it = entries_.find(make_key(client_port, message_id)); - if (it == entries_.end()) - return std::nullopt; - - if (now - it->second.created_at > ttl_) - { - entries_.erase(it); - return std::nullopt; - } - - return it->second.original; - } - - /// Removes every expired entry (maintenance thread). - void sweep(const clock::time_point now = clock::now()) - { - std::scoped_lock lock(lock_); - for_each_entry_locked([this, now](const auto it) - { - return now - it->second.created_at > ttl_ ? entries_.erase(it) : std::next(it); - }); - expire_front_locked(now); - } - - /// Removes every entry (router start). - void clear() - { - std::scoped_lock lock(lock_); - entries_.clear(); - order_.clear(); - } - - [[nodiscard]] std::size_t size() const - { - std::scoped_lock lock(lock_); - return entries_.size(); - } - - /// Number of insertion-order records, including stale ones (bounded; for tests). - [[nodiscard]] std::size_t order_records() const - { - std::scoped_lock lock(lock_); - return order_.size(); - } - - /** - * @brief Total number of table entries and queue records examined by expiry, eviction, - * compaction, and sweeps since construction. - * - * Every loop over the table or the queue counts here, so tests can assert that the work - * done by remember() stays bounded per call when the table is full, without measuring time. - */ - [[nodiscard]] std::uint64_t visits() const - { - std::scoped_lock lock(lock_); - return visits_; - } - - private: - struct entry - { - clock::time_point created_at; - Endpoint original; - }; - - struct record - { - uint32_t key; - clock::time_point created_at; - }; - - static constexpr uint32_t make_key(const uint16_t client_port, const uint16_t message_id) noexcept - { - return (static_cast(client_port) << 16) | message_id; - } - - /// True when @p r is the current record of a live entry. - [[nodiscard]] bool is_current_locked(const record& r) const - { - const auto it = entries_.find(r.key); - return it != entries_.end() && it->second.created_at == r.created_at; - } - - // Every iteration over entries_ or order_ goes through one of the two helpers below, - // which count each element examined in visits_. Do not add raw loops over either - // container: visits() is how tests bound the work done on the packet thread. - - /** - * @brief Visits table entries, counting each. @p step receives an iterator to the current - * entry and returns the iterator to continue from (the erase() result or the next). - */ - template - void for_each_entry_locked(Step&& step) - { - for (auto it = entries_.begin(); it != entries_.end();) - { - ++visits_; - it = step(it); - } - } - - /// What consume_front_locked() does after examining the front record. - enum class front_step : uint8_t - { - pop_and_continue, - pop_and_stop, - stop - }; - - /** - * @brief Examines records at the front of the queue, counting each, and pops them as - * @p step decides. - */ - template - void consume_front_locked(Step&& step) - { - while (!order_.empty()) - { - ++visits_; - const auto front = order_.front(); - const front_step next = step(front); - if (next == front_step::stop) - return; - order_.pop_front(); - if (next == front_step::pop_and_stop) - return; - } - } - - /// Pops expired records from the front, erasing the entries they still describe. - void expire_front_locked(const clock::time_point now) - { - consume_front_locked([this, now](const record& front) - { - if (!(now - front.created_at > ttl_)) - return front_step::stop; - if (is_current_locked(front)) - entries_.erase(front.key); - return front_step::pop_and_continue; - }); - } - - /// Erases the oldest live entry, skipping stale records. - void evict_oldest_locked() - { - consume_front_locked([this](const record& front) - { - if (!is_current_locked(front)) - return front_step::pop_and_continue; - entries_.erase(front.key); - return front_step::pop_and_stop; - }); - } - - /// Keeps the queue bounded when keys are refreshed repeatedly: rebuilds it from the - /// live entries, oldest first, once stale records outnumber them. - void compact_if_needed_locked() - { - if (order_.size() <= 2 * capacity_ + 16) - return; - - std::vector live; - live.reserve(entries_.size()); - for_each_entry_locked([&live](const auto it) - { - live.push_back({ it->first, it->second.created_at }); - return std::next(it); - }); - std::sort(live.begin(), live.end(), - [](const record& left, const record& right) { return left.created_at < right.created_at; }); - order_.assign(live.begin(), live.end()); - } - - mutable std::mutex lock_; - std::unordered_map entries_; - std::deque order_; - std::uint64_t visits_{}; - std::chrono::seconds ttl_; - std::size_t capacity_; - }; - /// SOCKS5 UDP request/reply header fields (RFC 1928 section 7) of a relayed datagram. struct socks5_udp_datagram_view { @@ -932,121 +681,6 @@ namespace proxy return view; } - /** - * @brief Whether replies leaving the DNS proxy's UDP listener may need their source restored - * (classify_dns_reply()): in Proxy mode with a usable proxy, with or without - * a server override, because a relay can report a source other than the server the - * resolver queried either way. In Direct mode, or without a usable proxy, no DNS is - * redirected and the reply path needs no DNS work at all. - */ - [[nodiscard]] constexpr bool dns_reply_restore_needed(const dns_routing_mode mode, const bool proxy_selected) noexcept - { - return mode == dns_routing_mode::proxy && proxy_selected; - } - - /// What the UDP handler does about remembering the server a redirected query was addressed to. - enum class dns_query_tracking : uint8_t - { - track, ///< remember the queried server so the answer can be restored to it - untracked, ///< redirect without remembering: the answer keeps the source the relay reports - drop ///< cannot be redirected usefully: drop it - }; - - /** - * @brief Decides whether a UDP datagram about to be redirected to the DNS proxy is tracked. - * - * A datagram that carries a DNS header is tracked by (client port, message ID), so its answer - * can be presented as coming from the server the resolver queried whatever source the relay - * reports. A datagram too short to carry a DNS header cannot be tracked. Without a server - * override it is still redirected: its answer, if any, carries the relay-reported source, - * which for an RFC 1928 relay is the server that was queried. With a server override the - * relay reports the override, the answer could never be matched to the queried server, and - * the resolver would discard it, so the datagram is dropped instead. - */ - [[nodiscard]] constexpr dns_query_tracking decide_dns_query_tracking(const bool server_override_configured, - const bool has_message_id) noexcept - { - if (has_message_id) - return dns_query_tracking::track; - return server_override_configured ? dns_query_tracking::drop : dns_query_tracking::untracked; - } - - /// How a datagram leaving a local UDP proxy listener is presented to the client. - enum class dns_reply_restore : uint8_t - { - unchanged, ///< not an answer to a tracked query: present the relay's SOCKS5 header source - restore, ///< answer to a tracked query: present it as coming from the original server - drop ///< names the override server but answers no tracked query: drop it - }; - - /** - * @brief Decides what to do with a reply leaving a local UDP proxy listener. - * - * An override answer that matches no tracked query (@p restore == drop) is dropped without - * being translated; otherwise the reply is re-injected when translated and dropped when not. - * Both drops are listener replies that are not sent to the network and are reported the same - * way. - */ - [[nodiscard]] constexpr listener_reply_action decide_udp_listener_reply(const dns_reply_restore restore, - const bool translated) noexcept - { - if (restore == dns_reply_restore::drop) - return listener_reply_action::drop; - return decide_listener_reply(translated); - } - - /** - * @brief Classifies a datagram relayed back by the DNS proxy, with or without a server - * override, and finds the server the resolver originally queried. - * - * A datagram whose (@p client_port, DNS message ID) matches a tracked query is restored to - * the original server whatever source its SOCKS5 header reports, of either address family: - * RFC 1928 relays report the server that answered (the override, when one is configured), - * but some report another address (for example their own, which is IPv4 even for an IPv6 - * query), and an answer presented from any address other than the queried server is - * discarded by the resolver. The redirect strips such a header by its real size when it is - * given the source to present. With a server override, a datagram that names the override - * server but matches no tracked query is dropped. Any other datagram relayed through the - * same proxy is left unchanged; if its ATYP is not the listener's family - * (@p expected_address_type), the redirect then rejects it and it is dropped. - * - * The match is on the client port and the first two bytes of the relayed data only. A - * datagram that is not a DNS answer is restored by mistake only if it arrives for a client - * port that sent a port-53 datagram within the tracker's lifetime and begins with that - * datagram's ID. - * - * @param socks_datagram The UDP payload as relayed: SOCKS5 UDP header followed by the data. - * @param expected_address_type 1 for the IPv4 path, 4 for the IPv6 path. - * @param override_address The override address bytes (network byte order), or nullptr when - * no server override is configured for this family; @p override_address_size and - * @p override_port are then ignored. - */ - template - [[nodiscard]] std::pair> classify_dns_reply( - const uint8_t* socks_datagram, const std::size_t size, const uint8_t expected_address_type, - const uint8_t* override_address, const std::size_t override_address_size, const uint16_t override_port, - const uint16_t client_port, dns_udp_origin_tracker& origins) - { - const auto view = parse_socks5_udp_datagram(socks_datagram, size); - if (!view) - return { dns_reply_restore::unchanged, std::nullopt }; - - if (const auto message_id = dns_message_id(view->data, view->data_size)) - { - if (auto original = origins.resolve(client_port, *message_id)) - return { dns_reply_restore::restore, std::move(original) }; - } - - if (view->address_type != expected_address_type) - return { dns_reply_restore::unchanged, std::nullopt }; - - const bool names_override = override_address != nullptr && - view->address_size == override_address_size && view->port == override_port && - std::equal(view->address, view->address + view->address_size, override_address); - - return { names_override ? dns_reply_restore::drop : dns_reply_restore::unchanged, std::nullopt }; - } - // Compile-time checks of the decision table's key invariants. static_assert(decide_listener_reply(false) == listener_reply_action::drop, "An untranslatable listener reply must never be passed to the wire."); diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h new file mode 100644 index 0000000..830bfb8 --- /dev/null +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -0,0 +1,340 @@ +#pragma once + +// Bookkeeping for the DNS proxy's shared SOCKS5 UDP association (socks5_dns_udp_relay.h). +// +// All UDP DNS queries of one address family travel through a single SOCKS5 UDP ASSOCIATE +// relay. Answers then no longer arrive per client socket, so each query's DNS message ID is +// replaced by a unique, randomly chosen relay ID on the way out, and the answer carrying that +// ID is mapped back to the client socket, its original ID and the server it queried. +// +// Like dns_routing_policy.h, this header is free of Windows, driver and socket types so it can +// be unit tested on any platform. The relay supplies time, randomness and raw datagrams. + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dns_routing_policy.h" + +namespace proxy +{ + /// Writes a DNS message ID (network byte order) into the first two bytes of @p payload. + constexpr void set_dns_message_id(uint8_t* payload, const uint16_t id) noexcept + { + payload[0] = static_cast(id >> 8); + payload[1] = static_cast(id & 0xff); + } + + /// SOCKS5 UDP header size for an IPv4 (ATYP 1) or IPv6 (ATYP 4) address. + [[nodiscard]] constexpr std::size_t socks5_udp_header_size(const uint8_t address_type) noexcept + { + return address_type == 1 ? 4 + 4 + 2 : address_type == 4 ? 4 + 16 + 2 : 0; + } + + /** + * @brief Validates a query the local redirect delivered to the DNS relay's listener and + * returns the offset of its DNS message. + * + * The redirect prepends a SOCKS5 UDP header of the listener's family (@p address_type) + * naming the server to ask (the queried server or the server override). A datagram without + * that header, or too short to carry a DNS header after it, cannot be multiplexed and is + * dropped by the relay. + */ + [[nodiscard]] constexpr std::optional socks5_dns_query_offset(const uint8_t* datagram, + const std::size_t size, const uint8_t address_type) noexcept + { + const auto view = parse_socks5_udp_datagram(datagram, size); + if (!view || view->address_type != address_type || view->data_size < dns_header_size) + return std::nullopt; + return static_cast(view->data - datagram); + } + + /** + * @brief Builds the datagram the DNS relay returns to a local client from an answer the + * SOCKS5 relay delivered. + * + * The output is a SOCKS5 UDP header of the listener's family naming the server the client + * queried (@p server_address, @p server_port), followed by the DNS answer with the client's + * original message ID. The local redirect presents the answer with that header's address as + * its source, so the client sees an answer from the server it asked, whatever source and + * address family the relay reported (always the override with a server override; for some + * relays their own address). + * + * @param relayed The relay's datagram, already parsed (parse_socks5_udp_datagram()). + * @param server_address Queried server address bytes (network byte order): 4 or 16 bytes. + * @param original_id The client's DNS message ID. + * @param out Output buffer. + * @return Bytes written, or 0 when the answer does not fit, carries no DNS header, or + * @p address_size is not 4 or 16. + */ + [[nodiscard]] inline std::size_t build_dns_client_answer(const socks5_udp_datagram_view& relayed, + const uint8_t* server_address, const std::size_t address_size, const uint16_t server_port, + const uint16_t original_id, uint8_t* out, const std::size_t out_capacity) noexcept + { + if (relayed.data == nullptr || relayed.data_size < dns_header_size || server_address == nullptr || + out == nullptr || (address_size != 4 && address_size != 16)) + return 0; + + const uint8_t address_type = address_size == 4 ? 1 : 4; + const auto header_size = socks5_udp_header_size(address_type); + if (out_capacity < header_size || out_capacity - header_size < relayed.data_size) + return 0; + + out[0] = 0; // RSV + out[1] = 0; + out[2] = 0; // FRAG + out[3] = address_type; + std::memcpy(out + 4, server_address, address_size); + out[4 + address_size] = static_cast(server_port >> 8); + out[4 + address_size + 1] = static_cast(server_port & 0xff); + std::memmove(out + header_size, relayed.data, relayed.data_size); + set_dns_message_id(out + header_size, original_id); + return header_size + relayed.data_size; + } + + /** + * @brief Queries in flight through the shared association, keyed by relay ID. + * + * insert() replaces a query's message ID with a relay ID that is unique among the queries in + * flight and chosen by the caller's random source, so the 16-bit ID keeps its full entropy + * against forged answers. A retransmission (same client socket and original ID) reuses its + * relay ID, so duplicate answers map to it and it counts once as unanswered. Entries expire + * after the TTL; the table is bounded, and when full the oldest query is evicted. + * + * Not thread-safe: the relay serializes access. + * + * @tparam Client Client socket identity (equality-comparable, hashed by @p Hash). The relay + * uses the listener's sender endpoint: the queried server address and the client port. + */ + template , typename Clock = std::chrono::steady_clock> + class dns_query_table + { + public: + using time_point = typename Clock::time_point; + + struct pending + { + Client client; + uint16_t original_id{}; + }; + + dns_query_table(const std::chrono::seconds ttl, const std::size_t capacity) + : ttl_(ttl), capacity_(std::max(capacity, 1)) + { + } + + /** + * @brief Records a query and returns its relay ID. + * @param random Callable returning a uniformly distributed uint16_t. + * @return The relay ID, or std::nullopt only if no ID could be found (cannot happen while + * the capacity is below 65536). + */ + template + std::optional insert(const Client& client, const uint16_t original_id, const time_point now, + Random&& random) + { + const key k{ client, original_id }; + if (const auto existing = by_client_.find(k); existing != by_client_.end()) + { + auto& entry = entries_.at(existing->second); + entry.sent_at = now; + return existing->second; + } + + // Expiry is left to expire(), which reports the unanswered count; a full table only + // evicts its oldest query. + if (entries_.size() >= capacity_) + evict_oldest(); + + // Random probing; the table holds at most capacity_ of 65536 IDs, so a free ID is + // found within a few draws. Fall back to a linear scan from a random start. + std::optional relay_id; + for (int attempt = 0; attempt < 16 && !relay_id; ++attempt) + { + const auto candidate = static_cast(random()); + if (!entries_.contains(candidate)) + relay_id = candidate; + } + if (!relay_id) + { + const auto start = static_cast(random()); + for (uint32_t step = 0; step < 0x10000 && !relay_id; ++step) + { + const auto candidate = static_cast(start + step); + if (!entries_.contains(candidate)) + relay_id = candidate; + } + } + if (!relay_id) + return std::nullopt; + + entries_.emplace(*relay_id, entry{ client, original_id, now }); + by_client_.emplace(k, *relay_id); + return relay_id; + } + + /** + * @brief Removes and returns the query an answer with @p relay_id belongs to. + * @return std::nullopt for an unknown or expired relay ID. + */ + std::optional take(const uint16_t relay_id, const time_point now) + { + const auto it = entries_.find(relay_id); + if (it == entries_.end()) + return std::nullopt; + + const bool expired = now - it->second.sent_at > ttl_; + pending result{ it->second.client, it->second.original_id }; + erase(it); + if (expired) + return std::nullopt; + return result; + } + + /// Removes queries older than the TTL and returns how many expired unanswered. + std::size_t expire(const time_point now) + { + std::size_t expired = 0; + for (auto it = entries_.begin(); it != entries_.end();) + { + if (now - it->second.sent_at > ttl_) + { + it = erase(it); + ++expired; + } + else + { + ++it; + } + } + return expired; + } + + void clear() noexcept + { + entries_.clear(); + by_client_.clear(); + } + + [[nodiscard]] std::size_t size() const noexcept { return entries_.size(); } + [[nodiscard]] std::size_t capacity() const noexcept { return capacity_; } + + private: + struct entry + { + Client client; + uint16_t original_id{}; + time_point sent_at{}; + }; + + struct key + { + Client client; + uint16_t original_id{}; + bool operator==(const key& rhs) const { return client == rhs.client && original_id == rhs.original_id; } + }; + + struct key_hash + { + std::size_t operator()(const key& k) const noexcept + { + return Hash{}(k.client) ^ (static_cast(k.original_id) * 0x9E3779B1u); + } + }; + + using entries_t = std::unordered_map; + + typename entries_t::iterator erase(typename entries_t::iterator it) + { + by_client_.erase(key{ it->second.client, it->second.original_id }); + return entries_.erase(it); + } + + void evict_oldest() + { + const auto oldest = std::min_element(entries_.begin(), entries_.end(), + [](const auto& a, const auto& b) { return a.second.sent_at < b.second.sent_at; }); + if (oldest != entries_.end()) + erase(oldest); + } + + entries_t entries_; + std::unordered_map by_client_; + std::chrono::seconds ttl_; + std::size_t capacity_; + }; + + /** + * @brief Decides when the shared association is reopened and when a new one may be tried. + * + * - A failed open is retried after a backoff that doubles from 1 s up to 30 s; queries + * arriving meanwhile are dropped (Proxy mode never sends DNS directly). + * - An open association is reopened when its SOCKS5 control connection closes or the relay + * socket fails (reported by the relay), or when it looks silently dead: at least + * @p unanswered_limit queries in a row expired without any datagram arriving from the + * relay in between, and the association is at least @p minimum_age old. The age limit + * keeps a resolver that never answers from churning a working association. + * + * Not thread-safe: the relay serializes access. + */ + template + class dns_association_health + { + public: + using time_point = typename Clock::time_point; + + explicit dns_association_health(const std::size_t unanswered_limit = 3, + const std::chrono::seconds minimum_age = std::chrono::seconds{ 30 }) + : unanswered_limit_(std::max(unanswered_limit, 1)), minimum_age_(minimum_age) + { + } + + /// Whether opening an association may be attempted at @p now. + [[nodiscard]] bool may_open(const time_point now) const noexcept + { + return failures_ == 0 || now >= next_attempt_; + } + + void on_open_failed(const time_point now) noexcept + { + ++failures_; + const auto shift = std::min(failures_ - 1, 5); // 1, 2, 4, 8, 16, 32 s + next_attempt_ = now + (std::min)(std::chrono::seconds{ 1 } * (1u << shift), max_backoff); + } + + void on_opened(const time_point now) noexcept + { + failures_ = 0; + unanswered_ = 0; + opened_at_ = now; + } + + /// Any datagram from the relay shows the association is alive. + void on_relay_datagram() noexcept { unanswered_ = 0; } + + /// Records queries that expired unanswered; true when the association should be reopened. + [[nodiscard]] bool on_unanswered(const std::size_t count, const time_point now) noexcept + { + unanswered_ += count; + return unanswered_ >= unanswered_limit_ && now - opened_at_ >= minimum_age_; + } + + [[nodiscard]] std::size_t consecutive_failures() const noexcept { return failures_; } + [[nodiscard]] time_point next_attempt() const noexcept { return next_attempt_; } + + static constexpr std::chrono::seconds max_backoff{ 30 }; + + private: + std::size_t unanswered_limit_; + std::chrono::seconds minimum_age_; + std::size_t failures_{}; + std::size_t unanswered_{}; + time_point next_attempt_{}; + time_point opened_at_{}; + }; +} diff --git a/netlib/src/proxy/socks5_dns_udp_relay.h b/netlib/src/proxy/socks5_dns_udp_relay.h new file mode 100644 index 0000000..7a276fe --- /dev/null +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -0,0 +1,704 @@ +#pragma once + +// The DNS proxy's UDP path: one SOCKS5 control connection and one UDP ASSOCIATE relay shared by +// every UDP DNS query of one address family. +// +// The router redirects each UDP DNS query to this relay's local listener with a SOCKS5 UDP +// header already prepended (socks5_udp_local_redirect.h), naming the server to ask: the server +// the application queried, or the DNS server override. The relay replaces the query's message ID +// with a unique random relay ID and sends it through the shared association. The answer carrying +// that relay ID is returned to the client socket with its original ID and a SOCKS5 header naming +// the server the client queried, so the redirect presents it as an answer from that server. +// Bookkeeping and policy are in dns_udp_multiplexer.h. +// +// The association is opened on the first query and reopened, with backoff, after its control +// connection closes, its relay socket fails, or it stops answering. While none is open, queries +// that cannot wait are dropped: DNS is never sent directly in Proxy mode. +// +// DNS traffic is light, so the relay uses blocking sockets on three threads instead of the I/O +// completion port: the listener, the reader of the current relay socket, and maintenance (opens +// associations, expires queries, checks health). Socket receives have short timeouts so every +// thread notices stop() and a retired association; sockets are closed only after the threads +// using them have been joined. + +#include +#include +#include +#include + +#include "dns_udp_multiplexer.h" +#include "socks5_udp_association.h" + +namespace proxy +{ + template + class socks5_dns_udp_relay : public netlib::log::logger> // NOLINT(clang-diagnostic-padded) + { + public: + using log_level = netlib::log::log_level; + using logger = netlib::log::logger; + using address_type_t = AddressT; + using endpoint_t = net::ip_endpoint; + using negotiate_context_t = socks5_negotiate_context; + + /// Whether the router recently redirected a UDP DNS query from this local source port. + using authorize_client_t = bool(uint16_t); + + /// Observes each UDP relay endpoint the SOCKS5 server returns, before it is used. + using relay_endpoint_observed_t = void(const endpoint_t&); + + /// Queries in flight are forgotten after this long; Windows gives up on a query sooner. + static constexpr std::chrono::seconds query_ttl{ 10 }; + + /// Bound on queries in flight through one association. + static constexpr std::size_t max_queries_in_flight = 4096; + + /// Bound on queries held while an association is being opened. + static constexpr std::size_t max_waiting_queries = 64; + + /// Unanswered queries in a row (with no datagram from the relay) that retire an association. + static constexpr std::size_t unanswered_limit = 3; + + /// An association younger than this is not retired for unanswered queries. + static constexpr std::chrono::seconds minimum_association_age{ 30 }; + + /** + * @param upstream SOCKS5 server (for the IPv6 instance, an IPv4-mapped address reaches an + * IPv4 server). + * @param credentials Optional SOCKS5 username/password. + * @param upstream_options Transport and TLS settings for the control connection. + * @param authorize_client Required. The relay refuses datagrams from any other source port, + * so its listener cannot be used to send arbitrary UDP through the proxy. + * @param relay_endpoint_observed Optional; see relay_endpoint_observed_t. + */ + socks5_dns_udp_relay(const endpoint_t& upstream, + std::optional> credentials, + socks5_upstream_options upstream_options, + std::function authorize_client, + std::function relay_endpoint_observed = {}, + const log_level log_level = log_level::error, + std::shared_ptr log_stream = nullptr) + : logger(log_level, std::move(log_stream)), + upstream_(upstream), + credentials_(std::move(credentials)), + upstream_options_(std::move(upstream_options)), + authorize_client_(std::move(authorize_client)), + relay_endpoint_observed_(std::move(relay_endpoint_observed)), + association_client_(log_level, logger::log_stream_) + { + } + + ~socks5_dns_udp_relay() + { + stop(); + } + + socks5_dns_udp_relay(const socks5_dns_udp_relay&) = delete; + socks5_dns_udp_relay(socks5_dns_udp_relay&&) = delete; + socks5_dns_udp_relay& operator=(const socks5_dns_udp_relay&) = delete; + socks5_dns_udp_relay& operator=(socks5_dns_udp_relay&&) = delete; + + /// Local listener port the router redirects UDP DNS queries to (0 until started). + [[nodiscard]] uint16_t listener_port() const noexcept { return listener_port_; } + + /** + * @brief Creates the listener and starts the threads. No association is opened until the + * first query arrives. + * @return false if the listener socket could not be created. + */ + bool start() + { + if (running_) + return true; + + if (!create_listener_socket()) + return false; + + stopping_.store(false, std::memory_order_release); + running_ = true; + listener_thread_ = std::thread(&socks5_dns_udp_relay::listener_loop, this); + maintenance_thread_ = std::thread(&socks5_dns_udp_relay::maintenance_loop, this); + NETLIB_INFO("DNS relay: listening on UDP port {} for {} DNS queries via SOCKS5 server {}", + listener_port_, address_type_t::af_type == AF_INET ? "IPv4" : "IPv6", upstream_.to_string()); + return true; + } + + /// Stops the threads, closes the association and the listener. Idempotent. + void stop() + { + if (!running_) + return; + + stopping_.store(true, std::memory_order_release); + { + std::scoped_lock lock(lock_); + maintenance_cv_.notify_all(); + } + + if (listener_thread_.joinable()) + listener_thread_.join(); + if (maintenance_thread_.joinable()) + maintenance_thread_.join(); + + std::unique_ptr current; + { + std::scoped_lock lock(lock_); + current = std::move(association_); + waiting_.clear(); + queries_.clear(); + } + close_association(std::move(current)); + + closesocket(listener_socket_); + listener_socket_ = INVALID_SOCKET; + running_ = false; + } + + private: + /// Client socket identity: the listener's sender (the queried server and the client + /// port), plus the IPv6 scope so an answer to a link-local server can be sent back. + struct client_t + { + endpoint_t endpoint; + uint32_t scope_id{}; + + bool operator==(const client_t& rhs) const noexcept + { + return endpoint == rhs.endpoint && scope_id == rhs.scope_id; + } + }; + + struct client_hash + { + std::size_t operator()(const client_t& client) const noexcept + { + return std::hash{}(client.endpoint) ^ static_cast(client.scope_id); + } + }; + + /// One SOCKS5 control connection with its UDP relay socket and reader thread. + struct association + { + SOCKET control{ INVALID_SOCKET }; + SOCKET relay{ INVALID_SOCKET }; + std::thread reader; + std::atomic_bool retiring{ false }; + std::atomic_bool failed{ false }; + }; + + struct waiting_query + { + client_t client; + std::vector datagram; + }; + + static constexpr uint8_t own_address_type = address_type_t::af_type == AF_INET ? 1 : 4; + static constexpr std::size_t own_address_size = address_type_t::af_type == AF_INET ? 4 : 16; + static constexpr DWORD receive_timeout_ms = 500; + static constexpr std::size_t max_datagram_size = 65535; + + // --- Configuration ------------------------------------------------------------------- + + endpoint_t upstream_; + std::optional> credentials_; + socks5_upstream_options upstream_options_; + std::function authorize_client_; + std::function relay_endpoint_observed_; + socks5_udp_association_client association_client_; + + // --- State (lock_ protects everything below except the atomics and the listener) ----- + + std::mutex lock_; + std::condition_variable maintenance_cv_; + std::unique_ptr association_; + std::deque waiting_; + dns_query_table queries_{ query_ttl, max_queries_in_flight }; + dns_association_health<> health_{ unanswered_limit, minimum_association_age }; + std::random_device random_; + + SOCKET listener_socket_{ INVALID_SOCKET }; + uint16_t listener_port_{ 0 }; + bool running_{ false }; + std::atomic_bool stopping_{ true }; + std::thread listener_thread_; + std::thread maintenance_thread_; + + // --- Statistics, reported by the maintenance thread at a throttled rate --------------- + + std::atomic dropped_unauthorized_{ 0 }; + std::atomic dropped_malformed_{ 0 }; + std::atomic dropped_unavailable_{ 0 }; + std::atomic dropped_unmatched_answers_{ 0 }; + std::atomic dropped_send_failures_{ 0 }; + uint64_t reported_drops_{ 0 }; + std::chrono::steady_clock::time_point last_report_{}; + + // --- Helpers -------------------------------------------------------------------------- + + uint16_t random_id() + { + return static_cast(std::uniform_int_distribution{ 0, 0xFFFF }(random_)); + } + + static void set_receive_timeout(const SOCKET socket) noexcept + { + const DWORD timeout = receive_timeout_ms; + setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout), sizeof(timeout)); + } + + static void disable_connection_reset(const SOCKET socket) noexcept + { + BOOL new_behavior = FALSE; + DWORD bytes_returned = 0; + WSAIoctl(socket, SIO_UDP_CONNRESET, &new_behavior, sizeof(new_behavior), + nullptr, 0, &bytes_returned, nullptr, nullptr); + } + + [[nodiscard]] static std::optional client_from(const SOCKADDR_STORAGE& sender) noexcept + { + if constexpr (address_type_t::af_type == AF_INET) + { + if (sender.ss_family != AF_INET) + return std::nullopt; + const auto* address = reinterpret_cast(&sender); + return client_t{ endpoint_t{ address_type_t{ address->sin_addr }, ntohs(address->sin_port) }, 0 }; + } + else + { + if (sender.ss_family != AF_INET6) + return std::nullopt; + const auto* address = reinterpret_cast(&sender); + return client_t{ endpoint_t{ address_type_t{ address->sin6_addr }, ntohs(address->sin6_port) }, + address->sin6_scope_id }; + } + } + + [[nodiscard]] static std::pair sockaddr_from(const client_t& client) noexcept + { + SOCKADDR_STORAGE storage{}; + if constexpr (address_type_t::af_type == AF_INET) + { + auto* address = reinterpret_cast(&storage); + address->sin_family = AF_INET; + address->sin_addr = client.endpoint.ip; + address->sin_port = htons(client.endpoint.port); + return { storage, static_cast(sizeof(sockaddr_in)) }; + } + else + { + auto* address = reinterpret_cast(&storage); + address->sin6_family = AF_INET6; + address->sin6_addr = client.endpoint.ip; + address->sin6_port = htons(client.endpoint.port); + address->sin6_scope_id = client.scope_id; + return { storage, static_cast(sizeof(sockaddr_in6)) }; + } + } + + bool create_listener_socket() + { + // SO_RCVTIMEO only takes effect on sockets created with WSA_FLAG_OVERLAPPED. + listener_socket_ = WSASocket(address_type_t::af_type, SOCK_DGRAM, IPPROTO_UDP, nullptr, 0, + WSA_FLAG_OVERLAPPED); + if (listener_socket_ == INVALID_SOCKET) + { + NETLIB_ERROR("DNS relay: failed to create the listener socket: {}", WSAGetLastError()); + return false; + } + + disable_connection_reset(listener_socket_); + set_receive_timeout(listener_socket_); + + SOCKADDR_STORAGE local{}; + int local_size; + if constexpr (address_type_t::af_type == AF_INET) + { + auto* address = reinterpret_cast(&local); + address->sin_family = AF_INET; + address->sin_addr.s_addr = htonl(INADDR_ANY); + local_size = static_cast(sizeof(sockaddr_in)); + } + else + { + auto* address = reinterpret_cast(&local); + address->sin6_family = AF_INET6; + address->sin6_addr = in6addr_any; + local_size = static_cast(sizeof(sockaddr_in6)); + } + + if (bind(listener_socket_, reinterpret_cast(&local), local_size) == SOCKET_ERROR || + getsockname(listener_socket_, reinterpret_cast(&local), &local_size) == SOCKET_ERROR) + { + NETLIB_ERROR("DNS relay: failed to bind the listener socket: {}", WSAGetLastError()); + closesocket(listener_socket_); + listener_socket_ = INVALID_SOCKET; + return false; + } + + listener_port_ = address_type_t::af_type == AF_INET + ? ntohs(reinterpret_cast(&local)->sin_port) + : ntohs(reinterpret_cast(&local)->sin6_port); + return true; + } + + /// Sends one query through the open association. Caller holds lock_. + void send_query_locked(const client_t& client, std::vector& datagram, const std::size_t dns_offset) + { + const auto original_id = *dns_message_id(datagram.data() + dns_offset, datagram.size() - dns_offset); + const auto relay_id = queries_.insert(client, original_id, std::chrono::steady_clock::now(), + [this] { return random_id(); }); + if (!relay_id) + { + ++dropped_unavailable_; + return; + } + + set_dns_message_id(datagram.data() + dns_offset, *relay_id); + if (send(association_->relay, reinterpret_cast(datagram.data()), + static_cast(datagram.size()), 0) == SOCKET_ERROR) + { + ++dropped_send_failures_; + association_->failed.store(true, std::memory_order_release); + maintenance_cv_.notify_all(); + } + } + + // --- Threads ---------------------------------------------------------------------------- + + void listener_loop() + { + std::vector buffer(max_datagram_size); + + while (!stopping_.load(std::memory_order_acquire)) + { + SOCKADDR_STORAGE sender{}; + int sender_size = static_cast(sizeof(sender)); + const auto received = recvfrom(listener_socket_, reinterpret_cast(buffer.data()), + static_cast(buffer.size()), 0, reinterpret_cast(&sender), &sender_size); + if (received == SOCKET_ERROR || received <= 0) + continue; // timeout (checks stopping_), or a spurious error on a UDP socket + + const auto size = static_cast(received); + const auto client = client_from(sender); + if (!client || client->endpoint.port == 0 || !authorize_client_ || + !authorize_client_(client->endpoint.port)) + { + ++dropped_unauthorized_; + continue; + } + + const auto dns_offset = socks5_dns_query_offset(buffer.data(), size, own_address_type); + if (!dns_offset) + { + ++dropped_malformed_; + continue; + } + + std::vector datagram(buffer.begin(), buffer.begin() + static_cast(size)); + + std::scoped_lock lock(lock_); + if (association_ && !association_->failed.load(std::memory_order_acquire)) + { + send_query_locked(*client, datagram, *dns_offset); + continue; + } + + // No usable association: hold the query while one is opened, unless opening is + // backing off after a failure or too many queries are already waiting. + if (!health_.may_open(std::chrono::steady_clock::now()) || waiting_.size() >= max_waiting_queries) + { + ++dropped_unavailable_; + continue; + } + + waiting_.push_back(waiting_query{ *client, std::move(datagram) }); + maintenance_cv_.notify_all(); + } + } + + void reader_loop(association* const owner) + { + std::vector buffer(max_datagram_size); + std::vector answer(max_datagram_size + 32); + + while (!stopping_.load(std::memory_order_acquire) && !owner->retiring.load(std::memory_order_acquire)) + { + const auto received = recv(owner->relay, reinterpret_cast(buffer.data()), + static_cast(buffer.size()), 0); + if (received == SOCKET_ERROR) + { + if (WSAGetLastError() == WSAETIMEDOUT) + continue; + owner->failed.store(true, std::memory_order_release); + { + std::scoped_lock lock(lock_); + maintenance_cv_.notify_all(); + } + return; + } + + const auto relayed = parse_socks5_udp_datagram(buffer.data(), static_cast(received)); + const auto relay_id = relayed ? dns_message_id(relayed->data, relayed->data_size) : std::nullopt; + if (!relay_id) + { + ++dropped_unmatched_answers_; + continue; + } + + std::optional query; + { + std::scoped_lock lock(lock_); + health_.on_relay_datagram(); + query = queries_.take(*relay_id, std::chrono::steady_clock::now()); + } + + if (!query) + { + ++dropped_unmatched_answers_; + continue; + } + + const auto answer_size = build_dns_client_answer(*relayed, + reinterpret_cast(&query->client.endpoint.ip), own_address_size, dns_port, + query->original_id, answer.data(), answer.size()); + if (answer_size == 0) + { + ++dropped_unmatched_answers_; + continue; + } + + const auto [to, to_size] = sockaddr_from(query->client); + if (sendto(listener_socket_, reinterpret_cast(answer.data()), static_cast(answer_size), + 0, reinterpret_cast(&to), to_size) == SOCKET_ERROR) + { + ++dropped_send_failures_; + } + } + } + + void maintenance_loop() + { + using namespace std::chrono_literals; + + std::unique_lock lock(lock_); + while (!stopping_.load(std::memory_order_acquire)) + { + maintenance_cv_.wait_for(lock, 1s, [this] + { + return stopping_.load(std::memory_order_acquire) || + (association_ && association_->failed.load(std::memory_order_acquire)) || + (!association_ && !waiting_.empty() && health_.may_open(std::chrono::steady_clock::now())); + }); + if (stopping_.load(std::memory_order_acquire)) + break; + + const auto now = std::chrono::steady_clock::now(); + + // Retire an association whose relay or control connection failed, or that has + // stopped answering. + if (association_) + { + const auto unanswered = queries_.expire(now); + const char* reason = nullptr; + if (association_->failed.load(std::memory_order_acquire)) + reason = "the UDP relay socket failed"; + else if (control_channel_closed(association_->control)) + reason = "the SOCKS5 control connection closed"; + else if (health_.on_unanswered(unanswered, now)) + reason = "queries stopped being answered"; + + if (reason) + { + NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association because {}; it is reopened " + "on the next query", reason); + auto retired = std::move(association_); + queries_.clear(); + lock.unlock(); + close_association(std::move(retired)); + lock.lock(); + continue; + } + } + else + { + (void)queries_.expire(now); + } + + if (!association_ && !waiting_.empty() && health_.may_open(now)) + open_association(lock); + + report_drops(now); + } + } + + /// Opens an association for the waiting queries. Called with lock_ held; releases it + /// for the blocking SOCKS5 exchange. + void open_association(std::unique_lock& lock) + { + lock.unlock(); + + auto opened = connect_association(); + + lock.lock(); + const auto now = std::chrono::steady_clock::now(); + + if (!opened || stopping_.load(std::memory_order_acquire)) + { + const bool failed = !opened; + if (opened) + { + lock.unlock(); + close_association(std::move(opened)); + lock.lock(); + } + if (failed) + { + health_.on_open_failed(now); + dropped_unavailable_ += waiting_.size(); + waiting_.clear(); + const auto retry = std::chrono::duration_cast(health_.next_attempt() - now); + if (health_.consecutive_failures() == 1) + { + NETLIB_WARNING("DNS relay: could not open a SOCKS5 UDP association with {}; UDP DNS is " + "dropped until one opens (next attempt in {} s)", upstream_.to_string(), retry.count()); + } + else + { + NETLIB_DEBUG("DNS relay: SOCKS5 UDP association attempt {} failed; next attempt in {} s", + health_.consecutive_failures(), retry.count()); + } + } + return; + } + + if (health_.consecutive_failures() > 0) + NETLIB_INFO("DNS relay: SOCKS5 UDP association with {} opened", upstream_.to_string()); + else + NETLIB_DEBUG("DNS relay: SOCKS5 UDP association with {} opened", upstream_.to_string()); + + health_.on_opened(now); + association_ = std::move(opened); + association_->reader = std::thread(&socks5_dns_udp_relay::reader_loop, this, association_.get()); + + auto waiting = std::move(waiting_); + waiting_.clear(); + for (auto& query : waiting) + { + if (const auto offset = socks5_dns_query_offset(query.datagram.data(), query.datagram.size(), + own_address_type)) + { + send_query_locked(query.client, query.datagram, *offset); + } + } + } + + /// Blocking: SOCKS5 connect, authentication, UDP ASSOCIATE and relay socket. Lock not held. + std::unique_ptr connect_association() + { + auto control = association_client_.connect_to_socks5_proxy(upstream_.ip, upstream_.port); + if (control == INVALID_SOCKET) + return nullptr; + + auto negotiate_ctx = std::make_unique(address_type_t{}, 0, + credentials_ ? std::optional(credentials_->first) : std::nullopt, + credentials_ ? std::optional(credentials_->second) : std::nullopt, + upstream_options_); + + std::optional relay_endpoint; + try + { + relay_endpoint = association_client_.associate_to_socks5_proxy(control, upstream_.ip, negotiate_ctx); + } + catch (...) + { + relay_endpoint.reset(); + } + + if (!relay_endpoint) + { + closesocket(control); + return nullptr; + } + + // Report the relay endpoint before the relay socket exists (recursion guard). + if (relay_endpoint_observed_) + relay_endpoint_observed_(*relay_endpoint); + + const auto relay = association_client_.create_relay_socket(*relay_endpoint); + if (relay == INVALID_SOCKET) + { + closesocket(control); + return nullptr; + } + set_receive_timeout(relay); + + auto result = std::make_unique(); + result->control = control; + result->relay = relay; + return result; + } + + /// Stops the association's reader and closes its sockets. Lock not held. + static void close_association(std::unique_ptr retired) + { + if (!retired) + return; + + retired->retiring.store(true, std::memory_order_release); + if (retired->reader.joinable()) + retired->reader.join(); + if (retired->relay != INVALID_SOCKET) + closesocket(retired->relay); + if (retired->control != INVALID_SOCKET) + closesocket(retired->control); + } + + /// Whether the SOCKS5 control connection has closed. After the UDP ASSOCIATE reply no data + /// is expected on it, so readable data (for example a TLS close_notify) or EOF both mean + /// the association has ended. Zero-timeout select: never blocks. + [[nodiscard]] static bool control_channel_closed(const SOCKET control) noexcept + { + fd_set read_set; + FD_ZERO(&read_set); + FD_SET(control, &read_set); + timeval timeout{}; + + const auto select_result = select(0, &read_set, nullptr, nullptr, &timeout); + if (select_result == 0) + return false; + if (select_result == SOCKET_ERROR) + return WSAGetLastError() != WSAEINTR; + + char pending_byte{}; + const auto recv_result = recv(control, &pending_byte, 1, MSG_PEEK); + if (recv_result == SOCKET_ERROR) + { + const auto error = WSAGetLastError(); + return error != WSAEWOULDBLOCK && error != WSAEINTR && error != WSAETIMEDOUT; + } + return true; + } + + /// Logs what was dropped since the last report, at most every 30 seconds. + void report_drops(const std::chrono::steady_clock::time_point now) + { + using namespace std::chrono_literals; + + const auto unauthorized = dropped_unauthorized_.load(std::memory_order_relaxed); + const auto malformed = dropped_malformed_.load(std::memory_order_relaxed); + const auto unavailable = dropped_unavailable_.load(std::memory_order_relaxed); + const auto unmatched = dropped_unmatched_answers_.load(std::memory_order_relaxed); + const auto send_failures = dropped_send_failures_.load(std::memory_order_relaxed); + const auto total = unauthorized + malformed + unavailable + unmatched + send_failures; + + if (total == reported_drops_ || now - last_report_ < 30s) + return; + + NETLIB_INFO("DNS relay: dropped so far: {} queries while no SOCKS5 UDP association was available, " + "{} not from a redirected DNS client, {} without a DNS header, {} answers matching no query, " + "{} send failures", unavailable, unauthorized, malformed, unmatched, send_failures); + reported_drops_ = total; + last_report_ = now; + } + }; +} diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index d6465dd..4fde8d2 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -254,6 +254,17 @@ namespace proxy */ std::vector> proxy_upstreams_; + /** + * @brief SOCKS5 credentials and upstream transport options of each proxy, index-aligned + * with proxy_servers_. Used to open the DNS relay's shared UDP association. + */ + struct proxy_session_settings + { + std::optional> credentials; + socks5_upstream_options upstream_options; + }; + std::vector proxy_session_settings_; + /** * @brief Global DNS routing state. Written only by set_dns_routing() while the router is * inactive (under lifecycle_mutex_ and lock_); read by the packet handlers under @@ -264,14 +275,6 @@ namespace proxy std::optional> dns_server_override_v4_; std::optional> dns_server_override_v6_; - /** - * @brief True when replies from the DNS proxy's UDP listener may need their source - * restored (dns_reply_restore_needed()): in Proxy mode with a usable DNS proxy. - * Lets every listener reply skip lock_ in Direct mode. Written by - * set_dns_routing() while the router is inactive. - */ - std::atomic_bool dns_reply_restore_active_{ false }; - /** * @brief Set once any SOCKS5 server has returned a UDP relay endpoint on port 53, before * the relay socket sends anything. Only then can ProxiFyre's own UDP traffic that @@ -282,12 +285,13 @@ namespace proxy std::atomic_bool udp_relay_on_dns_port_{ false }; /** - * @brief Original server of each UDP DNS query redirected to the DNS proxy, so the answer - * can be restored to the server the resolver actually queried whatever source the - * relay reports (with or without a server override). + * @brief The DNS proxy's UDP path: one SOCKS5 UDP association per address family shared + * by every UDP DNS query (socks5_dns_udp_relay.h). Created by start() in Proxy mode + * when the selected proxy carries UDP for that family, destroyed by stop(). Their + * listener ports are the DNS proxy's UDP listeners. Guarded by lock_. */ - dns_udp_origin_tracker> dns_udp_origins_v4_; - dns_udp_origin_tracker> dns_udp_origins_v6_; + std::unique_ptr> dns_udp_relay_v4_; + std::unique_ptr> dns_udp_relay_v6_; /** * @brief Count of DNS packets dropped by the Proxy-mode policy since the last @@ -617,12 +621,12 @@ namespace proxy } template - auto& dns_udp_origins_for() noexcept + const auto& dns_udp_relay_for() const noexcept { if constexpr (std::is_same_v) - return dns_udp_origins_v4_; + return dns_udp_relay_v4_; else - return dns_udp_origins_v6_; + return dns_udp_relay_v6_; } template @@ -818,6 +822,8 @@ namespace proxy GetLastError()); } + stop_dns_udp_relays(); + std::vector> proxies_to_stop; std::vector> proxies_to_stop_v6; { @@ -989,8 +995,7 @@ namespace proxy // Proxy-mode DNS must take precedence over the LAN-bypass PASS filters: (re)install // the front-of-table REDIRECT filters with the current listener ports. If that fails, // fail start() instead of running with DNS able to bypass the policy. - dns_udp_origins_v4_.clear(); - dns_udp_origins_v6_.clear(); + start_dns_udp_relays(); dns_blocked_packets_.store(0, std::memory_order_relaxed); untranslated_listener_replies_.store(0, std::memory_order_relaxed); untranslated_listener_reply_logged_.clear(std::memory_order_relaxed); @@ -1103,6 +1108,9 @@ namespace proxy udp_redirect_v6_->stop(); // This should join the cleanup thread } + // Step 3b: Stop the DNS relays (their threads are joined without lock_ held). + stop_dns_udp_relays(); + // Step 4: Stop all proxy servers WITHOUT holding lock_ // CRITICAL: We must NOT hold lock_ while calling stop() or during destruction // because the cleanup threads inside the proxies need to acquire the same lock @@ -1430,6 +1438,7 @@ namespace proxy // registration still works on hosts where IPv6 sockets are disabled. std::unique_ptr socks_tcp_proxy_server; std::unique_ptr socks_udp_proxy_server; + proxy_session_settings session_settings{ cred_pair, upstream_options }; if (ipv4_destinations_enabled) { @@ -1573,6 +1582,7 @@ namespace proxy proxy_protocols_.reserve(proxy_protocols_.size() + 1); proxy_address_families_.reserve(proxy_address_families_.size() + 1); proxy_upstreams_.reserve(proxy_upstreams_.size() + 1); + proxy_session_settings_.reserve(proxy_session_settings_.size() + 1); } // Install PASS filters only for upstream addresses selected by @@ -1690,6 +1700,7 @@ namespace proxy proxy_protocols_.push_back(protocols); proxy_address_families_.push_back(address_families); proxy_upstreams_.push_back(*proxy_endpoint->ipv4); + proxy_session_settings_.push_back(std::move(session_settings)); return proxy_servers_.size() - 1; // Return the index of the added proxy server } @@ -1827,7 +1838,6 @@ namespace proxy dns_proxy_id_.reset(); dns_server_override_v4_.reset(); dns_server_override_v6_.reset(); - dns_reply_restore_active_.store(false, std::memory_order_release); if (settings.mode == dns_routing_mode::direct) { @@ -1883,7 +1893,6 @@ namespace proxy } dns_proxy_id_ = proxy_id; - dns_reply_restore_active_.store(dns_reply_restore_needed(dns_mode_, true), std::memory_order_release); const auto upstream = proxy_id < proxy_upstreams_.size() ? proxy_upstreams_[proxy_id].to_string() @@ -2159,8 +2168,11 @@ namespace proxy // Locks the proxy servers list for reading. std::shared_lock lock(lock_); - // Checks each proxy server to see if the given port number is being used. - // Returns true if any server is using the port, false otherwise. + // Checks each proxy server, and the DNS relay, to see if the given port number is + // being used. Returns true if any of them is using the port, false otherwise. + if (dns_udp_relay_v4_ && dns_udp_relay_v4_->listener_port() == port) + return true; + return std::ranges::any_of(std::as_const(proxy_servers_), [port](auto& proxy) { if (proxy.second && proxy.second->proxy_port() == port) @@ -2186,12 +2198,16 @@ namespace proxy } /** - * IPv6 counterpart of is_udp_proxy_port(): checks the IPv6 UDP proxy listeners. + * IPv6 counterpart of is_udp_proxy_port(): checks the IPv6 UDP proxy listeners and the + * IPv6 DNS relay. */ bool is_udp_proxy_port_v6(const uint16_t port) { std::shared_lock lock(lock_); + if (dns_udp_relay_v6_ && dns_udp_relay_v6_->listener_port() == port) + return true; + return std::ranges::any_of(std::as_const(proxy_servers_v6_), [port](auto& proxy) { if (proxy.second && proxy.second->proxy_port() == port) @@ -2214,20 +2230,27 @@ namespace proxy if (!dns_proxy_id_) return std::nullopt; - const auto listener = [id = *dns_proxy_id_](const auto& servers) -> std::optional + if constexpr (Transport == dns_transport::udp) { - if (id >= servers.size()) - return std::nullopt; - if constexpr (Transport == dns_transport::tcp) - return servers[id].first ? std::optional{ servers[id].first->proxy_port() } : std::nullopt; - else - return servers[id].second ? std::optional{ servers[id].second->proxy_port() } : std::nullopt; - }; - - if constexpr (std::is_same_v) - return listener(proxy_servers_); + // UDP DNS goes through the DNS relay's shared association, not the proxy's + // per-source-port UDP listener. + const auto& relay = dns_udp_relay_for(); + return relay ? std::optional{ relay->listener_port() } : std::nullopt; + } else - return listener(proxy_servers_v6_); + { + const auto listener = [id = *dns_proxy_id_](const auto& servers) -> std::optional + { + if (id >= servers.size() || !servers[id].first) + return std::nullopt; + return servers[id].first->proxy_port(); + }; + + if constexpr (std::is_same_v) + return listener(proxy_servers_); + else + return listener(proxy_servers_v6_); + } } /** @@ -2457,12 +2480,13 @@ namespace proxy /** * @brief Handles an outbound UDP datagram addressed to port 53 according to @p route. * - * In Proxy mode the datagram is redirected to the DNS proxy's local UDP listener via the + * In Proxy mode the datagram is redirected to the DNS relay's local listener via the * existing socks5_udp_local_redirect, which also writes the SOCKS5 UDP header. With a * server override the header carries the override while the IP header keeps the - * original destination. The server the resolver addressed is remembered, with or without - * an override, so the answer can be restored to it whatever source the relay reports. - * Anything that cannot be redirected is dropped, never passed. + * original destination. The relay sends the query through its shared SOCKS5 association + * and answers the client as the server it queried (socks5_dns_udp_relay.h). The source + * port is recorded in the UDP source-port mapper, which is what authorizes the relay to + * accept datagrams from it. Anything that cannot be redirected is dropped, never passed. */ template packet_filter::packet_action handle_dns_udp(netlib::ndisapi::intermediate_buffer& buffer, @@ -2488,23 +2512,14 @@ namespace proxy return packet_filter::packet_action{ action_type::drop }; } - // The relay may report a source other than the server the resolver addressed (always, - // with a server override), and the resolver accepts an answer only from that server. - // Remember it so the answer can be restored to it (decide_dns_query_tracking()). - const auto message_id = dns_message_id(payload, payload_size); - const auto tracking = decide_dns_query_tracking(route.server_override.has_value(), message_id.has_value()); - if (tracking == dns_query_tracking::drop) + // The DNS relay multiplexes queries by message ID (socks5_dns_udp_relay.h); a datagram + // too short to carry a DNS header cannot be relayed. + if (!dns_message_id(payload, payload_size)) { - note_dns_block(dns_block_reason::redirect_failed); + note_dns_block(dns_block_reason::not_dns_message); return packet_filter::packet_action{ action_type::drop }; } - if (tracking == dns_query_tracking::track) - { - dns_udp_origins_for().remember(source_port, *message_id, - net::ip_endpoint{ destination, destination_port }); - } - auto& redirect = udp_redirect_for(); const auto is_new_endpoint = redirect.is_new_endpoint(buffer); @@ -2591,66 +2606,136 @@ namespace proxy } /** - * @brief Determines how a reply leaving local UDP proxy listener @p listener_port toward - * client port @p client_port is presented, given the relayed SOCKS5 UDP datagram - * in @p socks_payload. Only answers to tracked queries relayed through the DNS - * proxy's listener are restored, with or without a server override (see - * classify_dns_reply()); other traffic through the same proxy is unchanged. + * @brief Bytes of the UDP payload of an IPv4/IPv6 frame that are actually captured. + */ + static size_t captured_udp_payload_size(const netlib::ndisapi::intermediate_buffer& buffer, const void* udp_header) noexcept + { + const auto* const start = reinterpret_cast(udp_header); + const auto* const end = buffer.m_IBuffer + buffer.m_Length; + if (start < buffer.m_IBuffer || start + sizeof(udphdr) > end) + return 0; + + const auto declared = static_cast(ntohs(static_cast(udp_header)->length)); + const auto captured = static_cast(end - start); + const auto udp_size = std::min(declared, captured); + return udp_size > sizeof(udphdr) ? udp_size - sizeof(udphdr) : 0; + } + + /** + * @brief The IPv4-mapped IPv6 form of an IPv4 SOCKS5 server endpoint, which IPv6 sockets + * use to reach it (as the proxy's IPv6 listeners do; see add_socks5_proxy()). + */ + static net::ip_endpoint ipv4_mapped(const net::ip_endpoint& upstream) + { + in6_addr mapped{}; + mapped.u.Byte[10] = 0xff; + mapped.u.Byte[11] = 0xff; + const in_addr address = upstream.ip; + memcpy(&mapped.u.Byte[12], &address, sizeof(address)); + return { net::ip_address_v6{ mapped }, upstream.port }; + } + + /** + * @brief Creates and starts a DNS relay for family @p AddrT through SOCKS5 server + * @p upstream. Its listener accepts only source ports the router recently redirected + * (the UDP source-port mapper), and every relay endpoint it is given is reported to + * the recursion guard. Returns null when the relay cannot be started. */ template - std::pair>> dns_udp_reply_origin( - const uint16_t listener_port, const uint16_t client_port, - const uint8_t* socks_payload, const size_t socks_payload_size) - { - // Lock-free early exit for every listener reply in Direct mode and when no DNS proxy - // is usable. - if (!dns_reply_restore_active_.load(std::memory_order_acquire)) - return { dns_reply_restore::unchanged, std::nullopt }; - - // Only replies from the DNS proxy's own UDP listener can answer a tracked query. The - // server override, when one is configured for this family, is optional here: tracked - // answers are restored with or without it. - std::optional> server_override; + std::unique_ptr> make_dns_udp_relay(const net::ip_endpoint& upstream, + const proxy_session_settings& settings) + { + try { - std::shared_lock lock(lock_); - if (dns_mode_ != dns_routing_mode::proxy) - return { dns_reply_restore::unchanged, std::nullopt }; - - if (dns_listener_port_locked() != listener_port) - return { dns_reply_restore::unchanged, std::nullopt }; + auto relay = std::make_unique>(upstream, settings.credentials, + settings.upstream_options, + [this](const uint16_t port) + { + auto& mapper = udp_mapper_for(); + std::scoped_lock lock(udp_mapper_lock_for()); + const auto it = mapper.find(port); + return it != mapper.end() && + std::chrono::steady_clock::now() - it->second <= udp_mapper_entry_ttl_; + }, + [this](const net::ip_endpoint& relay_endpoint) + { + note_udp_relay_endpoint(relay_endpoint.port); + }, + log_level_, log_stream_); - server_override = dns_server_override_for(); + if (relay->start()) + return relay; + } + catch (const std::exception& e) + { + NETLIB_LOG(log_level::error, "DNS routing: failed to create the {} DNS relay: {}", + std::is_same_v ? "IPv4" : "IPv6", e.what()); + return nullptr; } - constexpr auto v4 = std::is_same_v; - using raw_address_t = std::conditional_t; - const raw_address_t* raw = nullptr; - uint16_t override_port = 0; - if (server_override) + NETLIB_LOG(log_level::error, "DNS routing: the {} DNS relay could not be started; UDP DNS of this " + "family is blocked.", std::is_same_v ? "IPv4" : "IPv6"); + return nullptr; + } + + /** + * @brief Starts the DNS proxy's UDP relays (one shared SOCKS5 UDP association per address + * family) in Proxy mode, for the families the selected proxy carries over UDP. The + * IPv6 relay mirrors the proxy's IPv6 UDP listener and runs only while it does. + * Called from start() under lifecycle_mutex_, before the driver filters are + * installed, so the filter plan uses the relays' listener ports. A relay that cannot + * be started leaves UDP DNS of its family blocked, never direct. + */ + void start_dns_udp_relays() + { + std::optional> upstream; + proxy_session_settings settings; + bool ipv4 = false; + bool ipv6 = false; { - raw = &server_override->ip; - override_port = server_override->port; + std::shared_lock lock(lock_); + if (dns_mode_ != dns_routing_mode::proxy || !dns_proxy_id_) + return; + + const auto id = *dns_proxy_id_; + if (id >= proxy_upstreams_.size() || id >= proxy_session_settings_.size() || + id >= proxy_protocols_.size() || !protocol_supports_udp(proxy_protocols_[id])) + return; + + upstream = proxy_upstreams_[id]; + settings = proxy_session_settings_[id]; + const auto families = id < proxy_address_families_.size() + ? proxy_address_families_[id] + : supported_address_families::all; + ipv4 = family_supports_ipv4(families); + ipv6 = family_supports_ipv6(families) && id < proxy_servers_v6_.size() && proxy_servers_v6_[id].second; } - return classify_dns_reply(socks_payload, socks_payload_size, - static_cast(v4 ? 1 : 4), reinterpret_cast(raw), sizeof(raw_address_t), - override_port, client_port, dns_udp_origins_for()); + auto relay_v4 = ipv4 ? make_dns_udp_relay(*upstream, settings) : nullptr; + auto relay_v6 = ipv6 ? make_dns_udp_relay(ipv4_mapped(*upstream), settings) : nullptr; + + std::unique_lock lock(lock_); + dns_udp_relay_v4_ = std::move(relay_v4); + dns_udp_relay_v6_ = std::move(relay_v6); } /** - * @brief Bytes of the UDP payload of an IPv4/IPv6 frame that are actually captured. + * @brief Stops and destroys the DNS relays. Their threads are joined without lock_ held. */ - static size_t captured_udp_payload_size(const netlib::ndisapi::intermediate_buffer& buffer, const void* udp_header) noexcept + void stop_dns_udp_relays() { - const auto* const start = reinterpret_cast(udp_header); - const auto* const end = buffer.m_IBuffer + buffer.m_Length; - if (start < buffer.m_IBuffer || start + sizeof(udphdr) > end) - return 0; + std::unique_ptr> relay_v4; + std::unique_ptr> relay_v6; + { + std::unique_lock lock(lock_); + relay_v4 = std::move(dns_udp_relay_v4_); + relay_v6 = std::move(dns_udp_relay_v6_); + } - const auto declared = static_cast(ntohs(static_cast(udp_header)->length)); - const auto captured = static_cast(end - start); - const auto udp_size = std::min(declared, captured); - return udp_size > sizeof(udphdr) ? udp_size - sizeof(udphdr) : 0; + if (relay_v4) + relay_v4->stop(); + if (relay_v6) + relay_v6->stop(); } /** @@ -2763,19 +2848,14 @@ namespace proxy const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); const bool has_ports = ipv4_transport_header_present(fragment); - // If the packet is from a known proxy port, process for server-to-client redirection. - // Answers to tracked DNS queries are presented as coming from the server the resolver - // originally queried. + // If the packet is from a local UDP listener (a proxy's or the DNS relay's), process + // for server-to-client redirection. The DNS relay already names the server the client + // queried in the SOCKS5 header, so its answers need nothing more. if (has_ports && is_udp_proxy_port(ntohs(udp_header->th_sport))) { - const auto [restore, origin] = dns_udp_reply_origin( - ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), - reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); - // A listener reply never belongs on the wire: drop it when it cannot be translated. - const bool translated = restore != dns_reply_restore::drop && - udp_redirect_->process_server_to_client_packet(buffer, origin); - if (decide_udp_listener_reply(restore, translated) == listener_reply_action::revert) + const bool translated = udp_redirect_->process_server_to_client_packet(buffer); + if (decide_listener_reply(translated) == listener_reply_action::revert) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; @@ -3133,18 +3213,13 @@ namespace proxy const auto* const udp_header = static_cast(transport); - // If the packet is from a known proxy port, process for server-to-client redirection - // (restoring the original server of answers to tracked DNS queries, as on the IPv4 path). + // If the packet is from a local UDP listener (a proxy's or the DNS relay's), process + // for server-to-client redirection, as on the IPv4 path. if (is_udp_proxy_port_v6(ntohs(udp_header->th_sport))) { - const auto [restore, origin] = dns_udp_reply_origin( - ntohs(udp_header->th_sport), ntohs(udp_header->th_dport), - reinterpret_cast(udp_header + 1), captured_udp_payload_size(buffer, udp_header)); - // A listener reply never belongs on the wire: drop it when it cannot be translated. - const bool translated = restore != dns_reply_restore::drop && - udp_redirect_v6_->process_server_to_client_packet(buffer, origin); - if (decide_udp_listener_reply(restore, translated) == listener_reply_action::revert) + const bool translated = udp_redirect_v6_->process_server_to_client_packet(buffer); + if (decide_listener_reply(translated) == listener_reply_action::revert) { log_packet_to_pcap(buffer); return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; @@ -3558,8 +3633,6 @@ namespace proxy } // Expire DNS answer-origin mappings for queries that were never answered. - dns_udp_origins_v4_.sweep(now); - dns_udp_origins_v6_.sweep(now); } // Report Proxy-mode DNS drops and untranslatable listener replies at the same diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index 9e431a0..e7e5d49 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -2,13 +2,14 @@ // // Each test builds a real Ethernet/IP/UDP or TCP frame, drives it through the production // socks5_udp_local_redirect / tcp_local_redirect translations exactly as socks_local_router's -// DNS handlers do (handle_dns_udp(), handle_dns_tcp(), dns_udp_reply_origin()), and checks -// every rewritten header field, the SOCKS5 UDP header carried to the relay, the restored source -// of the answer, and the IP/UDP/TCP checksums (verified independently of the product checksum -// code, which is extracted from ndisapi/ndisapi.cpp by run-portable-tests.sh). +// DNS handlers do (handle_dns_udp(), handle_dns_tcp()), and checks every rewritten header field, +// the SOCKS5 UDP datagram sent through the DNS relay's shared association, the source the client +// sees on the answer, and the IP/UDP/TCP checksums (verified independently of the product +// checksum code, which is extracted from the ndisapi submodule by run-portable-tests.sh). // -// The Windows Packet Filter driver and SOCKS5 sockets are not involved: the local proxy's reply -// is synthesized as the bytes socks5_local_udp_proxy_server sends back. This suite builds only on +// The Windows Packet Filter driver and SOCKS5 sockets are not involved: the DNS relay's listener +// step is reproduced with its shipped bookkeeping (dns_udp_multiplexer.h), and the SOCKS5 +// relay's answers are synthesized. This suite builds only on // non-Windows hosts through winshim/ (see run-portable-tests.sh). #include "winshim/packet_env.h" @@ -213,36 +214,91 @@ namespace return frame::udp6(local_address, original_server, udp_listener, client_port, datagram); } - template - std::pair>> classify(frame& reply, - const net::ip_endpoint& server_override, proxy::dns_udp_origin_tracker>& origins) + /// The DNS relay's listener step (socks5_dns_udp_relay.h), using the shipped bookkeeping: + /// forward() takes the datagram the redirect delivered to the listener, records the query and + /// returns the datagram sent through the shared SOCKS5 association, with the relay ID in + /// place of the client's message ID; answer() maps a relay datagram back and returns the + /// listener's reply frame to the client, or nothing when the answer matches no query. + template + struct dns_relay { - const Raw& raw = server_override.ip; - return proxy::classify_dns_reply(reply.udp_payload(), reply.udp_payload_size(), - static_cast(std::is_same_v ? 1 : 4), reinterpret_cast(&raw), sizeof(Raw), - server_override.port, ntohs(reply.udp()->th_dport), origins); - } + using client = net::ip_endpoint; + static constexpr uint8_t address_type = std::is_same_v ? 1 : 4; + static constexpr size_t address_size = std::is_same_v ? 4 : 16; + + proxy::dns_query_table queries{ std::chrono::seconds{ 10 }, 64 }; + std::chrono::steady_clock::time_point now{ std::chrono::seconds{ 1000 } }; + + std::vector forward(frame& redirected, const uint16_t relay_id) + { + auto datagram = redirected.payload(); + const auto offset = proxy::socks5_dns_query_offset(datagram.data(), datagram.size(), address_type); + EXPECT_TRUE(offset.has_value()); + if (!offset) + return {}; + + // The listener's sender: the (swapped) queried server and the client port. + Addr server; + if constexpr (std::is_same_v) + server = Addr{ redirected.ip4()->ip_src }; + else + server = Addr{ redirected.ip6()->ip6_src }; + const client sender{ server, ntohs(redirected.udp()->th_sport) }; + + const auto original_id = *proxy::dns_message_id(datagram.data() + *offset, datagram.size() - *offset); + const auto id = queries.insert(sender, original_id, now, [relay_id] { return relay_id; }); + EXPECT_EQ(id, std::optional{ relay_id }); + proxy::set_dns_message_id(datagram.data() + *offset, relay_id); + return datagram; + } + + std::optional answer(const std::vector& relayed_bytes, const char* local_address) + { + const auto relayed = proxy::parse_socks5_udp_datagram(relayed_bytes.data(), relayed_bytes.size()); + if (!relayed) + return std::nullopt; + const auto relay_id = proxy::dns_message_id(relayed->data, relayed->data_size); + if (!relay_id) + return std::nullopt; + const auto query = queries.take(*relay_id, now); + if (!query) + return std::nullopt; + + std::vector out(relayed_bytes.size() + 32); + const auto size = proxy::build_dns_client_answer(*relayed, + reinterpret_cast(&query->client.ip), address_size, 53, query->original_id, + out.data(), out.size()); + if (size == 0) + return std::nullopt; + out.resize(size); + + const std::string server{ query->client.ip }; + if constexpr (std::is_same_v) + return frame::udp4(local_address, server.c_str(), udp_listener, query->client.port, out); + else + return frame::udp6(local_address, server.c_str(), udp_listener, query->client.port, out); + } + }; - /// classify() for a DNS proxy without a server override, with the arguments the router - /// passes then: no override address, but still the family's address size, and port 0. + /// What the SOCKS5 relay returns for a forwarded query: @p source in the SOCKS5 header and + /// the answer carrying the relay ID it was asked with. template - std::pair>> classify_without_override(frame& reply, - proxy::dns_udp_origin_tracker>& origins) + std::vector relay_answer(const Addr& source, const uint16_t port, std::vector answer, + const uint16_t relay_id) { - constexpr bool is_v4 = std::is_same_v; - return proxy::classify_dns_reply(reply.udp_payload(), reply.udp_payload_size(), - static_cast(is_v4 ? 1 : 4), nullptr, is_v4 ? sizeof(in_addr) : sizeof(in6_addr), 0, - ntohs(reply.udp()->th_dport), origins); + proxy::set_dns_message_id(answer.data(), relay_id); + return socks5_udp_datagram(source, port, answer); } } -// 6./7. IPv4 UDP query to a private resolver with an IPv4 override: the relay is asked for the -// override, the IP packet keeps the original destination, and the answer is presented to -// the client as coming from the original server. +// 6./7. IPv4 UDP query to a private resolver with an IPv4 override: the redirect asks the relay +// for the override while the IP packet keeps the original destination; the DNS relay sends +// it with a relay ID; the answer reaches the client from the server it queried, with its +// own message ID. TEST(DnsPacketRedirect, Ipv4UdpOverrideRewritesTheSocksDestinationAndRestoresTheAnswer) { ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; - proxy::dns_udp_origin_tracker> origins; + dns_relay relay; const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; const auto query = dns_message(0xabcd); @@ -250,9 +306,7 @@ TEST(DnsPacketRedirect, Ipv4UdpOverrideRewritesTheSocksDestinationAndRestoresThe ASSERT_TRUE(packet.ip4_checksum_valid()); ASSERT_TRUE(packet.l4_checksum_valid()); - // handle_dns_udp(): remember the original server, register the endpoint, redirect. - origins.remember(client_port, *proxy::dns_message_id(query.data(), query.size()), - net::ip_endpoint{ v4{ packet.ip4()->ip_dst }, 53 }); + // handle_dns_udp(): register the endpoint and redirect to the DNS relay's listener. EXPECT_TRUE(redirect.is_new_endpoint(packet.buffer)); ASSERT_TRUE(redirect.process_client_to_server_packet(packet.buffer, htons(udp_listener), server_override)); @@ -262,335 +316,262 @@ TEST(DnsPacketRedirect, Ipv4UdpOverrideRewritesTheSocksDestinationAndRestoresThe EXPECT_EQ(v4{ packet.ip4()->ip_dst }, v4{ std::string{ "192.168.1.10" } }); EXPECT_EQ(ntohs(packet.udp()->th_sport), client_port); EXPECT_EQ(ntohs(packet.udp()->th_dport), udp_listener); + EXPECT_TRUE(packet.ip4_checksum_valid()); + EXPECT_TRUE(packet.l4_checksum_valid()); - // The SOCKS5 UDP header carried to the relay names the override. - const auto relayed = packet.payload(); - const auto view = proxy::parse_socks5_udp_datagram(relayed.data(), relayed.size()); + // What goes through the shared association: the override, and the relay ID instead of 0xabcd. + const auto sent = relay.forward(packet, 0x5a5a); + const auto view = proxy::parse_socks5_udp_datagram(sent.data(), sent.size()); ASSERT_TRUE(view.has_value()); EXPECT_EQ(view->address_type, 1); EXPECT_EQ(std::vector(view->address, view->address + 4), (std::vector{ 1, 1, 1, 1 })); EXPECT_EQ(view->port, 53); - EXPECT_EQ(std::vector(view->data, view->data + view->data_size), query); - EXPECT_TRUE(packet.ip4_checksum_valid()); - EXPECT_TRUE(packet.l4_checksum_valid()); + auto expected_query = query; + proxy::set_dns_message_id(expected_query.data(), 0x5a5a); + EXPECT_EQ(std::vector(view->data, view->data + view->data_size), expected_query); - // The relay answers from the override; dns_udp_reply_origin() restores the original server. + // The relay answers from the override; the client sees the original server and ID. const auto answer = dns_message(0xabcd, 40); - auto reply = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, answer); - const auto [restore, origin] = classify(reply, server_override, origins); - ASSERT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(origin.has_value()); - ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); - - EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); - EXPECT_EQ(v4{ reply.ip4()->ip_dst }, v4{ std::string{ "192.168.1.10" } }); - EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); - EXPECT_EQ(ntohs(reply.udp()->th_dport), client_port); - EXPECT_EQ(reply.payload(), answer); - EXPECT_EQ(ntohs(reply.ip4()->ip_len), sizeof(iphdr) + sizeof(udphdr) + answer.size()); - EXPECT_TRUE(reply.ip4_checksum_valid()); - EXPECT_TRUE(reply.l4_checksum_valid()); + auto reply = relay.answer(relay_answer(server_override.ip, 53, answer, 0x5a5a), "192.168.1.10"); + ASSERT_TRUE(reply.has_value()); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply->buffer)); + + EXPECT_EQ(v4{ reply->ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(v4{ reply->ip4()->ip_dst }, v4{ std::string{ "192.168.1.10" } }); + EXPECT_EQ(ntohs(reply->udp()->th_sport), 53); + EXPECT_EQ(ntohs(reply->udp()->th_dport), client_port); + EXPECT_EQ(reply->payload(), answer); + EXPECT_EQ(ntohs(reply->ip4()->ip_len), sizeof(iphdr) + sizeof(udphdr) + answer.size()); + EXPECT_TRUE(reply->ip4_checksum_valid()); + EXPECT_TRUE(reply->l4_checksum_valid()); } -// 2./7. Without an override the original destination is preserved end to end. +// 2./7. Without an override the relay is asked for the server the resolver queried. TEST(DnsPacketRedirect, Ipv4UdpWithoutOverrideKeepsTheOriginalDestination) { ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + dns_relay relay; const auto query = dns_message(0x0102); auto packet = frame::udp4("10.0.0.20", "8.8.8.8", client_port, 53, query); EXPECT_TRUE(redirect.is_new_endpoint(packet.buffer)); ASSERT_TRUE(redirect.process_client_to_server_packet(packet.buffer, htons(udp_listener))); - const auto relayed = packet.payload(); - const auto view = proxy::parse_socks5_udp_datagram(relayed.data(), relayed.size()); + const auto sent = relay.forward(packet, 0x0909); + const auto view = proxy::parse_socks5_udp_datagram(sent.data(), sent.size()); ASSERT_TRUE(view.has_value()); EXPECT_EQ(std::vector(view->address, view->address + 4), (std::vector{ 8, 8, 8, 8 })); EXPECT_EQ(view->port, 53); const auto answer = dns_message(0x0102, 5); - auto reply = local_proxy_reply("10.0.0.20", "8.8.8.8", v4{ std::string{ "8.8.8.8" } }, 53, answer); - ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer)); - EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "8.8.8.8" } }); - EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); - EXPECT_EQ(reply.payload(), answer); - EXPECT_TRUE(reply.ip4_checksum_valid()); - EXPECT_TRUE(reply.l4_checksum_valid()); + auto reply = relay.answer(relay_answer(v4{ std::string{ "8.8.8.8" } }, 53, answer, 0x0909), "10.0.0.20"); + ASSERT_TRUE(reply.has_value()); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply->buffer)); + EXPECT_EQ(v4{ reply->ip4()->ip_src }, v4{ std::string{ "8.8.8.8" } }); + EXPECT_EQ(ntohs(reply->udp()->th_sport), 53); + EXPECT_EQ(reply->payload(), answer); + EXPECT_TRUE(reply->ip4_checksum_valid()); + EXPECT_TRUE(reply->l4_checksum_valid()); } // 2./6./7. IPv6 UDP query with an IPv6 override. TEST(DnsPacketRedirect, Ipv6UdpOverrideRewritesTheSocksDestinationAndRestoresTheAnswer) { ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; - proxy::dns_udp_origin_tracker> origins; + dns_relay relay; const net::ip_endpoint server_override{ v6{ std::string{ "2606:4700:4700::1111" } }, 53 }; const auto query = dns_message(0x7777); auto packet = frame::udp6("fd00::10", "fd00::1", client_port, 53, query); ASSERT_TRUE(packet.l4_checksum_valid()); - origins.remember(client_port, 0x7777, net::ip_endpoint{ v6{ packet.ip6()->ip6_dst }, 53 }); EXPECT_TRUE(redirect.is_new_endpoint(packet.buffer)); ASSERT_TRUE(redirect.process_client_to_server_packet(packet.buffer, htons(udp_listener), server_override)); EXPECT_TRUE(packet.ethernet_swapped()); EXPECT_EQ(v6{ packet.ip6()->ip6_src }, v6{ std::string{ "fd00::1" } }); EXPECT_EQ(ntohs(packet.udp()->th_dport), udp_listener); - const auto relayed = packet.payload(); - const auto view = proxy::parse_socks5_udp_datagram(relayed.data(), relayed.size()); + EXPECT_TRUE(packet.l4_checksum_valid()); + + const auto sent = relay.forward(packet, 0x4321); + const auto view = proxy::parse_socks5_udp_datagram(sent.data(), sent.size()); ASSERT_TRUE(view.has_value()); EXPECT_EQ(view->address_type, 4); EXPECT_EQ(v6{ *reinterpret_cast(view->address) }, server_override.ip); EXPECT_EQ(view->port, 53); - EXPECT_TRUE(packet.l4_checksum_valid()); + EXPECT_EQ(proxy::dns_message_id(view->data, view->data_size), std::optional{ 0x4321 }); const auto answer = dns_message(0x7777, 64); - auto reply = local_proxy_reply("fd00::10", "fd00::1", server_override.ip, 53, answer); - const auto [restore, origin] = classify(reply, server_override, origins); - ASSERT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); - - EXPECT_EQ(v6{ reply.ip6()->ip6_src }, v6{ std::string{ "fd00::1" } }); - EXPECT_EQ(v6{ reply.ip6()->ip6_dst }, v6{ std::string{ "fd00::10" } }); - EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); - EXPECT_EQ(reply.payload(), answer); - EXPECT_TRUE(reply.l4_checksum_valid()); -} - -// 7./8. Answers to tracked queries are restored whatever source the relay reports; answers -// naming the override that match no query are dropped; other traffic is unchanged. -TEST(DnsPacketRedirect, AnswersToTrackedQueriesAreRestoredWhateverSourceTheRelayReports) -{ - proxy::dns_udp_origin_tracker> origins; - const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; - origins.remember(client_port, 0x1111, net::ip_endpoint{ v4{ std::string{ "192.168.1.1" } }, 53 }); - - // Tracked query, relay reports the override: restored. - auto known = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x1111)); - const auto [restore, origin] = classify(known, server_override, origins); - EXPECT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(origin.has_value()); - EXPECT_EQ(origin->ip, v4{ std::string{ "192.168.1.1" } }); - EXPECT_EQ(origin->port, 53); - - // Tracked query, relay reports another source (its own address, another port): restored too. - auto relay_source = local_proxy_reply("192.168.1.10", "192.168.1.1", v4{ std::string{ "203.0.113.5" } }, 40000, dns_message(0x1111)); - const auto [relay_restore, relay_origin] = classify(relay_source, server_override, origins); - EXPECT_EQ(relay_restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(relay_origin.has_value()); - EXPECT_EQ(relay_origin->ip, v4{ std::string{ "192.168.1.1" } }); - - // Names the override but answers no tracked query: dropped. - auto unknown = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x2222)); - EXPECT_EQ((classify(unknown, server_override, origins).first), proxy::dns_reply_restore::drop); - auto truncated = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, std::vector{ 0x11, 0x11, 0x01 }); - EXPECT_EQ((classify(truncated, server_override, origins).first), proxy::dns_reply_restore::drop); - - // Other traffic through the same proxy that matches no tracked query: unchanged. - auto other = local_proxy_reply("192.168.1.10", "203.0.113.5", v4{ std::string{ "203.0.113.5" } }, 443, dns_message(0x2222)); - EXPECT_EQ((classify(other, server_override, origins).first), proxy::dns_reply_restore::unchanged); - auto other_port = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 5353, dns_message(0x2222)); - EXPECT_EQ((classify(other_port, server_override, origins).first), proxy::dns_reply_restore::unchanged); - - // A malformed SOCKS5 header (non-zero FRAG) is not restored, and neither is a header of the - // other family that matches no tracked query; the redirect then fails to translate either - // and the router drops it. - auto fragmented = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, dns_message(0x1111)); - fragmented.udp_payload()[2] = 1; - EXPECT_EQ((classify(fragmented, server_override, origins).first), proxy::dns_reply_restore::unchanged); - auto wrong_family = frame::udp4("192.168.1.10", "192.168.1.1", udp_listener, client_port, - socks5_udp_datagram(v6{ std::string{ "2001:db8::1" } }, 53, dns_message(0x2222))); - EXPECT_EQ((classify(wrong_family, server_override, origins).first), proxy::dns_reply_restore::unchanged); - - // A tracked answer is restored even when the relay's header has the other address family. - auto tracked_other_family = frame::udp4("192.168.1.10", "192.168.1.1", udp_listener, client_port, - socks5_udp_datagram(v6{ std::string{ "2001:db8::1" } }, 53, dns_message(0x1111))); - const auto [other_family_restore, other_family_origin] = classify(tracked_other_family, server_override, origins); - EXPECT_EQ(other_family_restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(other_family_origin.has_value()); - EXPECT_EQ(other_family_origin->ip, v4{ std::string{ "192.168.1.1" } }); + auto reply = relay.answer(relay_answer(server_override.ip, 53, answer, 0x4321), "fd00::10"); + ASSERT_TRUE(reply.has_value()); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply->buffer)); + + EXPECT_EQ(v6{ reply->ip6()->ip6_src }, v6{ std::string{ "fd00::1" } }); + EXPECT_EQ(v6{ reply->ip6()->ip6_dst }, v6{ std::string{ "fd00::10" } }); + EXPECT_EQ(ntohs(reply->udp()->th_sport), 53); + EXPECT_EQ(reply->payload(), answer); + EXPECT_TRUE(reply->l4_checksum_valid()); } -// 8. End to end: a relay that reports its own address as the answer's source still produces an -// answer the resolver accepts (source = the server it queried). -TEST(DnsPacketRedirect, RelayReportingAnotherSourceStillRestoresTheQueriedServer) +// 7./8. Whatever source the relay reports (the override, its own address and port, or an +// address of the other family), the client sees the server it queried. Answers that match +// no query in flight, are too short for a DNS header, or are SOCKS5 fragments are never +// delivered. +TEST(DnsPacketRedirect, AnswersAreDeliveredFromTheQueriedServerWhateverSourceTheRelayReports) { ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; - proxy::dns_udp_origin_tracker> origins; - const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; + dns_relay relay; + const auto answer = dns_message(0x1111, 12); - auto query = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, dns_message(0x4242)); - origins.remember(client_port, 0x4242, net::ip_endpoint{ v4{ query.ip4()->ip_dst }, 53 }); - ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); - ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener), server_override)); - - const auto answer = dns_message(0x4242, 30); - auto reply = local_proxy_reply("192.168.1.10", "192.168.1.1", v4{ std::string{ "198.51.100.7" } }, 1080, answer); - const auto [restore, origin] = classify(reply, server_override, origins); - ASSERT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); - EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); - EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); - EXPECT_EQ(reply.payload(), answer); - EXPECT_TRUE(reply.ip4_checksum_valid()); - EXPECT_TRUE(reply.l4_checksum_valid()); -} + const std::vector> relay_reports{ + socks5_udp_datagram(v4{ std::string{ "1.1.1.1" } }, 53, answer), // the override + socks5_udp_datagram(v4{ std::string{ "203.0.113.5" } }, 40000, answer), // the relay itself + socks5_udp_datagram(v6{ std::string{ "2001:db8::1" } }, 53, answer), // the other family + }; -// 8. Without a server override the relay is asked for the server the resolver queried. A relay -// that reports another source (here its own address) must still produce an answer the -// resolver accepts; nothing is ever dropped for naming an override, because there is none. -TEST(DnsPacketRedirect, WithoutAnOverrideARelayReportingAnotherSourceIsStillRestored) -{ - ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; - proxy::dns_udp_origin_tracker> origins; + uint16_t relay_id = 0x2000; + for (auto report : relay_reports) + { + auto query = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, dns_message(0x1111)); + (void)redirect.is_new_endpoint(query.buffer); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener), + net::ip_endpoint{ v4{ std::string{ "1.1.1.1" } }, 53 })); + (void)relay.forward(query, ++relay_id); + + const auto data_offset = proxy::parse_socks5_udp_datagram(report.data(), report.size())->data - report.data(); + proxy::set_dns_message_id(report.data() + data_offset, relay_id); + + auto reply = relay.answer(report, "192.168.1.10"); + ASSERT_TRUE(reply.has_value()); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply->buffer)); + EXPECT_EQ(v4{ reply->ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(ntohs(reply->udp()->th_sport), 53); + EXPECT_EQ(reply->payload(), answer); + EXPECT_TRUE(reply->ip4_checksum_valid()); + EXPECT_TRUE(reply->l4_checksum_valid()); + } - auto query = frame::udp4("192.168.1.10", "8.8.8.8", client_port, 53, dns_message(0x6161)); - origins.remember(client_port, 0x6161, net::ip_endpoint{ v4{ query.ip4()->ip_dst }, 53 }); - ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); - ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); + // Matches no query in flight, including one already answered: not delivered. + EXPECT_FALSE(relay.answer(relay_answer(v4{ std::string{ "1.1.1.1" } }, 53, answer, 0x9999), "192.168.1.10")); + EXPECT_FALSE(relay.answer(relay_answer(v4{ std::string{ "1.1.1.1" } }, 53, answer, relay_id), "192.168.1.10")); - // The relay reports its own address and port instead of 8.8.8.8:53. - const auto answer = dns_message(0x6161, 30); - auto reply = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{ std::string{ "198.51.100.7" } }, 1080, answer); - const auto [restore, origin] = classify_without_override(reply, origins); - ASSERT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(origin.has_value()); - ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); - EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "8.8.8.8" } }); - EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); - EXPECT_EQ(reply.payload(), answer); - EXPECT_TRUE(reply.ip4_checksum_valid()); - EXPECT_TRUE(reply.l4_checksum_valid()); - - // A relay that reports the queried server is restored to the same endpoint (a no-op). - auto compliant = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{ std::string{ "8.8.8.8" } }, 53, answer); - const auto [compliant_restore, compliant_origin] = classify_without_override(compliant, origins); - EXPECT_EQ(compliant_restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(compliant_origin.has_value()); - EXPECT_EQ(compliant_origin->ip, v4{ std::string{ "8.8.8.8" } }); - - // Anything that matches no tracked query is left unchanged, never dropped: application - // traffic sharing the proxy, an unknown message ID, or a payload too short for a DNS header. - auto other = local_proxy_reply("192.168.1.10", "203.0.113.5", v4{ std::string{ "203.0.113.5" } }, 443, dns_message(0x7777)); - EXPECT_EQ(classify_without_override(other, origins).first, proxy::dns_reply_restore::unchanged); - auto unknown_id = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{ std::string{ "8.8.8.8" } }, 53, dns_message(0x7777)); - EXPECT_EQ(classify_without_override(unknown_id, origins).first, proxy::dns_reply_restore::unchanged); - auto short_payload = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{ std::string{ "8.8.8.8" } }, 53, std::vector{ 0x61, 0x61 }); - EXPECT_EQ(classify_without_override(short_payload, origins).first, proxy::dns_reply_restore::unchanged); + auto query = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, dns_message(0x1111)); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); + (void)relay.forward(query, 0x3000); + + // Too short for a DNS header, or a SOCKS5 fragment: not delivered. + EXPECT_FALSE(relay.answer(socks5_udp_datagram(v4{ std::string{ "1.1.1.1" } }, 53, std::vector{ 0x30, 0x00, 1 }), + "192.168.1.10")); + auto fragment = relay_answer(v4{ std::string{ "1.1.1.1" } }, 53, answer, 0x3000); + fragment[2] = 1; + EXPECT_FALSE(relay.answer(fragment, "192.168.1.10")); + // The query is still in flight for its real answer. + EXPECT_TRUE(relay.answer(relay_answer(v4{ std::string{ "1.1.1.1" } }, 53, answer, 0x3000), "192.168.1.10")); } -// 8. IPv6 without an override: the same restoration on the IPv6 path, with the arguments the -// router passes, including a relay-reported port of 0 that must not be compared with anything. -TEST(DnsPacketRedirect, Ipv6WithoutAnOverrideIsRestoredAndUnmatchedRepliesAreUnchanged) +// 8. Two client sockets query with the same message ID: each gets its own answer with its own ID, +// even when the answers arrive in the other order. +TEST(DnsPacketRedirect, ClientsSharingAMessageIdEachGetTheirOwnAnswer) { - ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; - proxy::dns_udp_origin_tracker> origins; - - auto query = frame::udp6("fd00::10", "2001:4860:4860::8888", client_port, 53, dns_message(0x6262)); - origins.remember(client_port, 0x6262, net::ip_endpoint{ v6{ query.ip6()->ip6_dst }, 53 }); - ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); - ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); - - const auto answer = dns_message(0x6262, 40); - auto reply = local_proxy_reply("fd00::10", "2001:4860:4860::8888", v6{ std::string{ "2001:db8::7" } }, 1080, answer); - const auto [restore, origin] = classify_without_override(reply, origins); - ASSERT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); - EXPECT_EQ(v6{ reply.ip6()->ip6_src }, v6{ std::string{ "2001:4860:4860::8888" } }); - EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); - EXPECT_EQ(reply.payload(), answer); - EXPECT_TRUE(reply.l4_checksum_valid()); - - // Unmatched, with a reported source of all zeroes and port 0: unchanged, never dropped. - auto zero_source = local_proxy_reply("fd00::10", "2001:4860:4860::8888", v6{}, 0, dns_message(0x7777)); - EXPECT_EQ(classify_without_override(zero_source, origins).first, proxy::dns_reply_restore::unchanged); - auto zero_source_v4 = local_proxy_reply("192.168.1.10", "8.8.8.8", v4{}, 0, dns_message(0x7777)); - proxy::dns_udp_origin_tracker> origins_v4; - EXPECT_EQ(classify_without_override(zero_source_v4, origins_v4).first, proxy::dns_reply_restore::unchanged); + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + dns_relay relay; + constexpr uint16_t other_port = client_port + 7; + + auto first = frame::udp4("192.168.1.10", "8.8.8.8", client_port, 53, dns_message(0x4242)); + auto second = frame::udp4("192.168.1.10", "1.1.1.1", other_port, 53, dns_message(0x4242)); + ASSERT_TRUE(redirect.is_new_endpoint(first.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(first.buffer, htons(udp_listener))); + ASSERT_TRUE(redirect.is_new_endpoint(second.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(second.buffer, htons(udp_listener))); + (void)relay.forward(first, 0x0101); + (void)relay.forward(second, 0x0202); + + const auto answer_second = dns_message(0x4242, 22); + auto reply_second = relay.answer(relay_answer(v4{ std::string{ "1.1.1.1" } }, 53, answer_second, 0x0202), "192.168.1.10"); + const auto answer_first = dns_message(0x4242, 11); + auto reply_first = relay.answer(relay_answer(v4{ std::string{ "8.8.8.8" } }, 53, answer_first, 0x0101), "192.168.1.10"); + ASSERT_TRUE(reply_first.has_value()); + ASSERT_TRUE(reply_second.has_value()); + + ASSERT_TRUE(redirect.process_server_to_client_packet(reply_first->buffer)); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply_second->buffer)); + EXPECT_EQ(ntohs(reply_first->udp()->th_dport), client_port); + EXPECT_EQ(v4{ reply_first->ip4()->ip_src }, v4{ std::string{ "8.8.8.8" } }); + EXPECT_EQ(reply_first->payload(), answer_first); + EXPECT_EQ(ntohs(reply_second->udp()->th_dport), other_port); + EXPECT_EQ(v4{ reply_second->ip4()->ip_src }, v4{ std::string{ "1.1.1.1" } }); + EXPECT_EQ(reply_second->payload(), answer_second); } // 8. A relay that reports a source of the other address family. Its own address is IPv4 even -// for an IPv6 query, because SOCKS5 servers are reached over IPv4. A tracked answer is -// restored anyway, and the redirect strips the relay's header by its real size. -TEST(DnsPacketRedirect, TrackedAnswerIsRestoredWhenTheRelayHeaderHasTheOtherAddressFamily) +// for an IPv6 query, because SOCKS5 servers are reached over IPv4. The DNS relay rewrites the +// header to the listener's family, so the redirect strips a header of its own size. +TEST(DnsPacketRedirect, AnswerIsDeliveredWhenTheRelayHeaderHasTheOtherAddressFamily) { const auto answer = dns_message(0x6363, 48); // IPv6 query, IPv4 relay header (10 bytes instead of 22). { ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; - proxy::dns_udp_origin_tracker> origins; + dns_relay relay; auto query = frame::udp6("fd00::10", "2001:4860:4860::8888", client_port, 53, dns_message(0x6363)); - origins.remember(client_port, 0x6363, net::ip_endpoint{ v6{ query.ip6()->ip6_dst }, 53 }); ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); - - auto reply = frame::udp6("fd00::10", "2001:4860:4860::8888", udp_listener, client_port, - socks5_udp_datagram(v4{ std::string{ "198.51.100.7" } }, 1080, answer)); - const auto [restore, origin] = classify_without_override(reply, origins); - ASSERT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); - EXPECT_EQ(v6{ reply.ip6()->ip6_src }, v6{ std::string{ "2001:4860:4860::8888" } }); - EXPECT_EQ(v6{ reply.ip6()->ip6_dst }, v6{ std::string{ "fd00::10" } }); - EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); - EXPECT_EQ(ntohs(reply.udp()->th_dport), client_port); - EXPECT_EQ(reply.payload(), answer); - EXPECT_TRUE(reply.l4_checksum_valid()); + (void)relay.forward(query, 0x0c0c); + + auto reply = relay.answer(relay_answer(v4{ std::string{ "198.51.100.7" } }, 1080, answer, 0x0c0c), "fd00::10"); + ASSERT_TRUE(reply.has_value()); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply->buffer)); + EXPECT_EQ(v6{ reply->ip6()->ip6_src }, v6{ std::string{ "2001:4860:4860::8888" } }); + EXPECT_EQ(v6{ reply->ip6()->ip6_dst }, v6{ std::string{ "fd00::10" } }); + EXPECT_EQ(ntohs(reply->udp()->th_sport), 53); + EXPECT_EQ(ntohs(reply->udp()->th_dport), client_port); + EXPECT_EQ(reply->payload(), answer); + EXPECT_TRUE(reply->l4_checksum_valid()); } // IPv4 query, IPv6 relay header (22 bytes instead of 10). { ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; - proxy::dns_udp_origin_tracker> origins; + dns_relay relay; auto query = frame::udp4("192.168.1.10", "8.8.8.8", client_port, 53, dns_message(0x6363)); - origins.remember(client_port, 0x6363, net::ip_endpoint{ v4{ query.ip4()->ip_dst }, 53 }); ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); - - auto reply = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, - socks5_udp_datagram(v6{ std::string{ "2001:db8::7" } }, 1080, answer)); - const auto [restore, origin] = classify_without_override(reply, origins); - ASSERT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer, origin)); - EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "8.8.8.8" } }); - EXPECT_EQ(ntohs(reply.udp()->th_sport), 53); - EXPECT_EQ(reply.payload(), answer); - EXPECT_TRUE(reply.ip4_checksum_valid()); - EXPECT_TRUE(reply.l4_checksum_valid()); + (void)relay.forward(query, 0x0d0d); + + auto reply = relay.answer(relay_answer(v6{ std::string{ "2001:db8::7" } }, 1080, answer, 0x0d0d), "192.168.1.10"); + ASSERT_TRUE(reply.has_value()); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply->buffer)); + EXPECT_EQ(v4{ reply->ip4()->ip_src }, v4{ std::string{ "8.8.8.8" } }); + EXPECT_EQ(ntohs(reply->udp()->th_sport), 53); + EXPECT_EQ(reply->payload(), answer); + EXPECT_TRUE(reply->ip4_checksum_valid()); + EXPECT_TRUE(reply->l4_checksum_valid()); } } -// A header of the other family is stripped only when the caller supplies the source to present. -// Without it, or when the header is not fully captured, the packet is rejected and left untouched. -TEST(DnsPacketRedirect, OtherFamilyRelayHeaderIsRejectedWithoutASuppliedSourceOrWhenTruncated) +// A listener reply whose SOCKS5 header is of the other family, truncated, or not an IP literal is +// rejected by the redirect and left untouched; the router then drops it. +TEST(DnsPacketRedirect, MalformedListenerRepliesAreRejectedUntouched) { ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; auto query = frame::udp4("192.168.1.10", "8.8.8.8", client_port, 53, dns_message(0x6464)); ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); - const std::optional> queried{ net::ip_endpoint{ v4{ std::string{ "8.8.8.8" } }, 53 } }; - - // Not tracked, so no source is supplied: rejected, as before. - auto unsupplied = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, - socks5_udp_datagram(v6{ std::string{ "2001:db8::7" } }, 1080, dns_message(0x6464))); - const auto unsupplied_before = unsupplied.payload(); - EXPECT_FALSE(redirect.process_server_to_client_packet(unsupplied.buffer)); - EXPECT_EQ(unsupplied.payload(), unsupplied_before); - - // An IPv6 header announced by ATYP but cut short after the 4-byte prefix: rejected even - // with a supplied source, without reading or moving anything past the datagram. - auto truncated = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, - std::vector{ 0x00, 0x00, 0x00, 0x04, 0x20, 0x01, 0x0d, 0xb8 }); - const auto truncated_before = truncated.payload(); - EXPECT_FALSE(redirect.process_server_to_client_packet(truncated.buffer, queried)); - EXPECT_EQ(truncated.payload(), truncated_before); - - // Fewer bytes than the prefix, and an address type that is neither IPv4 nor IPv6. - auto tiny = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, std::vector{ 0x00, 0x00 }); - EXPECT_FALSE(redirect.process_server_to_client_packet(tiny.buffer, queried)); - auto domain = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, - std::vector{ 0x00, 0x00, 0x00, 0x03, 0x01, 'a', 0x00, 0x35, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }); - EXPECT_FALSE(redirect.process_server_to_client_packet(domain.buffer, queried)); + + const std::vector> payloads{ + socks5_udp_datagram(v6{ std::string{ "2001:db8::7" } }, 1080, dns_message(0x6464)), + { 0x00, 0x00, 0x00, 0x04, 0x20, 0x01, 0x0d, 0xb8 }, + { 0x00, 0x00 }, + { 0x00, 0x00, 0x00, 0x03, 0x01, 'a', 0x00, 0x35, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }, + }; + for (const auto& payload : payloads) + { + auto reply = frame::udp4("192.168.1.10", "8.8.8.8", udp_listener, client_port, payload); + const auto before = reply.payload(); + EXPECT_FALSE(redirect.process_server_to_client_packet(reply.buffer)); + EXPECT_EQ(reply.payload(), before); + } } // 8. A datagram that cannot be redirected is reported as such (the router then drops it rather @@ -849,26 +830,25 @@ TEST(DnsPacketRedirect, TruncatedUdpAnswerAndTcpRetryBothGoThroughTheDnsProxy) { ndisapi::socks5_udp_local_redirect udp{ log_level::error }; ndisapi::tcp_local_redirect tcp{ log_level::error }; - proxy::dns_udp_origin_tracker> origins; + dns_relay relay; const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; - // UDP query, redirected with the override. + // UDP query, redirected with the override and sent through the shared association. auto query = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, dns_message(0x5151)); - origins.remember(client_port, 0x5151, net::ip_endpoint{ v4{ query.ip4()->ip_dst }, 53 }); ASSERT_TRUE(udp.is_new_endpoint(query.buffer)); ASSERT_TRUE(udp.process_client_to_server_packet(query.buffer, htons(udp_listener), server_override)); + (void)relay.forward(query, 0x1515); // Truncated answer (TC bit, byte 2 bit 0x02) relayed from the override. auto truncated_answer = dns_message(0x5151, 20); truncated_answer[2] = static_cast(0x80 | 0x02); - auto reply = local_proxy_reply("192.168.1.10", "192.168.1.1", server_override.ip, 53, truncated_answer); - const auto [restore, origin] = classify(reply, server_override, origins); - ASSERT_EQ(restore, proxy::dns_reply_restore::restore); - ASSERT_TRUE(udp.process_server_to_client_packet(reply.buffer, origin)); - EXPECT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); - EXPECT_EQ(reply.payload(), truncated_answer); - EXPECT_EQ(reply.payload()[2] & 0x02, 0x02); - EXPECT_TRUE(reply.l4_checksum_valid()); + auto reply = relay.answer(relay_answer(server_override.ip, 53, truncated_answer, 0x1515), "192.168.1.10"); + ASSERT_TRUE(reply.has_value()); + ASSERT_TRUE(udp.process_server_to_client_packet(reply->buffer)); + EXPECT_EQ(v4{ reply->ip4()->ip_src }, v4{ std::string{ "192.168.1.1" } }); + EXPECT_EQ(reply->payload(), truncated_answer); + EXPECT_EQ(reply->payload()[2] & 0x02, 0x02); + EXPECT_TRUE(reply->l4_checksum_valid()); // The resolver retries over TCP to the same server from a new port. constexpr uint16_t retry_port = client_port + 1; diff --git a/netlib/test/portable/run-portable-tests.sh b/netlib/test/portable/run-portable-tests.sh index 2c3f331..29eaf43 100755 --- a/netlib/test/portable/run-portable-tests.sh +++ b/netlib/test/portable/run-portable-tests.sh @@ -5,6 +5,7 @@ # be exercised on Linux/macOS CI hosts and developer machines. # # * ../proxy/dns_routing_policy_test.cpp - also part of the Windows netlib-tests project +# * ../proxy/dns_udp_multiplexer_test.cpp - also part of the Windows netlib-tests project # * dns_packet_redirect_test.cpp - portable only: compiles the production # tcp_local_redirect.h / socks5_udp_local_redirect.h against winshim/ and the product # CNdisApi checksum routines extracted verbatim from external/ndisapi/ndisapi/ndisapi.cpp @@ -47,6 +48,7 @@ fi "$cxx" "${flags[@]}" -I"$here" -I"$here/winshim" \ "$here/../proxy/dns_routing_policy_test.cpp" \ + "$here/../proxy/dns_udp_multiplexer_test.cpp" \ "$here/dns_packet_redirect_test.cpp" \ "$checksums" \ -lgtest -lgtest_main \ diff --git a/netlib/test/portable/winshim/packet_env.h b/netlib/test/portable/winshim/packet_env.h index 8954403..7bdfe34 100644 --- a/netlib/test/portable/winshim/packet_env.h +++ b/netlib/test/portable/winshim/packet_env.h @@ -22,3 +22,4 @@ #include "../../../src/ndisapi/tcp_local_redirect.h" #include "../../../src/ndisapi/socks5_udp_local_redirect.h" #include "../../../src/proxy/dns_routing_policy.h" +#include "../../../src/proxy/dns_udp_multiplexer.h" diff --git a/netlib/test/portable/winshim/winshim.h b/netlib/test/portable/winshim/winshim.h index a8dc9a4..fc74203 100644 --- a/netlib/test/portable/winshim/winshim.h +++ b/netlib/test/portable/winshim/winshim.h @@ -130,8 +130,8 @@ inline PWSTR RtlIpv6AddressToStringW(const in6_addr*, PWSTR s) { if (s) *s = 0; #define IN6ADDR_LOOPBACK_INIT { { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 } } } // CNdisApi: only the static checksum routines used by the redirect headers. Their definitions -// are extracted verbatim from ndisapi/ndisapi.cpp by run-portable-tests.sh, so the tests run the -// product implementations. +// are extracted verbatim from the ndisapi submodule (external/ndisapi) by run-portable-tests.sh, +// so the tests run the product implementations. struct _INTERMEDIATE_BUFFER; class CNdisApi { diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index ff616ca..bd4f3d4 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -4,8 +4,8 @@ // outbound packet before process attribution: Direct mode passes port-53 traffic, Proxy mode // redirects it to the selected proxy's listener or blocks it (never passes it), ProxiFyre's own // upstream traffic is never captured, and non-DNS traffic keeps its ordinary routing. They also -// cover the DNS server override syntax and the bookkeeping that restores override answers to -// the server the resolver originally queried. +// cover the DNS server override syntax. The shared UDP association's bookkeeping is tested in +// dns_udp_multiplexer_test.cpp. // // The header has no Windows dependencies, so this file also builds outside the Windows test // project (see netlib/test/portable/run-portable-tests.sh). @@ -14,7 +14,6 @@ #include "../../src/proxy/dns_routing_policy.h" #include -#include #include namespace @@ -352,109 +351,6 @@ TEST(DnsMessageId, ReadsTheIdOfACompleteHeaderOnly) EXPECT_FALSE(dns_message_id(nullptr, 64).has_value()); } -namespace -{ - struct endpoint - { - std::string address; - uint16_t port{}; - bool operator==(const endpoint&) const = default; - }; - - using tracker = proxy::dns_udp_origin_tracker; - using clock = tracker::clock; -} - -// 6./7. Answers relayed from the override are mapped back to the original (often private) server -// by client port and DNS message ID. -TEST(DnsUdpOriginTracker, MapsOverrideAnswersToTheOriginalServer) -{ - tracker origins; - const auto now = clock::now(); - - origins.remember(50001, 0x1234, { "192.168.1.1", 53 }, now); - origins.remember(50001, 0x9999, { "10.0.0.53", 53 }, now); - origins.remember(50002, 0x1234, { "fd00::53", 53 }, now); - - EXPECT_EQ(origins.resolve(50001, 0x1234, now), (endpoint{ "192.168.1.1", 53 })); - EXPECT_EQ(origins.resolve(50001, 0x9999, now), (endpoint{ "10.0.0.53", 53 })); - EXPECT_EQ(origins.resolve(50002, 0x1234, now), (endpoint{ "fd00::53", 53 })); - - // Unknown query: no mapping (the router drops such an answer). - EXPECT_FALSE(origins.resolve(50003, 0x1234, now).has_value()); - EXPECT_FALSE(origins.resolve(50001, 0x4321, now).has_value()); - - // A lookup does not consume the entry: duplicate answers to a retransmitted query are - // restored consistently. - EXPECT_EQ(origins.resolve(50001, 0x1234, now), (endpoint{ "192.168.1.1", 53 })); - - // A retransmission to another server with the same port and ID updates the mapping. - origins.remember(50001, 0x1234, { "192.168.1.2", 53 }, now); - EXPECT_EQ(origins.resolve(50001, 0x1234, now), (endpoint{ "192.168.1.2", 53 })); -} - -TEST(DnsUdpOriginTracker, EntriesExpire) -{ - tracker origins{ std::chrono::seconds{ 30 } }; - const auto start = clock::now(); - origins.remember(50001, 1, { "192.168.1.1", 53 }, start); - origins.remember(50002, 2, { "192.168.1.1", 53 }, start + std::chrono::seconds{ 20 }); - - EXPECT_TRUE(origins.resolve(50001, 1, start + std::chrono::seconds{ 30 }).has_value()); - EXPECT_FALSE(origins.resolve(50001, 1, start + std::chrono::seconds{ 31 }).has_value()); - - origins.sweep(start + std::chrono::seconds{ 45 }); - EXPECT_EQ(origins.size(), 1u); - origins.sweep(start + std::chrono::seconds{ 60 }); - EXPECT_EQ(origins.size(), 0u); - - origins.remember(50003, 3, { "192.168.1.1", 53 }, start); - origins.clear(); - EXPECT_EQ(origins.size(), 0u); -} - -TEST(DnsUdpOriginTracker, IsBoundedAndEvictsTheOldestLiveEntry) -{ - tracker origins{ std::chrono::seconds{ 30 }, 3 }; - const auto start = clock::now(); - origins.remember(1, 1, { "a", 53 }, start); - origins.remember(2, 1, { "b", 53 }, start + std::chrono::milliseconds{ 1 }); - origins.remember(3, 1, { "c", 53 }, start + std::chrono::milliseconds{ 2 }); - origins.remember(4, 1, { "d", 53 }, start + std::chrono::milliseconds{ 3 }); - - EXPECT_EQ(origins.size(), 3u); - EXPECT_FALSE(origins.resolve(1, 1, start + std::chrono::milliseconds{ 4 }).has_value()); - EXPECT_TRUE(origins.resolve(4, 1, start + std::chrono::milliseconds{ 4 }).has_value()); - - // Expired entries are reclaimed before a live entry is evicted. - origins.remember(5, 1, { "e", 53 }, start + std::chrono::seconds{ 40 }); - EXPECT_EQ(origins.size(), 1u); -} - -TEST(DnsUdpOriginTracker, IsSafeForConcurrentPacketAndMaintenanceThreads) -{ - tracker origins{ std::chrono::seconds{ 30 }, 4096 }; - std::vector threads; - for (uint16_t t = 0; t < 4; ++t) - { - threads.emplace_back([&origins, t] - { - for (uint16_t i = 0; i < 2000; ++i) - { - const auto port = static_cast(10000 + t * 2000 + i); - origins.remember(port, i, { "server", 53 }); - EXPECT_TRUE(origins.resolve(port, i).has_value()); - if (i % 100 == 0) - origins.sweep(); - } - }); - } - for (auto& thread : threads) - thread.join(); - - EXPECT_LE(origins.size(), 4096u); -} - // 1. Packets sourced from a local proxy listener are re-injected when translated and dropped // otherwise; there is no outcome that passes them to the wire. TEST(ListenerReplyPolicy, UntranslatedListenerRepliesAreDroppedNeverPassed) @@ -625,116 +521,6 @@ TEST(DnsFilterPlan, ListenersThatAreNotRunningGetNoSourcePortFilter) EXPECT_EQ(proxy::plan_dns_filters(proxy_mode, {}).size(), 4u); } -// 9. Listener replies need DNS work (and lock_) in Proxy mode with a usable proxy, whether or not -// a server override is configured: a relay can report another source either way. Direct mode -// and Proxy mode without a usable proxy redirect no DNS and need none. -TEST(DnsReplyRestore, NeededInProxyModeWithAUsableProxy) -{ - using proxy::dns_reply_restore_needed; - EXPECT_TRUE(dns_reply_restore_needed(proxy_mode, true)); - EXPECT_FALSE(dns_reply_restore_needed(proxy_mode, false)); - EXPECT_FALSE(dns_reply_restore_needed(direct, true)); - EXPECT_FALSE(dns_reply_restore_needed(direct, false)); -} - -// A redirected query is tracked whenever it carries a DNS header, with or without a server -// override. One that is too short to carry a header is still redirected without an override -// (as before), and dropped with one, because its answer could never be restored. -TEST(DnsReplyRestore, QueriesAreTrackedWithOrWithoutAnOverride) -{ - using proxy::decide_dns_query_tracking; - using proxy::dns_query_tracking; - EXPECT_EQ(decide_dns_query_tracking(false, true), dns_query_tracking::track); - EXPECT_EQ(decide_dns_query_tracking(true, true), dns_query_tracking::track); - EXPECT_EQ(decide_dns_query_tracking(false, false), dns_query_tracking::untracked); - EXPECT_EQ(decide_dns_query_tracking(true, false), dns_query_tracking::drop); -} - -// 10. Eviction uses insertion order: a refreshed key is not the oldest, the queue of insertion -// records stays bounded under repeated refreshes, and inserting into a full table is cheap. -TEST(DnsUdpOriginTracker, RefreshedKeysAreEvictedByTheirLatestTime) -{ - tracker origins{ std::chrono::seconds{ 30 }, 2 }; - const auto start = clock::now(); - origins.remember(1, 1, { "a", 53 }, start); - origins.remember(2, 1, { "b", 53 }, start + std::chrono::milliseconds{ 1 }); - origins.remember(1, 1, { "a2", 53 }, start + std::chrono::milliseconds{ 2 }); // refresh: now newest - origins.remember(3, 1, { "c", 53 }, start + std::chrono::milliseconds{ 3 }); // evicts key 2 - - const auto at = start + std::chrono::milliseconds{ 4 }; - EXPECT_EQ(origins.resolve(1, 1, at), (endpoint{ "a2", 53 })); - EXPECT_FALSE(origins.resolve(2, 1, at).has_value()); - EXPECT_TRUE(origins.resolve(3, 1, at).has_value()); - EXPECT_EQ(origins.size(), 2u); -} - -TEST(DnsUdpOriginTracker, InsertionRecordsStayBoundedUnderRepeatedRefreshes) -{ - constexpr std::size_t capacity = 64; - tracker origins{ std::chrono::seconds{ 30 }, capacity }; - const auto start = clock::now(); - for (int i = 0; i < 100000; ++i) - origins.remember(static_cast(i % 8), 7, { "x", 53 }, start + std::chrono::microseconds{ i }); - - EXPECT_EQ(origins.size(), 8u); - EXPECT_LE(origins.order_records(), 2 * capacity + 16); - for (uint16_t port = 0; port < 8; ++port) - EXPECT_TRUE(origins.resolve(port, 7, start + std::chrono::seconds{ 1 }).has_value()); -} - -TEST(DnsUdpOriginTracker, InsertingIntoAFullTableOfLiveEntriesDoesBoundedWorkPerInsert) -{ - constexpr std::size_t capacity = 8192; - constexpr uint32_t inserts = 100000; - tracker origins{ std::chrono::seconds{ 30 }, capacity }; - const auto start = clock::now(); - const auto remember = [&](const uint32_t i) - { - origins.remember(static_cast(i >> 16), static_cast(i), { "s", 53 }, - start + std::chrono::microseconds{ i }); - }; - - // Fill the table with live entries (nothing expires within the test's time span). - for (uint32_t i = 0; i < capacity; ++i) - remember(i); - ASSERT_EQ(origins.size(), capacity); - - // Every further insert must evict one live entry. Count the entries and records examined: - // insertion-order eviction examines a constant amortized number per insert, while a sweep or - // a search for the oldest entry examines the whole table (8192) on every insert. - // - // Limitation: visits() counts work done through the tracker's two iteration helpers, which - // every loop over its table and queue uses. The test bounds that counted work; it cannot see a - // raw loop added later that bypasses the helpers. - const auto before = origins.visits(); - for (uint32_t i = capacity; i < capacity + inserts; ++i) - remember(i); - const auto work = origins.visits() - before; - - EXPECT_EQ(origins.size(), capacity); - EXPECT_LE(work, 4ull * inserts) << "entries/records examined per insert: " << double(work) / inserts; - EXPECT_LE(origins.order_records(), 2 * capacity + 16); - // The newest entries survive, the oldest are evicted. - const auto newest = capacity + inserts - 1; - EXPECT_TRUE(origins.resolve(static_cast(newest >> 16), static_cast(newest), start + std::chrono::seconds{ 1 }).has_value()); - EXPECT_FALSE(origins.resolve(0, 0, start + std::chrono::seconds{ 1 }).has_value()); -} - -TEST(DnsUdpOriginTracker, RepeatedRefreshesDoBoundedWork) -{ - constexpr std::size_t capacity = 64; - constexpr int refreshes = 100000; - tracker origins{ std::chrono::seconds{ 30 }, capacity }; - const auto start = clock::now(); - const auto before = origins.visits(); - for (int i = 0; i < refreshes; ++i) - origins.remember(static_cast(i % 8), 7, { "x", 53 }, start + std::chrono::microseconds{ i }); - - // Compaction rebuilds the queue from the 8 live entries only after at least `capacity` - // stale records have accumulated, so its cost is amortized to well under one visit per call. - EXPECT_LE(origins.visits() - before, static_cast(refreshes)); -} - // ------------------------------------------------------------------ listener replies and fragments // // A fragmented listener reply must not reach the wire, and a later fragment's payload must never @@ -797,20 +583,6 @@ TEST(ListenerFragmentPolicy, LaterIpv4FragmentsAreNeverReadForPorts) EXPECT_TRUE(ipv4_transport_header_present(classify_ipv4_fragment(0x0000))); } -TEST(ListenerFragmentPolicy, UdpListenerRepliesAreDroppedOnBothPaths) -{ - using proxy::decide_udp_listener_reply; - using proxy::dns_reply_restore; - using proxy::listener_reply_action; - - EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::unchanged, true), listener_reply_action::revert); - EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::restore, true), listener_reply_action::revert); - EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::unchanged, false), listener_reply_action::drop); - // An override answer to no tracked query is dropped even if it could be translated. - EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::drop, true), listener_reply_action::drop); - EXPECT_EQ(decide_udp_listener_reply(dns_reply_restore::drop, false), listener_reply_action::drop); -} - // Listener segments: translated ones are re-injected; those of a connection that was just reset // are dropped quietly (an expected part of an abort); others are dropped and reported. TEST(ListenerSegmentPolicy, OutcomesMapToRevertQuietDropAndReportedDrop) diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp new file mode 100644 index 0000000..85111c1 --- /dev/null +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -0,0 +1,346 @@ +// Shared SOCKS5 UDP association for the DNS proxy (dns_udp_multiplexer.h). +// +// All UDP DNS queries of one address family go through one SOCKS5 UDP association. These tests +// cover what makes that safe: every query in flight gets a unique, randomly chosen relay ID; +// each answer is mapped back to the client socket, its original ID and the server it queried, +// whatever source or address family the relay reports; unmatched answers are not delivered; +// the table stays bounded; and a failing or silently dead association is reopened without +// churning a working one. +// +// No test reads a clock: time points are constructed explicitly. The header has no Windows +// dependencies, so this file also builds outside the Windows test project (see +// netlib/test/portable/run-portable-tests.sh). + +#include "pch.h" +#include "../../src/proxy/dns_udp_multiplexer.h" + +#include +#include +#include +#include + +namespace +{ + struct test_client + { + uint32_t server{}; + uint16_t port{}; + bool operator==(const test_client& rhs) const { return server == rhs.server && port == rhs.port; } + }; +} + +namespace std +{ + template <> + struct hash + { + std::size_t operator()(const test_client& c) const noexcept + { + return std::hash{}((static_cast(c.server) << 16) | c.port); + } + }; +} + +namespace +{ + using namespace std::chrono_literals; + using time_point = std::chrono::steady_clock::time_point; + using table_t = proxy::dns_query_table; + + const time_point t0{ std::chrono::seconds{ 1000 } }; + + /// Deterministic "random" source returning the given values in order, then repeating the last. + struct scripted_random + { + std::vector values; + std::size_t next{}; + uint16_t operator()() + { + const auto value = values[(std::min)(next, values.size() - 1)]; + ++next; + return value; + } + }; + + /// A SOCKS5 UDP datagram: header for @p address (4 or 16 bytes), port, then @p data. + std::vector socks_datagram(const std::vector& address, const uint16_t port, + const std::vector& data) + { + std::vector d{ 0, 0, 0, static_cast(address.size() == 4 ? 1 : 4) }; + d.insert(d.end(), address.begin(), address.end()); + d.push_back(static_cast(port >> 8)); + d.push_back(static_cast(port & 0xff)); + d.insert(d.end(), data.begin(), data.end()); + return d; + } + + /// A 12-byte DNS header with message ID @p id followed by @p extra bytes of body. + std::vector dns_message(const uint16_t id, const std::vector& extra = {}) + { + std::vector m{ static_cast(id >> 8), static_cast(id & 0xff), + 0x81, 0x80, 0, 1, 0, 1, 0, 0, 0, 0 }; + m.insert(m.end(), extra.begin(), extra.end()); + return m; + } + + const std::vector v4_server{ 192, 168, 1, 1 }; + const std::vector v4_override{ 1, 1, 1, 1 }; + const std::vector v6_relay_source{ 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x35 }; +} + +// --- Wire format ------------------------------------------------------------------------------ + +TEST(DnsUdpMultiplexer, MessageIdIsWrittenInNetworkByteOrder) +{ + std::array id{}; + proxy::set_dns_message_id(id.data(), 0xBEEF); + EXPECT_EQ(id[0], 0xBE); + EXPECT_EQ(id[1], 0xEF); + EXPECT_EQ(proxy::socks5_udp_header_size(1), 10u); + EXPECT_EQ(proxy::socks5_udp_header_size(4), 22u); + EXPECT_EQ(proxy::socks5_udp_header_size(3), 0u); +} + +TEST(DnsUdpMultiplexer, QueryOffsetRequiresTheListenersFamilyAndADnsHeader) +{ + const auto v4 = socks_datagram(v4_server, 53, dns_message(0x1234)); + EXPECT_EQ(proxy::socks5_dns_query_offset(v4.data(), v4.size(), 1), std::optional{ 10 }); + // The IPv6 listener only accepts ATYP 4 headers, and vice versa. + EXPECT_FALSE(proxy::socks5_dns_query_offset(v4.data(), v4.size(), 4)); + + const auto v6 = socks_datagram(v6_relay_source, 53, dns_message(0x1234)); + EXPECT_EQ(proxy::socks5_dns_query_offset(v6.data(), v6.size(), 4), std::optional{ 22 }); + + // Too short to carry a DNS header: cannot be multiplexed. + auto short_query = socks_datagram(v4_server, 53, { 0x12, 0x34, 0, 0 }); + EXPECT_FALSE(proxy::socks5_dns_query_offset(short_query.data(), short_query.size(), 1)); + + // A fragmented SOCKS5 datagram (FRAG != 0) is not accepted. + auto fragmented = v4; + fragmented[2] = 1; + EXPECT_FALSE(proxy::socks5_dns_query_offset(fragmented.data(), fragmented.size(), 1)); +} + +TEST(DnsUdpMultiplexer, ClientAnswerNamesTheQueriedServerAndRestoresTheOriginalId) +{ + // The relay answers from the override, in an IPv6 header, with the relay ID 0x7777. + const std::vector body{ 0xC0, 0x0C, 0x00, 0x01 }; + const auto relayed_bytes = socks_datagram(v6_relay_source, 53, dns_message(0x7777, body)); + const auto relayed = proxy::parse_socks5_udp_datagram(relayed_bytes.data(), relayed_bytes.size()); + ASSERT_TRUE(relayed); + + std::array out{}; + const auto size = proxy::build_dns_client_answer(*relayed, v4_server.data(), v4_server.size(), 53, 0x1234, + out.data(), out.size()); + + const auto expected = socks_datagram(v4_server, 53, dns_message(0x1234, body)); + ASSERT_EQ(size, expected.size()); + EXPECT_TRUE(std::equal(expected.begin(), expected.end(), out.begin())); +} + +TEST(DnsUdpMultiplexer, ClientAnswerIsNotBuiltWhenItCannotBeDelivered) +{ + const auto relayed_bytes = socks_datagram(v4_override, 53, dns_message(0x7777, { 1, 2, 3 })); + const auto relayed = proxy::parse_socks5_udp_datagram(relayed_bytes.data(), relayed_bytes.size()); + ASSERT_TRUE(relayed); + + std::array out{}; + // Output buffer one byte too small. + EXPECT_EQ(proxy::build_dns_client_answer(*relayed, v4_server.data(), 4, 53, 1, out.data(), 10 + 15 - 1), 0u); + EXPECT_EQ(proxy::build_dns_client_answer(*relayed, v4_server.data(), 4, 53, 1, out.data(), 10 + 15), 25u); + // Address size other than 4 or 16. + EXPECT_EQ(proxy::build_dns_client_answer(*relayed, v4_server.data(), 5, 53, 1, out.data(), out.size()), 0u); + + // Data too short for a DNS header. + const auto short_bytes = socks_datagram(v4_override, 53, { 0x77, 0x77 }); + const auto short_view = proxy::parse_socks5_udp_datagram(short_bytes.data(), short_bytes.size()); + ASSERT_TRUE(short_view); + EXPECT_EQ(proxy::build_dns_client_answer(*short_view, v4_server.data(), 4, 53, 1, out.data(), out.size()), 0u); +} + +// --- Query table ------------------------------------------------------------------------------ + +TEST(DnsQueryTable, RelayIdComesFromTheRandomSourceAndMapsBack) +{ + table_t table{ 10s, 1024 }; + scripted_random random{ { 0xA1B2 } }; + const test_client client{ 0xC0A80101, 50000 }; + + const auto relay_id = table.insert(client, 0x1234, t0, random); + ASSERT_EQ(relay_id, std::optional{ 0xA1B2 }); + + const auto pending = table.take(0xA1B2, t0 + 1s); + ASSERT_TRUE(pending); + EXPECT_EQ(pending->client, client); + EXPECT_EQ(pending->original_id, 0x1234); + + // The entry is consumed: a second answer with the same relay ID is not delivered. + EXPECT_FALSE(table.take(0xA1B2, t0 + 1s)); + EXPECT_EQ(table.size(), 0u); +} + +TEST(DnsQueryTable, ClientsWithTheSameMessageIdGetDistinctRelayIds) +{ + // Two sockets (or the same ID to two servers) pick the same message ID; the relay must still + // tell their answers apart. + table_t table{ 10s, 1024 }; + scripted_random random{ { 0x0101, 0x0202 } }; + const test_client a{ 0xC0A80101, 50000 }; + const test_client b{ 0xC0A80101, 50001 }; + + const auto id_a = table.insert(a, 0x1234, t0, random); + const auto id_b = table.insert(b, 0x1234, t0, random); + ASSERT_TRUE(id_a && id_b); + EXPECT_NE(*id_a, *id_b); + EXPECT_EQ(table.take(*id_b, t0)->client, b); + EXPECT_EQ(table.take(*id_a, t0)->client, a); +} + +TEST(DnsQueryTable, RandomCollisionsAreRedrawnAndTheScanFallbackFindsAFreeId) +{ + table_t table{ 10s, 1024 }; + const test_client a{ 1, 1 }; + const test_client b{ 2, 2 }; + const test_client c{ 3, 3 }; + + scripted_random first{ { 0x0500 } }; + ASSERT_EQ(table.insert(a, 1, t0, first), std::optional{ 0x0500 }); + + // The first draw collides, the second is free. + scripted_random second{ { 0x0500, 0x0600 } }; + EXPECT_EQ(table.insert(b, 1, t0, second), std::optional{ 0x0600 }); + + // Every draw collides: the linear scan from the (colliding) start finds the next free ID. + scripted_random stuck{ { 0x0500 } }; + EXPECT_EQ(table.insert(c, 1, t0, stuck), std::optional{ 0x0501 }); +} + +TEST(DnsQueryTable, RetransmissionReusesItsRelayId) +{ + table_t table{ 10s, 1024 }; + scripted_random random{ { 0x1111, 0x2222 } }; + const test_client client{ 0xC0A80101, 50000 }; + + const auto first = table.insert(client, 0xABCD, t0, random); + const auto retransmit = table.insert(client, 0xABCD, t0 + 2s, random); + EXPECT_EQ(first, retransmit); + EXPECT_EQ(table.size(), 1u); + + // The retransmission refreshed the entry: still alive 9 s after it, 11 s after the first. + EXPECT_EQ(table.expire(t0 + 11s), 0u); + EXPECT_TRUE(table.take(*first, t0 + 11s)); +} + +TEST(DnsQueryTable, ExpiredQueriesAreCountedAndNotDelivered) +{ + table_t table{ 10s, 1024 }; + scripted_random random{ { 1, 2, 3 } }; + (void)table.insert({ 1, 1 }, 1, t0, random); + (void)table.insert({ 2, 2 }, 1, t0 + 5s, random); + const auto late = table.insert({ 3, 3 }, 1, t0, random); + + // An answer arriving after the TTL is not delivered, and its entry is removed. + EXPECT_FALSE(table.take(*late, t0 + 11s)); + EXPECT_EQ(table.size(), 2u); + + EXPECT_EQ(table.expire(t0 + 10s), 0u); + EXPECT_EQ(table.expire(t0 + 11s), 1u); + EXPECT_EQ(table.size(), 1u); + EXPECT_EQ(table.expire(t0 + 16s), 1u); + EXPECT_EQ(table.size(), 0u); +} + +TEST(DnsQueryTable, FullTableEvictsTheOldestQuery) +{ + table_t table{ 10s, 3 }; + scripted_random random{ { 10, 20, 30, 40 } }; + (void)table.insert({ 1, 1 }, 1, t0 + 2s, random); + (void)table.insert({ 2, 2 }, 1, t0, random); // oldest + (void)table.insert({ 3, 3 }, 1, t0 + 1s, random); + (void)table.insert({ 4, 4 }, 1, t0 + 3s, random); + + EXPECT_EQ(table.size(), 3u); + EXPECT_FALSE(table.take(20, t0 + 3s)); // evicted + EXPECT_TRUE(table.take(10, t0 + 3s)); + EXPECT_TRUE(table.take(30, t0 + 3s)); + EXPECT_TRUE(table.take(40, t0 + 3s)); + + // An evicted query's retransmission is a new query. + EXPECT_TRUE(table.insert({ 2, 2 }, 1, t0 + 4s, random)); +} + +TEST(DnsQueryTable, ClearForgetsEverythingIncludingRetransmissionIndex) +{ + table_t table{ 10s, 16 }; + scripted_random random{ { 7, 8 } }; + (void)table.insert({ 1, 1 }, 1, t0, random); + table.clear(); + EXPECT_EQ(table.size(), 0u); + EXPECT_FALSE(table.take(7, t0)); + // Not treated as a retransmission of the forgotten query. + EXPECT_EQ(table.insert({ 1, 1 }, 1, t0, random), std::optional{ 8 }); +} + +// --- Association health ----------------------------------------------------------------------- + +TEST(DnsAssociationHealth, FailedOpensBackOffExponentiallyUpTo30Seconds) +{ + proxy::dns_association_health<> health; + EXPECT_TRUE(health.may_open(t0)); + + const std::array expected{ 1s, 2s, 4s, 8s, 16s, 30s, 30s }; + for (const auto delay : expected) + { + health.on_open_failed(t0); + EXPECT_FALSE(health.may_open(t0 + delay - 1ms)); + EXPECT_TRUE(health.may_open(t0 + delay)); + } + + health.on_opened(t0); + EXPECT_EQ(health.consecutive_failures(), 0u); + EXPECT_TRUE(health.may_open(t0)); +} + +TEST(DnsAssociationHealth, SilentAssociationIsReopenedOnlyAfterUnansweredQueriesAndMinimumAge) +{ + proxy::dns_association_health<> health{ 3, 30s }; + health.on_opened(t0); + + EXPECT_FALSE(health.on_unanswered(2, t0 + 40s)); + EXPECT_TRUE(health.on_unanswered(1, t0 + 40s)); +} + +TEST(DnsAssociationHealth, YoungAssociationIsNotChurnedByAResolverThatNeverAnswers) +{ + proxy::dns_association_health<> health{ 3, 30s }; + health.on_opened(t0); + EXPECT_FALSE(health.on_unanswered(10, t0 + 29s)); + // Still no datagram from the relay once old enough: reopen. + EXPECT_TRUE(health.on_unanswered(0, t0 + 30s)); +} + +TEST(DnsAssociationHealth, AnyRelayDatagramResetsTheUnansweredCount) +{ + proxy::dns_association_health<> health{ 3, 30s }; + health.on_opened(t0); + EXPECT_FALSE(health.on_unanswered(2, t0 + 40s)); + health.on_relay_datagram(); + EXPECT_FALSE(health.on_unanswered(2, t0 + 41s)); + EXPECT_TRUE(health.on_unanswered(1, t0 + 42s)); + + // Reopening resets the count and the age. + health.on_opened(t0 + 50s); + EXPECT_FALSE(health.on_unanswered(5, t0 + 60s)); +} + +TEST(DnsQueryTable, InsertDoesNotSilentlyDiscardExpiredQueries) +{ + // Unanswered queries feed the association health check, so they must be counted by + // expire() even when new queries keep arriving. + table_t table{ 10s, 1024 }; + scripted_random random{ { 1, 2 } }; + (void)table.insert({ 1, 1 }, 1, t0, random); + (void)table.insert({ 2, 2 }, 1, t0 + 20s, random); + EXPECT_EQ(table.expire(t0 + 20s), 1u); + EXPECT_EQ(table.size(), 1u); +} diff --git a/socksify/socksify.vcxproj b/socksify/socksify.vcxproj index 85fbf3c..a610fe7 100644 --- a/socksify/socksify.vcxproj +++ b/socksify/socksify.vcxproj @@ -269,6 +269,8 @@ + + diff --git a/socksify/socksify.vcxproj.filters b/socksify/socksify.vcxproj.filters index 082679f..3e5c0ba 100644 --- a/socksify/socksify.vcxproj.filters +++ b/socksify/socksify.vcxproj.filters @@ -144,6 +144,12 @@ Header Files\netlib\proxy + + Header Files\netlib\proxy + + + Header Files\netlib\proxy + Header Files\netlib\proxy diff --git a/socksify/unmanaged.h b/socksify/unmanaged.h index 1169059..bb892c0 100644 --- a/socksify/unmanaged.h +++ b/socksify/unmanaged.h @@ -71,6 +71,7 @@ #include "../netlib/src/proxy/socks5_udp_proxy_socket.h" #include "../netlib/src/proxy/socks5_udp_association.h" #include "../netlib/src/proxy/socks5_local_udp_proxy_server.h" +#include "../netlib/src/proxy/socks5_dns_udp_relay.h" #include "../netlib/src/iphelper/network_adapter_info.h" #include "../netlib/src/iphelper/process_lookup.h" #include "../netlib/src/proxy/socks_local_router.h" From c61763c5cf2cfb46b647d3375f1c2776f07fce0f Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 16:25:15 +0000 Subject: [PATCH 34/62] fix(gui): never turn an unrecognized DNS mode into Direct A configuration with an unrecognized dns.mode was shown as Direct, and editing the server override or proxy then saved "Direct", so a typo the service would have refused to start with became a configuration that sends DNS directly. The mode box now shows no selection for an unrecognized mode, and only a change of the mode box itself writes the mode; validation keeps reporting DNS_MODE_UNKNOWN until a mode is chosen. --- ProxiFyreUI/Forms/MainForm.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/ProxiFyreUI/Forms/MainForm.cs b/ProxiFyreUI/Forms/MainForm.cs index f715a45..7e1d0b9 100644 --- a/ProxiFyreUI/Forms/MainForm.cs +++ b/ProxiFyreUI/Forms/MainForm.cs @@ -243,9 +243,12 @@ private void BindDnsControls() _suppressChanges = true; try { + // An unrecognized mode is shown as no selection, never as Direct: validation reports + // it, and it is only replaced when the user picks a mode (DnsControlChanged). DnsRoutingMode mode; - DnsConfiguration.TryGetMode(dns?.Mode, out mode); - dnsModeComboBox.SelectedIndex = mode == DnsRoutingMode.Proxy ? 1 : 0; + dnsModeComboBox.SelectedIndex = !DnsConfiguration.TryGetMode(dns?.Mode, out mode) + ? -1 + : mode == DnsRoutingMode.Proxy ? 1 : 0; dnsServerOverrideTextBox.Text = dns?.ServerOverride ?? string.Empty; RefreshDnsProxyChoices(); } @@ -308,7 +311,10 @@ private void DnsControlChanged(object sender, EventArgs e) return; var dns = configuration.Dns ?? new DnsSettings(); - dns.Mode = dnsModeComboBox.SelectedIndex == 1 ? DnsConfiguration.ProxyMode : DnsConfiguration.DirectMode; + // Only the mode box changes the mode, so editing another DNS field never turns an + // unrecognized mode into Direct. + if (ReferenceEquals(sender, dnsModeComboBox) && dnsModeComboBox.SelectedIndex >= 0) + dns.Mode = dnsModeComboBox.SelectedIndex == 1 ? DnsConfiguration.ProxyMode : DnsConfiguration.DirectMode; if (ReferenceEquals(sender, dnsProxyComboBox) && dnsProxyComboBox.SelectedItem is DnsProxyChoice choice && choice.Rule != null) From 4aca43ffe8aa204339e9731eb6a56629625fdbb3 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 16:25:46 +0000 Subject: [PATCH 35/62] fix: report throttled DNS and listener drop counts within five seconds The counts are not signalled through the resolver thread's condition variable, so with no deferred packets they were reported only when its 15-second wait timed out, while the documentation says every five seconds. The thread now wakes at least once per report interval; the mapper sweeps keep their own 15-second rate limit. --- netlib/src/proxy/socks_local_router.h | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 4fde8d2..42c19a3 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -3519,9 +3519,15 @@ namespace proxy // Run the source-port mapper sweeps at most once per maintenance interval, // even under heavy resolver activity. The interval is half the TTL so an // entry is evicted within at most 1.5 * TTL of becoming stale, and the - // condition variable below uses the same period as its wait timeout so - // the sweep still runs when the deferred-resolve queue stays empty. + // condition variable below times out at least that often so the sweep + // still runs when the deferred-resolve queue stays empty. constexpr auto maintenance_interval = tcp_mapper_entry_ttl_ / 2; + + // The wait below also bounds how late the throttled DNS and listener drop counts are + // reported: they are not signalled through the condition variable, so wake at least + // once per report interval. + constexpr auto wake_interval = (std::min)(std::chrono::duration_cast(maintenance_interval), + std::chrono::duration_cast(drop_log_throttle_interval_)); auto last_sweep = std::chrono::steady_clock::now(); auto last_drop_log = last_sweep; auto last_dns_block_log = last_sweep; @@ -3540,7 +3546,7 @@ namespace proxy // non-zero until the throttled log path runs and exchanges // them, so waking unconditionally on non-zero counters would // re-fire every iteration until the throttle elapses). - process_resolve_buffer_queue_cv_.wait_for(lock, maintenance_interval, [this, &last_drop_log] { + process_resolve_buffer_queue_cv_.wait_for(lock, wake_interval, [this, &last_drop_log] { if (!process_resolve_buffer_queue_.empty() || resolver_should_exit_.load()) return true; @@ -3631,8 +3637,6 @@ namespace proxy } } } - - // Expire DNS answer-origin mappings for queries that were never answered. } // Report Proxy-mode DNS drops and untranslatable listener replies at the same From 10e0b65755505466261cd85a13a696023e85be7b Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 16:27:57 +0000 Subject: [PATCH 36/62] fix: restart the redirect cleanup threads when the router starts again stop() joins the TCP and UDP redirects' cleanup threads and nothing started them again, so after a stop/start of the same router instance closed, reset and idle entries would never expire. The service starts the router once, so this was latent. start() now restarts them; restart() has no effect while the thread is running. --- .../src/ndisapi/socks5_udp_local_redirect.h | 19 +++++++++++++ netlib/src/ndisapi/tcp_local_redirect.h | 19 +++++++++++++ netlib/src/proxy/socks_local_router.h | 11 ++++++++ .../portable/dns_packet_redirect_test.cpp | 28 +++++++++++++++++++ 4 files changed, 77 insertions(+) diff --git a/netlib/src/ndisapi/socks5_udp_local_redirect.h b/netlib/src/ndisapi/socks5_udp_local_redirect.h index 1f75086..049a1b5 100644 --- a/netlib/src/ndisapi/socks5_udp_local_redirect.h +++ b/netlib/src/ndisapi/socks5_udp_local_redirect.h @@ -698,5 +698,24 @@ namespace ndisapi } } } + + /** + * @brief Restarts the cleanup thread after stop(), for a router that is started again + * in the same process. Without it, expired entries would never be removed. + * @note No effect while the cleanup thread is running. Not to be called concurrently + * with stop(). + */ + void restart() + { + if (bool expected = true; terminate_.compare_exchange_strong(expected, false, std::memory_order_acq_rel)) + start_cleanup_thread(); + } + + /// Whether the cleanup thread is running (it is until stop()). For the thread that + /// calls stop() and restart(). + [[nodiscard]] bool cleanup_running() const noexcept + { + return !terminate_.load(std::memory_order_acquire) && cleanup_thread_.joinable(); + } }; } diff --git a/netlib/src/ndisapi/tcp_local_redirect.h b/netlib/src/ndisapi/tcp_local_redirect.h index a6bfde3..17bc195 100644 --- a/netlib/src/ndisapi/tcp_local_redirect.h +++ b/netlib/src/ndisapi/tcp_local_redirect.h @@ -609,5 +609,24 @@ namespace ndisapi } } } + + /** + * @brief Restarts the cleanup thread after stop(), for a router that is started again + * in the same process. Without it, expired entries would never be removed. + * @note No effect while the cleanup thread is running. Not to be called concurrently + * with stop(). + */ + void restart() + { + if (bool expected = true; terminate_.compare_exchange_strong(expected, false, std::memory_order_acq_rel)) + start_cleanup_thread(); + } + + /// Whether the cleanup thread is running (it is until stop()). For the thread that + /// calls stop() and restart(). + [[nodiscard]] bool cleanup_running() const noexcept + { + return !terminate_.load(std::memory_order_acquire) && cleanup_thread_.joinable(); + } }; } diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 42c19a3..d0a1a2e 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -995,6 +995,17 @@ namespace proxy // Proxy-mode DNS must take precedence over the LAN-bypass PASS filters: (re)install // the front-of-table REDIRECT filters with the current listener ports. If that fails, // fail start() instead of running with DNS able to bypass the policy. + // stop() joined the redirects' cleanup threads; a later start() must run them again + // so expired TCP and UDP entries (including closed and reset connections) are removed. + if (tcp_redirect_) + tcp_redirect_->restart(); + if (udp_redirect_) + udp_redirect_->restart(); + if (tcp_redirect_v6_) + tcp_redirect_v6_->restart(); + if (udp_redirect_v6_) + udp_redirect_v6_->restart(); + start_dns_udp_relays(); dns_blocked_packets_.store(0, std::memory_order_relaxed); untranslated_listener_replies_.store(0, std::memory_order_relaxed); diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index e7e5d49..7a84edf 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -998,3 +998,31 @@ TEST(DnsTcpResetTracking, UnknownConnectionsStillReportUnknown) tcp_redirect4 redirect{ log_level::error }; EXPECT_EQ(listener_segment_result(redirect, TH_ACK), segment_result::unknown); } + +// The router's stop() joins the redirects' cleanup threads, and a later start() in the same +// process restarts them; otherwise closed, reset and idle entries would never expire again. +TEST(RedirectCleanup, CleanupThreadsRestartAfterStop) +{ + ndisapi::tcp_local_redirect tcp{ log_level::error }; + ndisapi::socks5_udp_local_redirect udp{ log_level::error }; + EXPECT_TRUE(tcp.cleanup_running()); + EXPECT_TRUE(udp.cleanup_running()); + + tcp.stop(); + udp.stop(); + EXPECT_FALSE(tcp.cleanup_running()); + EXPECT_FALSE(udp.cleanup_running()); + + tcp.restart(); + udp.restart(); + EXPECT_TRUE(tcp.cleanup_running()); + EXPECT_TRUE(udp.cleanup_running()); + + // Restarting a running redirect has no effect; stop() still joins the one thread. + tcp.restart(); + udp.restart(); + tcp.stop(); + udp.stop(); + EXPECT_FALSE(tcp.cleanup_running()); + EXPECT_FALSE(udp.cleanup_running()); +} From 6cd6f36fb0fbf827e5cbae4d8d8e7ac6d1636c40 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 16:28:20 +0000 Subject: [PATCH 37/62] chore: name the unreachable DNS fallback accurately; drop a dead IPv6 match The fail-closed fallback in handle_dns_udp() and handle_dns_tcp() cannot be reached (decide_dns() returns only pass, block, proxy or defer for port 53, and defer is handled by the caller); it was reported as an unattributable sender and is now reported as a failed redirect. On the IPv6 path the recursion guard compared destinations with the IPv4-mapped form of each SOCKS5 server, which no IPv6 packet carries because mapped addresses leave the host as IPv4; it now says so and returns false. No behavior change. --- netlib/src/proxy/socks_local_router.h | 23 ++++++++++------------- 1 file changed, 10 insertions(+), 13 deletions(-) diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index d0a1a2e..1fe0e2e 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -2287,13 +2287,10 @@ namespace proxy } else { - // Dual-stack IPv6 listeners reach the IPv4 upstream through its IPv4-mapped form. - in6_addr mapped{}; - mapped.u.Byte[10] = 0xff; - mapped.u.Byte[11] = 0xff; - const in_addr v4 = upstream.ip; - memcpy(&mapped.u.Byte[12], &v4, sizeof(v4)); - return destination == net::ip_address_v6{ mapped }; + // SOCKS5 servers are IPv4 (add_socks5_proxy()). IPv6 sockets reach them through + // IPv4-mapped addresses, which leave the host as IPv4 packets, so no IPv6 packet + // is addressed to one. + return false; } }); } @@ -2517,9 +2514,9 @@ namespace proxy if (route.decision.action != dns_route_action::proxy) { - // `defer` is handled by the caller (queued for deferred resolution); anything - // else that is not a redirect must fail closed. - note_dns_block(dns_block_reason::upstream_sender_unknown); + // Unreachable: `defer` is handled by the caller (queued for deferred resolution) + // and decide_dns() returns no other action for port 53. Fail closed regardless. + note_dns_block(dns_block_reason::redirect_failed); return packet_filter::packet_action{ action_type::drop }; } @@ -2584,9 +2581,9 @@ namespace proxy if (route.decision.action != dns_route_action::proxy) { - // `defer` is handled by the caller (queued for deferred resolution); anything - // else that is not a redirect must fail closed. - note_dns_block(dns_block_reason::upstream_sender_unknown); + // Unreachable: `defer` is handled by the caller (queued for deferred resolution) + // and decide_dns() returns no other action for port 53. Fail closed regardless. + note_dns_block(dns_block_reason::redirect_failed); return packet_filter::packet_action{ action_type::drop }; } From 00c54fd0ff2e9cba4f7f1bb12e861018ce313ffb Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 16:32:22 +0000 Subject: [PATCH 38/62] feat: return oversized UDP DNS answers truncated so Windows retries over TCP An answer too large for one unfragmented packet left the DNS relay's listener fragmented, and the first fragment of a listener reply is dropped, so such lookups failed every time and, the answer not being marked truncated, Windows never retried over TCP. The relay now returns an answer larger than fits a 1280-byte packet (the IPv6 minimum MTU) the way a server does when an answer does not fit: TC set, header and question kept, record counts zeroed. The resolver then repeats the query over TCP through the proxy. --- netlib/src/proxy/dns_udp_multiplexer.h | 86 +++++++++++++++- .../portable/dns_packet_redirect_test.cpp | 50 ++++++++++ .../test/proxy/dns_udp_multiplexer_test.cpp | 97 +++++++++++++++++++ 3 files changed, 232 insertions(+), 1 deletion(-) diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index 830bfb8..5febf32 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -54,6 +54,86 @@ namespace proxy return static_cast(view->data - datagram); } + /** + * @brief Largest DNS answer the relay returns over UDP: the size that keeps the listener's + * reply (IP + UDP + SOCKS5 header + answer) within a 1280-byte packet, the IPv6 + * minimum MTU, so it is never fragmented. A fragmented listener reply cannot be + * delivered: its first fragment is dropped. + * @param address_type SOCKS5 ATYP of the listener's family: 1 (IPv4) or 4 (IPv6). + */ + [[nodiscard]] constexpr std::size_t dns_udp_answer_limit(const uint8_t address_type) noexcept + { + constexpr std::size_t minimum_mtu = 1280; + constexpr std::size_t udp_header = 8; + const std::size_t ip_header = address_type == 1 ? 20 : 40; + return minimum_mtu - ip_header - udp_header - socks5_udp_header_size(address_type); + } + + /** + * @brief Truncates a DNS answer larger than @p limit the way a server does when an answer + * does not fit (RFC 1035 section 4.2.1, RFC 7766): the TC bit is set, and only the + * header and question section are kept, so the resolver repeats the query over TCP. + * + * The answer, authority and additional counts are zeroed. If the question section cannot be + * parsed, only the header is kept, with a zero question count. + * + * @return The new size (unchanged when @p size <= @p limit or the message has no header). + */ + [[nodiscard]] constexpr std::size_t truncate_dns_answer(uint8_t* message, const std::size_t size, + const std::size_t limit) noexcept + { + if (message == nullptr || size <= limit || size < dns_header_size) + return size; + + const auto question_count = static_cast((message[4] << 8) | message[5]); + std::size_t end = dns_header_size; + bool parsed = true; + for (std::size_t question = 0; question < question_count && parsed; ++question) + { + // QNAME: labels ending with a zero byte, or a two-byte compression pointer. + while (true) + { + if (end >= size) + { + parsed = false; + break; + } + const auto length = message[end]; + if (length == 0) + { + ++end; + break; + } + if ((length & 0xC0) == 0xC0) + { + end += 2; + break; + } + if ((length & 0xC0) != 0) + { + parsed = false; + break; + } + end += 1 + static_cast(length); + } + end += 4; // QTYPE, QCLASS + if (end > size || end > limit) + parsed = false; + } + + if (!parsed) + { + end = dns_header_size; + message[4] = 0; + message[5] = 0; + } + + message[2] = static_cast(message[2] | 0x02); // TC + for (std::size_t field = 6; field < dns_header_size; ++field) + message[field] = 0; // ANCOUNT, NSCOUNT, ARCOUNT + return end; + } + /** * @brief Builds the datagram the DNS relay returns to a local client from an answer the * SOCKS5 relay delivered. @@ -68,6 +148,9 @@ namespace proxy * @param relayed The relay's datagram, already parsed (parse_socks5_udp_datagram()). * @param server_address Queried server address bytes (network byte order): 4 or 16 bytes. * @param original_id The client's DNS message ID. + * An answer larger than dns_udp_answer_limit() is truncated (truncate_dns_answer()), so the + * resolver retries over TCP instead of receiving a fragmented reply it would never get. + * * @param out Output buffer. * @return Bytes written, or 0 when the answer does not fit, carries no DNS header, or * @p address_size is not 4 or 16. @@ -94,7 +177,8 @@ namespace proxy out[4 + address_size + 1] = static_cast(server_port & 0xff); std::memmove(out + header_size, relayed.data, relayed.data_size); set_dns_message_id(out + header_size, original_id); - return header_size + relayed.data_size; + return header_size + truncate_dns_answer(out + header_size, relayed.data_size, + dns_udp_answer_limit(address_type)); } /** diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index 7a84edf..9a06a70 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -1026,3 +1026,53 @@ TEST(RedirectCleanup, CleanupThreadsRestartAfterStop) EXPECT_FALSE(tcp.cleanup_running()); EXPECT_FALSE(udp.cleanup_running()); } + +// 12. A UDP answer too large for one unfragmented 1280-byte packet would leave the DNS relay's +// listener fragmented, and the first fragment of a listener reply is never delivered. The +// relay returns it truncated instead (TC set, question kept), within the limit, so the +// resolver retries over TCP through the proxy. +TEST(DnsPacketRedirect, OversizedUdpAnswerIsDeliveredTruncatedSoTheResolverRetriesOverTcp) +{ + for (const bool ipv6 : { false, true }) + { + std::vector big{ 0x2b, 0x2b, 0x81, 0x80, 0, 1, 0, 40, 0, 0, 0, 0, + 7, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 3, 'c', 'o', 'm', 0, 0, 1, 0, 1 }; + big.resize(1400, 0x5a); + + std::optional reply; + if (!ipv6) + { + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + dns_relay relay; + auto query = frame::udp4("192.168.1.10", "8.8.8.8", client_port, 53, dns_message(0x2b2b)); + ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); + (void)relay.forward(query, 0x0e0e); + reply = relay.answer(relay_answer(v4{ std::string{ "8.8.8.8" } }, 53, big, 0x0e0e), "192.168.1.10"); + ASSERT_TRUE(reply.has_value()); + EXPECT_LE(ntohs(reply->ip4()->ip_len), 1280); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply->buffer)); + EXPECT_TRUE(reply->ip4_checksum_valid()); + } + else + { + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + dns_relay relay; + auto query = frame::udp6("fd00::10", "2001:4860:4860::8888", client_port, 53, dns_message(0x2b2b)); + ASSERT_TRUE(redirect.is_new_endpoint(query.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(query.buffer, htons(udp_listener))); + (void)relay.forward(query, 0x0e0e); + reply = relay.answer(relay_answer(v6{ std::string{ "2001:4860:4860::8888" } }, 53, big, 0x0e0e), "fd00::10"); + ASSERT_TRUE(reply.has_value()); + EXPECT_LE(sizeof(ipv6hdr) + ntohs(reply->ip6()->ip6_len), 1280u); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply->buffer)); + } + + const auto payload = reply->payload(); + ASSERT_EQ(payload.size(), 12u + 17u) << ipv6; + EXPECT_EQ(proxy::dns_message_id(payload.data(), payload.size()), std::optional{ 0x2b2b }); + EXPECT_EQ(payload[2] & 0x02, 0x02); + EXPECT_EQ(ntohs(reply->udp()->th_sport), 53); + EXPECT_TRUE(reply->l4_checksum_valid()); + } +} diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index 85111c1..d6bb5f6 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -344,3 +344,100 @@ TEST(DnsQueryTable, InsertDoesNotSilentlyDiscardExpiredQueries) EXPECT_EQ(table.expire(t0 + 20s), 1u); EXPECT_EQ(table.size(), 1u); } + +// --- Answers too large for one unfragmented packet --------------------------------------------- + +namespace +{ + /// A DNS answer for "example.com" A with @p answer_bytes bytes of answer records. + std::vector large_answer(const uint16_t id, const std::size_t answer_bytes) + { + std::vector m{ static_cast(id >> 8), static_cast(id & 0xff), + 0x81, 0x80, 0, 1, 0, 9, 0, 1, 0, 2 }; + const std::vector question{ 7, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 3, 'c', 'o', 'm', 0, 0, 1, 0, 1 }; + m.insert(m.end(), question.begin(), question.end()); + m.insert(m.end(), answer_bytes, 0x5a); + return m; + } +} + +TEST(DnsAnswerTruncation, LimitKeepsTheListenerReplyWithinTheMinimumMtu) +{ + // 1280 bytes = IP + UDP (8) + SOCKS5 header + DNS answer. + EXPECT_EQ(proxy::dns_udp_answer_limit(1), 1280u - 20 - 8 - 10); + EXPECT_EQ(proxy::dns_udp_answer_limit(4), 1280u - 40 - 8 - 22); +} + +TEST(DnsAnswerTruncation, AnswersWithinTheLimitAreUnchanged) +{ + auto answer = large_answer(0x1234, 100); + const auto original = answer; + EXPECT_EQ(proxy::truncate_dns_answer(answer.data(), answer.size(), answer.size()), answer.size()); + EXPECT_EQ(answer, original); +} + +TEST(DnsAnswerTruncation, LargeAnswerKeepsHeaderAndQuestionWithTheTcBit) +{ + auto answer = large_answer(0x1234, 2000); + const auto size = proxy::truncate_dns_answer(answer.data(), answer.size(), 1242); + + ASSERT_EQ(size, 12u + 17u); + EXPECT_EQ(answer[0], 0x12); + EXPECT_EQ(answer[1], 0x34); + EXPECT_EQ(answer[2], 0x81 | 0x02); // QR, RD kept; TC set + EXPECT_EQ(answer[3], 0x80); + EXPECT_EQ(answer[4], 0); // QDCOUNT 1 kept + EXPECT_EQ(answer[5], 1); + for (std::size_t i = 6; i < 12; ++i) + EXPECT_EQ(answer[i], 0) << i; // ANCOUNT, NSCOUNT, ARCOUNT zeroed + const std::vector question(answer.begin() + 12, answer.begin() + static_cast(size)); + EXPECT_EQ(question, (std::vector{ 7, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 3, 'c', 'o', 'm', 0, 0, 1, 0, 1 })); +} + +TEST(DnsAnswerTruncation, CompressedQuestionNameIsKept) +{ + std::vector answer{ 0, 1, 0x81, 0x80, 0, 1, 0, 1, 0, 0, 0, 0, 0xC0, 0x0C, 0, 1, 0, 1 }; + answer.insert(answer.end(), 2000, 0x5a); + EXPECT_EQ(proxy::truncate_dns_answer(answer.data(), answer.size(), 1242), 12u + 6u); + EXPECT_EQ(answer[5], 1); +} + +TEST(DnsAnswerTruncation, UnparsableQuestionLeavesOnlyTheHeader) +{ + // A label length that runs past the end of the message, and a reserved label type (0x80). + for (const uint8_t bad_label : { uint8_t{ 0x3f }, uint8_t{ 0x80 } }) + { + std::vector answer{ 0, 1, 0x81, 0x80, 0, 1, 0, 1, 0, 0, 0, 0, bad_label }; + answer.resize(bad_label == 0x3f ? 40 : 2000, 0x5a); + answer[12] = bad_label; + const auto limit = std::size_t{ 30 }; + const auto size = proxy::truncate_dns_answer(answer.data(), answer.size(), limit); + EXPECT_EQ(size, 12u) << int{ bad_label }; + EXPECT_EQ(answer[2] & 0x02, 0x02); + EXPECT_EQ(answer[4], 0); + EXPECT_EQ(answer[5], 0); + } +} + +TEST(DnsAnswerTruncation, ClientAnswerIsTruncatedToTheListenersLimit) +{ + const auto big = large_answer(0x7777, 1500); + const auto relayed_bytes = socks_datagram(v4_override, 53, big); + const auto relayed = proxy::parse_socks5_udp_datagram(relayed_bytes.data(), relayed_bytes.size()); + ASSERT_TRUE(relayed); + + std::vector out(4096); + const auto size = proxy::build_dns_client_answer(*relayed, v4_server.data(), 4, 53, 0x1234, out.data(), out.size()); + ASSERT_EQ(size, 10u + 12u + 17u); + EXPECT_EQ(out[10], 0x12); // original ID restored + EXPECT_EQ(out[11], 0x34); + EXPECT_EQ(out[12] & 0x02, 0x02); // TC set + + // An answer that fits is delivered whole. + const auto fits = large_answer(0x7777, proxy::dns_udp_answer_limit(1) - 12 - 17); + const auto fits_bytes = socks_datagram(v4_override, 53, fits); + const auto fits_view = proxy::parse_socks5_udp_datagram(fits_bytes.data(), fits_bytes.size()); + ASSERT_TRUE(fits_view); + EXPECT_EQ(proxy::build_dns_client_answer(*fits_view, v4_server.data(), 4, 53, 1, out.data(), out.size()), + 10u + proxy::dns_udp_answer_limit(1)); +} From 371992b6740656ec104c7607740ac1c2d411ed1a Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 16:33:42 +0000 Subject: [PATCH 39/62] docs: describe the shared UDP DNS association and truncated large answers docs/configuration.md gains a "Shared UDP association" section: one control connection and UDP ASSOCIATE per address family, relay message IDs, answers presented from the queried server, truncation of answers that do not fit an unfragmented 1280-byte packet, opening and reopening with backoff, and logging. The listener-reply rule, the server override, the recursion guard and the limitations are updated to match: the per-query handshake limitation is replaced by the shared source port and the queries lost on a reopen. README.md no longer says flatly that DNS is never sent directly and links to the limitations. The Windows checklist covers the association count, recovery after a SOCKS5 restart, truncated large answers and parallel lookups. netlib/README.md lists the new test suite. --- README.md | 2 +- docs/configuration.md | 37 ++++++++++++++++++++++++------------- docs/gui.md | 8 ++++---- netlib/README.md | 15 ++++++++++----- 4 files changed, 39 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 0349c8b..19c48ad 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ DNS (UDP/TCP port 53) bypasses the proxies by default. To prevent DNS leaks, giv "dns": { "mode": "Proxy", "proxyId": "office", "serverOverride": "1.1.1.1" } ``` -In `Proxy` mode DNS is never sent directly: if the selected proxy cannot carry a query, the query is dropped. See [DNS routing](docs/configuration.md#dns-routing) for the behavior and limitations. +In `Proxy` mode DNS is not sent directly: if the selected proxy cannot carry a query, the query is dropped. UDP DNS shares one SOCKS5 association per address family. The few exceptions, such as later fragments and other packets that cannot be classified as DNS, are listed under [DNS routing limitations](docs/configuration.md#limitations). > [!IMPORTANT] > **Upgrade note — DNS over TCP port 53.** In the default `Direct` DNS mode, which also applies to existing configurations without a `dns` section, DNS over TCP port 53 now always bypasses the proxies, as DNS over UDP port 53 already did. Rules that previously carried TCP port 53 through a proxy, for example a catch-all rule, no longer do so. To route DNS through a proxy, use DNS `Proxy` mode. diff --git a/docs/configuration.md b/docs/configuration.md index c619305..7d1901f 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -134,7 +134,7 @@ In DNS `Proxy` mode, DNS takes precedence over LAN bypass: a query addressed to ProxiFyre redirects a matched connection to a local listener and translates the listener's replies back before the application sees them. Two rules apply to every proxied connection, not only to DNS: -- **A reply that cannot be translated back is dropped.** A reply from a local listener is addressed to the original server only because redirection swapped the addresses, so it must never reach the network. It is dropped when its TCP connection or UDP endpoint is no longer tracked, when it is the first fragment of a fragmented reply, when its SOCKS5 relay header is malformed, when that header is of the other address family and the reply does not answer an outstanding DNS query, or, with a DNS `serverOverride`, when it names the override server but answers no outstanding query. Earlier releases passed such packets toward the original server. The first such drop after the service starts is logged once as a warning, and a count is logged at `Info` level at most every five seconds while drops continue. Later fragments of a fragmented reply carry no ports, cannot be attributed to a listener, and are still passed. +- **A reply that cannot be translated back is dropped.** A reply from a local listener is addressed to the original server only because redirection swapped the addresses, so it must never reach the network. It is dropped when its TCP connection or UDP endpoint is no longer tracked, when it is the first fragment of a fragmented reply, or when its SOCKS5 relay header is malformed or of the other address family. Earlier releases passed such packets toward the original server. The first such drop after the service starts is logged once as a warning, and a count is logged at `Info` level at most every five seconds while drops continue. Later fragments of a fragmented reply carry no ports, cannot be attributed to a listener, and are still passed. - **A TCP connection is tracked through its whole close.** The FIN/ACK exchange is translated in both directions instead of reaching the real server. A reset (RST) ends the connection immediately; segments the local proxy had already sent when the reset arrived are dropped without the warning and are counted at `Debug` level only. A proxied TCP connection that stays idle for more than 5 minutes loses its redirect entry; see [Limitations](#limitations). @@ -159,41 +159,51 @@ UDP and TCP DNS to port 53 bypass every SOCKS5 proxy for both address families, ### Proxy mode -All captured UDP and TCP DNS is sent through the selected proxy: UDP through a SOCKS5 `UDP ASSOCIATE`, TCP through a SOCKS5 `CONNECT`, reusing the same engine paths as application traffic. Queries from the Windows DNS Client service and from applications with their own resolvers are treated the same. +All captured UDP and TCP DNS is sent through the selected proxy. Queries from the Windows DNS Client service and from applications with their own resolvers are treated the same. + +- **UDP** goes through one SOCKS5 control connection and one `UDP ASSOCIATE` per address family, shared by every query (see [Shared UDP association](#shared-udp-association)). +- **TCP** goes through a SOCKS5 `CONNECT` per connection, the same path as application TCP traffic. ProxiFyre never falls back to sending DNS directly. The DNS policy itself drops a query when: - the selected proxy could not be created at startup, or the configuration is rejected by the engine; - the proxy does not accept the destination's address family (for example IPv6 DNS with an IPv4-only rule); - a `serverOverride` is configured and the query is addressed to a server of the other address family (an IPv4 override blocks queries to IPv6 servers and vice versa); -- the packet cannot be redirected, such as a TCP connection to port 53 that was opened before ProxiFyre started, a datagram too large to carry the SOCKS5 UDP header, or, with a `serverOverride`, a datagram too short to carry a DNS header; +- the packet cannot be redirected, such as a TCP connection to port 53 that was opened before ProxiFyre started, or a datagram too large to carry the SOCKS5 UDP header; +- a UDP datagram is too short to carry a DNS header (12 bytes): the shared association tells answers apart by DNS message ID, so it cannot be relayed; - the datagram is fragmented. Only the first fragment carries the UDP or TCP header, so only a first fragment (IPv4 or IPv6) addressed to port 53 can be recognized as DNS; it is dropped, which also prevents the datagram from being reassembled at the server. Later fragments carry no ports, cannot be classified, and are passed unchanged, so other fragmented traffic is not affected. In `Direct` mode fragmented DNS is passed like any other DNS; or - it is addressed to a configured SOCKS5 server and its sending process cannot be determined (see [Recursion and ProxiFyre's own traffic](#recursion-and-proxifyres-own-traffic)). For these drops the engine logs one warning per cause, address family, and transport, followed by a count of dropped packets at most every five seconds. -A query can also fail after it has been redirected to the DNS proxy's local listener: the SOCKS5 connection, authentication, TLS handshake, or `UDP ASSOCIATE` fails, or the proxy disconnects. The query is then not sent directly either, but these failures are reported by the local proxy server in the same way as for application traffic, not by the DNS policy's warnings and counts. +A query can also fail after it has been redirected to the DNS proxy's local listener: the SOCKS5 connection, authentication, TLS handshake, or `UDP ASSOCIATE` fails, or the proxy disconnects. The query is then not sent directly either. For TCP these failures are reported by the local proxy server in the same way as for application traffic; for UDP, see [Shared UDP association](#shared-udp-association). Whether name resolution still succeeds after a drop depends on Windows: it retries, and may try its other configured DNS servers, but ProxiFyre does not control that. Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. -For UDP, ProxiFyre remembers the server each redirected query was addressed to (by client port and DNS message ID, for 30 seconds) and presents the answer as coming from that server, whatever source address the SOCKS5 relay reports for it, IPv4 or IPv6, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered, but some report another address, such as their own. This applies with or without a `serverOverride`. Two consequences follow from matching on the client port and message ID alone: +If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. + +The selection is made by `proxyId`, never by position, so reordering rules does not change the DNS proxy. If the referenced rule is removed or renamed, validation fails with `DNS_PROXY_NOT_FOUND`; ProxiFyre never silently switches to another proxy. The GUI assigns an id such as `proxy-1` to a rule when it is selected as the DNS proxy, and clears the id on a duplicated copy. -- If one socket sends the same message ID to several servers, the answer is presented as coming from the server queried last. -- A datagram that is not a DNS answer is given a DNS server's address by mistake only if it arrives for a client port that sent a port-53 datagram in the last 30 seconds and its first two bytes equal that datagram's message ID. +### Shared UDP association -Datagrams relayed through the same proxy that match no outstanding query are delivered with the source the relay reports. Two kinds are dropped instead: one that names the `serverOverride` server (see [Server override](#server-override)), and one whose relay header is of the other address family, such as an answer that arrives after its query's 30 seconds from a relay that reports its own IPv4 address for an IPv6 query. +UDP DNS of each address family goes through a single SOCKS5 control connection and `UDP ASSOCIATE`, however many processes and source ports send queries. Only the first query, and the first after the association is reopened, waits for the SOCKS5 handshake (and, with `TLS` transport, the TLS handshake). -If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. +- **Matching answers to queries.** While a query is in flight, its DNS message ID is replaced by a unique, randomly chosen ID. The answer carrying that ID is returned to the socket that asked, with the socket's own message ID. A retransmission from the same socket reuses the ID. Up to 4,096 queries can be in flight; a query without an answer is forgotten after 10 seconds, and an answer that matches no query in flight is dropped. +- **Source of the answer.** The answer is presented as coming from the server Windows queried, whatever source address (IPv4 or IPv6) the SOCKS5 relay reports, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered (the `serverOverride` server when one is set); some report their own address. This applies with or without a `serverOverride`. +- **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. +- **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it. It is closed and reopened on the next query when its control connection closes, its relay socket fails, or it looks silently dead: three queries in a row went unanswered while nothing arrived from the relay, and it has been open for at least 30 seconds. Queries in flight at that moment are lost, and Windows retries them. +- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. +- **Logging.** The first failure to open the association is logged as a warning and later failures at `Debug`; closing and reopening are logged at `Info`. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds. -The selection is made by `proxyId`, never by position, so reordering rules does not change the DNS proxy. If the referenced rule is removed or renamed, validation fails with `DNS_PROXY_NOT_FOUND`; ProxiFyre never silently switches to another proxy. The GUI assigns an id such as `proxy-1` to a rule when it is selected as the DNS proxy, and clears the id on a duplicated copy. +The local listener accepts only datagrams from source ports ProxiFyre has just redirected there, so it cannot be used to send arbitrary UDP through the proxy. ### Server override Without `serverOverride`, each query keeps its original destination: the SOCKS5 server is asked to reach the DNS server Windows queried. That fails when Windows uses a local resolver, such as a home router at `192.168.1.1`, which the remote SOCKS5 server cannot reach. Set `serverOverride` to a resolver that is reachable from the SOCKS5 server, such as `1.1.1.1`. -With an override, only the SOCKS5 destination changes: the `UDP ASSOCIATE` datagram header or the `CONNECT` target names the override, while the packets the application sees keep the original server address. A UDP answer is restored to the server the resolver queried as described under [Proxy mode](#proxy-mode); an RFC 1928 relay reports the override server as its source. A datagram that names the override server but matches no outstanding query is dropped; other datagrams relayed through the same proxy are delivered unchanged. Checksums are recalculated on every rewritten packet. +With an override, only the SOCKS5 destination changes: the `UDP ASSOCIATE` datagram header or the `CONNECT` target names the override, while the packets the application sees keep the original server address. A UDP answer comes back from the override server and is presented as coming from the server the resolver queried (see [Shared UDP association](#shared-udp-association)). Checksums are recalculated on every rewritten packet. ### Examples @@ -220,7 +230,7 @@ Proxy with an IPv4 override for a configuration that uses a router-provided reso SOCKS5 endpoint host names are resolved once while the configuration is loaded, before packet filtering starts, so that lookup is never captured. ProxiFyre's own traffic to a configured SOCKS5 server is never redirected into the DNS proxy, even if it is addressed to port 53, while queries from any other process to a host that is both a SOCKS5 server and a resolver follow the DNS policy like any other query, including `serverOverride`: - **TCP:** ProxiFyre connects to a SOCKS5 server only on its configured port. A TCP packet to port 53 of a SOCKS5 server is therefore a candidate for ProxiFyre's own traffic only when that server is configured on port 53, and it is exempt only when its sending process is ProxiFyre itself. -- **UDP:** the only ProxiFyre UDP traffic to a SOCKS5 server's address that can reach this check goes to the UDP relay endpoint the server returns for `UDP ASSOCIATE`. (Replies from ProxiFyre's local UDP listeners can also be addressed to a SOCKS5 server's host, but they are handled as listener replies before any DNS decision and are never passed.) Unless a server has returned a relay on port 53, no UDP packet to port 53 of a SOCKS5 server can be ProxiFyre's own, so all of them follow the DNS policy with no sender check. Once a relay on port 53 has been seen (logged once at Info), such a packet is exempt only when its sending process is ProxiFyre itself. +- **UDP:** the only ProxiFyre UDP traffic to a SOCKS5 server's address that can reach this check goes to the UDP relay endpoints the server returns for `UDP ASSOCIATE`, both for application UDP and for the DNS proxy's shared association. (Replies from ProxiFyre's local UDP listeners can also be addressed to a SOCKS5 server's host, but they are handled as listener replies before any DNS decision and are never passed.) Unless a server has returned a relay on port 53, no UDP packet to port 53 of a SOCKS5 server can be ProxiFyre's own, so all of them follow the DNS policy with no sender check. Once a relay on port 53 has been seen (logged once at Info), such a packet is exempt only when its sending process is ProxiFyre itself. When a sender check is needed and the sender cannot be determined, even after the connection table is refreshed, the packet is dropped rather than passed or redirected. Senders that typically cannot be determined include traffic that Windows forwards on behalf of virtual machines or containers (for example through Hyper-V, WSL, or Internet Connection Sharing), which has no owning local process, and sockets owned by the kernel or by drivers rather than by a user-mode process. @@ -231,7 +241,8 @@ The sender is taken from ProxiFyre's cached copy of the Windows connection table - Only conventional DNS on port 53 is affected. DNS over HTTPS, DNS over TLS, DNS over QUIC, mDNS (5353), and LLMNR (5355) are outside the scope of this feature; applications that resolve names internally over encrypted transports (for example browsers with secure DNS enabled) are routed according to their ordinary application rules. - ProxiFyre does not change Windows DNS adapter settings, does not disable or reconfigure the DNS Client service, and does not run its own resolver or cache. Answers already cached by Windows before the service started or before `Proxy` mode was enabled are still served from that cache; run `ipconfig /flushdns` after switching modes for an immediate effect. - Only traffic visible to the Windows Packet Filter layer is captured. Loopback and local resolvers (for example a resolver on `127.0.0.1` or `::1`, or a resolver inside a local VM or container reached through a virtual adapter that is not filtered) are not routed, and their own upstream queries are subject to the same policy only if they leave through a filtered adapter. -- Each new UDP source port needs its own SOCKS5 control connection and `UDP ASSOCIATE`, as for application UDP traffic. The Windows DNS Client uses a fresh source port for most queries, so the first answer through the proxy is delayed by the SOCKS5 (and, for `TLS`, the TLS) handshake. +- All UDP DNS of one address family leaves the SOCKS5 server's relay from the same source port, so the per-query source port randomization Windows applies does not extend beyond the proxy. Between the SOCKS5 server and the DNS server, forged answers are guarded against by the random 16-bit message ID ProxiFyre assigns (and by the relay, if it accepts answers only from the servers it was asked to reach). +- Queries in flight when the shared UDP association is reopened are lost; Windows retries them. - When the service is stopped, packet filtering stops and all traffic, including DNS, is direct. - UDP sent to a broadcast or multicast link-layer address is passed before the DNS policy is applied, as it is for application traffic, so a port-53 datagram addressed to a broadcast or multicast address is not proxied. Conventional DNS is unicast. - An IPv6 packet whose extension-header chain ProxiFyre cannot walk to a UDP or TCP header (for example one protected by AH or ESP, or a truncated chain) is passed without being classified. diff --git a/docs/gui.md b/docs/gui.md index ec7ad79..a3e1aed 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -162,18 +162,18 @@ On a Windows test machine with the appropriate driver and administrator access: The routing policy and the packet rewriting are covered by automated tests (`netlib-tests` and `netlib/test/portable/run-portable-tests.sh`); the end-to-end path through the driver and a live SOCKS5 server needs a Windows test machine. Capture with Wireshark on the physical adapter and use `Resolve-DnsName -Server -DnsOnly` (UDP) and `Resolve-DnsName -TcpOnly` (TCP), running `ipconfig /flushdns` before each step: 1. With no `dns` section (or `Direct`), confirm UDP and TCP queries to the system resolver and to `8.8.8.8` leave the adapter directly for IPv4 and IPv6, including with a catch-all rule. -2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). +2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). Browse for a few minutes and confirm the SOCKS5 server sees one control connection and one `UDP ASSOCIATE` per address family for UDP DNS, not one per query. 3. Enable `bypassLan` with a router resolver (`192.168.x.1`): without an override the SOCKS5 server is asked for the router address; with `serverOverride: "1.1.1.1"` it is asked for `1.1.1.1` and `Resolve-DnsName` still reports answers from the router address. 4. Reorder the rules, Apply & Restart, and confirm DNS still uses the selected proxy. -5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log reports the SOCKS5 connection or `UDP ASSOCIATE` failures from the local proxy server. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. +5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning, and attempts back off to one every 30 seconds. Start the SOCKS5 server again and confirm lookups recover within 30 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" at `Info`) and lookups recover. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. 6. Configure an IPv4 override with an IPv6 resolver and confirm IPv6 queries are dropped while IPv4 queries succeed. 7. **Upgrade.** With a configuration from an earlier release (no `dns` section, a catch-all rule), confirm that `Resolve-DnsName -TcpOnly` now leaves the adapter directly, that UDP DNS still does, and that the rule's other traffic is still proxied. 8. **Restart.** With `Proxy` mode and `bypassLan`, use **Apply & Restart** (or stop and start the service) and repeat step 3: DNS to the router resolver must still be proxied. 9. **DNS proxy unavailable at start.** Give the DNS proxy rule an endpoint that cannot be created (for example a host name that does not resolve) and start the service. Confirm the service starts, the log states that all DNS is blocked until the service is restarted, and no port-53 packet leaves the adapter. 10. **TCP close.** Run `Resolve-DnsName -TcpOnly` several times in `Proxy` mode. Confirm each lookup completes, that no FIN, ACK, or RST of those connections reaches the real DNS server, and that the log has no "dropped … DNS packet(s)" lines. 11. **Aborted connection.** Start a large download in a proxied application and cancel it. Confirm no segment from the local listener's port leaves the adapter and that the log has no "could not be translated back" warning. -12. **Large answer.** In `Proxy` mode request a UDP answer larger than about 1,460 bytes over IPv4, and larger than about 1,430 bytes over IPv6, from a DNS server that sends UDP answers of that size (most public resolvers truncate them instead). `Resolve-DnsName` cannot request this; use a tool that sets the EDNS buffer size, such as BIND's `dig +dnssec +bufsize=4096 +ignore DNSKEY @`, which is not part of Windows. Confirm the first fragment of the local listener's reply (the one that carries a UDP header from the listener's port) does not leave the adapter. The listener-reply warning is logged if it has not been logged since the service started; otherwise only the `Info` count increases. Later fragments may leave, and the UDP lookup itself is expected to fail. -13. **Relay source.** If the SOCKS5 server reports an address other than the queried DNS server as the source of UDP replies (for example its own IPv4 address), confirm lookups succeed without and with `serverOverride`, to an IPv4 resolver and to an IPv6 resolver. +12. **Large answer.** In `Proxy` mode request a UDP answer larger than about 1,200 bytes, over IPv4 and over IPv6, from a DNS server that sends UDP answers of that size (most public resolvers truncate them instead). Use a tool that sets the EDNS buffer size, such as BIND's `dig +dnssec +bufsize=4096 DNSKEY @`, which is not part of Windows. Confirm the answer arrives truncated (the `tc` flag) and unfragmented, that `dig` then retries over TCP through the proxy and succeeds, and that no listener-reply warning is logged. +13. **Relay source and shared IDs.** If the SOCKS5 server reports an address other than the queried DNS server as the source of UDP replies (for example its own IPv4 address), confirm lookups succeed without and with `serverOverride`, to an IPv4 resolver and to an IPv6 resolver. Run many lookups in parallel (for example `1..200 | ForEach-Object -Parallel { Resolve-DnsName "host$_.example.com" -DnsOnly -ErrorAction SilentlyContinue }` in PowerShell 7) and confirm each one gets its own answer. 14. **SOCKS5 server used as a resolver.** Send a lookup to the SOCKS5 server's own IP address (`Resolve-DnsName example.com -Server -DnsOnly`). Confirm the query goes through the proxy, not directly. If the server listens on TCP port 53 or returns a UDP relay on port 53, also confirm ProxiFyre still reaches it and the one-time `Info` line about the relay appears. 15. **Limited mode.** Repeat step 2 in the optional unelevated console mode. 16. **GUI.** On the **Settings / Diagnostics** tab at 100% and 150% scaling, confirm the DNS routing group and the Uninstall button are reachable (scrolling is expected). Confirm Alt+M, Alt+P, and Alt+S focus the mode, proxy, and override fields; that the DNS proxy selection survives **Move Up**/**Move Down** and a reload; that **Duplicate** does not copy the id; and that removing the selected rule shows the missing id and fails validation. diff --git a/netlib/README.md b/netlib/README.md index 3c21e44..342fa91 100644 --- a/netlib/README.md +++ b/netlib/README.md @@ -101,13 +101,18 @@ SANITIZE=1 netlib/test/portable/run-portable-tests.sh # AddressSanitizer + Und CXX=clang++ netlib/test/portable/run-portable-tests.sh ``` -- `netlib/test/proxy/dns_routing_policy_test.cpp` covers the global DNS routing decisions, - DNS server override syntax, and the override answer bookkeeping (`dns_routing_policy.h`). It is - also part of `netlib-tests` on Windows. +- `netlib/test/proxy/dns_routing_policy_test.cpp` covers the global DNS routing decisions and + the DNS server override syntax (`dns_routing_policy.h`). It is also part of `netlib-tests` on + Windows. +- `netlib/test/proxy/dns_udp_multiplexer_test.cpp` covers the DNS proxy's shared UDP + association (`dns_udp_multiplexer.h`): relay message IDs, mapping answers back to the client + and the server it queried, truncation of oversized answers, and when the association is + reopened. It is also part of `netlib-tests` on Windows. - `netlib/test/portable/dns_packet_redirect_test.cpp` drives real Ethernet/IP/UDP/TCP frames through the production `socks5_udp_local_redirect.h` and `tcp_local_redirect.h` exactly as the - router's DNS handlers do, and checks every rewritten field, the SOCKS5 UDP header sent to the - relay, the restored answer source, and independently verified checksums. `winshim/` supplies + router's DNS handlers do, with the DNS relay's listener step in between, and checks every + rewritten field, the SOCKS5 UDP datagram sent through the shared association, the source the + client sees on the answer, and independently verified checksums. `winshim/` supplies the few Windows SDK declarations those headers need, and the script extracts the product `CNdisApi` checksum routines verbatim from `external/ndisapi/ndisapi/ndisapi.cpp` (the `wiresock/ndisapi` submodule, which must be checked out). The Windows Packet Filter From b3790f59100a05f9173732a6af92e9efc380c1a5 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 18:21:29 +0000 Subject: [PATCH 40/62] fix(dns relay): keep a working association open; match answers by question Review findings on the shared UDP association: - Health. An answer from the relay reset the unanswered count at once, but queries are counted as unanswered only when they expire 10 s later, so queries to a resolver the proxy cannot reach still retired an association that kept delivering other answers, every 30 s. A query now counts as unanswered only if it was sent after the last datagram from the relay. - Backoff. An association that closes less than 30 s after opening counts as a failed open, so a server that accepts UDP ASSOCIATE and drops the connection is not reconnected about once a second. The backoff resets once an association has stayed open for 30 s. - Matching. Answers were matched by the 16-bit relay ID alone, so a late or forged answer could reach another client. Each query now keeps a fingerprint of its question section (names compared without regard to ASCII case); an answer must carry the same question, or be a question-less error response, and a mismatch does not consume the query. Queries without a parsable question are dropped. - Stop. stop() interrupts an association being opened: the connect wait polls the stop flag (connect_to_socks5_proxy() takes an optional cancel flag; without it the wait is unchanged) and a connected control socket is shut down so a blocked negotiation returns. - Robustness. TCP keepalive on the control connection; ICMP-induced and other transient UDP errors no longer retire the association or spin the listener; thread creation failures are handled instead of terminating; the last drop counts are logged on stop; every successful open is logged at Info. The relay's per-datagram logic moves into dns_relay_session (dns_udp_multiplexer.h), which the relay and the packet tests now share, so the tests exercise the shipped logic instead of a copy. New tests cover the two-resolver scenario, silence after answers, early-close backoff, the question check and question-less error responses. --- netlib/src/proxy/dns_udp_multiplexer.h | 379 ++++++++++++++--- netlib/src/proxy/socks5_dns_udp_relay.h | 399 +++++++++++------- netlib/src/proxy/socks5_udp_association.h | 62 ++- .../portable/dns_packet_redirect_test.cpp | 61 ++- .../test/proxy/dns_udp_multiplexer_test.cpp | 277 +++++++++++- 5 files changed, 915 insertions(+), 263 deletions(-) diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index 5febf32..4946315 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -18,6 +18,7 @@ #include #include #include +#include #include "dns_routing_policy.h" @@ -70,58 +71,136 @@ namespace proxy } /** - * @brief Truncates a DNS answer larger than @p limit the way a server does when an answer - * does not fit (RFC 1035 section 4.2.1, RFC 7766): the TC bit is set, and only the - * header and question section are kept, so the resolver repeats the query over TCP. + * @brief Walks the question section of a DNS message (RFC 1035 section 4.1.2). * - * The answer, authority and additional counts are zeroed. If the question section cannot be - * parsed, only the header is kept, with a zero question count. + * @p visit is called, in order, for every byte range of the section: each QNAME label's + * length byte, its content (with @p is_label_text true), the terminating zero byte or + * two-byte compression pointer, and each question's QTYPE and QCLASS. * - * @return The new size (unchanged when @p size <= @p limit or the message has no header). + * @param limit The section must end at or before this offset. + * @return The offset just past the section, or std::nullopt when it is malformed, truncated, + * or ends after @p limit. */ - [[nodiscard]] constexpr std::size_t truncate_dns_answer(uint8_t* message, const std::size_t size, - const std::size_t limit) noexcept + template + [[nodiscard]] constexpr std::optional walk_dns_questions(const uint8_t* message, + const std::size_t size, const std::size_t limit, Visitor&& visit) { - if (message == nullptr || size <= limit || size < dns_header_size) - return size; + if (message == nullptr || size < dns_header_size) + return std::nullopt; const auto question_count = static_cast((message[4] << 8) | message[5]); std::size_t end = dns_header_size; - bool parsed = true; - for (std::size_t question = 0; question < question_count && parsed; ++question) + for (std::size_t question = 0; question < question_count; ++question) { // QNAME: labels ending with a zero byte, or a two-byte compression pointer. while (true) { if (end >= size) - { - parsed = false; - break; - } - const auto length = message[end]; + return std::nullopt; + const auto length = static_cast(message[end]); if (length == 0) { + visit(message + end, 1, false); ++end; break; } if ((length & 0xC0) == 0xC0) { + if (size - end < 2) + return std::nullopt; + visit(message + end, 2, false); end += 2; break; } - if ((length & 0xC0) != 0) - { - parsed = false; - break; - } - end += 1 + static_cast(length); + if ((length & 0xC0) != 0 || size - end < 1 + length) + return std::nullopt; + visit(message + end, 1, false); + visit(message + end + 1, length, true); + end += 1 + length; } - end += 4; // QTYPE, QCLASS - if (end > size || end > limit) - parsed = false; + if (size - end < 4) + return std::nullopt; + visit(message + end, 4, false); // QTYPE, QCLASS + end += 4; + if (end > limit) + return std::nullopt; } + return end; + } + + /** + * @brief A 64-bit fingerprint of a DNS message's question section (count, names ignoring + * ASCII case, types and classes), used to check that an answer belongs to the query + * it claims to answer. + * @return std::nullopt when the message has no question or its question section is malformed. + */ + [[nodiscard]] inline std::optional dns_question_fingerprint(const uint8_t* message, + const std::size_t size) noexcept + { + if (message == nullptr || size < dns_header_size || ((message[4] << 8) | message[5]) == 0) + return std::nullopt; + + uint64_t hash = 14695981039346656037ull; // FNV-1a + const auto mix = [&hash](const uint8_t byte) noexcept + { + hash ^= byte; + hash *= 1099511628211ull; + }; + mix(message[4]); + mix(message[5]); + const auto end = walk_dns_questions(message, size, size, + [&mix](const uint8_t* bytes, const std::size_t count, const bool is_label_text) noexcept + { + for (std::size_t i = 0; i < count; ++i) + { + const auto byte = bytes[i]; + mix(is_label_text && byte >= 'A' && byte <= 'Z' ? static_cast(byte + ('a' - 'A')) : byte); + } + }); + if (!end) + return std::nullopt; + return hash; + } - if (!parsed) + /** + * @brief Whether a DNS answer belongs to a query with question fingerprint @p question. + * + * The answer must carry the same question section (RFC 1035 servers copy it). An error + * response without a question section (QR set, non-zero RCODE, QDCOUNT 0), which some + * servers send for queries they cannot parse or do not implement, is also accepted. + */ + [[nodiscard]] inline bool dns_answer_matches_question(const uint8_t* answer, const std::size_t size, + const uint64_t question) noexcept + { + if (answer == nullptr || size < dns_header_size) + return false; + if (const auto fingerprint = dns_question_fingerprint(answer, size)) + return *fingerprint == question; + + const bool is_response = (answer[2] & 0x80) != 0; + const bool is_error = (answer[3] & 0x0F) != 0; + const bool no_question = answer[4] == 0 && answer[5] == 0; + return is_response && is_error && no_question; + } + + /** + * @brief Truncates a DNS answer larger than @p limit the way a server does when an answer + * does not fit (RFC 1035 section 4.2.1, RFC 7766): the TC bit is set, and only the + * header and question section are kept, so the resolver repeats the query over TCP. + * + * The answer, authority and additional counts are zeroed. If the question section cannot be + * parsed, only the header is kept, with a zero question count. + * + * @return The new size (unchanged when @p size <= @p limit or the message has no header). + */ + [[nodiscard]] constexpr std::size_t truncate_dns_answer(uint8_t* message, const std::size_t size, + const std::size_t limit) noexcept + { + if (message == nullptr || size <= limit || size < dns_header_size) + return size; + + auto end = walk_dns_questions(message, size, limit, [](const uint8_t*, std::size_t, bool) noexcept {}); + if (!end) { end = dns_header_size; message[4] = 0; @@ -131,7 +210,7 @@ namespace proxy message[2] = static_cast(message[2] | 0x02); // TC for (std::size_t field = 6; field < dns_header_size; ++field) message[field] = 0; // ANCOUNT, NSCOUNT, ARCOUNT - return end; + return *end; } /** @@ -147,10 +226,10 @@ namespace proxy * * @param relayed The relay's datagram, already parsed (parse_socks5_udp_datagram()). * @param server_address Queried server address bytes (network byte order): 4 or 16 bytes. - * @param original_id The client's DNS message ID. * An answer larger than dns_udp_answer_limit() is truncated (truncate_dns_answer()), so the * resolver retries over TCP instead of receiving a fragmented reply it would never get. * + * @param original_id The client's DNS message ID. * @param out Output buffer. * @return Bytes written, or 0 when the answer does not fit, carries no DNS header, or * @p address_size is not 4 or 16. @@ -181,16 +260,19 @@ namespace proxy dns_udp_answer_limit(address_type)); } + /** * @brief Queries in flight through the shared association, keyed by relay ID. * * insert() replaces a query's message ID with a relay ID that is unique among the queries in * flight and chosen by the caller's random source, so the 16-bit ID keeps its full entropy * against forged answers. A retransmission (same client socket and original ID) reuses its - * relay ID, so duplicate answers map to it and it counts once as unanswered. Entries expire - * after the TTL; the table is bounded, and when full the oldest query is evicted. + * relay ID, so duplicate answers map to it and it counts once as unanswered. Each entry also + * keeps the query's question fingerprint (dns_question_fingerprint()) so an answer can be + * checked against it. Entries expire after the TTL; the table is bounded, and when full the + * oldest query is evicted. * - * Not thread-safe: the relay serializes access. + * Not thread-safe: the caller serializes access. * * @tparam Client Client socket identity (equality-comparable, hashed by @p Hash). The relay * uses the listener's sender endpoint: the queried server address and the client port. @@ -205,6 +287,7 @@ namespace proxy { Client client; uint16_t original_id{}; + uint64_t question{}; }; dns_query_table(const std::chrono::seconds ttl, const std::size_t capacity) @@ -214,19 +297,21 @@ namespace proxy /** * @brief Records a query and returns its relay ID. + * @param question The query's question fingerprint. * @param random Callable returning a uniformly distributed uint16_t. * @return The relay ID, or std::nullopt only if no ID could be found (cannot happen while * the capacity is below 65536). */ template - std::optional insert(const Client& client, const uint16_t original_id, const time_point now, - Random&& random) + std::optional insert(const Client& client, const uint16_t original_id, const uint64_t question, + const time_point now, Random&& random) { const key k{ client, original_id }; if (const auto existing = by_client_.find(k); existing != by_client_.end()) { auto& entry = entries_.at(existing->second); entry.sent_at = now; + entry.question = question; return existing->second; } @@ -257,11 +342,28 @@ namespace proxy if (!relay_id) return std::nullopt; - entries_.emplace(*relay_id, entry{ client, original_id, now }); + entries_.emplace(*relay_id, entry{ client, original_id, question, now }); by_client_.emplace(k, *relay_id); return relay_id; } + /// insert() for a query without a question fingerprint (fingerprint 0). + template + std::optional insert(const Client& client, const uint16_t original_id, const time_point now, + Random&& random) + { + return insert(client, original_id, uint64_t{ 0 }, now, std::forward(random)); + } + + /// The live query with @p relay_id, without removing it. + [[nodiscard]] std::optional find(const uint16_t relay_id, const time_point now) const + { + const auto it = entries_.find(relay_id); + if (it == entries_.end() || now - it->second.sent_at > ttl_) + return std::nullopt; + return pending{ it->second.client, it->second.original_id, it->second.question }; + } + /** * @brief Removes and returns the query an answer with @p relay_id belongs to. * @return std::nullopt for an unknown or expired relay ID. @@ -273,30 +375,35 @@ namespace proxy return std::nullopt; const bool expired = now - it->second.sent_at > ttl_; - pending result{ it->second.client, it->second.original_id }; + pending result{ it->second.client, it->second.original_id, it->second.question }; erase(it); if (expired) return std::nullopt; return result; } - /// Removes queries older than the TTL and returns how many expired unanswered. - std::size_t expire(const time_point now) + /** + * @brief Removes queries older than the TTL. + * @param counted_after When set, only expired queries sent after this time are counted. + * @return How many expired queries were counted. + */ + std::size_t expire(const time_point now, const std::optional counted_after = std::nullopt) { - std::size_t expired = 0; + std::size_t counted = 0; for (auto it = entries_.begin(); it != entries_.end();) { if (now - it->second.sent_at > ttl_) { + if (!counted_after || it->second.sent_at > *counted_after) + ++counted; it = erase(it); - ++expired; } else { ++it; } } - return expired; + return counted; } void clear() noexcept @@ -313,6 +420,7 @@ namespace proxy { Client client; uint16_t original_id{}; + uint64_t question{}; time_point sent_at{}; }; @@ -357,14 +465,18 @@ namespace proxy * @brief Decides when the shared association is reopened and when a new one may be tried. * * - A failed open is retried after a backoff that doubles from 1 s up to 30 s; queries - * arriving meanwhile are dropped (Proxy mode never sends DNS directly). - * - An open association is reopened when its SOCKS5 control connection closes or the relay + * arriving meanwhile are dropped (Proxy mode never sends DNS directly). An association that + * closes less than @p minimum_age after opening counts as a failed open, so a server that + * accepts UDP ASSOCIATE and then drops the connection is not reconnected in a tight loop. + * The backoff resets once an association has stayed open for @p minimum_age. + * - An open association is reopened when its SOCKS5 control connection closes or its relay * socket fails (reported by the relay), or when it looks silently dead: at least - * @p unanswered_limit queries in a row expired without any datagram arriving from the - * relay in between, and the association is at least @p minimum_age old. The age limit - * keeps a resolver that never answers from churning a working association. + * @p unanswered_limit queries expired unanswered that were sent after the last datagram + * from the relay, and the association is at least @p minimum_age old. A query sent before + * a datagram that did arrive is not counted, so a resolver that never answers cannot + * retire an association that keeps delivering other answers. * - * Not thread-safe: the relay serializes access. + * Not thread-safe: the caller serializes access. */ template class dns_association_health @@ -393,19 +505,41 @@ namespace proxy void on_opened(const time_point now) noexcept { - failures_ = 0; unanswered_ = 0; opened_at_ = now; + last_datagram_.reset(); + } + + /// The association was closed at @p now (for any reason). + void on_closed(const time_point now) noexcept + { + if (now - opened_at_ < minimum_age_) + on_open_failed(now); + else + failures_ = 0; } /// Any datagram from the relay shows the association is alive. - void on_relay_datagram() noexcept { unanswered_ = 0; } + void on_relay_datagram(const time_point now) noexcept + { + unanswered_ = 0; + last_datagram_ = now; + } - /// Records queries that expired unanswered; true when the association should be reopened. + /// Time of the last datagram from the relay since the association opened, if any. + [[nodiscard]] std::optional last_datagram() const noexcept { return last_datagram_; } + + /** + * @brief Records @p count queries that expired unanswered (counted as expire() does with + * last_datagram()); true when the association should be reopened. + */ [[nodiscard]] bool on_unanswered(const std::size_t count, const time_point now) noexcept { + const bool old_enough = now - opened_at_ >= minimum_age_; + if (old_enough) + failures_ = 0; // the association has proved itself unanswered_ += count; - return unanswered_ >= unanswered_limit_ && now - opened_at_ >= minimum_age_; + return unanswered_ >= unanswered_limit_ && old_enough; } [[nodiscard]] std::size_t consecutive_failures() const noexcept { return failures_; } @@ -420,5 +554,148 @@ namespace proxy std::size_t unanswered_{}; time_point next_attempt_{}; time_point opened_at_{}; + std::optional last_datagram_; + }; + + /// What happens to a query the DNS relay's listener received. + enum class dns_relay_query : uint8_t + { + send, ///< rewritten with its relay ID: send it through the association + malformed, ///< no SOCKS5 header of the listener's family, or no parsable DNS question + no_id ///< no free relay ID (cannot happen below 65536 queries in flight) + }; + + /// What happens to a datagram the SOCKS5 relay delivered. + enum class dns_relay_answer : uint8_t + { + deliver, ///< return it to the client + malformed, ///< no SOCKS5 UDP header, no DNS header, or does not fit the output + unmatched, ///< matches no query in flight (late, duplicate or unsolicited) + question_mismatch ///< its relay ID is in flight but its question is another query's + }; + + /** + * @brief The DNS relay's per-datagram logic for one shared association, free of sockets so + * it is unit tested on any platform (socks5_dns_udp_relay.h does the I/O). + * + * Combines the table of queries in flight, the association health, the question check and + * the answer returned to the client. Not thread-safe: the relay serializes access. + */ + template , typename Clock = std::chrono::steady_clock> + class dns_relay_session + { + public: + using time_point = typename Clock::time_point; + using table_t = dns_query_table; + + struct answer + { + dns_relay_answer outcome{ dns_relay_answer::malformed }; + std::optional client; + std::size_t size{}; ///< bytes written to the output buffer when delivered + }; + + dns_relay_session(const std::chrono::seconds query_ttl, const std::size_t max_queries, + const std::size_t unanswered_limit, const std::chrono::seconds minimum_association_age) + : queries_(query_ttl, max_queries), health_(unanswered_limit, minimum_association_age) + { + } + + /** + * @brief Prepares a query from the listener for the association: validates it, records + * it, and replaces its DNS message ID with the relay ID in place. + * @param datagram SOCKS5 UDP header of the listener's family (@p address_type) followed + * by the DNS query, as the local redirect delivered it. + */ + template + dns_relay_query prepare_query(const Client& client, uint8_t* datagram, const std::size_t size, + const uint8_t address_type, const time_point now, Random&& random) + { + const auto offset = socks5_dns_query_offset(datagram, size, address_type); + if (!offset) + return dns_relay_query::malformed; + + auto* const message = datagram + *offset; + const auto message_size = size - *offset; + const auto question = dns_question_fingerprint(message, message_size); + if (!question) + return dns_relay_query::malformed; + + const auto original_id = *dns_message_id(message, message_size); + const auto relay_id = queries_.insert(client, original_id, *question, now, std::forward(random)); + if (!relay_id) + return dns_relay_query::no_id; + + set_dns_message_id(message, *relay_id); + return dns_relay_query::send; + } + + /** + * @brief Maps a datagram from the SOCKS5 relay back to its client. + * + * Every datagram from the relay counts as a sign of life. An answer is delivered only if + * its relay ID is in flight and its question section matches that query's + * (dns_answer_matches_question()); a mismatch does not consume the query. + * + * @param address_of (const Client&) -> std::pair: the + * address bytes of the server the client queried. + * @param out Output buffer for the datagram returned to the client + * (build_dns_client_answer()). + */ + template + answer prepare_answer(const uint8_t* relayed, const std::size_t size, AddressOf&& address_of, + uint8_t* out, const std::size_t out_capacity, const time_point now) + { + health_.on_relay_datagram(now); + + const auto view = parse_socks5_udp_datagram(relayed, size); + const auto relay_id = view ? dns_message_id(view->data, view->data_size) : std::nullopt; + if (!relay_id) + return { dns_relay_answer::malformed, std::nullopt, 0 }; + + const auto query = queries_.find(*relay_id, now); + if (!query) + return { dns_relay_answer::unmatched, std::nullopt, 0 }; + if (!dns_answer_matches_question(view->data, view->data_size, query->question)) + return { dns_relay_answer::question_mismatch, std::nullopt, 0 }; + + (void)queries_.take(*relay_id, now); + const auto [address, address_size] = address_of(query->client); + const auto written = build_dns_client_answer(*view, address, address_size, dns_port, + query->original_id, out, out_capacity); + if (written == 0) + return { dns_relay_answer::malformed, std::nullopt, 0 }; + return { dns_relay_answer::deliver, query->client, written }; + } + + /// Expires queries; true when the association looks silently dead and should be reopened. + [[nodiscard]] bool expire(const time_point now) + { + return health_.on_unanswered(queries_.expire(now, health_.last_datagram()), now); + } + + /// Expires queries while no association is open (nothing is counted). + void expire_closed(const time_point now) { (void)queries_.expire(now); } + + [[nodiscard]] bool may_open(const time_point now) const noexcept { return health_.may_open(now); } + void on_open_failed(const time_point now) noexcept { health_.on_open_failed(now); } + void on_opened(const time_point now) noexcept { health_.on_opened(now); } + + /// The association closed: its queries in flight can no longer be answered. + void on_closed(const time_point now) noexcept + { + queries_.clear(); + health_.on_closed(now); + } + + void clear() noexcept { queries_.clear(); } + + [[nodiscard]] std::size_t queries_in_flight() const noexcept { return queries_.size(); } + [[nodiscard]] std::size_t consecutive_failures() const noexcept { return health_.consecutive_failures(); } + [[nodiscard]] time_point next_attempt() const noexcept { return health_.next_attempt(); } + + private: + table_t queries_; + dns_association_health health_; }; } diff --git a/netlib/src/proxy/socks5_dns_udp_relay.h b/netlib/src/proxy/socks5_dns_udp_relay.h index 7a276fe..9db1ef9 100644 --- a/netlib/src/proxy/socks5_dns_udp_relay.h +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -7,9 +7,10 @@ // header already prepended (socks5_udp_local_redirect.h), naming the server to ask: the server // the application queried, or the DNS server override. The relay replaces the query's message ID // with a unique random relay ID and sends it through the shared association. The answer carrying -// that relay ID is returned to the client socket with its original ID and a SOCKS5 header naming -// the server the client queried, so the redirect presents it as an answer from that server. -// Bookkeeping and policy are in dns_udp_multiplexer.h. +// that relay ID and the query's question is returned to the client socket with its original ID +// and a SOCKS5 header naming the server the client queried, so the redirect presents it as an +// answer from that server. The per-datagram logic is in dns_udp_multiplexer.h +// (dns_relay_session), where it is unit tested; this file does the I/O. // // The association is opened on the first query and reopened, with backoff, after its control // connection closes, its relay socket fails, or it stops answering. While none is open, queries @@ -19,7 +20,7 @@ // completion port: the listener, the reader of the current relay socket, and maintenance (opens // associations, expires queries, checks health). Socket receives have short timeouts so every // thread notices stop() and a retired association; sockets are closed only after the threads -// using them have been joined. +// using them have been joined. stop() also interrupts an association being opened. #include #include @@ -44,7 +45,7 @@ namespace proxy /// Whether the router recently redirected a UDP DNS query from this local source port. using authorize_client_t = bool(uint16_t); - /// Observes each UDP relay endpoint the SOCKS5 server returns, before it is used. + /// Observes each UDP relay endpoint the SOCKS5 server returns, before anything is sent to it. using relay_endpoint_observed_t = void(const endpoint_t&); /// Queries in flight are forgotten after this long; Windows gives up on a query sooner. @@ -56,10 +57,11 @@ namespace proxy /// Bound on queries held while an association is being opened. static constexpr std::size_t max_waiting_queries = 64; - /// Unanswered queries in a row (with no datagram from the relay) that retire an association. + /// Unanswered queries (sent after the last datagram from the relay) that retire an association. static constexpr std::size_t unanswered_limit = 3; - /// An association younger than this is not retired for unanswered queries. + /// An association younger than this is not retired for unanswered queries, and closing + /// sooner than this counts as a failed open for the backoff. static constexpr std::chrono::seconds minimum_association_age{ 30 }; /** @@ -104,7 +106,7 @@ namespace proxy /** * @brief Creates the listener and starts the threads. No association is opened until the * first query arrives. - * @return false if the listener socket could not be created. + * @return false if the listener socket or a thread could not be created. */ bool start() { @@ -115,9 +117,23 @@ namespace proxy return false; stopping_.store(false, std::memory_order_release); + try + { + listener_thread_ = std::thread(&socks5_dns_udp_relay::listener_loop, this); + maintenance_thread_ = std::thread(&socks5_dns_udp_relay::maintenance_loop, this); + } + catch (const std::exception& e) + { + NETLIB_ERROR("DNS relay: failed to start its threads: {}", e.what()); + stopping_.store(true, std::memory_order_release); + if (listener_thread_.joinable()) + listener_thread_.join(); + closesocket(listener_socket_); + listener_socket_ = INVALID_SOCKET; + return false; + } + running_ = true; - listener_thread_ = std::thread(&socks5_dns_udp_relay::listener_loop, this); - maintenance_thread_ = std::thread(&socks5_dns_udp_relay::maintenance_loop, this); NETLIB_INFO("DNS relay: listening on UDP port {} for {} DNS queries via SOCKS5 server {}", listener_port_, address_type_t::af_type == AF_INET ? "IPv4" : "IPv6", upstream_.to_string()); return true; @@ -130,6 +146,14 @@ namespace proxy return; stopping_.store(true, std::memory_order_release); + + // Interrupt an association being opened: the connect wait polls stopping_, and a + // connected control socket is shut down so a blocked negotiation returns at once. + { + std::scoped_lock lock(handshake_lock_); + if (handshake_socket_ != INVALID_SOCKET) + shutdown(handshake_socket_, SD_BOTH); + } { std::scoped_lock lock(lock_); maintenance_cv_.notify_all(); @@ -144,14 +168,17 @@ namespace proxy { std::scoped_lock lock(lock_); current = std::move(association_); + dropped_unavailable_ += waiting_.size(); waiting_.clear(); - queries_.clear(); + session_.clear(); } close_association(std::move(current)); closesocket(listener_socket_); listener_socket_ = INVALID_SOCKET; running_ = false; + + report_drops(std::chrono::steady_clock::now(), true); } private: @@ -196,6 +223,7 @@ namespace proxy static constexpr std::size_t own_address_size = address_type_t::af_type == AF_INET ? 4 : 16; static constexpr DWORD receive_timeout_ms = 500; static constexpr std::size_t max_datagram_size = 65535; + static constexpr std::chrono::seconds report_interval{ 30 }; // --- Configuration ------------------------------------------------------------------- @@ -212,10 +240,14 @@ namespace proxy std::condition_variable maintenance_cv_; std::unique_ptr association_; std::deque waiting_; - dns_query_table queries_{ query_ttl, max_queries_in_flight }; - dns_association_health<> health_{ unanswered_limit, minimum_association_age }; + dns_relay_session session_{ query_ttl, max_queries_in_flight, unanswered_limit, + minimum_association_age }; std::random_device random_; + /// Control socket of an association being opened, so stop() can interrupt it. + std::mutex handshake_lock_; + SOCKET handshake_socket_{ INVALID_SOCKET }; + SOCKET listener_socket_{ INVALID_SOCKET }; uint16_t listener_port_{ 0 }; bool running_{ false }; @@ -254,6 +286,27 @@ namespace proxy nullptr, 0, &bytes_returned, nullptr, nullptr); } + /// Keepalive on the control connection, so a silently dropped connection (NAT timeout, + /// server crash) is detected and the association reopened. + static void enable_keepalive(const SOCKET socket) noexcept + { + const BOOL enabled = TRUE; + setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast(&enabled), sizeof(enabled)); +#if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL) + const DWORD idle_seconds = 60; + const DWORD interval_seconds = 10; + setsockopt(socket, IPPROTO_TCP, TCP_KEEPIDLE, reinterpret_cast(&idle_seconds), sizeof(idle_seconds)); + setsockopt(socket, IPPROTO_TCP, TCP_KEEPINTVL, reinterpret_cast(&interval_seconds), sizeof(interval_seconds)); +#endif + } + + /// Socket errors after which a UDP socket keeps working (ICMP-induced or oversized datagrams). + [[nodiscard]] static bool transient_udp_error(const int error) noexcept + { + return error == WSAETIMEDOUT || error == WSAECONNRESET || error == WSAENETRESET || + error == WSAEMSGSIZE || error == WSAEINTR; + } + [[nodiscard]] static std::optional client_from(const SOCKADDR_STORAGE& sender) noexcept { if constexpr (address_type_t::af_type == AF_INET) @@ -342,24 +395,30 @@ namespace proxy } /// Sends one query through the open association. Caller holds lock_. - void send_query_locked(const client_t& client, std::vector& datagram, const std::size_t dns_offset) + void send_query_locked(const client_t& client, std::vector& datagram) { - const auto original_id = *dns_message_id(datagram.data() + dns_offset, datagram.size() - dns_offset); - const auto relay_id = queries_.insert(client, original_id, std::chrono::steady_clock::now(), - [this] { return random_id(); }); - if (!relay_id) + switch (session_.prepare_query(client, datagram.data(), datagram.size(), own_address_type, + std::chrono::steady_clock::now(), [this] { return random_id(); })) { + case dns_relay_query::send: + break; + case dns_relay_query::malformed: + ++dropped_malformed_; + return; + case dns_relay_query::no_id: ++dropped_unavailable_; return; } - set_dns_message_id(datagram.data() + dns_offset, *relay_id); if (send(association_->relay, reinterpret_cast(datagram.data()), static_cast(datagram.size()), 0) == SOCKET_ERROR) { ++dropped_send_failures_; - association_->failed.store(true, std::memory_order_release); - maintenance_cv_.notify_all(); + if (!transient_udp_error(WSAGetLastError())) + { + association_->failed.store(true, std::memory_order_release); + maintenance_cv_.notify_all(); + } } } @@ -375,45 +434,65 @@ namespace proxy int sender_size = static_cast(sizeof(sender)); const auto received = recvfrom(listener_socket_, reinterpret_cast(buffer.data()), static_cast(buffer.size()), 0, reinterpret_cast(&sender), &sender_size); - if (received == SOCKET_ERROR || received <= 0) - continue; // timeout (checks stopping_), or a spurious error on a UDP socket - - const auto size = static_cast(received); - const auto client = client_from(sender); - if (!client || client->endpoint.port == 0 || !authorize_client_ || - !authorize_client_(client->endpoint.port)) + if (received == SOCKET_ERROR) { - ++dropped_unauthorized_; + // A timeout lets the loop check stopping_. Back off on a persistent error + // instead of spinning. + if (!transient_udp_error(WSAGetLastError())) + std::this_thread::sleep_for(std::chrono::milliseconds{ 100 }); continue; } - - const auto dns_offset = socks5_dns_query_offset(buffer.data(), size, own_address_type); - if (!dns_offset) - { - ++dropped_malformed_; + if (received <= 0) continue; - } - std::vector datagram(buffer.begin(), buffer.begin() + static_cast(size)); - - std::scoped_lock lock(lock_); - if (association_ && !association_->failed.load(std::memory_order_acquire)) + try { - send_query_locked(*client, datagram, *dns_offset); - continue; + handle_listener_datagram(buffer, static_cast(received), sender); } - - // No usable association: hold the query while one is opened, unless opening is - // backing off after a failure or too many queries are already waiting. - if (!health_.may_open(std::chrono::steady_clock::now()) || waiting_.size() >= max_waiting_queries) + catch (const std::exception& e) { ++dropped_unavailable_; - continue; + NETLIB_DEBUG("DNS relay: dropped a query: {}", e.what()); } + } + } - waiting_.push_back(waiting_query{ *client, std::move(datagram) }); - maintenance_cv_.notify_all(); + void handle_listener_datagram(const std::vector& buffer, const std::size_t size, + const SOCKADDR_STORAGE& sender) + { + const auto client = client_from(sender); + if (!client || client->endpoint.port == 0 || !authorize_client_ || + !authorize_client_(client->endpoint.port)) + { + ++dropped_unauthorized_; + return; + } + + if (!socks5_dns_query_offset(buffer.data(), size, own_address_type)) + { + ++dropped_malformed_; + return; + } + + std::vector datagram(buffer.begin(), buffer.begin() + static_cast(size)); + + std::scoped_lock lock(lock_); + if (association_ && !association_->failed.load(std::memory_order_acquire)) + { + send_query_locked(*client, datagram); + return; } + + // No usable association: hold the query while one is opened, unless opening is + // backing off after a failure or too many queries are already waiting. + if (!session_.may_open(std::chrono::steady_clock::now()) || waiting_.size() >= max_waiting_queries) + { + ++dropped_unavailable_; + return; + } + + waiting_.push_back(waiting_query{ *client, std::move(datagram) }); + maintenance_cv_.notify_all(); } void reader_loop(association* const owner) @@ -427,7 +506,7 @@ namespace proxy static_cast(buffer.size()), 0); if (received == SOCKET_ERROR) { - if (WSAGetLastError() == WSAETIMEDOUT) + if (transient_udp_error(WSAGetLastError())) continue; owner->failed.store(true, std::memory_order_release); { @@ -437,38 +516,25 @@ namespace proxy return; } - const auto relayed = parse_socks5_udp_datagram(buffer.data(), static_cast(received)); - const auto relay_id = relayed ? dns_message_id(relayed->data, relayed->data_size) : std::nullopt; - if (!relay_id) - { - ++dropped_unmatched_answers_; - continue; - } - - std::optional query; + typename dns_relay_session::answer result; { std::scoped_lock lock(lock_); - health_.on_relay_datagram(); - query = queries_.take(*relay_id, std::chrono::steady_clock::now()); - } - - if (!query) - { - ++dropped_unmatched_answers_; - continue; + result = session_.prepare_answer(buffer.data(), static_cast(received), + [](const client_t& client) + { + return std::pair{ reinterpret_cast(&client.endpoint.ip), own_address_size }; + }, + answer.data(), answer.size(), std::chrono::steady_clock::now()); } - const auto answer_size = build_dns_client_answer(*relayed, - reinterpret_cast(&query->client.endpoint.ip), own_address_size, dns_port, - query->original_id, answer.data(), answer.size()); - if (answer_size == 0) + if (result.outcome != dns_relay_answer::deliver) { ++dropped_unmatched_answers_; continue; } - const auto [to, to_size] = sockaddr_from(query->client); - if (sendto(listener_socket_, reinterpret_cast(answer.data()), static_cast(answer_size), + const auto [to, to_size] = sockaddr_from(*result.client); + if (sendto(listener_socket_, reinterpret_cast(answer.data()), static_cast(result.size), 0, reinterpret_cast(&to), to_size) == SOCKET_ERROR) { ++dropped_send_failures_; @@ -487,48 +553,62 @@ namespace proxy { return stopping_.load(std::memory_order_acquire) || (association_ && association_->failed.load(std::memory_order_acquire)) || - (!association_ && !waiting_.empty() && health_.may_open(std::chrono::steady_clock::now())); + (!association_ && !waiting_.empty() && session_.may_open(std::chrono::steady_clock::now())); }); if (stopping_.load(std::memory_order_acquire)) break; - const auto now = std::chrono::steady_clock::now(); - - // Retire an association whose relay or control connection failed, or that has - // stopped answering. - if (association_) + try { - const auto unanswered = queries_.expire(now); - const char* reason = nullptr; - if (association_->failed.load(std::memory_order_acquire)) - reason = "the UDP relay socket failed"; - else if (control_channel_closed(association_->control)) - reason = "the SOCKS5 control connection closed"; - else if (health_.on_unanswered(unanswered, now)) - reason = "queries stopped being answered"; - - if (reason) - { - NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association because {}; it is reopened " - "on the next query", reason); - auto retired = std::move(association_); - queries_.clear(); - lock.unlock(); - close_association(std::move(retired)); - lock.lock(); - continue; - } + maintain(lock); } - else + catch (const std::exception& e) { - (void)queries_.expire(now); + if (!lock.owns_lock()) + lock.lock(); + NETLIB_ERROR("DNS relay: maintenance failed: {}", e.what()); } + } + } - if (!association_ && !waiting_.empty() && health_.may_open(now)) - open_association(lock); + /// One maintenance pass. Called with lock_ held; may release it for blocking work. + void maintain(std::unique_lock& lock) + { + const auto now = std::chrono::steady_clock::now(); - report_drops(now); + // Retire an association whose relay or control connection failed, or that has + // stopped answering. + if (association_) + { + const char* reason = nullptr; + if (association_->failed.load(std::memory_order_acquire)) + reason = "the UDP relay socket failed"; + else if (control_channel_closed(association_->control)) + reason = "the SOCKS5 control connection closed"; + else if (session_.expire(now)) + reason = "queries stopped being answered"; + + if (reason) + { + NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association with {} because {}; it is reopened " + "on the next query", upstream_.to_string(), reason); + auto retired = std::move(association_); + session_.on_closed(now); + lock.unlock(); + close_association(std::move(retired)); + lock.lock(); + return; + } + } + else + { + session_.expire_closed(now); } + + if (!association_ && !waiting_.empty() && session_.may_open(now)) + open_association(lock); + + report_drops(now, false); } /// Opens an association for the waiting queries. Called with lock_ held; releases it @@ -536,91 +616,112 @@ namespace proxy void open_association(std::unique_lock& lock) { lock.unlock(); - auto opened = connect_association(); - lock.lock(); const auto now = std::chrono::steady_clock::now(); + if (opened && !stopping_.load(std::memory_order_acquire)) + { + try + { + opened->reader = std::thread(&socks5_dns_udp_relay::reader_loop, this, opened.get()); + } + catch (const std::exception& e) + { + NETLIB_ERROR("DNS relay: failed to start the UDP relay reader: {}", e.what()); + lock.unlock(); + close_association(std::move(opened)); + lock.lock(); + } + } + if (!opened || stopping_.load(std::memory_order_acquire)) { - const bool failed = !opened; if (opened) { lock.unlock(); close_association(std::move(opened)); lock.lock(); + return; + } + + if (stopping_.load(std::memory_order_acquire)) + return; + + session_.on_open_failed(now); + dropped_unavailable_ += waiting_.size(); + waiting_.clear(); + const auto retry = std::chrono::duration_cast(session_.next_attempt() - now); + if (session_.consecutive_failures() == 1) + { + NETLIB_WARNING("DNS relay: could not open a SOCKS5 UDP association with {}; UDP DNS is " + "dropped until one opens (next attempt in {} s)", upstream_.to_string(), retry.count()); } - if (failed) + else { - health_.on_open_failed(now); - dropped_unavailable_ += waiting_.size(); - waiting_.clear(); - const auto retry = std::chrono::duration_cast(health_.next_attempt() - now); - if (health_.consecutive_failures() == 1) - { - NETLIB_WARNING("DNS relay: could not open a SOCKS5 UDP association with {}; UDP DNS is " - "dropped until one opens (next attempt in {} s)", upstream_.to_string(), retry.count()); - } - else - { - NETLIB_DEBUG("DNS relay: SOCKS5 UDP association attempt {} failed; next attempt in {} s", - health_.consecutive_failures(), retry.count()); - } + NETLIB_DEBUG("DNS relay: SOCKS5 UDP association attempt {} failed; next attempt in {} s", + session_.consecutive_failures(), retry.count()); } return; } - if (health_.consecutive_failures() > 0) - NETLIB_INFO("DNS relay: SOCKS5 UDP association with {} opened", upstream_.to_string()); - else - NETLIB_DEBUG("DNS relay: SOCKS5 UDP association with {} opened", upstream_.to_string()); - - health_.on_opened(now); + NETLIB_INFO("DNS relay: SOCKS5 UDP association with {} opened", upstream_.to_string()); + session_.on_opened(now); association_ = std::move(opened); - association_->reader = std::thread(&socks5_dns_udp_relay::reader_loop, this, association_.get()); auto waiting = std::move(waiting_); waiting_.clear(); for (auto& query : waiting) - { - if (const auto offset = socks5_dns_query_offset(query.datagram.data(), query.datagram.size(), - own_address_type)) - { - send_query_locked(query.client, query.datagram, *offset); - } - } + send_query_locked(query.client, query.datagram); } - /// Blocking: SOCKS5 connect, authentication, UDP ASSOCIATE and relay socket. Lock not held. + /// Blocking: SOCKS5 connect, authentication, UDP ASSOCIATE and relay socket. Lock not + /// held. stop() interrupts it (see stop()). The relay endpoint is reported before the + /// relay socket exists, so the recursion guard knows it before anything is sent to it. std::unique_ptr connect_association() { - auto control = association_client_.connect_to_socks5_proxy(upstream_.ip, upstream_.port); + auto control = association_client_.connect_to_socks5_proxy(upstream_.ip, upstream_.port, &stopping_); if (control == INVALID_SOCKET) return nullptr; - auto negotiate_ctx = std::make_unique(address_type_t{}, 0, - credentials_ ? std::optional(credentials_->first) : std::nullopt, - credentials_ ? std::optional(credentials_->second) : std::nullopt, - upstream_options_); + { + std::scoped_lock lock(handshake_lock_); + if (stopping_.load(std::memory_order_acquire)) + { + closesocket(control); + return nullptr; + } + handshake_socket_ = control; + } std::optional relay_endpoint; try { + auto negotiate_ctx = std::make_unique(address_type_t{}, 0, + credentials_ ? std::optional(credentials_->first) : std::nullopt, + credentials_ ? std::optional(credentials_->second) : std::nullopt, + upstream_options_); relay_endpoint = association_client_.associate_to_socks5_proxy(control, upstream_.ip, negotiate_ctx); } - catch (...) + catch (const std::exception& e) { + NETLIB_DEBUG("DNS relay: SOCKS5 UDP ASSOCIATE failed: {}", e.what()); relay_endpoint.reset(); } - if (!relay_endpoint) + { + std::scoped_lock lock(handshake_lock_); + handshake_socket_ = INVALID_SOCKET; + } + + if (!relay_endpoint || stopping_.load(std::memory_order_acquire)) { closesocket(control); return nullptr; } - // Report the relay endpoint before the relay socket exists (recursion guard). + enable_keepalive(control); + if (relay_endpoint_observed_) relay_endpoint_observed_(*relay_endpoint); @@ -679,11 +780,9 @@ namespace proxy return true; } - /// Logs what was dropped since the last report, at most every 30 seconds. - void report_drops(const std::chrono::steady_clock::time_point now) + /// Logs what was dropped since the last report: at most every 30 seconds, and on stop(). + void report_drops(const std::chrono::steady_clock::time_point now, const bool final_report) { - using namespace std::chrono_literals; - const auto unauthorized = dropped_unauthorized_.load(std::memory_order_relaxed); const auto malformed = dropped_malformed_.load(std::memory_order_relaxed); const auto unavailable = dropped_unavailable_.load(std::memory_order_relaxed); @@ -691,11 +790,11 @@ namespace proxy const auto send_failures = dropped_send_failures_.load(std::memory_order_relaxed); const auto total = unauthorized + malformed + unavailable + unmatched + send_failures; - if (total == reported_drops_ || now - last_report_ < 30s) + if (total == reported_drops_ || (!final_report && now - last_report_ < report_interval)) return; NETLIB_INFO("DNS relay: dropped so far: {} queries while no SOCKS5 UDP association was available, " - "{} not from a redirected DNS client, {} without a DNS header, {} answers matching no query, " + "{} not from a redirected DNS client, {} without a DNS question, {} answers matching no query, " "{} send failures", unavailable, unauthorized, malformed, unmatched, send_failures); reported_drops_ = total; last_report_ = now; diff --git a/netlib/src/proxy/socks5_udp_association.h b/netlib/src/proxy/socks5_udp_association.h index 0610829..9290ae8 100644 --- a/netlib/src/proxy/socks5_udp_association.h +++ b/netlib/src/proxy/socks5_udp_association.h @@ -86,9 +86,11 @@ namespace proxy * * @param socks_server_address The address of the SOCKS5 proxy server to connect to. * @param socks_server_port The port of the SOCKS5 proxy server. + * @param cancel Optional flag that abandons the connect attempt once set. * @return A connected TCP SOCKET handle, or INVALID_SOCKET on failure. */ - SOCKET connect_to_socks5_proxy(address_type_t socks_server_address, const uint16_t socks_server_port) + SOCKET connect_to_socks5_proxy(address_type_t socks_server_address, const uint16_t socks_server_port, + const std::atomic_bool* const cancel = nullptr) { auto socks_tcp_socket = WSASocket(address_type_t::af_type, SOCK_STREAM, IPPROTO_TCP, nullptr, 0, WSA_FLAG_OVERLAPPED); @@ -165,7 +167,7 @@ namespace proxy sa_service.sin_port = htons(socks_server_port); if (!connect_with_timeout(socks_tcp_socket, reinterpret_cast(&sa_service), - sizeof(sa_service), 5000)) + sizeof(sa_service), 5000, cancel)) { closesocket(socks_tcp_socket); return INVALID_SOCKET; @@ -179,7 +181,7 @@ namespace proxy sa_service.sin6_port = htons(socks_server_port); if (!connect_with_timeout(socks_tcp_socket, reinterpret_cast(&sa_service), - sizeof(sa_service), 5000)) + sizeof(sa_service), 5000, cancel)) { closesocket(socks_tcp_socket); return INVALID_SOCKET; @@ -201,7 +203,7 @@ namespace proxy * @return true if the connection completed within the timeout, false otherwise. */ static bool connect_with_timeout(const SOCKET s, const sockaddr* const addr, const int addr_len, - const DWORD timeout_ms) noexcept + const DWORD timeout_ms, const std::atomic_bool* const cancel = nullptr) noexcept { u_long non_blocking = 1; if (ioctlsocket(s, FIONBIO, &non_blocking) == SOCKET_ERROR) @@ -214,27 +216,43 @@ namespace proxy } else if (WSAGetLastError() == WSAEWOULDBLOCK) { - fd_set write_set; - FD_ZERO(&write_set); - FD_SET(s, &write_set); - fd_set error_set; - FD_ZERO(&error_set); - FD_SET(s, &error_set); - - timeval tv; - tv.tv_sec = static_cast(timeout_ms / 1000); - tv.tv_usec = static_cast((timeout_ms % 1000) * 1000); - - if (const auto sel = select(0, nullptr, &write_set, &error_set, &tv); - sel > 0 && FD_ISSET(s, &write_set)) + // Wait in slices of at most 100 ms so that a caller's @p cancel flag ends the + // wait promptly; without a flag this is the same single bounded wait. + const auto deadline = GetTickCount64() + timeout_ms; + while (true) { - auto so_error = 0; - auto len = static_cast(sizeof(so_error)); - if (getsockopt(s, SOL_SOCKET, SO_ERROR, reinterpret_cast(&so_error), &len) == 0 && - so_error == 0) + const auto now = GetTickCount64(); + if (now >= deadline || (cancel && cancel->load(std::memory_order_acquire))) + break; + auto slice = deadline - now; + if (cancel && slice > 100) + slice = 100; + + fd_set write_set; + FD_ZERO(&write_set); + FD_SET(s, &write_set); + fd_set error_set; + FD_ZERO(&error_set); + FD_SET(s, &error_set); + + timeval tv; + tv.tv_sec = static_cast(slice / 1000); + tv.tv_usec = static_cast((slice % 1000) * 1000); + + const auto sel = select(0, nullptr, &write_set, &error_set, &tv); + if (sel == 0) + continue; + if (sel > 0 && FD_ISSET(s, &write_set)) { - succeeded = true; + auto so_error = 0; + auto len = static_cast(sizeof(so_error)); + if (getsockopt(s, SOL_SOCKET, SO_ERROR, reinterpret_cast(&so_error), &len) == 0 && + so_error == 0) + { + succeeded = true; + } } + break; } } diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index 9a06a70..f5497c8 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -37,10 +37,12 @@ namespace const uint8_t client_mac[6] = { 0x02, 0, 0, 0, 0, 0x10 }; const uint8_t gateway_mac[6] = { 0x02, 0, 0, 0, 0, 0x01 }; + /// A DNS message for "example.com" A IN followed by @p extra bytes standing for records. std::vector dns_message(const uint16_t id, const size_t extra = 17) { std::vector m{ static_cast(id >> 8), static_cast(id & 0xff), - 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; + 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 7, 'e', 'x', 'a', 'm', 'p', 'l', 'e', 3, 'c', 'o', 'm', 0, 0, 1, 0, 1 }; for (size_t i = 0; i < extra; ++i) m.push_back(static_cast(0x30 + i)); return m; @@ -214,11 +216,11 @@ namespace return frame::udp6(local_address, original_server, udp_listener, client_port, datagram); } - /// The DNS relay's listener step (socks5_dns_udp_relay.h), using the shipped bookkeeping: - /// forward() takes the datagram the redirect delivered to the listener, records the query and - /// returns the datagram sent through the shared SOCKS5 association, with the relay ID in - /// place of the client's message ID; answer() maps a relay datagram back and returns the - /// listener's reply frame to the client, or nothing when the answer matches no query. + /// The DNS relay's per-datagram steps (socks5_dns_udp_relay.h) through the shipped + /// dns_relay_session: forward() takes the datagram the redirect delivered to the listener and + /// returns the datagram sent through the shared SOCKS5 association, with the relay ID in place + /// of the client's message ID; answer() maps a relay datagram back and returns the listener's + /// reply frame to the client, or nothing when the session does not deliver it. template struct dns_relay { @@ -226,16 +228,14 @@ namespace static constexpr uint8_t address_type = std::is_same_v ? 1 : 4; static constexpr size_t address_size = std::is_same_v ? 4 : 16; - proxy::dns_query_table queries{ std::chrono::seconds{ 10 }, 64 }; + proxy::dns_relay_session session{ std::chrono::seconds{ 10 }, 64, 3, std::chrono::seconds{ 30 } }; std::chrono::steady_clock::time_point now{ std::chrono::seconds{ 1000 } }; + dns_relay() { session.on_opened(now); } + std::vector forward(frame& redirected, const uint16_t relay_id) { auto datagram = redirected.payload(); - const auto offset = proxy::socks5_dns_query_offset(datagram.data(), datagram.size(), address_type); - EXPECT_TRUE(offset.has_value()); - if (!offset) - return {}; // The listener's sender: the (swapped) queried server and the client port. Addr server; @@ -245,38 +245,26 @@ namespace server = Addr{ redirected.ip6()->ip6_src }; const client sender{ server, ntohs(redirected.udp()->th_sport) }; - const auto original_id = *proxy::dns_message_id(datagram.data() + *offset, datagram.size() - *offset); - const auto id = queries.insert(sender, original_id, now, [relay_id] { return relay_id; }); - EXPECT_EQ(id, std::optional{ relay_id }); - proxy::set_dns_message_id(datagram.data() + *offset, relay_id); + EXPECT_EQ(session.prepare_query(sender, datagram.data(), datagram.size(), address_type, now, + [relay_id] { return relay_id; }), proxy::dns_relay_query::send); return datagram; } - std::optional answer(const std::vector& relayed_bytes, const char* local_address) + std::optional answer(const std::vector& relayed, const char* local_address) { - const auto relayed = proxy::parse_socks5_udp_datagram(relayed_bytes.data(), relayed_bytes.size()); - if (!relayed) - return std::nullopt; - const auto relay_id = proxy::dns_message_id(relayed->data, relayed->data_size); - if (!relay_id) - return std::nullopt; - const auto query = queries.take(*relay_id, now); - if (!query) - return std::nullopt; - - std::vector out(relayed_bytes.size() + 32); - const auto size = proxy::build_dns_client_answer(*relayed, - reinterpret_cast(&query->client.ip), address_size, 53, query->original_id, - out.data(), out.size()); - if (size == 0) + std::vector out(relayed.size() + 32); + const auto result = session.prepare_answer(relayed.data(), relayed.size(), + [](const client& c) { return std::pair{ reinterpret_cast(&c.ip), address_size }; }, + out.data(), out.size(), now); + if (result.outcome != proxy::dns_relay_answer::deliver) return std::nullopt; - out.resize(size); + out.resize(result.size); - const std::string server{ query->client.ip }; + const std::string server{ result.client->ip }; if constexpr (std::is_same_v) - return frame::udp4(local_address, server.c_str(), udp_listener, query->client.port, out); + return frame::udp4(local_address, server.c_str(), udp_listener, result.client->port, out); else - return frame::udp6(local_address, server.c_str(), udp_listener, query->client.port, out); + return frame::udp6(local_address, server.c_str(), udp_listener, result.client->port, out); } }; @@ -579,7 +567,8 @@ TEST(DnsPacketRedirect, MalformedListenerRepliesAreRejectedUntouched) TEST(DnsPacketRedirect, UnredirectableUdpIsRejectedSoTheRouterDropsIt) { ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; - const auto big = dns_message(0x3333, MAX_ETHER_FRAME - ETHER_HEADER_LENGTH - sizeof(iphdr) - sizeof(udphdr) - 12 - 4); + // Room for everything but 4 of the 10 SOCKS5 header bytes (12-byte header, 17-byte question). + const auto big = dns_message(0x3333, MAX_ETHER_FRAME - ETHER_HEADER_LENGTH - sizeof(iphdr) - sizeof(udphdr) - 12 - 17 - 4); auto packet = frame::udp4("192.168.1.10", "192.168.1.1", client_port, 53, big); EXPECT_TRUE(redirect.is_new_endpoint(packet.buffer)); EXPECT_FALSE(redirect.process_client_to_server_packet(packet.buffer, htons(udp_listener))); diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index d6bb5f6..d817f9c 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -296,9 +296,42 @@ TEST(DnsAssociationHealth, FailedOpensBackOffExponentiallyUpTo30Seconds) EXPECT_TRUE(health.may_open(t0 + delay)); } + // An association that stays open for the minimum age resets the backoff. + health.on_opened(t0 + 30s); + EXPECT_EQ(health.consecutive_failures(), 7u); + health.on_closed(t0 + 60s); + EXPECT_EQ(health.consecutive_failures(), 0u); + EXPECT_TRUE(health.may_open(t0 + 60s)); +} + +TEST(DnsAssociationHealth, AssociationClosingSoonAfterOpeningBacksOff) +{ + // A server that accepts UDP ASSOCIATE and then drops the control connection must not be + // reconnected in a tight loop. + proxy::dns_association_health<> health{ 3, 30s }; health.on_opened(t0); + health.on_closed(t0 + 1s); + EXPECT_EQ(health.consecutive_failures(), 1u); + EXPECT_FALSE(health.may_open(t0 + 1s)); + EXPECT_TRUE(health.may_open(t0 + 2s)); + + health.on_opened(t0 + 2s); + health.on_closed(t0 + 3s); + EXPECT_EQ(health.consecutive_failures(), 2u); + EXPECT_FALSE(health.may_open(t0 + 4s)); + EXPECT_TRUE(health.may_open(t0 + 5s)); +} + +TEST(DnsAssociationHealth, LongLivedAssociationResetsTheBackoffWhileOpen) +{ + proxy::dns_association_health<> health{ 3, 30s }; + health.on_open_failed(t0); + health.on_open_failed(t0); + health.on_opened(t0 + 2s); + EXPECT_FALSE(health.on_unanswered(0, t0 + 31s)); + EXPECT_EQ(health.consecutive_failures(), 1u + 1u); + EXPECT_FALSE(health.on_unanswered(0, t0 + 32s)); EXPECT_EQ(health.consecutive_failures(), 0u); - EXPECT_TRUE(health.may_open(t0)); } TEST(DnsAssociationHealth, SilentAssociationIsReopenedOnlyAfterUnansweredQueriesAndMinimumAge) @@ -319,20 +352,35 @@ TEST(DnsAssociationHealth, YoungAssociationIsNotChurnedByAResolverThatNeverAnswe EXPECT_TRUE(health.on_unanswered(0, t0 + 30s)); } -TEST(DnsAssociationHealth, AnyRelayDatagramResetsTheUnansweredCount) +TEST(DnsAssociationHealth, RelayDatagramResetsTheCountAndIsRemembered) { proxy::dns_association_health<> health{ 3, 30s }; health.on_opened(t0); + EXPECT_FALSE(health.last_datagram().has_value()); EXPECT_FALSE(health.on_unanswered(2, t0 + 40s)); - health.on_relay_datagram(); + health.on_relay_datagram(t0 + 41s); + EXPECT_EQ(health.last_datagram(), std::optional{ t0 + 41s }); EXPECT_FALSE(health.on_unanswered(2, t0 + 41s)); EXPECT_TRUE(health.on_unanswered(1, t0 + 42s)); - // Reopening resets the count and the age. + // Reopening resets the count, the age and the last datagram. health.on_opened(t0 + 50s); + EXPECT_FALSE(health.last_datagram().has_value()); EXPECT_FALSE(health.on_unanswered(5, t0 + 60s)); } +TEST(DnsQueryTable, ExpireCountsOnlyQueriesSentAfterTheGivenTime) +{ + table_t table{ 10s, 1024 }; + scripted_random random{ { 1, 2, 3 } }; + (void)table.insert({ 1, 1 }, 1, t0, random); + (void)table.insert({ 2, 2 }, 1, t0 + 2s, random); + (void)table.insert({ 3, 3 }, 1, t0 + 3s, random); + // All three expire; only the two sent after t0 + 1 s are counted. + EXPECT_EQ(table.expire(t0 + 20s, t0 + 1s), 2u); + EXPECT_EQ(table.size(), 0u); +} + TEST(DnsQueryTable, InsertDoesNotSilentlyDiscardExpiredQueries) { // Unanswered queries feed the association health check, so they must be counted by @@ -441,3 +489,224 @@ TEST(DnsAnswerTruncation, ClientAnswerIsTruncatedToTheListenersLimit) EXPECT_EQ(proxy::build_dns_client_answer(*fits_view, v4_server.data(), 4, 53, 1, out.data(), out.size()), 10u + proxy::dns_udp_answer_limit(1)); } + +// --- Question check --------------------------------------------------------------------------- + +namespace +{ + /// A DNS message with header flags @p flags and one question for @p name (dot-separated). + std::vector dns_with_question(const uint16_t id, const uint16_t flags, const std::string& name, + const uint16_t type = 1, const std::vector& records = {}) + { + std::vector m{ static_cast(id >> 8), static_cast(id & 0xff), + static_cast(flags >> 8), static_cast(flags & 0xff), 0, 1, + 0, static_cast(records.empty() ? 0 : 1), 0, 0, 0, 0 }; + std::size_t start = 0; + while (start <= name.size()) + { + const auto dot = name.find('.', start); + const auto label = name.substr(start, dot == std::string::npos ? std::string::npos : dot - start); + m.push_back(static_cast(label.size())); + m.insert(m.end(), label.begin(), label.end()); + if (dot == std::string::npos) + break; + start = dot + 1; + } + m.push_back(0); + m.push_back(static_cast(type >> 8)); + m.push_back(static_cast(type & 0xff)); + m.push_back(0); + m.push_back(1); + m.insert(m.end(), records.begin(), records.end()); + return m; + } + + std::vector query(const uint16_t id, const std::string& name, const uint16_t type = 1) + { + return dns_with_question(id, 0x0100, name, type); + } + + std::vector response(const uint16_t id, const std::string& name, const uint16_t type = 1) + { + return dns_with_question(id, 0x8180, name, type, { 0xC0, 0x0C, 0, 1, 0, 1, 0, 0, 0, 60, 0, 4, 93, 184, 216, 34 }); + } +} + +TEST(DnsQuestionCheck, AnswerMustCarryTheQueriedQuestion) +{ + const auto asked = query(1, "example.com"); + const auto fingerprint = proxy::dns_question_fingerprint(asked.data(), asked.size()); + ASSERT_TRUE(fingerprint.has_value()); + + const auto same = response(2, "example.com"); + EXPECT_TRUE(proxy::dns_answer_matches_question(same.data(), same.size(), *fingerprint)); + // Names compare without regard to ASCII case (resolvers may randomize it). + const auto mixed_case = response(2, "ExAmPlE.CoM"); + EXPECT_TRUE(proxy::dns_answer_matches_question(mixed_case.data(), mixed_case.size(), *fingerprint)); + + const auto other_name = response(2, "example.org"); + EXPECT_FALSE(proxy::dns_answer_matches_question(other_name.data(), other_name.size(), *fingerprint)); + const auto other_type = response(2, "example.com", 28); + EXPECT_FALSE(proxy::dns_answer_matches_question(other_type.data(), other_type.size(), *fingerprint)); +} + +TEST(DnsQuestionCheck, QuestionlessErrorResponsesAreAcceptedOtherQuestionlessMessagesAreNot) +{ + const auto asked = query(1, "example.com"); + const auto fingerprint = *proxy::dns_question_fingerprint(asked.data(), asked.size()); + + // FORMERR / NOTIMP without a question section. + std::vector error{ 0, 2, 0x81, 0x84, 0, 0, 0, 0, 0, 0, 0, 0 }; + EXPECT_TRUE(proxy::dns_answer_matches_question(error.data(), error.size(), fingerprint)); + + std::vector success_without_question{ 0, 2, 0x81, 0x80, 0, 0, 0, 0, 0, 0, 0, 0 }; + EXPECT_FALSE(proxy::dns_answer_matches_question(success_without_question.data(), success_without_question.size(), fingerprint)); + std::vector query_without_question{ 0, 2, 0x01, 0x04, 0, 0, 0, 0, 0, 0, 0, 0 }; + EXPECT_FALSE(proxy::dns_answer_matches_question(query_without_question.data(), query_without_question.size(), fingerprint)); + + // A query without a parsable question has no fingerprint. + EXPECT_FALSE(proxy::dns_question_fingerprint(success_without_question.data(), success_without_question.size())); + auto truncated = asked; + truncated.resize(truncated.size() - 2); + EXPECT_FALSE(proxy::dns_question_fingerprint(truncated.data(), truncated.size())); +} + +// --- Relay session ------------------------------------------------------------------------------ + +namespace +{ + using session_t = proxy::dns_relay_session; + + session_t make_session() + { + return session_t{ 10s, 4096, 3, 30s }; + } + + std::pair address_bytes(const test_client& client) + { + return { reinterpret_cast(&client.server), sizeof(client.server) }; + } + + /// Sends @p name from @p client through @p session; returns the relay ID used. + uint16_t send_query(session_t& session, const test_client& client, const uint16_t id, const std::string& name, + const time_point at, const uint16_t relay_id) + { + auto datagram = socks_datagram(v4_override, 53, query(id, name)); + EXPECT_EQ(session.prepare_query(client, datagram.data(), datagram.size(), 1, at, [relay_id] { return relay_id; }), + proxy::dns_relay_query::send); + return static_cast((datagram[10] << 8) | datagram[11]); + } + + session_t::answer receive(session_t& session, const uint16_t relay_id, const std::string& name, const time_point at) + { + const auto relayed = socks_datagram(v4_override, 53, response(relay_id, name)); + std::vector out(1024); + return session.prepare_answer(relayed.data(), relayed.size(), address_bytes, out.data(), out.size(), at); + } +} + +TEST(DnsRelaySession, QueryIsRewrittenAndItsAnswerDelivered) +{ + auto session = make_session(); + const test_client client{ 0x0101A8C0, 50000 }; + session.on_opened(t0); + + EXPECT_EQ(send_query(session, client, 0x1234, "example.com", t0, 0x7777), 0x7777); + const auto answer = receive(session, 0x7777, "example.com", t0 + 1s); + EXPECT_EQ(answer.outcome, proxy::dns_relay_answer::deliver); + ASSERT_TRUE(answer.client.has_value()); + EXPECT_EQ(*answer.client, client); + EXPECT_GT(answer.size, 10u + 12u); + EXPECT_EQ(receive(session, 0x7777, "example.com", t0 + 1s).outcome, proxy::dns_relay_answer::unmatched); +} + +TEST(DnsRelaySession, MalformedQueriesAreRejected) +{ + auto session = make_session(); + auto no_question = socks_datagram(v4_override, 53, std::vector{ 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); + EXPECT_EQ(session.prepare_query({ 1, 1 }, no_question.data(), no_question.size(), 1, t0, [] { return uint16_t{ 1 }; }), + proxy::dns_relay_query::malformed); + auto wrong_family = socks_datagram(v6_relay_source, 53, query(1, "example.com")); + EXPECT_EQ(session.prepare_query({ 1, 1 }, wrong_family.data(), wrong_family.size(), 1, t0, [] { return uint16_t{ 1 }; }), + proxy::dns_relay_query::malformed); + EXPECT_EQ(session.queries_in_flight(), 0u); +} + +TEST(DnsRelaySession, AnswerToAnotherQuestionIsDroppedWithoutConsumingTheQuery) +{ + auto session = make_session(); + session.on_opened(t0); + (void)send_query(session, { 1, 1 }, 0x1111, "example.com", t0, 0x2222); + + // A late or forged answer carrying the same relay ID but another question. + EXPECT_EQ(receive(session, 0x2222, "attacker.example", t0 + 1s).outcome, proxy::dns_relay_answer::question_mismatch); + // The real answer still gets through. + EXPECT_EQ(receive(session, 0x2222, "example.com", t0 + 2s).outcome, proxy::dns_relay_answer::deliver); +} + +TEST(DnsRelaySession, UnparsableRelayDatagramsAreMalformed) +{ + auto session = make_session(); + std::vector out(64); + const std::vector garbage{ 1, 2, 3 }; + EXPECT_EQ(session.prepare_answer(garbage.data(), garbage.size(), address_bytes, out.data(), out.size(), t0).outcome, + proxy::dns_relay_answer::malformed); +} + +// The scenario behind a review finding: Windows also queries a resolver the proxy cannot reach. +// Its queries expire unanswered while answers from a working resolver keep arriving; the +// association must stay open, because the relay is clearly alive. +TEST(DnsRelaySession, UnreachableResolverDoesNotRetireAWorkingAssociation) +{ + auto session = make_session(); + session.on_opened(t0); + + uint16_t relay_id = 0x100; + for (int round = 0; round < 12; ++round) + { + const auto at = t0 + std::chrono::seconds{ round * 5 }; + // Three lookups to the dead resolver and one to the working resolver, sent together. + for (int dead = 0; dead < 3; ++dead) + (void)send_query(session, { 0xDEAD, static_cast(60000 + round * 4 + dead) }, 1, "dead.example", at, ++relay_id); + const auto working = send_query(session, { 0x0808, static_cast(61000 + round) }, 1, "ok.example", at, ++relay_id); + // The working resolver answers 50 ms later. + EXPECT_EQ(receive(session, working, "ok.example", at + 50ms).outcome, proxy::dns_relay_answer::deliver); + EXPECT_FALSE(session.expire(at + 1s)) << "round " << round; + EXPECT_FALSE(session.expire(at + 4s)) << "round " << round; + } +} + +TEST(DnsRelaySession, SilentlyDeadAssociationIsRetired) +{ + auto session = make_session(); + session.on_opened(t0); + // Nothing ever comes back from the relay. + for (int i = 0; i < 3; ++i) + (void)send_query(session, { 1, static_cast(i) }, 1, "a.example", t0 + 25s, static_cast(10 + i)); + EXPECT_FALSE(session.expire(t0 + 30s)); + EXPECT_TRUE(session.expire(t0 + 36s)); +} + +TEST(DnsRelaySession, AnswersAfterTheQueriesWereSentDoNotHideALaterSilence) +{ + auto session = make_session(); + session.on_opened(t0); + const auto first = send_query(session, { 1, 1 }, 1, "a.example", t0 + 30s, 1); + EXPECT_EQ(receive(session, first, "a.example", t0 + 31s).outcome, proxy::dns_relay_answer::deliver); + // The relay goes silent after t0 + 31 s: three later queries expire unanswered. + for (int i = 0; i < 3; ++i) + (void)send_query(session, { 1, static_cast(2 + i) }, 1, "a.example", t0 + 32s, static_cast(2 + i)); + EXPECT_TRUE(session.expire(t0 + 43s)); +} + +TEST(DnsRelaySession, ClosingForgetsQueriesInFlightAndBacksOffWhenEarly) +{ + auto session = make_session(); + session.on_opened(t0); + (void)send_query(session, { 1, 1 }, 1, "a.example", t0, 5); + session.on_closed(t0 + 2s); + EXPECT_EQ(session.queries_in_flight(), 0u); + EXPECT_EQ(session.consecutive_failures(), 1u); + EXPECT_FALSE(session.may_open(t0 + 2s)); + EXPECT_TRUE(session.may_open(t0 + 3s)); +} From 9294724e9a474d67ae424d97c3d853cd5007503e Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 18:21:29 +0000 Subject: [PATCH 41/62] fix(router): stop the DNS relays first; dedicated DNS client ports - stop() stopped the packet filter before the DNS relays, so answers a relay sent while stopping left the host unfiltered. The relays now stop first. New UDP DNS is blocked while they stop, but their listener ports stay recognized so their last answers are still translated. - The relay accepted any source port in the shared UDP source-port mapper, including ports of application UDP redirected to the per-port listeners, and an application UDP association could erase a DNS port's entry. UDP DNS source ports are now recorded in their own map, which the relay checks and the resolver thread sweeps. - The last DNS and listener drop counts are reported on stop(). - A comment that had drifted away from install_dns_filters() is back with it. --- netlib/src/proxy/socks_local_router.h | 173 +++++++++++++++++++------- 1 file changed, 125 insertions(+), 48 deletions(-) diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 1fe0e2e..db7ff26 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -293,6 +293,19 @@ namespace proxy std::unique_ptr> dns_udp_relay_v4_; std::unique_ptr> dns_udp_relay_v6_; + /** + * @brief Local source ports of UDP DNS queries redirected to the DNS relay, with the time + * of the last one. The relay accepts datagrams only from these ports (refreshed + * within udp_mapper_entry_ttl_). Swept by the resolver thread. + */ + /// Set while the DNS relays stop: new UDP DNS is blocked, but the relays' listener + /// ports are still recognized so their last answers are translated. Guarded by lock_. + bool dns_udp_relays_stopping_{ false }; + + std::unordered_map dns_udp_clients_v4_; + std::unordered_map dns_udp_clients_v6_; + std::mutex dns_udp_clients_lock_; + /** * @brief Count of DNS packets dropped by the Proxy-mode policy since the last * throttled report from the resolver thread. @@ -620,6 +633,15 @@ namespace proxy return *udp_redirect_v6_; } + template + auto& dns_udp_clients_for() noexcept + { + if constexpr (std::is_same_v) + return dns_udp_clients_v4_; + else + return dns_udp_clients_v6_; + } + template const auto& dns_udp_relay_for() const noexcept { @@ -992,9 +1014,6 @@ namespace proxy if (udp) udp->stop(); - // Proxy-mode DNS must take precedence over the LAN-bypass PASS filters: (re)install - // the front-of-table REDIRECT filters with the current listener ports. If that fails, - // fail start() instead of running with DNS able to bypass the policy. // stop() joined the redirects' cleanup threads; a later start() must run them again // so expired TCP and UDP entries (including closed and reset connections) are removed. if (tcp_redirect_) @@ -1006,6 +1025,11 @@ namespace proxy if (udp_redirect_v6_) udp_redirect_v6_->restart(); + { + std::scoped_lock lock(dns_udp_clients_lock_); + dns_udp_clients_v4_.clear(); + dns_udp_clients_v6_.clear(); + } start_dns_udp_relays(); dns_blocked_packets_.store(0, std::memory_order_relaxed); untranslated_listener_replies_.store(0, std::memory_order_relaxed); @@ -1013,6 +1037,10 @@ namespace proxy listener_segments_after_reset_.store(0, std::memory_order_relaxed); for (auto& flag : dns_block_reason_logged_) flag.clear(std::memory_order_relaxed); + + // Proxy-mode DNS must take precedence over the LAN-bypass PASS filters: (re)install + // the front-of-table REDIRECT filters with the current listener ports. If that fails, + // fail start() instead of running with DNS able to bypass the policy. if (!install_dns_filters()) { start_failure_cleanup(); @@ -1076,7 +1104,12 @@ namespace proxy if (auto expected = true; !is_active_.compare_exchange_strong(expected, false)) return false; - // Step 1: Stop the packet filter FIRST + // Step 0: Stop the DNS relays while the packet filter still runs, so answers they + // send while stopping are still translated (or dropped) instead of reaching the + // network. Without a relay, UDP DNS is blocked until the filter stops. + stop_dns_udp_relays(); + + // Step 1: Stop the packet filter // This prevents new packets from being processed and queued NETLIB_DEBUG("Stopping packet filter"); packet_filter_->stop_filter(); @@ -1095,6 +1128,10 @@ namespace proxy if (process_resolve_thread_.joinable()) process_resolve_thread_.join(); + // Report the last DNS and listener drop counts, which the resolver thread may not + // have reached. + (void)report_listener_and_dns_drops(); + // Step 3: Stop all redirect objects FIRST to stop their cleanup threads // CRITICAL: Stop redirects before stopping proxies to ensure cleanup threads finish NETLIB_DEBUG("Stopping redirect objects"); @@ -1119,9 +1156,6 @@ namespace proxy udp_redirect_v6_->stop(); // This should join the cleanup thread } - // Step 3b: Stop the DNS relays (their threads are joined without lock_ held). - stop_dns_udp_relays(); - // Step 4: Stop all proxy servers WITHOUT holding lock_ // CRITICAL: We must NOT hold lock_ while calling stop() or during destruction // because the cleanup threads inside the proxies need to acquire the same lock @@ -2246,7 +2280,9 @@ namespace proxy // UDP DNS goes through the DNS relay's shared association, not the proxy's // per-source-port UDP listener. const auto& relay = dns_udp_relay_for(); - return relay ? std::optional{ relay->listener_port() } : std::nullopt; + return relay && !dns_udp_relays_stopping_ + ? std::optional{ relay->listener_port() } + : std::nullopt; } else { @@ -2493,8 +2529,8 @@ namespace proxy * server override the header carries the override while the IP header keeps the * original destination. The relay sends the query through its shared SOCKS5 association * and answers the client as the server it queried (socks5_dns_udp_relay.h). The source - * port is recorded in the UDP source-port mapper, which is what authorizes the relay to - * accept datagrams from it. Anything that cannot be redirected is dropped, never passed. + * port is recorded in dns_udp_clients_, which is what authorizes the relay to accept + * datagrams from it. Anything that cannot be redirected is dropped, never passed. */ template packet_filter::packet_action handle_dns_udp(netlib::ndisapi::intermediate_buffer& buffer, @@ -2538,8 +2574,8 @@ namespace proxy } { - std::scoped_lock lock(udp_mapper_lock_for()); - udp_mapper_for().insert_or_assign(source_port, std::chrono::steady_clock::now()); + std::scoped_lock lock(dns_udp_clients_lock_); + dns_udp_clients_for().insert_or_assign(source_port, std::chrono::steady_clock::now()); } if (is_new_endpoint) @@ -2646,8 +2682,8 @@ namespace proxy /** * @brief Creates and starts a DNS relay for family @p AddrT through SOCKS5 server * @p upstream. Its listener accepts only source ports the router recently redirected - * (the UDP source-port mapper), and every relay endpoint it is given is reported to - * the recursion guard. Returns null when the relay cannot be started. + * to it (dns_udp_clients_), and every relay endpoint it is given is reported to the + * recursion guard. Returns null when the relay cannot be started. */ template std::unique_ptr> make_dns_udp_relay(const net::ip_endpoint& upstream, @@ -2659,10 +2695,10 @@ namespace proxy settings.upstream_options, [this](const uint16_t port) { - auto& mapper = udp_mapper_for(); - std::scoped_lock lock(udp_mapper_lock_for()); - const auto it = mapper.find(port); - return it != mapper.end() && + std::scoped_lock lock(dns_udp_clients_lock_); + const auto& clients = dns_udp_clients_for(); + const auto it = clients.find(port); + return it != clients.end() && std::chrono::steady_clock::now() - it->second <= udp_mapper_entry_ttl_; }, [this](const net::ip_endpoint& relay_endpoint) @@ -2728,22 +2764,36 @@ namespace proxy } /** - * @brief Stops and destroys the DNS relays. Their threads are joined without lock_ held. + * @brief Stops and destroys the DNS relays. New UDP DNS is blocked first; the relays stay + * registered while they stop so their listener ports are still recognized and + * answers they send meanwhile are translated rather than passed. Their threads are + * joined without lock_ held. Called under lifecycle_mutex_, which also serializes + * every write of the relay pointers. */ void stop_dns_udp_relays() { - std::unique_ptr> relay_v4; - std::unique_ptr> relay_v6; + socks5_dns_udp_relay* relay_v4; + socks5_dns_udp_relay* relay_v6; { std::unique_lock lock(lock_); - relay_v4 = std::move(dns_udp_relay_v4_); - relay_v6 = std::move(dns_udp_relay_v6_); + dns_udp_relays_stopping_ = true; + relay_v4 = dns_udp_relay_v4_.get(); + relay_v6 = dns_udp_relay_v6_.get(); } if (relay_v4) relay_v4->stop(); if (relay_v6) relay_v6->stop(); + + std::unique_ptr> stopped_v4; + std::unique_ptr> stopped_v6; + { + std::unique_lock lock(lock_); + stopped_v4 = std::move(dns_udp_relay_v4_); + stopped_v6 = std::move(dns_udp_relay_v6_); + dns_udp_relays_stopping_ = false; + } } /** @@ -3493,6 +3543,42 @@ namespace proxy ); } + /** + * @brief Logs and resets the counts of Proxy-mode DNS drops and of listener packets that + * were dropped. Called by the resolver thread at a throttled rate, and once more by + * stop() so the last counts are not lost. + * @return Whether anything was reported. + */ + bool report_listener_and_dns_drops() + { + bool reported = false; + if (const auto blocked = dns_blocked_packets_.exchange(0, std::memory_order_relaxed); blocked != 0) + { + reported = true; + NETLIB_LOG(log_level::warning, + "DNS routing: dropped {} DNS packet(s) that could not be sent through the DNS proxy " + "(they were not sent directly).", blocked); + } + if (const auto untranslated = untranslated_listener_replies_.exchange(0, std::memory_order_relaxed); + untranslated != 0) + { + reported = true; + NETLIB_LOG(log_level::info, + "Dropped {} packet(s) from local proxy listeners that could not be translated back " + "(no tracked connection, fragmented, or malformed); they were not sent to the network.", + untranslated); + } + if (const auto after_reset = listener_segments_after_reset_.exchange(0, std::memory_order_relaxed); + after_reset != 0) + { + reported = true; + NETLIB_LOG(log_level::debug, + "Dropped {} segment(s) from local TCP listeners for connections that had just been reset " + "(expected during aborts).", after_reset); + } + return reported; + } + /** * @brief Thread procedure for deferred process resolution and packet forwarding. * @@ -3645,39 +3731,30 @@ namespace proxy } } } + + // Same TTL sweep for the DNS relay's client ports. + { + std::scoped_lock lock(dns_udp_clients_lock_); + for (auto* clients : { &dns_udp_clients_v4_, &dns_udp_clients_v6_ }) + { + for (auto it = clients->begin(); it != clients->end();) + { + if (now - it->second > udp_mapper_entry_ttl_) + it = clients->erase(it); + else + ++it; + } + } + } } // Report Proxy-mode DNS drops and untranslatable listener replies at the same // throttled rate as the queue drops so a resolver retrying against an // unreachable proxy cannot flood the log. if (const auto now = std::chrono::steady_clock::now(); - now - last_dns_block_log >= drop_log_throttle_interval_ && - (dns_blocked_packets_.load(std::memory_order_relaxed) != 0 || - untranslated_listener_replies_.load(std::memory_order_relaxed) != 0 || - listener_segments_after_reset_.load(std::memory_order_relaxed) != 0)) + now - last_dns_block_log >= drop_log_throttle_interval_ && report_listener_and_dns_drops()) { last_dns_block_log = now; - if (const auto blocked = dns_blocked_packets_.exchange(0, std::memory_order_relaxed); blocked != 0) - { - NETLIB_LOG(log_level::warning, - "DNS routing: dropped {} DNS packet(s) that could not be sent through the DNS proxy " - "(they were not sent directly).", blocked); - } - if (const auto untranslated = untranslated_listener_replies_.exchange(0, std::memory_order_relaxed); - untranslated != 0) - { - NETLIB_LOG(log_level::info, - "Dropped {} packet(s) from local proxy listeners that could not be translated back " - "(no tracked connection, fragmented, or malformed); they were not sent to the network.", - untranslated); - } - if (const auto after_reset = listener_segments_after_reset_.exchange(0, std::memory_order_relaxed); - after_reset != 0) - { - NETLIB_LOG(log_level::debug, - "Dropped {} segment(s) from local TCP listeners for connections that had just been reset " - "(expected during aborts).", after_reset); - } } // Periodically surface the counts of packets dropped due to a From 20bfaa53d78c35e7422e96ef59f0fbce8a669be5 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 18:21:29 +0000 Subject: [PATCH 42/62] chore: reuse the shared UDP socket buffer size in the per-port UDP proxy --- netlib/src/proxy/socks5_local_udp_proxy_server.h | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/netlib/src/proxy/socks5_local_udp_proxy_server.h b/netlib/src/proxy/socks5_local_udp_proxy_server.h index e1c9aaa..7f7f6ad 100644 --- a/netlib/src/proxy/socks5_local_udp_proxy_server.h +++ b/netlib/src/proxy/socks5_local_udp_proxy_server.h @@ -106,16 +106,8 @@ namespace proxy */ constexpr static size_t connections_array_size = 64; - /** - * @brief Requested UDP socket buffer size for QUIC-sized bursts. - * - * Browser QUIC can emit many ~1200 byte datagrams immediately. The first - * datagram for a local UDP source port may need to establish a SOCKS5 TCP - * control connection and complete UDP ASSOCIATE before it can be forwarded; - * while that happens, the local UDP proxy socket relies on the kernel - * receive buffer to hold the rest of the burst. - */ - constexpr static int udp_socket_buffer_size = 4 * 1024 * 1024; + /** Requested UDP socket buffer size (see socks5_udp_association_client). */ + constexpr static int udp_socket_buffer_size = socks5_udp_association_client::udp_socket_buffer_size; /** Number of blocking SOCKS5 UDP ASSOCIATE operations allowed in parallel. */ constexpr static size_t association_worker_count = 4; From beea6fe104f9b8185d19a7e4d68953d58a8b4a0e Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 18:21:58 +0000 Subject: [PATCH 43/62] docs: match the shared UDP association's behavior after the review fixes Waiting queries, the question check, when an association is retired (only queries sent after the last datagram from the relay count), the early-close backoff, keepalive, logging per address family (every open and close at Info, final counts on stop), which source ports the listener accepts, and the stop order. The Windows checklist adds the two-resolver case and a service stop while the SOCKS5 server is black-holed. --- docs/configuration.md | 12 ++++++------ docs/gui.md | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 7d1901f..9db5bee 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -188,16 +188,16 @@ The selection is made by `proxyId`, never by position, so reordering rules does ### Shared UDP association -UDP DNS of each address family goes through a single SOCKS5 control connection and `UDP ASSOCIATE`, however many processes and source ports send queries. Only the first query, and the first after the association is reopened, waits for the SOCKS5 handshake (and, with `TLS` transport, the TLS handshake). +UDP DNS of each address family goes through a single SOCKS5 control connection and `UDP ASSOCIATE`, however many processes and source ports send queries. Only queries that arrive while the association is being opened (when the first query arrives, or after it was closed) wait for the SOCKS5 handshake (and, with `TLS` transport, the TLS handshake); after that, queries are sent at once. -- **Matching answers to queries.** While a query is in flight, its DNS message ID is replaced by a unique, randomly chosen ID. The answer carrying that ID is returned to the socket that asked, with the socket's own message ID. A retransmission from the same socket reuses the ID. Up to 4,096 queries can be in flight; a query without an answer is forgotten after 10 seconds, and an answer that matches no query in flight is dropped. +- **Matching answers to queries.** While a query is in flight, its DNS message ID is replaced by a unique, randomly chosen ID. The answer carrying that ID is returned to the socket that asked, with the socket's own message ID, but only if it also carries the query's question (name, ignoring case, type and class). A question-less error response from the server is accepted too. A retransmission from the same socket reuses the ID. Up to 4,096 queries can be in flight; a query without an answer is forgotten after 10 seconds. An answer that matches no query in flight, or whose question differs, is dropped. A query whose question section cannot be parsed is dropped. - **Source of the answer.** The answer is presented as coming from the server Windows queried, whatever source address (IPv4 or IPv6) the SOCKS5 relay reports, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered (the `serverOverride` server when one is set); some report their own address. This applies with or without a `serverOverride`. - **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. -- **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it. It is closed and reopened on the next query when its control connection closes, its relay socket fails, or it looks silently dead: three queries in a row went unanswered while nothing arrived from the relay, and it has been open for at least 30 seconds. Queries in flight at that moment are lost, and Windows retries them. -- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. -- **Logging.** The first failure to open the association is logged as a warning and later failures at `Debug`; closing and reopening are logged at `Info`. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds. +- **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it. It is closed, and reopened on the next query, when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. +- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening counts as a failed attempt, so a server that accepts `UDP ASSOCIATE` and then drops the connection is not reconnected in a tight loop. +- **Logging.** Per address family, the first failure to open the association is logged as a warning and later failures at `Debug`; every successful open and every close is logged at `Info` with its reason. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. -The local listener accepts only datagrams from source ports ProxiFyre has just redirected there, so it cannot be used to send arbitrary UDP through the proxy. +The local listener accepts only datagrams from source ports from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, so it cannot be used to send arbitrary UDP through the proxy. When the service stops, the DNS relays stop while packet filtering is still active, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile. ### Server override diff --git a/docs/gui.md b/docs/gui.md index a3e1aed..e3a27c5 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -165,7 +165,7 @@ The routing policy and the packet rewriting are covered by automated tests (`net 2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). Browse for a few minutes and confirm the SOCKS5 server sees one control connection and one `UDP ASSOCIATE` per address family for UDP DNS, not one per query. 3. Enable `bypassLan` with a router resolver (`192.168.x.1`): without an override the SOCKS5 server is asked for the router address; with `serverOverride: "1.1.1.1"` it is asked for `1.1.1.1` and `Resolve-DnsName` still reports answers from the router address. 4. Reorder the rules, Apply & Restart, and confirm DNS still uses the selected proxy. -5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning, and attempts back off to one every 30 seconds. Start the SOCKS5 server again and confirm lookups recover within 30 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" at `Info`) and lookups recover. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. +5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning per address family in use, and attempts back off to one every 30 seconds. Start the SOCKS5 server again and confirm lookups recover within 30 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" and "opened" at `Info`) and lookups recover. Configure Windows with a second DNS server the SOCKS5 server cannot reach (for example a LAN address, without `serverOverride`), browse for two minutes, and confirm the log has no "queries stopped being answered" line. Stop the service while the SOCKS5 server is unreachable (black-holed, not refusing) and confirm it stops within a few seconds. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. 6. Configure an IPv4 override with an IPv6 resolver and confirm IPv6 queries are dropped while IPv4 queries succeed. 7. **Upgrade.** With a configuration from an earlier release (no `dns` section, a catch-all rule), confirm that `Resolve-DnsName -TcpOnly` now leaves the adapter directly, that UDP DNS still does, and that the rule's other traffic is still proxied. 8. **Restart.** With `Proxy` mode and `bypassLan`, use **Apply & Restart** (or stop and start the service) and repeat step 3: DNS to the router resolver must still be proxied. From e06af8cdc66c3898536fb61e806394adc132887b Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 18:37:58 +0000 Subject: [PATCH 44/62] fix(dns relay): drop stale queued queries, check query destinations, close the stop window Review findings on the shared UDP association and its shutdown: - Queued queries. Queries queued after the association failed could wait through a backoff of up to 30 s and then be sent long after Windows gave up. A query now waits at most 3 s, and the queue is dropped when a failure starts a backoff. - Listener access. The relay checked only the sender's source port. It now also refuses loopback senders and accepts only a SOCKS5 destination of port 53 of the sender's address (the server the client queried) or, with a server override, the override, which the router now passes to each relay (dns_relay_destination_allowed()). - Stop window. stop() unregistered the relays right after stopping them, before the packet filter stopped, so an answer sent at the last moment could no longer be recognized as a listener reply. The stopped relays now stay registered until the filter has stopped (release_dns_udp_relays()). UDP DNS blocked during that window uses a new service_stopping reason, which is neither counted nor warned about. - Silent association. An association retired because queries stopped being answered now starts a backoff whatever its age, instead of reopening at once every 30 to 40 s while the relay is unreachable. - Keepalive is set with SIO_KEEPALIVE_VALS (60 s idle, 10 s interval), which every supported Windows version honors, instead of options an older SDK or Windows may lack. - A misplaced member comment is fixed. --- netlib/src/proxy/dns_routing_policy.h | 3 + netlib/src/proxy/dns_udp_multiplexer.h | 88 ++++++++++++++++-- netlib/src/proxy/socks5_dns_udp_relay.h | 91 +++++++++++++++---- netlib/src/proxy/socks_local_router.h | 65 +++++++++---- .../test/proxy/dns_udp_multiplexer_test.cpp | 69 ++++++++++++++ 5 files changed, 272 insertions(+), 44 deletions(-) diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 0ac12d2..629b806 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -57,6 +57,7 @@ namespace proxy upstream_sender_unknown, ///< addressed to a SOCKS5 server, and its sender could not be resolved fragmented, ///< the first fragment of a fragmented datagram addressed to port 53 not_dns_message, ///< a UDP datagram too short for a DNS header: it cannot be relayed + service_stopping, ///< the DNS proxy is stopping (expected; not reported) count }; @@ -215,6 +216,8 @@ namespace proxy case dns_block_reason::fragmented: return "the datagram is fragmented and cannot be redirected through the DNS proxy; only its first " "fragment, which carries the port, is dropped"; + case dns_block_reason::service_stopping: + return "the DNS proxy is stopping"; case dns_block_reason::not_dns_message: return "the UDP datagram is too short to be a DNS message, so the DNS proxy cannot relay it"; case dns_block_reason::upstream_sender_unknown: diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index 4946315..49a62a7 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -55,6 +55,71 @@ namespace proxy return static_cast(view->data - datagram); } + /// Whether @p address (network byte order, 4 or 16 bytes) is a loopback address, including + /// an IPv4-mapped IPv6 loopback address. + [[nodiscard]] constexpr bool is_loopback_address(const uint8_t* address, const std::size_t size) noexcept + { + if (address == nullptr) + return false; + if (size == 4) + return address[0] == 127; + if (size != 16) + return false; + + bool zero_prefix = true; + for (std::size_t i = 0; i < 10; ++i) + zero_prefix = zero_prefix && address[i] == 0; + if (zero_prefix && address[10] == 0xff && address[11] == 0xff) + return address[12] == 127; // ::ffff:127.x.y.z + if (!zero_prefix || address[10] != 0 || address[11] != 0) + return false; + for (std::size_t i = 12; i < 15; ++i) + { + if (address[i] != 0) + return false; + } + return address[15] == 1; // ::1 + } + + /** + * @brief Whether the DNS relay may send a query its listener received. + * + * Redirected queries reach the listener from the address of the server the client queried, + * with a SOCKS5 header the redirect wrote: port 53 of that same address, or the DNS server + * override when one is configured. Anything else, and anything from a loopback address + * (loopback traffic is never redirected), was sent to the listener directly by a local + * process and is refused, so the listener cannot be used to reach other destinations + * through the proxy. + * + * @param query The listener datagram's SOCKS5 header (parse_socks5_udp_datagram()). + * @param sender_address The listener's sender address (network byte order). + * @param override_address The override address for this family, or nullptr when none is + * configured; @p override_size and @p override_port are then ignored. + */ + [[nodiscard]] constexpr bool dns_relay_destination_allowed(const socks5_udp_datagram_view& query, + const uint8_t* sender_address, const std::size_t sender_size, const uint8_t* override_address, + const std::size_t override_size, const uint16_t override_port) noexcept + { + if (sender_address == nullptr || is_loopback_address(sender_address, sender_size)) + return false; + + const auto same_address = [&query](const uint8_t* address, const std::size_t size) noexcept + { + if (query.address == nullptr || query.address_size != size) + return false; + for (std::size_t i = 0; i < size; ++i) + { + if (query.address[i] != address[i]) + return false; + } + return true; + }; + + if (override_address != nullptr) + return query.port == override_port && same_address(override_address, override_size); + return query.port == dns_port && same_address(sender_address, sender_size); + } + /** * @brief Largest DNS answer the relay returns over UDP: the size that keeps the listener's * reply (IP + UDP + SOCKS5 header + answer) within a 1280-byte packet, the IPv6 @@ -467,8 +532,9 @@ namespace proxy * - A failed open is retried after a backoff that doubles from 1 s up to 30 s; queries * arriving meanwhile are dropped (Proxy mode never sends DNS directly). An association that * closes less than @p minimum_age after opening counts as a failed open, so a server that - * accepts UDP ASSOCIATE and then drops the connection is not reconnected in a tight loop. - * The backoff resets once an association has stayed open for @p minimum_age. + * accepts UDP ASSOCIATE and then drops the connection is not reconnected in a tight loop, + * and so does one retired because it stopped answering. The backoff resets once an + * association has stayed open for @p minimum_age. * - An open association is reopened when its SOCKS5 control connection closes or its relay * socket fails (reported by the relay), or when it looks silently dead: at least * @p unanswered_limit queries expired unanswered that were sent after the last datagram @@ -510,10 +576,15 @@ namespace proxy last_datagram_.reset(); } - /// The association was closed at @p now (for any reason). - void on_closed(const time_point now) noexcept + /** + * @brief The association was closed at @p now. + * @param failed The association stopped working (for example it was retired for + * unanswered queries): back off before the next attempt whatever its age. An + * association younger than the minimum age always counts as a failed open. + */ + void on_closed(const time_point now, const bool failed = false) noexcept { - if (now - opened_at_ < minimum_age_) + if (failed || now - opened_at_ < minimum_age_) on_open_failed(now); else failures_ = 0; @@ -681,11 +752,12 @@ namespace proxy void on_open_failed(const time_point now) noexcept { health_.on_open_failed(now); } void on_opened(const time_point now) noexcept { health_.on_opened(now); } - /// The association closed: its queries in flight can no longer be answered. - void on_closed(const time_point now) noexcept + /// The association closed: its queries in flight can no longer be answered. See + /// dns_association_health::on_closed() for @p failed. + void on_closed(const time_point now, const bool failed = false) noexcept { queries_.clear(); - health_.on_closed(now); + health_.on_closed(now, failed); } void clear() noexcept { queries_.clear(); } diff --git a/netlib/src/proxy/socks5_dns_udp_relay.h b/netlib/src/proxy/socks5_dns_udp_relay.h index 9db1ef9..85e1593 100644 --- a/netlib/src/proxy/socks5_dns_udp_relay.h +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -57,6 +57,10 @@ namespace proxy /// Bound on queries held while an association is being opened. static constexpr std::size_t max_waiting_queries = 64; + /// A query held longer than this while an association is opened is dropped instead of + /// being sent late; Windows retransmits a query after about a second. + static constexpr std::chrono::seconds max_wait{ 3 }; + /// Unanswered queries (sent after the last datagram from the relay) that retire an association. static constexpr std::size_t unanswered_limit = 3; @@ -69,6 +73,8 @@ namespace proxy * IPv4 server). * @param credentials Optional SOCKS5 username/password. * @param upstream_options Transport and TLS settings for the control connection. + * @param server_override The DNS server override for this family, if configured: the + * only destination a query may then name (dns_relay_destination_allowed()). * @param authorize_client Required. The relay refuses datagrams from any other source port, * so its listener cannot be used to send arbitrary UDP through the proxy. * @param relay_endpoint_observed Optional; see relay_endpoint_observed_t. @@ -76,6 +82,7 @@ namespace proxy socks5_dns_udp_relay(const endpoint_t& upstream, std::optional> credentials, socks5_upstream_options upstream_options, + std::optional server_override, std::function authorize_client, std::function relay_endpoint_observed = {}, const log_level log_level = log_level::error, @@ -84,6 +91,7 @@ namespace proxy upstream_(upstream), credentials_(std::move(credentials)), upstream_options_(std::move(upstream_options)), + server_override_(std::move(server_override)), authorize_client_(std::move(authorize_client)), relay_endpoint_observed_(std::move(relay_endpoint_observed)), association_client_(log_level, logger::log_stream_) @@ -168,8 +176,7 @@ namespace proxy { std::scoped_lock lock(lock_); current = std::move(association_); - dropped_unavailable_ += waiting_.size(); - waiting_.clear(); + drop_waiting_locked(waiting_.size()); session_.clear(); } close_association(std::move(current)); @@ -217,6 +224,7 @@ namespace proxy { client_t client; std::vector datagram; + std::chrono::steady_clock::time_point queued_at; }; static constexpr uint8_t own_address_type = address_type_t::af_type == AF_INET ? 1 : 4; @@ -230,6 +238,7 @@ namespace proxy endpoint_t upstream_; std::optional> credentials_; socks5_upstream_options upstream_options_; + std::optional server_override_; std::function authorize_client_; std::function relay_endpoint_observed_; socks5_udp_association_client association_client_; @@ -286,18 +295,27 @@ namespace proxy nullptr, 0, &bytes_returned, nullptr, nullptr); } - /// Keepalive on the control connection, so a silently dropped connection (NAT timeout, - /// server crash) is detected and the association reopened. - static void enable_keepalive(const SOCKET socket) noexcept + /// Keepalive on the control connection (first probe after 60 s idle, then every 10 s), + /// so a silently dropped connection (NAT timeout, server crash) is detected and the + /// association reopened. SIO_KEEPALIVE_VALS works on every supported Windows version; + /// its definitions are repeated here because is not reliably included. + void enable_keepalive(const SOCKET socket) const noexcept { - const BOOL enabled = TRUE; - setsockopt(socket, SOL_SOCKET, SO_KEEPALIVE, reinterpret_cast(&enabled), sizeof(enabled)); -#if defined(TCP_KEEPIDLE) && defined(TCP_KEEPINTVL) - const DWORD idle_seconds = 60; - const DWORD interval_seconds = 10; - setsockopt(socket, IPPROTO_TCP, TCP_KEEPIDLE, reinterpret_cast(&idle_seconds), sizeof(idle_seconds)); - setsockopt(socket, IPPROTO_TCP, TCP_KEEPINTVL, reinterpret_cast(&interval_seconds), sizeof(interval_seconds)); -#endif + struct keepalive_values + { + ULONG onoff; + ULONG keepalivetime; + ULONG keepaliveinterval; + } values{ 1, 60 * 1000, 10 * 1000 }; + constexpr DWORD sio_keepalive_vals = _WSAIOW(IOC_VENDOR, 4); + + DWORD bytes_returned = 0; + if (WSAIoctl(socket, sio_keepalive_vals, &values, sizeof(values), nullptr, 0, &bytes_returned, + nullptr, nullptr) == SOCKET_ERROR) + { + NETLIB_DEBUG("DNS relay: failed to set keepalive on the SOCKS5 control connection: {}", + WSAGetLastError()); + } } /// Socket errors after which a UDP socket keeps working (ICMP-induced or oversized datagrams). @@ -422,6 +440,23 @@ namespace proxy } } + /// Drops the oldest @p count waiting queries. Caller holds lock_. + void drop_waiting_locked(std::size_t count) + { + count = (std::min)(count, waiting_.size()); + dropped_unavailable_ += count; + waiting_.erase(waiting_.begin(), waiting_.begin() + static_cast(count)); + } + + /// Drops waiting queries held longer than max_wait. Caller holds lock_. + void drop_stale_waiting_locked(const std::chrono::steady_clock::time_point now) + { + std::size_t stale = 0; + while (stale < waiting_.size() && now - waiting_[stale].queued_at > max_wait) + ++stale; + drop_waiting_locked(stale); + } + // --- Threads ---------------------------------------------------------------------------- void listener_loop() @@ -474,6 +509,18 @@ namespace proxy return; } + const auto header = parse_socks5_udp_datagram(buffer.data(), size); + const auto* override_address = server_override_ + ? reinterpret_cast(&server_override_->ip) + : nullptr; + if (!header || !dns_relay_destination_allowed(*header, + reinterpret_cast(&client->endpoint.ip), own_address_size, + override_address, own_address_size, server_override_ ? server_override_->port : 0)) + { + ++dropped_unauthorized_; + return; + } + std::vector datagram(buffer.begin(), buffer.begin() + static_cast(size)); std::scoped_lock lock(lock_); @@ -491,7 +538,7 @@ namespace proxy return; } - waiting_.push_back(waiting_query{ *client, std::move(datagram) }); + waiting_.push_back(waiting_query{ *client, std::move(datagram), std::chrono::steady_clock::now() }); maintenance_cv_.notify_all(); } @@ -581,19 +628,26 @@ namespace proxy if (association_) { const char* reason = nullptr; + bool silent = false; if (association_->failed.load(std::memory_order_acquire)) reason = "the UDP relay socket failed"; else if (control_channel_closed(association_->control)) reason = "the SOCKS5 control connection closed"; else if (session_.expire(now)) + { reason = "queries stopped being answered"; + silent = true; + } if (reason) { NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association with {} because {}; it is reopened " "on the next query", upstream_.to_string(), reason); auto retired = std::move(association_); - session_.on_closed(now); + session_.on_closed(now, silent); + // Queries queued meanwhile cannot wait out a backoff. + if (!session_.may_open(now)) + drop_waiting_locked(waiting_.size()); lock.unlock(); close_association(std::move(retired)); lock.lock(); @@ -605,6 +659,7 @@ namespace proxy session_.expire_closed(now); } + drop_stale_waiting_locked(now); if (!association_ && !waiting_.empty() && session_.may_open(now)) open_association(lock); @@ -649,8 +704,7 @@ namespace proxy return; session_.on_open_failed(now); - dropped_unavailable_ += waiting_.size(); - waiting_.clear(); + drop_waiting_locked(waiting_.size()); const auto retry = std::chrono::duration_cast(session_.next_attempt() - now); if (session_.consecutive_failures() == 1) { @@ -669,6 +723,9 @@ namespace proxy session_.on_opened(now); association_ = std::move(opened); + // Opening can take seconds; queries Windows has given up on are not sent late. + drop_stale_waiting_locked(now); + auto waiting = std::move(waiting_); waiting_.clear(); for (auto& query : waiting) diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index db7ff26..7cea7cd 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -293,15 +293,16 @@ namespace proxy std::unique_ptr> dns_udp_relay_v4_; std::unique_ptr> dns_udp_relay_v6_; + /// Set from the moment the DNS relays start stopping until stop() has stopped the packet + /// filter: new UDP DNS is blocked, but the relays' listener ports are still recognized so + /// their last answers are translated. Guarded by lock_. + bool dns_udp_relays_stopping_{ false }; + /** * @brief Local source ports of UDP DNS queries redirected to the DNS relay, with the time * of the last one. The relay accepts datagrams only from these ports (refreshed * within udp_mapper_entry_ttl_). Swept by the resolver thread. */ - /// Set while the DNS relays stop: new UDP DNS is blocked, but the relays' listener - /// ports are still recognized so their last answers are translated. Guarded by lock_. - bool dns_udp_relays_stopping_{ false }; - std::unordered_map dns_udp_clients_v4_; std::unordered_map dns_udp_clients_v6_; std::mutex dns_udp_clients_lock_; @@ -845,6 +846,7 @@ namespace proxy } stop_dns_udp_relays(); + release_dns_udp_relays(); std::vector> proxies_to_stop; std::vector> proxies_to_stop_v6; @@ -1106,13 +1108,15 @@ namespace proxy // Step 0: Stop the DNS relays while the packet filter still runs, so answers they // send while stopping are still translated (or dropped) instead of reaching the - // network. Without a relay, UDP DNS is blocked until the filter stops. + // network. They stay registered until the filter has stopped (release below), and + // new UDP DNS is blocked meanwhile. stop_dns_udp_relays(); // Step 1: Stop the packet filter // This prevents new packets from being processed and queued NETLIB_DEBUG("Stopping packet filter"); packet_filter_->stop_filter(); + release_dns_udp_relays(); // Step 2: Signal and join the process resolve thread // This ensures no more packets are being queued for processing. @@ -2460,6 +2464,7 @@ namespace proxy dns_proxy_target target; bool destination_matches_upstream = false; + bool relays_stopping = false; std::optional> server_override; { std::shared_lock lock(lock_); @@ -2479,6 +2484,7 @@ namespace proxy target.listener_port = dns_listener_port_locked(); } + relays_stopping = dns_udp_relays_stopping_; target.override_configured = dns_server_override_v4_.has_value() || dns_server_override_v6_.has_value(); target.override_family_matches = dns_server_override_for().has_value(); server_override = dns_server_override_for(); @@ -2495,7 +2501,11 @@ namespace proxy const auto guard = decide_dns_upstream_guard(exemption_candidate, exemption_candidate ? sender_lookup(postponed) : std::optional{}, postponed); - const auto decision = decide_dns_route(dns_routing_mode::proxy, destination_port, guard, target); + auto decision = decide_dns_route(dns_routing_mode::proxy, destination_port, guard, target); + // While the router stops, the DNS relays are gone on purpose: not worth a warning. + if (Transport == dns_transport::udp && relays_stopping && + decision.reason == dns_block_reason::listener_unavailable) + decision.reason = dns_block_reason::service_stopping; return { decision, decision.action == dns_route_action::proxy ? server_override : std::nullopt }; } @@ -2507,6 +2517,10 @@ namespace proxy template void note_dns_block(const dns_block_reason reason) { + // Expected while stopping (stop_dns_udp_relays()): neither counted nor reported. + if (reason == dns_block_reason::service_stopping) + return; + dns_blocked_packets_.fetch_add(1, std::memory_order_relaxed); const auto family_index = std::is_same_v ? 0u : 1u; @@ -2687,12 +2701,12 @@ namespace proxy */ template std::unique_ptr> make_dns_udp_relay(const net::ip_endpoint& upstream, - const proxy_session_settings& settings) + const proxy_session_settings& settings, const std::optional>& server_override) { try { auto relay = std::make_unique>(upstream, settings.credentials, - settings.upstream_options, + settings.upstream_options, server_override, [this](const uint16_t port) { std::scoped_lock lock(dns_udp_clients_lock_); @@ -2734,6 +2748,8 @@ namespace proxy { std::optional> upstream; proxy_session_settings settings; + std::optional> override_v4; + std::optional> override_v6; bool ipv4 = false; bool ipv6 = false; { @@ -2748,6 +2764,8 @@ namespace proxy upstream = proxy_upstreams_[id]; settings = proxy_session_settings_[id]; + override_v4 = dns_server_override_v4_; + override_v6 = dns_server_override_v6_; const auto families = id < proxy_address_families_.size() ? proxy_address_families_[id] : supported_address_families::all; @@ -2755,8 +2773,10 @@ namespace proxy ipv6 = family_supports_ipv6(families) && id < proxy_servers_v6_.size() && proxy_servers_v6_[id].second; } - auto relay_v4 = ipv4 ? make_dns_udp_relay(*upstream, settings) : nullptr; - auto relay_v6 = ipv6 ? make_dns_udp_relay(ipv4_mapped(*upstream), settings) : nullptr; + auto relay_v4 = ipv4 ? make_dns_udp_relay(*upstream, settings, override_v4) : nullptr; + auto relay_v6 = ipv6 + ? make_dns_udp_relay(ipv4_mapped(*upstream), settings, override_v6) + : nullptr; std::unique_lock lock(lock_); dns_udp_relay_v4_ = std::move(relay_v4); @@ -2764,11 +2784,11 @@ namespace proxy } /** - * @brief Stops and destroys the DNS relays. New UDP DNS is blocked first; the relays stay - * registered while they stop so their listener ports are still recognized and - * answers they send meanwhile are translated rather than passed. Their threads are - * joined without lock_ held. Called under lifecycle_mutex_, which also serializes - * every write of the relay pointers. + * @brief Stops the DNS relays. New UDP DNS is blocked first; the relays stay registered + * (until release_dns_udp_relays()) so their listener ports are still recognized and + * answers they send while stopping are translated rather than passed. Their threads + * are joined without lock_ held. Called under lifecycle_mutex_, which also + * serializes every write of the relay pointers. */ void stop_dns_udp_relays() { @@ -2785,13 +2805,20 @@ namespace proxy relay_v4->stop(); if (relay_v6) relay_v6->stop(); + } - std::unique_ptr> stopped_v4; - std::unique_ptr> stopped_v6; + /** + * @brief Destroys the stopped DNS relays and ends the stopping state. Called after the + * packet filter has stopped (or never started), under lifecycle_mutex_. + */ + void release_dns_udp_relays() + { + std::unique_ptr> released_v4; + std::unique_ptr> released_v6; { std::unique_lock lock(lock_); - stopped_v4 = std::move(dns_udp_relay_v4_); - stopped_v6 = std::move(dns_udp_relay_v6_); + released_v4 = std::move(dns_udp_relay_v4_); + released_v6 = std::move(dns_udp_relay_v6_); dns_udp_relays_stopping_ = false; } } diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index d817f9c..aec53ec 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -710,3 +710,72 @@ TEST(DnsRelaySession, ClosingForgetsQueriesInFlightAndBacksOffWhenEarly) EXPECT_FALSE(session.may_open(t0 + 2s)); EXPECT_TRUE(session.may_open(t0 + 3s)); } + +// --- Which destinations the listener relays --------------------------------------------------- + +TEST(DnsRelayDestination, LoopbackAddressesAreRecognized) +{ + const uint8_t v4_loopback[4]{ 127, 0, 0, 1 }; + const uint8_t v4_other_loopback[4]{ 127, 1, 2, 3 }; + const uint8_t v4_public[4]{ 8, 8, 8, 8 }; + EXPECT_TRUE(proxy::is_loopback_address(v4_loopback, 4)); + EXPECT_TRUE(proxy::is_loopback_address(v4_other_loopback, 4)); + EXPECT_FALSE(proxy::is_loopback_address(v4_public, 4)); + + uint8_t v6[16]{}; + v6[15] = 1; + EXPECT_TRUE(proxy::is_loopback_address(v6, 16)); // ::1 + v6[15] = 2; + EXPECT_FALSE(proxy::is_loopback_address(v6, 16)); // ::2 + uint8_t mapped[16]{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 127, 0, 0, 1 }; + EXPECT_TRUE(proxy::is_loopback_address(mapped, 16)); // ::ffff:127.0.0.1 + mapped[12] = 10; + EXPECT_FALSE(proxy::is_loopback_address(mapped, 16)); // ::ffff:10.0.0.1 + EXPECT_FALSE(proxy::is_loopback_address(v6_relay_source.data(), 16)); + EXPECT_FALSE(proxy::is_loopback_address(nullptr, 4)); +} + +TEST(DnsRelayDestination, QueriesMayNameOnlyPort53OfTheQueriedServerOrTheOverride) +{ + const auto check = [](const std::vector& header_address, const uint16_t header_port, + const std::vector& sender, const std::vector* override_address, const uint16_t override_port) + { + const auto datagram = socks_datagram(header_address, header_port, query(1, "example.com")); + const auto view = proxy::parse_socks5_udp_datagram(datagram.data(), datagram.size()); + return view && proxy::dns_relay_destination_allowed(*view, sender.data(), sender.size(), + override_address ? override_address->data() : nullptr, override_address ? override_address->size() : 0, + override_port); + }; + + // Without an override: port 53 of the address the query came from (the queried server). + EXPECT_TRUE(check(v4_server, 53, v4_server, nullptr, 0)); + EXPECT_FALSE(check(v4_server, 5353, v4_server, nullptr, 0)); + EXPECT_FALSE(check(v4_override, 53, v4_server, nullptr, 0)); + + // With an override: only the override endpoint, whatever server was queried. + EXPECT_TRUE(check(v4_override, 53, v4_server, &v4_override, 53)); + EXPECT_TRUE(check(v4_override, 5300, v4_server, &v4_override, 5300)); + EXPECT_FALSE(check(v4_override, 53, v4_server, &v4_override, 5300)); + EXPECT_FALSE(check(v4_server, 53, v4_server, &v4_override, 53)); + + // A local process sending to the listener over loopback is refused. + const std::vector loopback{ 127, 0, 0, 1 }; + EXPECT_FALSE(check(loopback, 53, loopback, nullptr, 0)); + EXPECT_FALSE(check(v4_override, 53, loopback, &v4_override, 53)); +} + +TEST(DnsAssociationHealth, AssociationRetiredForSilenceBacksOffWhateverItsAge) +{ + proxy::dns_association_health<> health{ 3, 30s }; + health.on_opened(t0); + health.on_closed(t0 + 60s, true); + EXPECT_EQ(health.consecutive_failures(), 1u); + EXPECT_FALSE(health.may_open(t0 + 60s)); + EXPECT_TRUE(health.may_open(t0 + 61s)); + + // A long-lived association closed for another reason reopens at once. + health.on_opened(t0 + 61s); + health.on_closed(t0 + 200s); + EXPECT_EQ(health.consecutive_failures(), 0u); + EXPECT_TRUE(health.may_open(t0 + 200s)); +} From 584330c6a28c7d55804602dec90956f9f530c9f3 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 18:37:58 +0000 Subject: [PATCH 45/62] docs: describe the queued-query limit, the listener's destination check and the stop order --- docs/configuration.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 9db5bee..f7ce043 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -193,11 +193,11 @@ UDP DNS of each address family goes through a single SOCKS5 control connection a - **Matching answers to queries.** While a query is in flight, its DNS message ID is replaced by a unique, randomly chosen ID. The answer carrying that ID is returned to the socket that asked, with the socket's own message ID, but only if it also carries the query's question (name, ignoring case, type and class). A question-less error response from the server is accepted too. A retransmission from the same socket reuses the ID. Up to 4,096 queries can be in flight; a query without an answer is forgotten after 10 seconds. An answer that matches no query in flight, or whose question differs, is dropped. A query whose question section cannot be parsed is dropped. - **Source of the answer.** The answer is presented as coming from the server Windows queried, whatever source address (IPv4 or IPv6) the SOCKS5 relay reports, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered (the `serverOverride` server when one is set); some report their own address. This applies with or without a `serverOverride`. - **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. -- **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it. It is closed, and reopened on the next query, when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. -- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening counts as a failed attempt, so a server that accepts `UDP ASSOCIATE` and then drops the connection is not reconnected in a tight loop. +- **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it, each for at most 3 seconds (Windows retransmits a query after about a second). It is closed, and reopened on the next query, when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. +- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening counts as a failed attempt, so a server that accepts `UDP ASSOCIATE` and then drops the connection is not reconnected in a tight loop; so does one closed because queries stopped being answered, whatever its age. Queries waiting when a failure starts a backoff are dropped. - **Logging.** Per address family, the first failure to open the association is logged as a warning and later failures at `Debug`; every successful open and every close is logged at `Info` with its reason. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. -The local listener accepts only datagrams from source ports from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, so it cannot be used to send arbitrary UDP through the proxy. When the service stops, the DNS relays stop while packet filtering is still active, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile. +The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. ### Server override From a74fb2b38743db2f2ed7c8bcb00ec1785ce35b3a Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 18:54:36 +0000 Subject: [PATCH 46/62] fix(dns relay): escalate the backoff for silent associations; keep the warning Review findings on the previous round's fixes: - A silent association was retired only once at least 30 s old, and at that age the backoff had already been reset, so it always backed off 1 s and reopened every 31 to 41 s. The backoff now resets only when an association proves itself: a datagram arrives from the relay once it is 30 s old, or it closes normally at that age. Silent associations now back off 1, 2, 4 ... 30 s. - After a silent retirement the first failed reopen was logged at Debug only, because the warning was keyed to the first consecutive failure. It is now keyed to the first failed open since the last successful one. - The queue of queries waiting for an association moves into a portable, tested dns_waiting_queue (bounded, at most 3 s per query, arrival order). - The router releases the stopped relays only after the resolver thread has been joined, so deferred DNS packets processed during stop are also blocked quietly, and start clears the stopping flag in case an earlier stop() did not finish. - The listener's drop report counts refused destinations separately; the SOCKS5 header is parsed once; keepalive uses SIO_KEEPALIVE_VALS and tcp_keepalive from , which socksify already includes. - Tests: silent-retirement escalation through the normal path, the warning rule, the waiting queue, and IPv6 (including link-local) destinations. - Docs: when the backoff resets, the warning rule, and that another host guessing an authorized port can only make the proxy query its own port 53 or the override, never seeing the answer. --- docs/configuration.md | 6 +- netlib/src/proxy/dns_udp_multiplexer.h | 110 +++++++++++++++--- netlib/src/proxy/socks5_dns_udp_relay.h | 80 +++++-------- netlib/src/proxy/socks_local_router.h | 28 +++-- .../test/proxy/dns_udp_multiplexer_test.cpp | 97 ++++++++++++++- 5 files changed, 241 insertions(+), 80 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index f7ce043..0e44cb3 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -194,10 +194,10 @@ UDP DNS of each address family goes through a single SOCKS5 control connection a - **Source of the answer.** The answer is presented as coming from the server Windows queried, whatever source address (IPv4 or IPv6) the SOCKS5 relay reports, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered (the `serverOverride` server when one is set); some report their own address. This applies with or without a `serverOverride`. - **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. - **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it, each for at most 3 seconds (Windows retransmits a query after about a second). It is closed, and reopened on the next query, when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. -- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening counts as a failed attempt, so a server that accepts `UDP ASSOCIATE` and then drops the connection is not reconnected in a tight loop; so does one closed because queries stopped being answered, whatever its age. Queries waiting when a failure starts a backoff are dropped. -- **Logging.** Per address family, the first failure to open the association is logged as a warning and later failures at `Debug`; every successful open and every close is logged at `Info` with its reason. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. +- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening counts as a failed attempt, so a server that accepts `UDP ASSOCIATE` and then drops the connection is not reconnected in a tight loop; so does one closed because queries stopped being answered, whatever its age, so a relay that never answers is retried less and less often. The delay resets only once an association has proved itself: something arrived from the relay after it had been open for 30 seconds, or it closed normally at that age. Queries waiting when a failure starts a backoff are dropped. +- **Logging.** Per address family, the first failure to open an association since the last successful open is logged as a warning and later failures at `Debug`; every successful open and every close is logged at `Info` with its reason. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. -The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. +The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. The listener is bound to all local addresses, like the proxy's other local listeners, so another host that guesses an authorized port could still make the proxy send a DNS query to that host's own port 53, or to the override; it never receives the answer, which is delivered to the local client port. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. ### Server override diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index 49a62a7..13cb94c 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -15,10 +15,12 @@ #include #include #include +#include #include #include #include #include +#include #include "dns_routing_policy.h" @@ -533,8 +535,9 @@ namespace proxy * arriving meanwhile are dropped (Proxy mode never sends DNS directly). An association that * closes less than @p minimum_age after opening counts as a failed open, so a server that * accepts UDP ASSOCIATE and then drops the connection is not reconnected in a tight loop, - * and so does one retired because it stopped answering. The backoff resets once an - * association has stayed open for @p minimum_age. + * and so does one retired because it stopped answering. The backoff resets only when an + * association proves itself: a datagram arrives from the relay once it is at least + * @p minimum_age old, or it closes normally at that age. * - An open association is reopened when its SOCKS5 control connection closes or its relay * socket fails (reported by the relay), or when it looks silently dead: at least * @p unanswered_limit queries expired unanswered that were sent after the last datagram @@ -562,11 +565,17 @@ namespace proxy return failures_ == 0 || now >= next_attempt_; } - void on_open_failed(const time_point now) noexcept + /** + * @brief Records a failed attempt to open an association and backs off. + * @return true for the first failed attempt since the last successful open (or since + * the relay started), which the relay reports as a warning. + */ + bool on_open_failed(const time_point now) noexcept { - ++failures_; - const auto shift = std::min(failures_ - 1, 5); // 1, 2, 4, 8, 16, 32 s - next_attempt_ = now + (std::min)(std::chrono::seconds{ 1 } * (1u << shift), max_backoff); + back_off(now); + const bool first = !open_failure_reported_; + open_failure_reported_ = true; + return first; } void on_opened(const time_point now) noexcept @@ -574,6 +583,7 @@ namespace proxy unanswered_ = 0; opened_at_ = now; last_datagram_.reset(); + open_failure_reported_ = false; } /** @@ -585,16 +595,19 @@ namespace proxy void on_closed(const time_point now, const bool failed = false) noexcept { if (failed || now - opened_at_ < minimum_age_) - on_open_failed(now); + back_off(now); else failures_ = 0; } - /// Any datagram from the relay shows the association is alive. + /// Any datagram from the relay shows the association is alive; once it is also at least + /// the minimum age, it has proved itself and the backoff resets. void on_relay_datagram(const time_point now) noexcept { unanswered_ = 0; last_datagram_ = now; + if (now - opened_at_ >= minimum_age_) + failures_ = 0; } /// Time of the last datagram from the relay since the association opened, if any. @@ -606,11 +619,8 @@ namespace proxy */ [[nodiscard]] bool on_unanswered(const std::size_t count, const time_point now) noexcept { - const bool old_enough = now - opened_at_ >= minimum_age_; - if (old_enough) - failures_ = 0; // the association has proved itself unanswered_ += count; - return unanswered_ >= unanswered_limit_ && old_enough; + return unanswered_ >= unanswered_limit_ && now - opened_at_ >= minimum_age_; } [[nodiscard]] std::size_t consecutive_failures() const noexcept { return failures_; } @@ -619,6 +629,14 @@ namespace proxy static constexpr std::chrono::seconds max_backoff{ 30 }; private: + void back_off(const time_point now) noexcept + { + ++failures_; + const auto shift = std::min(failures_ - 1, 5); // 1, 2, 4, 8, 16, 32 s + next_attempt_ = now + (std::min)(std::chrono::seconds{ 1 } * (1u << shift), max_backoff); + } + + bool open_failure_reported_{ false }; std::size_t unanswered_limit_; std::chrono::seconds minimum_age_; std::size_t failures_{}; @@ -749,7 +767,8 @@ namespace proxy void expire_closed(const time_point now) { (void)queries_.expire(now); } [[nodiscard]] bool may_open(const time_point now) const noexcept { return health_.may_open(now); } - void on_open_failed(const time_point now) noexcept { health_.on_open_failed(now); } + /// See dns_association_health::on_open_failed(). + bool on_open_failed(const time_point now) noexcept { return health_.on_open_failed(now); } void on_opened(const time_point now) noexcept { health_.on_opened(now); } /// The association closed: its queries in flight can no longer be answered. See @@ -770,4 +789,69 @@ namespace proxy table_t queries_; dns_association_health health_; }; + + /** + * @brief Queries held while the shared association is being opened: bounded in number, and + * each held at most @p max_wait, so nothing is sent long after the client gave up. + * Items stay in arrival order. Not thread-safe: the relay serializes access. + */ + template + class dns_waiting_queue + { + public: + using time_point = typename Clock::time_point; + + dns_waiting_queue(const std::size_t capacity, const std::chrono::milliseconds max_wait) + : capacity_(capacity), max_wait_(max_wait) + { + } + + /// Queues @p item; false (and @p item is not queued) when the queue is full. + bool push(Item item, const time_point now) + { + if (items_.size() >= capacity_) + return false; + items_.emplace_back(now, std::move(item)); + return true; + } + + /// Drops items held longer than max_wait; returns how many. + std::size_t drop_stale(const time_point now) + { + std::size_t stale = 0; + while (!items_.empty() && now - items_.front().first > max_wait_) + { + items_.pop_front(); + ++stale; + } + return stale; + } + + /// Drops everything; returns how many. + std::size_t drop_all() noexcept + { + const auto dropped = items_.size(); + items_.clear(); + return dropped; + } + + /// Removes and returns every item, oldest first. + std::vector take_all() + { + std::vector taken; + taken.reserve(items_.size()); + for (auto& [queued_at, item] : items_) + taken.push_back(std::move(item)); + items_.clear(); + return taken; + } + + [[nodiscard]] bool empty() const noexcept { return items_.empty(); } + [[nodiscard]] std::size_t size() const noexcept { return items_.size(); } + + private: + std::deque> items_; + std::size_t capacity_; + std::chrono::milliseconds max_wait_; + }; } diff --git a/netlib/src/proxy/socks5_dns_udp_relay.h b/netlib/src/proxy/socks5_dns_udp_relay.h index 85e1593..ad22bc3 100644 --- a/netlib/src/proxy/socks5_dns_udp_relay.h +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -59,7 +59,7 @@ namespace proxy /// A query held longer than this while an association is opened is dropped instead of /// being sent late; Windows retransmits a query after about a second. - static constexpr std::chrono::seconds max_wait{ 3 }; + static constexpr std::chrono::milliseconds max_wait{ 3000 }; /// Unanswered queries (sent after the last datagram from the relay) that retire an association. static constexpr std::size_t unanswered_limit = 3; @@ -176,7 +176,7 @@ namespace proxy { std::scoped_lock lock(lock_); current = std::move(association_); - drop_waiting_locked(waiting_.size()); + dropped_unavailable_ += waiting_.drop_all(); session_.clear(); } close_association(std::move(current)); @@ -224,7 +224,6 @@ namespace proxy { client_t client; std::vector datagram; - std::chrono::steady_clock::time_point queued_at; }; static constexpr uint8_t own_address_type = address_type_t::af_type == AF_INET ? 1 : 4; @@ -248,7 +247,7 @@ namespace proxy std::mutex lock_; std::condition_variable maintenance_cv_; std::unique_ptr association_; - std::deque waiting_; + dns_waiting_queue waiting_{ max_waiting_queries, max_wait }; dns_relay_session session_{ query_ttl, max_queries_in_flight, unanswered_limit, minimum_association_age }; std::random_device random_; @@ -267,6 +266,7 @@ namespace proxy // --- Statistics, reported by the maintenance thread at a throttled rate --------------- std::atomic dropped_unauthorized_{ 0 }; + std::atomic dropped_refused_{ 0 }; std::atomic dropped_malformed_{ 0 }; std::atomic dropped_unavailable_{ 0 }; std::atomic dropped_unmatched_answers_{ 0 }; @@ -297,20 +297,17 @@ namespace proxy /// Keepalive on the control connection (first probe after 60 s idle, then every 10 s), /// so a silently dropped connection (NAT timeout, server crash) is detected and the - /// association reopened. SIO_KEEPALIVE_VALS works on every supported Windows version; - /// its definitions are repeated here because is not reliably included. + /// association reopened. SIO_KEEPALIVE_VALS () works on every supported + /// Windows version. void enable_keepalive(const SOCKET socket) const noexcept { - struct keepalive_values - { - ULONG onoff; - ULONG keepalivetime; - ULONG keepaliveinterval; - } values{ 1, 60 * 1000, 10 * 1000 }; - constexpr DWORD sio_keepalive_vals = _WSAIOW(IOC_VENDOR, 4); + tcp_keepalive values{}; + values.onoff = 1; + values.keepalivetime = 60 * 1000; + values.keepaliveinterval = 10 * 1000; DWORD bytes_returned = 0; - if (WSAIoctl(socket, sio_keepalive_vals, &values, sizeof(values), nullptr, 0, &bytes_returned, + if (WSAIoctl(socket, SIO_KEEPALIVE_VALS, &values, sizeof(values), nullptr, 0, &bytes_returned, nullptr, nullptr) == SOCKET_ERROR) { NETLIB_DEBUG("DNS relay: failed to set keepalive on the SOCKS5 control connection: {}", @@ -440,23 +437,6 @@ namespace proxy } } - /// Drops the oldest @p count waiting queries. Caller holds lock_. - void drop_waiting_locked(std::size_t count) - { - count = (std::min)(count, waiting_.size()); - dropped_unavailable_ += count; - waiting_.erase(waiting_.begin(), waiting_.begin() + static_cast(count)); - } - - /// Drops waiting queries held longer than max_wait. Caller holds lock_. - void drop_stale_waiting_locked(const std::chrono::steady_clock::time_point now) - { - std::size_t stale = 0; - while (stale < waiting_.size() && now - waiting_[stale].queued_at > max_wait) - ++stale; - drop_waiting_locked(stale); - } - // --- Threads ---------------------------------------------------------------------------- void listener_loop() @@ -503,21 +483,22 @@ namespace proxy return; } - if (!socks5_dns_query_offset(buffer.data(), size, own_address_type)) + // The redirect's SOCKS5 header (of the listener's family) and a DNS header. + const auto header = parse_socks5_udp_datagram(buffer.data(), size); + if (!header || header->address_type != own_address_type || header->data_size < dns_header_size) { ++dropped_malformed_; return; } - const auto header = parse_socks5_udp_datagram(buffer.data(), size); const auto* override_address = server_override_ ? reinterpret_cast(&server_override_->ip) : nullptr; - if (!header || !dns_relay_destination_allowed(*header, + if (!dns_relay_destination_allowed(*header, reinterpret_cast(&client->endpoint.ip), own_address_size, override_address, own_address_size, server_override_ ? server_override_->port : 0)) { - ++dropped_unauthorized_; + ++dropped_refused_; return; } @@ -532,13 +513,13 @@ namespace proxy // No usable association: hold the query while one is opened, unless opening is // backing off after a failure or too many queries are already waiting. - if (!session_.may_open(std::chrono::steady_clock::now()) || waiting_.size() >= max_waiting_queries) + const auto now = std::chrono::steady_clock::now(); + if (!session_.may_open(now) || !waiting_.push(waiting_query{ *client, std::move(datagram) }, now)) { ++dropped_unavailable_; return; } - waiting_.push_back(waiting_query{ *client, std::move(datagram), std::chrono::steady_clock::now() }); maintenance_cv_.notify_all(); } @@ -647,7 +628,7 @@ namespace proxy session_.on_closed(now, silent); // Queries queued meanwhile cannot wait out a backoff. if (!session_.may_open(now)) - drop_waiting_locked(waiting_.size()); + dropped_unavailable_ += waiting_.drop_all(); lock.unlock(); close_association(std::move(retired)); lock.lock(); @@ -659,7 +640,7 @@ namespace proxy session_.expire_closed(now); } - drop_stale_waiting_locked(now); + dropped_unavailable_ += waiting_.drop_stale(now); if (!association_ && !waiting_.empty() && session_.may_open(now)) open_association(lock); @@ -703,10 +684,10 @@ namespace proxy if (stopping_.load(std::memory_order_acquire)) return; - session_.on_open_failed(now); - drop_waiting_locked(waiting_.size()); + const bool first_failure = session_.on_open_failed(now); + dropped_unavailable_ += waiting_.drop_all(); const auto retry = std::chrono::duration_cast(session_.next_attempt() - now); - if (session_.consecutive_failures() == 1) + if (first_failure) { NETLIB_WARNING("DNS relay: could not open a SOCKS5 UDP association with {}; UDP DNS is " "dropped until one opens (next attempt in {} s)", upstream_.to_string(), retry.count()); @@ -724,11 +705,8 @@ namespace proxy association_ = std::move(opened); // Opening can take seconds; queries Windows has given up on are not sent late. - drop_stale_waiting_locked(now); - - auto waiting = std::move(waiting_); - waiting_.clear(); - for (auto& query : waiting) + dropped_unavailable_ += waiting_.drop_stale(now); + for (auto& query : waiting_.take_all()) send_query_locked(query.client, query.datagram); } @@ -841,18 +819,20 @@ namespace proxy void report_drops(const std::chrono::steady_clock::time_point now, const bool final_report) { const auto unauthorized = dropped_unauthorized_.load(std::memory_order_relaxed); + const auto refused = dropped_refused_.load(std::memory_order_relaxed); const auto malformed = dropped_malformed_.load(std::memory_order_relaxed); const auto unavailable = dropped_unavailable_.load(std::memory_order_relaxed); const auto unmatched = dropped_unmatched_answers_.load(std::memory_order_relaxed); const auto send_failures = dropped_send_failures_.load(std::memory_order_relaxed); - const auto total = unauthorized + malformed + unavailable + unmatched + send_failures; + const auto total = unauthorized + refused + malformed + unavailable + unmatched + send_failures; if (total == reported_drops_ || (!final_report && now - last_report_ < report_interval)) return; NETLIB_INFO("DNS relay: dropped so far: {} queries while no SOCKS5 UDP association was available, " - "{} not from a redirected DNS client, {} without a DNS question, {} answers matching no query, " - "{} send failures", unavailable, unauthorized, malformed, unmatched, send_failures); + "{} not from a redirected DNS client, {} naming a destination other than the queried server or the " + "override, or from a loopback address, {} without a DNS question, {} answers matching no query, " + "{} send failures", unavailable, unauthorized, refused, malformed, unmatched, send_failures); reported_drops_ = total; last_report_ = now; } diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 7cea7cd..7954f04 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -293,9 +293,10 @@ namespace proxy std::unique_ptr> dns_udp_relay_v4_; std::unique_ptr> dns_udp_relay_v6_; - /// Set from the moment the DNS relays start stopping until stop() has stopped the packet - /// filter: new UDP DNS is blocked, but the relays' listener ports are still recognized so - /// their last answers are translated. Guarded by lock_. + /// Set from the moment the DNS relays start stopping until stop() no longer processes + /// packets: new UDP DNS is blocked, but the relays' listener ports are still recognized + /// so their last answers are translated. Cleared again by start_dns_udp_relays(). + /// Guarded by lock_. bool dns_udp_relays_stopping_{ false }; /** @@ -1108,15 +1109,14 @@ namespace proxy // Step 0: Stop the DNS relays while the packet filter still runs, so answers they // send while stopping are still translated (or dropped) instead of reaching the - // network. They stay registered until the filter has stopped (release below), and - // new UDP DNS is blocked meanwhile. + // network. They stay registered until no packet is processed any more (release + // after Step 2), and new UDP DNS is blocked meanwhile. stop_dns_udp_relays(); // Step 1: Stop the packet filter // This prevents new packets from being processed and queued NETLIB_DEBUG("Stopping packet filter"); packet_filter_->stop_filter(); - release_dns_udp_relays(); // Step 2: Signal and join the process resolve thread // This ensures no more packets are being queued for processing. @@ -1132,6 +1132,10 @@ namespace proxy if (process_resolve_thread_.joinable()) process_resolve_thread_.join(); + // No packet is processed any more (deferred packets included), so the stopped DNS + // relays can be released. + release_dns_udp_relays(); + // Report the last DNS and listener drop counts, which the resolver thread may not // have reached. (void)report_listener_and_dns_drops(); @@ -2746,6 +2750,13 @@ namespace proxy */ void start_dns_udp_relays() { + { + // A stop() that did not finish (for example stop_filter() threw) must not leave + // UDP DNS silently blocked after this start. + std::unique_lock lock(lock_); + dns_udp_relays_stopping_ = false; + } + std::optional> upstream; proxy_session_settings settings; std::optional> override_v4; @@ -2808,8 +2819,9 @@ namespace proxy } /** - * @brief Destroys the stopped DNS relays and ends the stopping state. Called after the - * packet filter has stopped (or never started), under lifecycle_mutex_. + * @brief Destroys the stopped DNS relays and ends the stopping state. Called once no + * packet is processed any more (the packet filter and the resolver thread have + * stopped, or never started), under lifecycle_mutex_. */ void release_dns_udp_relays() { diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index aec53ec..8fac7be 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -322,15 +322,17 @@ TEST(DnsAssociationHealth, AssociationClosingSoonAfterOpeningBacksOff) EXPECT_TRUE(health.may_open(t0 + 5s)); } -TEST(DnsAssociationHealth, LongLivedAssociationResetsTheBackoffWhileOpen) +TEST(DnsAssociationHealth, AssociationThatDeliversOnceOldEnoughResetsTheBackoff) { proxy::dns_association_health<> health{ 3, 30s }; - health.on_open_failed(t0); - health.on_open_failed(t0); + (void)health.on_open_failed(t0); + (void)health.on_open_failed(t0); health.on_opened(t0 + 2s); - EXPECT_FALSE(health.on_unanswered(0, t0 + 31s)); - EXPECT_EQ(health.consecutive_failures(), 1u + 1u); - EXPECT_FALSE(health.on_unanswered(0, t0 + 32s)); + // Age alone, or a datagram while young, does not prove the association. + EXPECT_FALSE(health.on_unanswered(0, t0 + 40s)); + health.on_relay_datagram(t0 + 31s); + EXPECT_EQ(health.consecutive_failures(), 2u); + health.on_relay_datagram(t0 + 32s); EXPECT_EQ(health.consecutive_failures(), 0u); } @@ -773,9 +775,92 @@ TEST(DnsAssociationHealth, AssociationRetiredForSilenceBacksOffWhateverItsAge) EXPECT_FALSE(health.may_open(t0 + 60s)); EXPECT_TRUE(health.may_open(t0 + 61s)); + // Repeated silent associations (a relay that never answers behind a working control + // connection) back off further each time, through the normal retirement path. + auto at = t0 + 61s; + for (const auto delay : { 2s, 4s, 8s, 16s, 30s, 30s }) + { + ASSERT_TRUE(health.may_open(at)); + health.on_opened(at); + at += 40s; + ASSERT_TRUE(health.on_unanswered(3, at)); + health.on_closed(at, true); + EXPECT_FALSE(health.may_open(at + delay - 1ms)); + EXPECT_TRUE(health.may_open(at + delay)); + at += delay; + } + // A long-lived association closed for another reason reopens at once. health.on_opened(t0 + 61s); health.on_closed(t0 + 200s); EXPECT_EQ(health.consecutive_failures(), 0u); EXPECT_TRUE(health.may_open(t0 + 200s)); } + +TEST(DnsAssociationHealth, FirstOpenFailureSinceEachSuccessfulOpenIsReported) +{ + proxy::dns_association_health<> health{ 3, 30s }; + EXPECT_TRUE(health.on_open_failed(t0)); + EXPECT_FALSE(health.on_open_failed(t0 + 1s)); + health.on_opened(t0 + 3s); + + // A silent retirement is not an open failure and does not use up the report. + ASSERT_TRUE(health.on_unanswered(3, t0 + 40s)); + health.on_closed(t0 + 40s, true); + EXPECT_TRUE(health.on_open_failed(t0 + 41s)); + EXPECT_FALSE(health.on_open_failed(t0 + 43s)); +} + +// --- Queries waiting for the association -------------------------------------------------------- + +TEST(DnsWaitingQueue, IsBoundedAndKeepsArrivalOrder) +{ + proxy::dns_waiting_queue queue{ 3, 3000ms }; + EXPECT_TRUE(queue.push(1, t0)); + EXPECT_TRUE(queue.push(2, t0 + 1s)); + EXPECT_TRUE(queue.push(3, t0 + 2s)); + EXPECT_FALSE(queue.push(4, t0 + 2s)); + EXPECT_EQ(queue.size(), 3u); + EXPECT_EQ(queue.take_all(), (std::vector{ 1, 2, 3 })); + EXPECT_TRUE(queue.empty()); +} + +TEST(DnsWaitingQueue, QueriesHeldTooLongAreDroppedOldestFirst) +{ + proxy::dns_waiting_queue queue{ 64, 3000ms }; + (void)queue.push(1, t0); + (void)queue.push(2, t0 + 1s); + (void)queue.push(3, t0 + 2500ms); + EXPECT_EQ(queue.drop_stale(t0 + 3s), 0u); + EXPECT_EQ(queue.drop_stale(t0 + 4001ms), 2u); + EXPECT_EQ(queue.take_all(), (std::vector{ 3 })); + + (void)queue.push(4, t0); + (void)queue.push(5, t0); + EXPECT_EQ(queue.drop_all(), 2u); + EXPECT_TRUE(queue.empty()); +} + +TEST(DnsRelayDestination, Ipv6QueriesFollowTheSameRules) +{ + const std::vector link_local{ 0xfe, 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; + const std::vector v6_override{ 0x26, 0x06, 0x47, 0, 0x47, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x11, 0x11 }; + const auto check = [](const std::vector& header_address, const uint16_t header_port, + const std::vector& sender, const std::vector* override_address) + { + const auto datagram = socks_datagram(header_address, header_port, query(1, "example.com")); + const auto view = proxy::parse_socks5_udp_datagram(datagram.data(), datagram.size()); + return view && proxy::dns_relay_destination_allowed(*view, sender.data(), sender.size(), + override_address ? override_address->data() : nullptr, 16, 53); + }; + + // A link-local resolver: the scope id is not part of the address bytes. + EXPECT_TRUE(check(link_local, 53, link_local, nullptr)); + EXPECT_TRUE(check(v6_override, 53, link_local, &v6_override)); + EXPECT_FALSE(check(link_local, 53, link_local, &v6_override)); + EXPECT_FALSE(check(v6_relay_source, 53, link_local, nullptr)); + + std::vector loopback(16, 0); + loopback[15] = 1; + EXPECT_FALSE(check(loopback, 53, loopback, nullptr)); +} From 345db2df024294840f744e6e9647861cb4c008d6 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 19:08:06 +0000 Subject: [PATCH 47/62] fix(dns relay): restart the backoff when an association that answered goes silent Review findings on the previous fix: - An association that answered only during its first 30 s (a UDP path that dies whenever the machine idles, while keepalive holds the control connection) never proved itself, so each idle period escalated the backoff towards 30 s and every return from idle dropped UDP DNS for longer. A silent retirement of an association that delivered anything now starts a new outage: the backoff restarts at 1 s. A relay that never answers still backs off 1, 2, 4 ... 30 s, and early closes still escalate. - start_dns_udp_relays() now releases relays left registered by a stop() that did not finish, not just the stopping flag. - Log text: the repeated-failure Debug line no longer prints a misleading attempt number, and the malformed-query count says what it counts. - A test ran its clock backwards; fixed. New test for the idle scenario. - Docs: when the backoff restarts, that another host can only make the proxy query port 53 of the source address its datagram claims (or the override) and never sees the answer, and the black-holed server timing in the Windows checklist. --- docs/configuration.md | 4 +-- docs/gui.md | 2 +- netlib/src/proxy/dns_udp_multiplexer.h | 26 +++++++++++++---- netlib/src/proxy/socks5_dns_udp_relay.h | 7 +++-- netlib/src/proxy/socks_local_router.h | 9 ++---- .../test/proxy/dns_udp_multiplexer_test.cpp | 28 +++++++++++++++++-- 6 files changed, 56 insertions(+), 20 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 0e44cb3..126eb70 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -194,10 +194,10 @@ UDP DNS of each address family goes through a single SOCKS5 control connection a - **Source of the answer.** The answer is presented as coming from the server Windows queried, whatever source address (IPv4 or IPv6) the SOCKS5 relay reports, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered (the `serverOverride` server when one is set); some report their own address. This applies with or without a `serverOverride`. - **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. - **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it, each for at most 3 seconds (Windows retransmits a query after about a second). It is closed, and reopened on the next query, when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. -- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening counts as a failed attempt, so a server that accepts `UDP ASSOCIATE` and then drops the connection is not reconnected in a tight loop; so does one closed because queries stopped being answered, whatever its age, so a relay that never answers is retried less and less often. The delay resets only once an association has proved itself: something arrived from the relay after it had been open for 30 seconds, or it closed normally at that age. Queries waiting when a failure starts a backoff are dropped. +- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening counts as a failed attempt, so a server that accepts `UDP ASSOCIATE` and then drops the connection is not reconnected in a tight loop; so does one closed because queries stopped being answered, whatever its age. If that association had answered before going silent, the delay restarts at 1 second; a relay that never answers is retried less and less often. The delay also resets once an association has proved itself: something arrived from the relay after it had been open for 30 seconds, or it closed normally at that age. Queries waiting when a failure starts a backoff are dropped. - **Logging.** Per address family, the first failure to open an association since the last successful open is logged as a warning and later failures at `Debug`; every successful open and every close is logged at `Info` with its reason. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. -The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. The listener is bound to all local addresses, like the proxy's other local listeners, so another host that guesses an authorized port could still make the proxy send a DNS query to that host's own port 53, or to the override; it never receives the answer, which is delivered to the local client port. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. +The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. The listener is bound to all local addresses, like the proxy's other local listeners, so another host that guesses an authorized port could still make the proxy send a DNS query to port 53 of whatever source address its datagram claims, or to the override. It never receives the answer, which is delivered to the local client port. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. ### Server override diff --git a/docs/gui.md b/docs/gui.md index e3a27c5..d40dd8f 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -165,7 +165,7 @@ The routing policy and the packet rewriting are covered by automated tests (`net 2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). Browse for a few minutes and confirm the SOCKS5 server sees one control connection and one `UDP ASSOCIATE` per address family for UDP DNS, not one per query. 3. Enable `bypassLan` with a router resolver (`192.168.x.1`): without an override the SOCKS5 server is asked for the router address; with `serverOverride: "1.1.1.1"` it is asked for `1.1.1.1` and `Resolve-DnsName` still reports answers from the router address. 4. Reorder the rules, Apply & Restart, and confirm DNS still uses the selected proxy. -5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning per address family in use, and attempts back off to one every 30 seconds. Start the SOCKS5 server again and confirm lookups recover within 30 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" and "opened" at `Info`) and lookups recover. Configure Windows with a second DNS server the SOCKS5 server cannot reach (for example a LAN address, without `serverOverride`), browse for two minutes, and confirm the log has no "queries stopped being answered" line. Stop the service while the SOCKS5 server is unreachable (black-holed, not refusing) and confirm it stops within a few seconds. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. +5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning per address family in use, and attempts back off to about one every 30 seconds (plus the 5-second connect timeout when the server is black-holed). Start the SOCKS5 server again and confirm lookups recover within about 35 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" and "opened" at `Info`) and lookups recover. Configure Windows with a second DNS server the SOCKS5 server cannot reach (for example a LAN address, without `serverOverride`), browse for two minutes, and confirm the log has no "queries stopped being answered" line. Stop the service while the SOCKS5 server is unreachable (black-holed, not refusing) and confirm it stops within a few seconds. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. 6. Configure an IPv4 override with an IPv6 resolver and confirm IPv6 queries are dropped while IPv4 queries succeed. 7. **Upgrade.** With a configuration from an earlier release (no `dns` section, a catch-all rule), confirm that `Resolve-DnsName -TcpOnly` now leaves the adapter directly, that UDP DNS still does, and that the rule's other traffic is still proxied. 8. **Restart.** With `Proxy` mode and `bypassLan`, use **Apply & Restart** (or stop and start the service) and repeat step 3: DNS to the router resolver must still be proxied. diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index 13cb94c..653a936 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -535,9 +535,11 @@ namespace proxy * arriving meanwhile are dropped (Proxy mode never sends DNS directly). An association that * closes less than @p minimum_age after opening counts as a failed open, so a server that * accepts UDP ASSOCIATE and then drops the connection is not reconnected in a tight loop, - * and so does one retired because it stopped answering. The backoff resets only when an - * association proves itself: a datagram arrives from the relay once it is at least - * @p minimum_age old, or it closes normally at that age. + * and so does one retired because it stopped answering. A retired association that had + * delivered something restarts the backoff at its shortest delay; one that never did + * lets it grow. The backoff also resets when an association proves itself: a datagram + * arrives from the relay once it is at least @p minimum_age old, or it closes normally at + * that age. * - An open association is reopened when its SOCKS5 control connection closes or its relay * socket fails (reported by the relay), or when it looks silently dead: at least * @p unanswered_limit queries expired unanswered that were sent after the last datagram @@ -590,14 +592,28 @@ namespace proxy * @brief The association was closed at @p now. * @param failed The association stopped working (for example it was retired for * unanswered queries): back off before the next attempt whatever its age. An - * association younger than the minimum age always counts as a failed open. + * association younger than the minimum age always counts as a failed open. An + * association that worked (something arrived from the relay) and later stopped + * working at or past the minimum age starts a new outage: the backoff restarts + * at its shortest delay instead of growing, so a relay that answers after every + * reopen is never kept waiting long. */ void on_closed(const time_point now, const bool failed = false) noexcept { - if (failed || now - opened_at_ < minimum_age_) + const bool young = now - opened_at_ < minimum_age_; + if (failed && !young && last_datagram_) + { + failures_ = 0; + back_off(now); + } + else if (failed || young) + { back_off(now); + } else + { failures_ = 0; + } } /// Any datagram from the relay shows the association is alive; once it is also at least diff --git a/netlib/src/proxy/socks5_dns_udp_relay.h b/netlib/src/proxy/socks5_dns_udp_relay.h index ad22bc3..4fd195a 100644 --- a/netlib/src/proxy/socks5_dns_udp_relay.h +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -694,8 +694,8 @@ namespace proxy } else { - NETLIB_DEBUG("DNS relay: SOCKS5 UDP association attempt {} failed; next attempt in {} s", - session_.consecutive_failures(), retry.count()); + NETLIB_DEBUG("DNS relay: SOCKS5 UDP association attempt failed again; next attempt in {} s", + retry.count()); } return; } @@ -831,7 +831,8 @@ namespace proxy NETLIB_INFO("DNS relay: dropped so far: {} queries while no SOCKS5 UDP association was available, " "{} not from a redirected DNS client, {} naming a destination other than the queried server or the " - "override, or from a loopback address, {} without a DNS question, {} answers matching no query, " + "override, or from a loopback address, {} malformed (no SOCKS5 header of this family or no DNS " + "question), {} answers matching no query, " "{} send failures", unavailable, unauthorized, refused, malformed, unmatched, send_failures); reported_drops_ = total; last_report_ = now; diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 7954f04..11288e9 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -2750,12 +2750,9 @@ namespace proxy */ void start_dns_udp_relays() { - { - // A stop() that did not finish (for example stop_filter() threw) must not leave - // UDP DNS silently blocked after this start. - std::unique_lock lock(lock_); - dns_udp_relays_stopping_ = false; - } + // A stop() that did not finish (for example stop_filter() threw) must leave neither + // stopped relays registered nor UDP DNS silently blocked after this start. + release_dns_udp_relays(); std::optional> upstream; proxy_session_settings settings; diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index 8fac7be..2319a95 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -791,10 +791,32 @@ TEST(DnsAssociationHealth, AssociationRetiredForSilenceBacksOffWhateverItsAge) } // A long-lived association closed for another reason reopens at once. - health.on_opened(t0 + 61s); - health.on_closed(t0 + 200s); + health.on_opened(at); + health.on_closed(at + 140s); EXPECT_EQ(health.consecutive_failures(), 0u); - EXPECT_TRUE(health.may_open(t0 + 200s)); + EXPECT_TRUE(health.may_open(at + 140s)); +} + +// The relay's UDP path dies whenever the machine is idle (a NAT or server UDP timeout) while +// keepalive holds the control connection: each association answers for a while, goes silent and +// is retired. That is a new outage each time, so the delay must not grow towards 30 s. +TEST(DnsAssociationHealth, AssociationThatAnsweredBeforeGoingSilentRestartsTheBackoff) +{ + proxy::dns_association_health<> health{ 3, 30s }; + auto at = t0; + for (int cycle = 0; cycle < 8; ++cycle) + { + ASSERT_TRUE(health.may_open(at)) << cycle; + health.on_opened(at); + for (int i = 1; i <= 20; ++i) + health.on_relay_datagram(at + std::chrono::seconds{ i }); // busy for 20 s + at += 320s; // idle, then silent + ASSERT_TRUE(health.on_unanswered(3, at)) << cycle; + health.on_closed(at, true); + EXPECT_FALSE(health.may_open(at + 999ms)) << cycle; + EXPECT_TRUE(health.may_open(at + 1s)) << cycle; + at += 1s; + } } TEST(DnsAssociationHealth, FirstOpenFailureSinceEachSuccessfulOpenIsReported) From 7304bfa19506e7f19da4bc4307603d27790b4ef6 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 19:19:18 +0000 Subject: [PATCH 48/62] fix(dns relay): restart the backoff after any working association; warn when unusable Review findings on the previous fix: - A server that ends every UDP association after less than 30 s (an early idle timeout or a fixed lifetime) would push the backoff towards 30 s, because each association answered and then closed young. Any closure of an association that received something from the relay and lived at least 5 s now restarts the backoff at 1 s, whether it was retired for silence or closed young. Associations that received nothing, or died within seconds, still make it grow, so failing servers are not reconnected in a tight loop. - A SOCKS5 server whose relay never answers produced only Info lines. A close of an association that received nothing is now logged as a warning, once until an association works again. - The close log no longer says the association is reopened on the next query when the next attempt is delayed; it gives the delay instead. - Tests pin both close rules and the warning; docs describe them. --- docs/configuration.md | 4 +- netlib/src/proxy/dns_udp_multiplexer.h | 69 ++++++++++++------- netlib/src/proxy/socks5_dns_udp_relay.h | 27 ++++++-- .../test/proxy/dns_udp_multiplexer_test.cpp | 63 +++++++++++++++++ 4 files changed, 130 insertions(+), 33 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 126eb70..03783ed 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -194,8 +194,8 @@ UDP DNS of each address family goes through a single SOCKS5 control connection a - **Source of the answer.** The answer is presented as coming from the server Windows queried, whatever source address (IPv4 or IPv6) the SOCKS5 relay reports, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered (the `serverOverride` server when one is set); some report their own address. This applies with or without a `serverOverride`. - **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. - **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it, each for at most 3 seconds (Windows retransmits a query after about a second). It is closed, and reopened on the next query, when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. -- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening counts as a failed attempt, so a server that accepts `UDP ASSOCIATE` and then drops the connection is not reconnected in a tight loop; so does one closed because queries stopped being answered, whatever its age. If that association had answered before going silent, the delay restarts at 1 second; a relay that never answers is retried less and less often. The delay also resets once an association has proved itself: something arrived from the relay after it had been open for 30 seconds, or it closed normally at that age. Queries waiting when a failure starts a backoff are dropped. -- **Logging.** Per address family, the first failure to open an association since the last successful open is logged as a warning and later failures at `Debug`; every successful open and every close is logged at `Info` with its reason. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. +- **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening, or that is closed because queries stopped being answered, also delays the next attempt. If that association worked (it received anything from the relay and lived at least 5 seconds), the delay restarts at 1 second, so a relay whose UDP path dies on idle, or a server that ends associations early, is retried quickly each time. One that received nothing, or died within seconds, makes the delay grow, so a server that accepts `UDP ASSOCIATE` and then fails is not reconnected in a tight loop and a relay that never answers is retried less and less often. The delay also resets once an association has proved itself: something arrived from the relay after it had been open for 30 seconds, or it closed normally at that age. Queries waiting when a failure starts a backoff are dropped. +- **Logging.** Per address family, the first failure to open an association since the last successful open is logged as a warning and later failures at `Debug`. Every successful open and every close is logged at `Info` with its reason and, when the next attempt is delayed, the delay. A close of an association that never received anything from the relay is logged as a warning instead, once until an association works again, because the relay is then unusable even though the SOCKS5 server accepts connections. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. The listener is bound to all local addresses, like the proxy's other local listeners, so another host that guesses an authorized port could still make the proxy send a DNS query to port 53 of whatever source address its datagram claims, or to the override. It never receives the answer, which is delivered to the local client port. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index 653a936..ee4b69e 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -535,11 +535,11 @@ namespace proxy * arriving meanwhile are dropped (Proxy mode never sends DNS directly). An association that * closes less than @p minimum_age after opening counts as a failed open, so a server that * accepts UDP ASSOCIATE and then drops the connection is not reconnected in a tight loop, - * and so does one retired because it stopped answering. A retired association that had - * delivered something restarts the backoff at its shortest delay; one that never did - * lets it grow. The backoff also resets when an association proves itself: a datagram - * arrives from the relay once it is at least @p minimum_age old, or it closes normally at - * that age. + * and so does one retired because it stopped answering. A closed association that had + * worked restarts the backoff at its shortest delay; one that never delivered anything + * lets it grow (see on_closed()). The backoff also resets when an association proves + * itself: a datagram arrives from the relay once it is at least @p minimum_age old, or it + * closes normally at that age. * - An open association is reopened when its SOCKS5 control connection closes or its relay * socket fails (reported by the relay), or when it looks silently dead: at least * @p unanswered_limit queries expired unanswered that were sent after the last datagram @@ -590,30 +590,41 @@ namespace proxy /** * @brief The association was closed at @p now. - * @param failed The association stopped working (for example it was retired for - * unanswered queries): back off before the next attempt whatever its age. An - * association younger than the minimum age always counts as a failed open. An - * association that worked (something arrived from the relay) and later stopped - * working at or past the minimum age starts a new outage: the backoff restarts - * at its shortest delay instead of growing, so a relay that answers after every - * reopen is never kept waiting long. + * + * - A normal close (control connection or relay socket) of an association at least the + * minimum age old resets the backoff: the next query reopens at once. + * - Otherwise (it was retired for unanswered queries, @p failed, or it closed younger + * than the minimum age) the next attempt backs off. If the association worked, that + * is, something arrived from the relay and it lived at least minimum_working_life, + * the closure is a new outage and the backoff restarts at its shortest delay, so a + * relay that keeps answering after every reopen (one whose UDP path dies on idle, or + * a server that ends associations early) is never kept waiting long. An association + * that delivered nothing, or died within seconds, makes the backoff grow, so a server + * that accepts UDP ASSOCIATE and then fails is not reconnected in a tight loop. + * + * @return true when this closure should be reported as a warning: the association + * delivered nothing, and no such closure has been reported since the last + * association that delivered something (the relay looks unusable). */ - void on_closed(const time_point now, const bool failed = false) noexcept + bool on_closed(const time_point now, const bool failed = false) noexcept { - const bool young = now - opened_at_ < minimum_age_; - if (failed && !young && last_datagram_) + const auto age = now - opened_at_; + const bool delivered = last_datagram_.has_value(); + + if (!failed && age >= minimum_age_) { failures_ = 0; - back_off(now); - } - else if (failed || young) - { - back_off(now); + return false; } - else - { + + if (delivered && age >= minimum_working_life) failures_ = 0; - } + back_off(now); + + if (delivered || unusable_reported_) + return false; + unusable_reported_ = true; + return true; } /// Any datagram from the relay shows the association is alive; once it is also at least @@ -622,6 +633,7 @@ namespace proxy { unanswered_ = 0; last_datagram_ = now; + unusable_reported_ = false; if (now - opened_at_ >= minimum_age_) failures_ = 0; } @@ -644,6 +656,10 @@ namespace proxy static constexpr std::chrono::seconds max_backoff{ 30 }; + /// An association that delivered something and lived at least this long worked: its + /// closure restarts the backoff instead of growing it. + static constexpr std::chrono::seconds minimum_working_life{ 5 }; + private: void back_off(const time_point now) noexcept { @@ -653,6 +669,7 @@ namespace proxy } bool open_failure_reported_{ false }; + bool unusable_reported_{ false }; std::size_t unanswered_limit_; std::chrono::seconds minimum_age_; std::size_t failures_{}; @@ -788,11 +805,11 @@ namespace proxy void on_opened(const time_point now) noexcept { health_.on_opened(now); } /// The association closed: its queries in flight can no longer be answered. See - /// dns_association_health::on_closed() for @p failed. - void on_closed(const time_point now, const bool failed = false) noexcept + /// dns_association_health::on_closed() for @p failed and the result. + bool on_closed(const time_point now, const bool failed = false) noexcept { queries_.clear(); - health_.on_closed(now, failed); + return health_.on_closed(now, failed); } void clear() noexcept { queries_.clear(); } diff --git a/netlib/src/proxy/socks5_dns_udp_relay.h b/netlib/src/proxy/socks5_dns_udp_relay.h index 4fd195a..15a35bf 100644 --- a/netlib/src/proxy/socks5_dns_udp_relay.h +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -622,13 +622,30 @@ namespace proxy if (reason) { - NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association with {} because {}; it is reopened " - "on the next query", upstream_.to_string(), reason); auto retired = std::move(association_); - session_.on_closed(now, silent); - // Queries queued meanwhile cannot wait out a backoff. - if (!session_.may_open(now)) + const bool unusable = session_.on_closed(now, silent); + if (session_.may_open(now)) + { + NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association with {} because {}; it is " + "reopened on the next query", upstream_.to_string(), reason); + } + else + { + const auto retry = std::chrono::duration_cast(session_.next_attempt() - now); + if (unusable) + { + NETLIB_WARNING("DNS relay: closing the SOCKS5 UDP association with {} because {}, without " + "it having delivered anything; UDP DNS is dropped until an association works (next " + "attempt in {} s)", upstream_.to_string(), reason, retry.count()); + } + else + { + NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association with {} because {}; next " + "attempt in {} s", upstream_.to_string(), reason, retry.count()); + } + // Queries queued meanwhile cannot wait out a backoff. dropped_unavailable_ += waiting_.drop_all(); + } lock.unlock(); close_association(std::move(retired)); lock.lock(); diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index 2319a95..9ed4bcb 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -886,3 +886,66 @@ TEST(DnsRelayDestination, Ipv6QueriesFollowTheSameRules) loopback[15] = 1; EXPECT_FALSE(check(loopback, 53, loopback, nullptr)); } + +// A server that ends every UDP association after 20 s (an early idle timeout or a fixed +// lifetime): each association answers, then closes young. That is a new outage each time, so the +// delay must not grow towards 30 s. +TEST(DnsAssociationHealth, AssociationThatWorkedThenClosedYoungRestartsTheBackoff) +{ + proxy::dns_association_health<> health{ 3, 30s }; + auto at = t0; + for (int cycle = 0; cycle < 8; ++cycle) + { + ASSERT_TRUE(health.may_open(at)) << cycle; + health.on_opened(at); + health.on_relay_datagram(at + 1s); + at += 20s; + EXPECT_FALSE(health.on_closed(at)) << cycle; + EXPECT_FALSE(health.may_open(at + 999ms)) << cycle; + EXPECT_TRUE(health.may_open(at + 1s)) << cycle; + at += 1s; + } +} + +// Associations that die within seconds still make the backoff grow, whether or not a datagram +// arrived first, so such a server is not reconnected in a tight loop. +TEST(DnsAssociationHealth, AssociationsDyingWithinSecondsStillBackOffFurther) +{ + proxy::dns_association_health<> health{ 3, 30s }; + auto at = t0; + for (const auto delay : { 1s, 2s, 4s, 8s, 16s, 30s }) + { + ASSERT_TRUE(health.may_open(at)); + health.on_opened(at); + health.on_relay_datagram(at + 1s); + at += 3s; + (void)health.on_closed(at); + EXPECT_FALSE(health.may_open(at + delay - 1ms)); + EXPECT_TRUE(health.may_open(at + delay)); + at += delay; + } +} + +// An association that closes without ever delivering anything is reported once as a warning +// (the relay looks unusable), and again only after some association has delivered something. +TEST(DnsAssociationHealth, UnusableAssociationIsReportedOncePerOutage) +{ + proxy::dns_association_health<> health{ 3, 30s }; + health.on_opened(t0); + ASSERT_TRUE(health.on_unanswered(3, t0 + 40s)); + EXPECT_TRUE(health.on_closed(t0 + 40s, true)); + + health.on_opened(t0 + 42s); + EXPECT_FALSE(health.on_closed(t0 + 43s)); // young, delivered nothing: not again + + health.on_opened(t0 + 50s); + health.on_relay_datagram(t0 + 51s); // it worked + EXPECT_FALSE(health.on_closed(t0 + 90s, true)); // delivered something: not unusable + + health.on_opened(t0 + 91s); + EXPECT_TRUE(health.on_closed(t0 + 92s)); // a new outage is reported again + + // A normal close of an old association is never reported. + health.on_opened(t0 + 200s); + EXPECT_FALSE(health.on_closed(t0 + 300s)); +} From 1fdfaab092a6f4c23dc8565331a0f5cab3dc721e Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 19:33:27 +0000 Subject: [PATCH 49/62] fix(dns relay): accurate unanswered-relay warning; report a flapping server once Review findings on the previous fix: - The new warning blamed the SOCKS5 relay, while the commonest cause is a DNS server the proxy cannot reach (a local resolver without serverOverride). It now names both causes and suggests serverOverride. - That warning was skipped when an association that never received anything closed normally at 30 s or older. It is now given whatever ends the association, but only if queries were sent through it, so an association closed before its first query is not reported. - The "could not open" warning was re-armed by every successful open, so a server alternating between refusing and accepting without ever working repeated it about once a minute. It is now re-armed only when an association receives something. - A retired association's reader could still hand one late datagram to the session after the closure was recorded, cancelling the backoff just set. The association is marked retiring under the lock before the closure is recorded, and the reader checks that under the lock. - Docs: reopening may be delayed; the logging rules above. Class comment tightened. Tests for each rule. --- docs/configuration.md | 4 +- netlib/src/proxy/dns_udp_multiplexer.h | 42 +++++++----- netlib/src/proxy/socks5_dns_udp_relay.h | 26 ++++--- .../test/proxy/dns_udp_multiplexer_test.cpp | 68 ++++++++++++++++--- 4 files changed, 101 insertions(+), 39 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 03783ed..a932b9a 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -193,9 +193,9 @@ UDP DNS of each address family goes through a single SOCKS5 control connection a - **Matching answers to queries.** While a query is in flight, its DNS message ID is replaced by a unique, randomly chosen ID. The answer carrying that ID is returned to the socket that asked, with the socket's own message ID, but only if it also carries the query's question (name, ignoring case, type and class). A question-less error response from the server is accepted too. A retransmission from the same socket reuses the ID. Up to 4,096 queries can be in flight; a query without an answer is forgotten after 10 seconds. An answer that matches no query in flight, or whose question differs, is dropped. A query whose question section cannot be parsed is dropped. - **Source of the answer.** The answer is presented as coming from the server Windows queried, whatever source address (IPv4 or IPv6) the SOCKS5 relay reports, because a resolver discards an answer from an address it did not query. RFC 1928 relays report the server that answered (the `serverOverride` server when one is set); some report their own address. This applies with or without a `serverOverride`. - **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. -- **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it, each for at most 3 seconds (Windows retransmits a query after about a second). It is closed, and reopened on the next query, when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. +- **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it, each for at most 3 seconds (Windows retransmits a query after about a second). It is closed, and reopened on the next query (possibly after a delay, see below), when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. - **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening, or that is closed because queries stopped being answered, also delays the next attempt. If that association worked (it received anything from the relay and lived at least 5 seconds), the delay restarts at 1 second, so a relay whose UDP path dies on idle, or a server that ends associations early, is retried quickly each time. One that received nothing, or died within seconds, makes the delay grow, so a server that accepts `UDP ASSOCIATE` and then fails is not reconnected in a tight loop and a relay that never answers is retried less and less often. The delay also resets once an association has proved itself: something arrived from the relay after it had been open for 30 seconds, or it closed normally at that age. Queries waiting when a failure starts a backoff are dropped. -- **Logging.** Per address family, the first failure to open an association since the last successful open is logged as a warning and later failures at `Debug`. Every successful open and every close is logged at `Info` with its reason and, when the next attempt is delayed, the delay. A close of an association that never received anything from the relay is logged as a warning instead, once until an association works again, because the relay is then unusable even though the SOCKS5 server accepts connections. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. +- **Logging.** Per address family, the first failure to open an association since an association last received something (or since the service started) is logged as a warning and later failures at `Debug`. Every successful open and every close is logged at `Info` with its reason and, when the next attempt is delayed, the delay. When an association closes after queries were sent through it and nothing ever came back, a warning says so, once until an answer arrives: either the SOCKS5 server's UDP relay does not work, or the DNS servers Windows queries cannot be reached from the proxy (a local resolver without a `serverOverride`, for example). Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. The listener is bound to all local addresses, like the proxy's other local listeners, so another host that guesses an authorized port could still make the proxy send a DNS query to port 53 of whatever source address its datagram claims, or to the override. It never receives the answer, which is delivered to the local client port. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index ee4b69e..32ea481 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -533,11 +533,10 @@ namespace proxy * * - A failed open is retried after a backoff that doubles from 1 s up to 30 s; queries * arriving meanwhile are dropped (Proxy mode never sends DNS directly). An association that - * closes less than @p minimum_age after opening counts as a failed open, so a server that - * accepts UDP ASSOCIATE and then drops the connection is not reconnected in a tight loop, - * and so does one retired because it stopped answering. A closed association that had - * worked restarts the backoff at its shortest delay; one that never delivered anything - * lets it grow (see on_closed()). The backoff also resets when an association proves + * closes less than @p minimum_age after opening, or is retired because it stopped + * answering, also delays the next attempt: from the shortest delay again if it worked, + * growing if it delivered nothing or died within seconds (see on_closed()), so a server + * that accepts UDP ASSOCIATE and then fails is not reconnected in a tight loop. The backoff also resets when an association proves * itself: a datagram arrives from the relay once it is at least @p minimum_age old, or it * closes normally at that age. * - An open association is reopened when its SOCKS5 control connection closes or its relay @@ -569,8 +568,10 @@ namespace proxy /** * @brief Records a failed attempt to open an association and backs off. - * @return true for the first failed attempt since the last successful open (or since - * the relay started), which the relay reports as a warning. + * @return true for the first failed attempt since an association last received + * something from the relay (or since the relay started), which the relay reports + * as a warning. A server that alternates between refusing and accepting without + * ever working is therefore reported once, not on every cycle. */ bool on_open_failed(const time_point now) noexcept { @@ -585,9 +586,12 @@ namespace proxy unanswered_ = 0; opened_at_ = now; last_datagram_.reset(); - open_failure_reported_ = false; + query_sent_ = false; } + /// A query was sent through the open association. + void on_query_sent() noexcept { query_sent_ = true; } + /** * @brief The association was closed at @p now. * @@ -602,9 +606,9 @@ namespace proxy * that delivered nothing, or died within seconds, makes the backoff grow, so a server * that accepts UDP ASSOCIATE and then fails is not reconnected in a tight loop. * - * @return true when this closure should be reported as a warning: the association - * delivered nothing, and no such closure has been reported since the last - * association that delivered something (the relay looks unusable). + * @return true when this closure should be reported as a warning: queries were sent + * through the association and nothing came back, and no such closure has been + * reported since an association last received something. */ bool on_closed(const time_point now, const bool failed = false) noexcept { @@ -612,16 +616,15 @@ namespace proxy const bool delivered = last_datagram_.has_value(); if (!failed && age >= minimum_age_) - { failures_ = 0; - return false; + else + { + if (delivered && age >= minimum_working_life) + failures_ = 0; + back_off(now); } - if (delivered && age >= minimum_working_life) - failures_ = 0; - back_off(now); - - if (delivered || unusable_reported_) + if (delivered || !query_sent_ || unusable_reported_) return false; unusable_reported_ = true; return true; @@ -634,6 +637,7 @@ namespace proxy unanswered_ = 0; last_datagram_ = now; unusable_reported_ = false; + open_failure_reported_ = false; if (now - opened_at_ >= minimum_age_) failures_ = 0; } @@ -670,6 +674,7 @@ namespace proxy bool open_failure_reported_{ false }; bool unusable_reported_{ false }; + bool query_sent_{ false }; std::size_t unanswered_limit_; std::chrono::seconds minimum_age_; std::size_t failures_{}; @@ -749,6 +754,7 @@ namespace proxy return dns_relay_query::no_id; set_dns_message_id(message, *relay_id); + health_.on_query_sent(); return dns_relay_query::send; } diff --git a/netlib/src/proxy/socks5_dns_udp_relay.h b/netlib/src/proxy/socks5_dns_udp_relay.h index 15a35bf..616a75c 100644 --- a/netlib/src/proxy/socks5_dns_udp_relay.h +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -547,6 +547,8 @@ namespace proxy typename dns_relay_session::answer result; { std::scoped_lock lock(lock_); + if (owner->retiring.load(std::memory_order_acquire)) + return; result = session_.prepare_answer(buffer.data(), static_cast(received), [](const client_t& client) { @@ -623,7 +625,18 @@ namespace proxy if (reason) { auto retired = std::move(association_); + // Fence off the retiring reader (it checks this under lock_), so a late + // datagram cannot touch the session after the closure is recorded. + retired->retiring.store(true, std::memory_order_release); const bool unusable = session_.on_closed(now, silent); + if (unusable) + { + NETLIB_WARNING("DNS relay: no answer came back through the SOCKS5 UDP association with {} " + "(closed because {}): either its UDP relay does not work, or the DNS servers Windows " + "queries cannot be reached from the proxy (consider a DNS serverOverride). UDP DNS is " + "dropped until an answer arrives.", upstream_.to_string(), reason); + } + if (session_.may_open(now)) { NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association with {} because {}; it is " @@ -632,17 +645,8 @@ namespace proxy else { const auto retry = std::chrono::duration_cast(session_.next_attempt() - now); - if (unusable) - { - NETLIB_WARNING("DNS relay: closing the SOCKS5 UDP association with {} because {}, without " - "it having delivered anything; UDP DNS is dropped until an association works (next " - "attempt in {} s)", upstream_.to_string(), reason, retry.count()); - } - else - { - NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association with {} because {}; next " - "attempt in {} s", upstream_.to_string(), reason, retry.count()); - } + NETLIB_INFO("DNS relay: closing the SOCKS5 UDP association with {} because {}; next " + "attempt in {} s", upstream_.to_string(), reason, retry.count()); // Queries queued meanwhile cannot wait out a backoff. dropped_unavailable_ += waiting_.drop_all(); } diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index 9ed4bcb..cb04043 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -819,20 +819,43 @@ TEST(DnsAssociationHealth, AssociationThatAnsweredBeforeGoingSilentRestartsTheBa } } -TEST(DnsAssociationHealth, FirstOpenFailureSinceEachSuccessfulOpenIsReported) +TEST(DnsAssociationHealth, FirstOpenFailureSinceAnAssociationLastWorkedIsReported) { proxy::dns_association_health<> health{ 3, 30s }; EXPECT_TRUE(health.on_open_failed(t0)); EXPECT_FALSE(health.on_open_failed(t0 + 1s)); - health.on_opened(t0 + 3s); - // A silent retirement is not an open failure and does not use up the report. + // An association that works re-arms the report; a silent retirement does not use it up. + health.on_opened(t0 + 3s); + health.on_relay_datagram(t0 + 4s); + health.on_query_sent(); ASSERT_TRUE(health.on_unanswered(3, t0 + 40s)); - health.on_closed(t0 + 40s, true); + (void)health.on_closed(t0 + 40s, true); EXPECT_TRUE(health.on_open_failed(t0 + 41s)); EXPECT_FALSE(health.on_open_failed(t0 + 43s)); } +// A server that alternates between refusing connections and accepting UDP ASSOCIATE without ever +// working is reported once, not on every cycle. +TEST(DnsAssociationHealth, FlappingServerThatNeverWorksIsReportedOnce) +{ + proxy::dns_association_health<> health{ 3, 30s }; + int open_failure_reports = 0; + int unusable_reports = 0; + auto at = t0; + for (int cycle = 0; cycle < 10; ++cycle) + { + open_failure_reports += health.on_open_failed(at) ? 1 : 0; + at = health.next_attempt(); + health.on_opened(at); + health.on_query_sent(); + unusable_reports += health.on_closed(at + 100ms) ? 1 : 0; + at = health.next_attempt(); + } + EXPECT_EQ(open_failure_reports, 1); + EXPECT_EQ(unusable_reports, 1); +} + // --- Queries waiting for the association -------------------------------------------------------- TEST(DnsWaitingQueue, IsBoundedAndKeepsArrivalOrder) @@ -932,20 +955,49 @@ TEST(DnsAssociationHealth, UnusableAssociationIsReportedOncePerOutage) { proxy::dns_association_health<> health{ 3, 30s }; health.on_opened(t0); + health.on_query_sent(); ASSERT_TRUE(health.on_unanswered(3, t0 + 40s)); EXPECT_TRUE(health.on_closed(t0 + 40s, true)); health.on_opened(t0 + 42s); - EXPECT_FALSE(health.on_closed(t0 + 43s)); // young, delivered nothing: not again + health.on_query_sent(); + EXPECT_FALSE(health.on_closed(t0 + 43s)); // still the same outage: not again health.on_opened(t0 + 50s); + health.on_query_sent(); health.on_relay_datagram(t0 + 51s); // it worked EXPECT_FALSE(health.on_closed(t0 + 90s, true)); // delivered something: not unusable health.on_opened(t0 + 91s); + health.on_query_sent(); EXPECT_TRUE(health.on_closed(t0 + 92s)); // a new outage is reported again +} + +TEST(DnsAssociationHealth, UnusableIsReportedWhateverEndsTheAssociationButOnlyIfQueriesWereSent) +{ + // A normal close at any age, after queries got no answer: reported (and the backoff resets). + proxy::dns_association_health<> health{ 3, 30s }; + health.on_opened(t0); + health.on_query_sent(); + EXPECT_TRUE(health.on_closed(t0 + 60s)); + EXPECT_TRUE(health.may_open(t0 + 60s)); + + // No query was sent through it (a restart before the first query): not reported. + proxy::dns_association_health<> idle{ 3, 30s }; + idle.on_opened(t0); + EXPECT_FALSE(idle.on_closed(t0 + 2s)); + idle.on_opened(t0 + 10s); + EXPECT_FALSE(idle.on_closed(t0 + 100s)); +} + +TEST(DnsRelaySession, ClosureAfterUnansweredQueriesIsReportedButNotAnIdleOne) +{ + auto idle = make_session(); + idle.on_opened(t0); + EXPECT_FALSE(idle.on_closed(t0 + 60s)); - // A normal close of an old association is never reported. - health.on_opened(t0 + 200s); - EXPECT_FALSE(health.on_closed(t0 + 300s)); + auto unanswered = make_session(); + unanswered.on_opened(t0); + (void)send_query(unanswered, { 1, 1 }, 1, "a.example", t0 + 1s, 7); + EXPECT_TRUE(unanswered.on_closed(t0 + 60s)); } From 30452c01e9491edd34177628e0dfce30a8cb627f Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 19:42:25 +0000 Subject: [PATCH 50/62] fix(dns relay): distinguish an early-ended association in the warning; tidy Review findings on the previous fix: - When the server ended an association within seconds, the warning still suggested an unreachable resolver and serverOverride. That diagnosis is now given only when queries had time to be answered (an association retired for silence, or open at least the query lifetime); otherwise the warning says the server ended the association N s after it opened. It now says UDP DNS fails, not that it is dropped, and follows the Info close line instead of preceding it. - A query counts as sent through the association only once send() succeeds. - An overlong comment line is reflowed; trailing whitespace carried over with the moved SOCKS5 association code is removed. - Docs: the two warning texts; a Windows checklist step for the unreachable-resolver warning. --- docs/configuration.md | 2 +- docs/gui.md | 2 +- netlib/src/proxy/dns_udp_multiplexer.h | 17 ++++++++--- netlib/src/proxy/socks5_dns_udp_relay.h | 29 ++++++++++++++----- netlib/src/proxy/socks5_udp_association.h | 12 ++++---- .../test/proxy/dns_udp_multiplexer_test.cpp | 8 +++++ 6 files changed, 50 insertions(+), 20 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index a932b9a..4a57a23 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -195,7 +195,7 @@ UDP DNS of each address family goes through a single SOCKS5 control connection a - **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. - **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it, each for at most 3 seconds (Windows retransmits a query after about a second). It is closed, and reopened on the next query (possibly after a delay, see below), when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. - **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening, or that is closed because queries stopped being answered, also delays the next attempt. If that association worked (it received anything from the relay and lived at least 5 seconds), the delay restarts at 1 second, so a relay whose UDP path dies on idle, or a server that ends associations early, is retried quickly each time. One that received nothing, or died within seconds, makes the delay grow, so a server that accepts `UDP ASSOCIATE` and then fails is not reconnected in a tight loop and a relay that never answers is retried less and less often. The delay also resets once an association has proved itself: something arrived from the relay after it had been open for 30 seconds, or it closed normally at that age. Queries waiting when a failure starts a backoff are dropped. -- **Logging.** Per address family, the first failure to open an association since an association last received something (or since the service started) is logged as a warning and later failures at `Debug`. Every successful open and every close is logged at `Info` with its reason and, when the next attempt is delayed, the delay. When an association closes after queries were sent through it and nothing ever came back, a warning says so, once until an answer arrives: either the SOCKS5 server's UDP relay does not work, or the DNS servers Windows queries cannot be reached from the proxy (a local resolver without a `serverOverride`, for example). Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. +- **Logging.** Per address family, the first failure to open an association since an association last received something (or since the service started) is logged as a warning and later failures at `Debug`. Every successful open and every close is logged at `Info` with its reason and, when the next attempt is delayed, the delay. When an association closes after queries were sent through it and nothing ever came back, a warning says so, once until an answer arrives. If the queries had time to be answered, it says that either the SOCKS5 server's UDP relay does not work or the DNS servers Windows queries cannot be reached from the proxy (a local resolver without a `serverOverride`, for example); if the server ended the association within seconds, it says that instead. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. The listener is bound to all local addresses, like the proxy's other local listeners, so another host that guesses an authorized port could still make the proxy send a DNS query to port 53 of whatever source address its datagram claims, or to the override. It never receives the answer, which is delivered to the local client port. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. diff --git a/docs/gui.md b/docs/gui.md index d40dd8f..fc4a232 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -165,7 +165,7 @@ The routing policy and the packet rewriting are covered by automated tests (`net 2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). Browse for a few minutes and confirm the SOCKS5 server sees one control connection and one `UDP ASSOCIATE` per address family for UDP DNS, not one per query. 3. Enable `bypassLan` with a router resolver (`192.168.x.1`): without an override the SOCKS5 server is asked for the router address; with `serverOverride: "1.1.1.1"` it is asked for `1.1.1.1` and `Resolve-DnsName` still reports answers from the router address. 4. Reorder the rules, Apply & Restart, and confirm DNS still uses the selected proxy. -5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning per address family in use, and attempts back off to about one every 30 seconds (plus the 5-second connect timeout when the server is black-holed). Start the SOCKS5 server again and confirm lookups recover within about 35 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" and "opened" at `Info`) and lookups recover. Configure Windows with a second DNS server the SOCKS5 server cannot reach (for example a LAN address, without `serverOverride`), browse for two minutes, and confirm the log has no "queries stopped being answered" line. Stop the service while the SOCKS5 server is unreachable (black-holed, not refusing) and confirm it stops within a few seconds. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. +5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning per address family in use, and attempts back off to about one every 30 seconds (plus the 5-second connect timeout when the server is black-holed). Start the SOCKS5 server again and confirm lookups recover within about 35 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" and "opened" at `Info`) and lookups recover. Configure Windows with a second DNS server the SOCKS5 server cannot reach (for example a LAN address, without `serverOverride`), browse for two minutes, and confirm the log has no "queries stopped being answered" line. Stop the service while the SOCKS5 server is unreachable (black-holed, not refusing) and confirm it stops within a few seconds. Finally, with `serverOverride` removed and Windows using only a resolver the SOCKS5 server cannot reach (a LAN address), confirm one "no answer came back through the SOCKS5 UDP association" warning per address family within about a minute, not repeated; then set `serverOverride` and confirm lookups work. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. 6. Configure an IPv4 override with an IPv6 resolver and confirm IPv6 queries are dropped while IPv4 queries succeed. 7. **Upgrade.** With a configuration from an earlier release (no `dns` section, a catch-all rule), confirm that `Resolve-DnsName -TcpOnly` now leaves the adapter directly, that UDP DNS still does, and that the rule's other traffic is still proxied. 8. **Restart.** With `Proxy` mode and `bypassLan`, use **Apply & Restart** (or stop and start the service) and repeat step 3: DNS to the router resolver must still be proxied. diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index 32ea481..b964a55 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -536,9 +536,9 @@ namespace proxy * closes less than @p minimum_age after opening, or is retired because it stopped * answering, also delays the next attempt: from the shortest delay again if it worked, * growing if it delivered nothing or died within seconds (see on_closed()), so a server - * that accepts UDP ASSOCIATE and then fails is not reconnected in a tight loop. The backoff also resets when an association proves - * itself: a datagram arrives from the relay once it is at least @p minimum_age old, or it - * closes normally at that age. + * that accepts UDP ASSOCIATE and then fails is not reconnected in a tight loop. The + * backoff also resets when an association proves itself: a datagram arrives from the + * relay once it is at least @p minimum_age old, or it closes normally at that age. * - An open association is reopened when its SOCKS5 control connection closes or its relay * socket fails (reported by the relay), or when it looks silently dead: at least * @p unanswered_limit queries expired unanswered that were sent after the last datagram @@ -592,6 +592,9 @@ namespace proxy /// A query was sent through the open association. void on_query_sent() noexcept { query_sent_ = true; } + /// When the current (or last) association was opened. + [[nodiscard]] time_point opened_at() const noexcept { return opened_at_; } + /** * @brief The association was closed at @p now. * @@ -754,7 +757,6 @@ namespace proxy return dns_relay_query::no_id; set_dns_message_id(message, *relay_id); - health_.on_query_sent(); return dns_relay_query::send; } @@ -806,6 +808,13 @@ namespace proxy void expire_closed(const time_point now) { (void)queries_.expire(now); } [[nodiscard]] bool may_open(const time_point now) const noexcept { return health_.may_open(now); } + /// A prepared query was sent through the association (see dns_association_health). + void on_query_sent() noexcept { health_.on_query_sent(); } + /// How long the current (or last) association has been open at @p now. + [[nodiscard]] typename Clock::duration association_age(const time_point now) const noexcept + { + return now - health_.opened_at(); + } /// See dns_association_health::on_open_failed(). bool on_open_failed(const time_point now) noexcept { return health_.on_open_failed(now); } void on_opened(const time_point now) noexcept { health_.on_opened(now); } diff --git a/netlib/src/proxy/socks5_dns_udp_relay.h b/netlib/src/proxy/socks5_dns_udp_relay.h index 616a75c..06c92a4 100644 --- a/netlib/src/proxy/socks5_dns_udp_relay.h +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -426,7 +426,11 @@ namespace proxy } if (send(association_->relay, reinterpret_cast(datagram.data()), - static_cast(datagram.size()), 0) == SOCKET_ERROR) + static_cast(datagram.size()), 0) != SOCKET_ERROR) + { + session_.on_query_sent(); + } + else { ++dropped_send_failures_; if (!transient_udp_error(WSAGetLastError())) @@ -628,14 +632,8 @@ namespace proxy // Fence off the retiring reader (it checks this under lock_), so a late // datagram cannot touch the session after the closure is recorded. retired->retiring.store(true, std::memory_order_release); + const auto age = std::chrono::duration_cast(session_.association_age(now)); const bool unusable = session_.on_closed(now, silent); - if (unusable) - { - NETLIB_WARNING("DNS relay: no answer came back through the SOCKS5 UDP association with {} " - "(closed because {}): either its UDP relay does not work, or the DNS servers Windows " - "queries cannot be reached from the proxy (consider a DNS serverOverride). UDP DNS is " - "dropped until an answer arrives.", upstream_.to_string(), reason); - } if (session_.may_open(now)) { @@ -650,6 +648,21 @@ namespace proxy // Queries queued meanwhile cannot wait out a backoff. dropped_unavailable_ += waiting_.drop_all(); } + + if (unusable && (silent || age >= query_ttl)) + { + // Queries had time to be answered and none was. + NETLIB_WARNING("DNS relay: no answer came back through the SOCKS5 UDP association with {}: " + "either its UDP relay does not work, or the DNS servers Windows queries cannot be " + "reached from the proxy (consider a DNS serverOverride). UDP DNS fails until an " + "answer arrives.", upstream_.to_string()); + } + else if (unusable) + { + NETLIB_WARNING("DNS relay: the SOCKS5 UDP association with {} ended {} s after it opened ({}), " + "before any answer arrived. UDP DNS fails until an association works.", + upstream_.to_string(), age.count(), reason); + } lock.unlock(); close_association(std::move(retired)); lock.lock(); diff --git a/netlib/src/proxy/socks5_udp_association.h b/netlib/src/proxy/socks5_udp_association.h index 9290ae8..ea3d747 100644 --- a/netlib/src/proxy/socks5_udp_association.h +++ b/netlib/src/proxy/socks5_udp_association.h @@ -103,15 +103,15 @@ namespace proxy // Set socket timeouts to prevent indefinite blocking in recv/send calls // This prevents deadlock where IOCP worker holds lock_ while blocked on network I/O constexpr DWORD timeout_ms = 5000; // 5 second timeout - if (setsockopt(socks_tcp_socket, SOL_SOCKET, SO_RCVTIMEO, + if (setsockopt(socks_tcp_socket, SOL_SOCKET, SO_RCVTIMEO, reinterpret_cast(&timeout_ms), sizeof(timeout_ms)) == SOCKET_ERROR) { NETLIB_WARNING("Failed to set socket receive timeout: {}", WSAGetLastError()); closesocket(socks_tcp_socket); return INVALID_SOCKET; } - - if (setsockopt(socks_tcp_socket, SOL_SOCKET, SO_SNDTIMEO, + + if (setsockopt(socks_tcp_socket, SOL_SOCKET, SO_SNDTIMEO, reinterpret_cast(&timeout_ms), sizeof(timeout_ms)) == SOCKET_ERROR) { NETLIB_WARNING("Failed to set socket send timeout: {}", WSAGetLastError()); @@ -456,7 +456,7 @@ namespace proxy return {}; } - if (negotiate_ctx->socks5_username.value().length() > socks5_username_max_length || + if (negotiate_ctx->socks5_username.value().length() > socks5_username_max_length || negotiate_ctx->socks5_username.value().length() < 1) { NETLIB_INFO( @@ -471,7 +471,7 @@ namespace proxy return {}; } - if (negotiate_ctx->socks5_password.value().length() > socks5_username_max_length || + if (negotiate_ctx->socks5_password.value().length() > socks5_username_max_length || negotiate_ctx->socks5_password.value().length() < 1) { NETLIB_INFO( @@ -485,7 +485,7 @@ namespace proxy ); if (!send_control(reinterpret_cast(&auth_req), - 3 + static_cast(negotiate_ctx->socks5_username.value().length()) + + 3 + static_cast(negotiate_ctx->socks5_username.value().length()) + static_cast(negotiate_ctx->socks5_password.value().length()))) { NETLIB_INFO( diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index cb04043..9c5cbb0 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -996,8 +996,16 @@ TEST(DnsRelaySession, ClosureAfterUnansweredQueriesIsReportedButNotAnIdleOne) idle.on_opened(t0); EXPECT_FALSE(idle.on_closed(t0 + 60s)); + // Prepared but never sent (the send failed): not reported either. + auto unsent = make_session(); + unsent.on_opened(t0); + (void)send_query(unsent, { 1, 1 }, 1, "a.example", t0 + 1s, 7); + EXPECT_FALSE(unsent.on_closed(t0 + 60s)); + auto unanswered = make_session(); unanswered.on_opened(t0); (void)send_query(unanswered, { 1, 1 }, 1, "a.example", t0 + 1s, 7); + unanswered.on_query_sent(); + EXPECT_EQ(unanswered.association_age(t0 + 60s), 60s); EXPECT_TRUE(unanswered.on_closed(t0 + 60s)); } From 91e124088c12f9b1f27f37db815f9e7434037eec Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 19:53:48 +0000 Subject: [PATCH 51/62] fix(dns relay): report each cause of a failed association once; warn on unusable relay sockets Review findings on the previous fix: - The "ended N s after it opened" and the "no answer came back (consider a DNS serverOverride)" warnings shared one once-per-outage flag, so an early close (for example at boot) hid the more useful diagnosis for an unreachable resolver. dns_association_health::on_closed() now returns which report applies, and each has its own flag, re-armed when an association receives something. - Whether queries had time to be answered is measured from the first query actually sent, not from when the association opened. - An association whose relay socket failed before any query could be sent produced no warning, so UDP DNS could fail permanently with only Info lines. It now gets its own warning ("no query could be sent through the SOCKS5 UDP relay"). - The decision moved into the portable class, with tests for each cause, both orders, the timing rule and the relay-socket case. - Docs: the three warnings; the checklist says "per address family in use". --- docs/configuration.md | 2 +- docs/gui.md | 2 +- netlib/src/proxy/dns_udp_multiplexer.h | 116 ++++++++++++----- netlib/src/proxy/socks5_dns_udp_relay.h | 29 +++-- .../test/proxy/dns_udp_multiplexer_test.cpp | 119 +++++++++++------- 5 files changed, 185 insertions(+), 83 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 4a57a23..ca6ebeb 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -195,7 +195,7 @@ UDP DNS of each address family goes through a single SOCKS5 control connection a - **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. - **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it, each for at most 3 seconds (Windows retransmits a query after about a second). It is closed, and reopened on the next query (possibly after a delay, see below), when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. - **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening, or that is closed because queries stopped being answered, also delays the next attempt. If that association worked (it received anything from the relay and lived at least 5 seconds), the delay restarts at 1 second, so a relay whose UDP path dies on idle, or a server that ends associations early, is retried quickly each time. One that received nothing, or died within seconds, makes the delay grow, so a server that accepts `UDP ASSOCIATE` and then fails is not reconnected in a tight loop and a relay that never answers is retried less and less often. The delay also resets once an association has proved itself: something arrived from the relay after it had been open for 30 seconds, or it closed normally at that age. Queries waiting when a failure starts a backoff are dropped. -- **Logging.** Per address family, the first failure to open an association since an association last received something (or since the service started) is logged as a warning and later failures at `Debug`. Every successful open and every close is logged at `Info` with its reason and, when the next attempt is delayed, the delay. When an association closes after queries were sent through it and nothing ever came back, a warning says so, once until an answer arrives. If the queries had time to be answered, it says that either the SOCKS5 server's UDP relay does not work or the DNS servers Windows queries cannot be reached from the proxy (a local resolver without a `serverOverride`, for example); if the server ended the association within seconds, it says that instead. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. +- **Logging.** Per address family, the first failure to open an association since an association last received something (or since the service started) is logged as a warning and later failures at `Debug`. Every successful open and every close is logged at `Info` with its reason and, when the next attempt is delayed, the delay. When an association closes after queries were sent through it and nothing ever came back, a warning says so. If 10 seconds or more passed since its first query (or it was closed because queries stopped being answered), the warning says that either the SOCKS5 server's UDP relay does not work or the DNS servers Windows queries cannot be reached from the proxy (a local resolver without a `serverOverride`, for example); if the server ended the association sooner, it says that instead; if the relay socket failed before any query could be sent, it says that. Each of these three warnings is given once until an answer arrives, so one does not hide another. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. The listener is bound to all local addresses, like the proxy's other local listeners, so another host that guesses an authorized port could still make the proxy send a DNS query to port 53 of whatever source address its datagram claims, or to the override. It never receives the answer, which is delivered to the local client port. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. diff --git a/docs/gui.md b/docs/gui.md index fc4a232..d7600fd 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -165,7 +165,7 @@ The routing policy and the packet rewriting are covered by automated tests (`net 2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). Browse for a few minutes and confirm the SOCKS5 server sees one control connection and one `UDP ASSOCIATE` per address family for UDP DNS, not one per query. 3. Enable `bypassLan` with a router resolver (`192.168.x.1`): without an override the SOCKS5 server is asked for the router address; with `serverOverride: "1.1.1.1"` it is asked for `1.1.1.1` and `Resolve-DnsName` still reports answers from the router address. 4. Reorder the rules, Apply & Restart, and confirm DNS still uses the selected proxy. -5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning per address family in use, and attempts back off to about one every 30 seconds (plus the 5-second connect timeout when the server is black-holed). Start the SOCKS5 server again and confirm lookups recover within about 35 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" and "opened" at `Info`) and lookups recover. Configure Windows with a second DNS server the SOCKS5 server cannot reach (for example a LAN address, without `serverOverride`), browse for two minutes, and confirm the log has no "queries stopped being answered" line. Stop the service while the SOCKS5 server is unreachable (black-holed, not refusing) and confirm it stops within a few seconds. Finally, with `serverOverride` removed and Windows using only a resolver the SOCKS5 server cannot reach (a LAN address), confirm one "no answer came back through the SOCKS5 UDP association" warning per address family within about a minute, not repeated; then set `serverOverride` and confirm lookups work. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. +5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning per address family in use, and attempts back off to about one every 30 seconds (plus the 5-second connect timeout when the server is black-holed). Start the SOCKS5 server again and confirm lookups recover within about 35 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" and "opened" at `Info`) and lookups recover. Configure Windows with a second DNS server the SOCKS5 server cannot reach (for example a LAN address, without `serverOverride`), browse for two minutes, and confirm the log has no "queries stopped being answered" line. Stop the service while the SOCKS5 server is unreachable (black-holed, not refusing) and confirm it stops within a few seconds. Finally, with `serverOverride` removed and Windows using only a resolver the SOCKS5 server cannot reach (a LAN address), confirm one "no answer came back through the SOCKS5 UDP association" warning per address family in use within about a minute, not repeated; then set `serverOverride` and confirm lookups work. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. 6. Configure an IPv4 override with an IPv6 resolver and confirm IPv6 queries are dropped while IPv4 queries succeed. 7. **Upgrade.** With a configuration from an earlier release (no `dns` section, a catch-all rule), confirm that `Resolve-DnsName -TcpOnly` now leaves the adapter directly, that UDP DNS still does, and that the rule's other traffic is still proxied. 8. **Restart.** With `Proxy` mode and `bypassLan`, use **Apply & Restart** (or stop and start the service) and repeat step 3: DNS to the router resolver must still be proxied. diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index b964a55..fd654b3 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -11,6 +11,7 @@ // be unit tested on any platform. The relay supplies time, randomness and raw datagrams. #include +#include #include #include #include @@ -528,6 +529,24 @@ namespace proxy std::size_t capacity_; }; + /// Why the shared association was closed (dns_association_health::on_closed()). + enum class dns_association_close : uint8_t + { + normal, ///< its SOCKS5 control connection closed + silent, ///< retired because queries stopped being answered + relay_failed ///< its UDP relay socket failed + }; + + /// What a closure of the shared association should be reported as. + enum class dns_association_report : uint8_t + { + none, ///< nothing to report + no_answer, ///< queries had time to be answered and none was: the relay does not work, + ///< or the DNS servers queried cannot be reached from the proxy + ended_early, ///< the server ended it soon after queries were sent, before any answer + relay_unusable ///< its UDP relay socket failed before any query could be sent + }; + /** * @brief Decides when the shared association is reopened and when a new one may be tried. * @@ -554,9 +573,15 @@ namespace proxy public: using time_point = typename Clock::time_point; + /** + * @param answer_wait How long a sent query has to be answered before a closure without + * answers is attributed to the relay or the queried servers (the query lifetime). + */ explicit dns_association_health(const std::size_t unanswered_limit = 3, - const std::chrono::seconds minimum_age = std::chrono::seconds{ 30 }) - : unanswered_limit_(std::max(unanswered_limit, 1)), minimum_age_(minimum_age) + const std::chrono::seconds minimum_age = std::chrono::seconds{ 30 }, + const std::chrono::seconds answer_wait = std::chrono::seconds{ 10 }) + : unanswered_limit_(std::max(unanswered_limit, 1)), minimum_age_(minimum_age), + answer_wait_(answer_wait) { } @@ -589,36 +614,47 @@ namespace proxy query_sent_ = false; } - /// A query was sent through the open association. - void on_query_sent() noexcept { query_sent_ = true; } + /// A query was sent through the open association at @p now. + void on_query_sent(const time_point now) noexcept + { + if (!query_sent_) + { + query_sent_ = true; + first_sent_at_ = now; + } + } /// When the current (or last) association was opened. [[nodiscard]] time_point opened_at() const noexcept { return opened_at_; } /** - * @brief The association was closed at @p now. + * @brief The association was closed at @p now, for @p close. * * - A normal close (control connection or relay socket) of an association at least the * minimum age old resets the backoff: the next query reopens at once. - * - Otherwise (it was retired for unanswered queries, @p failed, or it closed younger - * than the minimum age) the next attempt backs off. If the association worked, that - * is, something arrived from the relay and it lived at least minimum_working_life, - * the closure is a new outage and the backoff restarts at its shortest delay, so a - * relay that keeps answering after every reopen (one whose UDP path dies on idle, or - * a server that ends associations early) is never kept waiting long. An association - * that delivered nothing, or died within seconds, makes the backoff grow, so a server - * that accepts UDP ASSOCIATE and then fails is not reconnected in a tight loop. + * - Otherwise (it was retired for unanswered queries, or it closed younger than the + * minimum age) the next attempt backs off. If the association worked, that is, + * something arrived from the relay and it lived at least minimum_working_life, the + * closure is a new outage and the backoff restarts at its shortest delay, so a relay + * that keeps answering after every reopen (one whose UDP path dies on idle, or a server + * that ends associations early) is never kept waiting long. An association that + * delivered nothing, or died within seconds, makes the backoff grow, so a server that + * accepts UDP ASSOCIATE and then fails is not reconnected in a tight loop. * - * @return true when this closure should be reported as a warning: queries were sent - * through the association and nothing came back, and no such closure has been - * reported since an association last received something. + * @return What to report, if the association received nothing: no_answer when a sent + * query had answer_wait to be answered (or it was retired for silence), + * ended_early when it closed sooner, relay_unusable when its relay socket failed + * before any query was sent. Each is reported once until an association receives + * something; otherwise none. */ - bool on_closed(const time_point now, const bool failed = false) noexcept + dns_association_report on_closed(const time_point now, + const dns_association_close close = dns_association_close::normal) noexcept { const auto age = now - opened_at_; const bool delivered = last_datagram_.has_value(); + const bool silent = close == dns_association_close::silent; - if (!failed && age >= minimum_age_) + if (!silent && age >= minimum_age_) failures_ = 0; else { @@ -627,10 +663,27 @@ namespace proxy back_off(now); } - if (delivered || !query_sent_ || unusable_reported_) - return false; - unusable_reported_ = true; - return true; + if (delivered) + return dns_association_report::none; + + auto report = dns_association_report::none; + if (!query_sent_) + { + if (close == dns_association_close::relay_failed) + report = dns_association_report::relay_unusable; + } + else if (silent || now - first_sent_at_ >= answer_wait_) + report = dns_association_report::no_answer; + else + report = dns_association_report::ended_early; + + if (report == dns_association_report::none) + return report; + auto& reported = reported_[static_cast(report)]; + if (reported) + return dns_association_report::none; + reported = true; + return report; } /// Any datagram from the relay shows the association is alive; once it is also at least @@ -639,7 +692,7 @@ namespace proxy { unanswered_ = 0; last_datagram_ = now; - unusable_reported_ = false; + reported_ = {}; open_failure_reported_ = false; if (now - opened_at_ >= minimum_age_) failures_ = 0; @@ -676,10 +729,12 @@ namespace proxy } bool open_failure_reported_{ false }; - bool unusable_reported_{ false }; + std::array reported_{}; ///< per dns_association_report value bool query_sent_{ false }; + time_point first_sent_at_{}; ///< valid while query_sent_ std::size_t unanswered_limit_; std::chrono::seconds minimum_age_; + std::chrono::seconds answer_wait_; std::size_t failures_{}; std::size_t unanswered_{}; time_point next_attempt_{}; @@ -727,7 +782,7 @@ namespace proxy dns_relay_session(const std::chrono::seconds query_ttl, const std::size_t max_queries, const std::size_t unanswered_limit, const std::chrono::seconds minimum_association_age) - : queries_(query_ttl, max_queries), health_(unanswered_limit, minimum_association_age) + : queries_(query_ttl, max_queries), health_(unanswered_limit, minimum_association_age, query_ttl) { } @@ -808,8 +863,8 @@ namespace proxy void expire_closed(const time_point now) { (void)queries_.expire(now); } [[nodiscard]] bool may_open(const time_point now) const noexcept { return health_.may_open(now); } - /// A prepared query was sent through the association (see dns_association_health). - void on_query_sent() noexcept { health_.on_query_sent(); } + /// A prepared query was sent through the association at @p now. + void on_query_sent(const time_point now) noexcept { health_.on_query_sent(now); } /// How long the current (or last) association has been open at @p now. [[nodiscard]] typename Clock::duration association_age(const time_point now) const noexcept { @@ -820,11 +875,12 @@ namespace proxy void on_opened(const time_point now) noexcept { health_.on_opened(now); } /// The association closed: its queries in flight can no longer be answered. See - /// dns_association_health::on_closed() for @p failed and the result. - bool on_closed(const time_point now, const bool failed = false) noexcept + /// dns_association_health::on_closed() for @p close and the result. + dns_association_report on_closed(const time_point now, + const dns_association_close close = dns_association_close::normal) noexcept { queries_.clear(); - return health_.on_closed(now, failed); + return health_.on_closed(now, close); } void clear() noexcept { queries_.clear(); } diff --git a/netlib/src/proxy/socks5_dns_udp_relay.h b/netlib/src/proxy/socks5_dns_udp_relay.h index 06c92a4..145dce3 100644 --- a/netlib/src/proxy/socks5_dns_udp_relay.h +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -428,7 +428,7 @@ namespace proxy if (send(association_->relay, reinterpret_cast(datagram.data()), static_cast(datagram.size()), 0) != SOCKET_ERROR) { - session_.on_query_sent(); + session_.on_query_sent(std::chrono::steady_clock::now()); } else { @@ -615,15 +615,20 @@ namespace proxy if (association_) { const char* reason = nullptr; - bool silent = false; + auto close = dns_association_close::normal; if (association_->failed.load(std::memory_order_acquire)) + { reason = "the UDP relay socket failed"; + close = dns_association_close::relay_failed; + } else if (control_channel_closed(association_->control)) + { reason = "the SOCKS5 control connection closed"; + } else if (session_.expire(now)) { reason = "queries stopped being answered"; - silent = true; + close = dns_association_close::silent; } if (reason) @@ -633,7 +638,7 @@ namespace proxy // datagram cannot touch the session after the closure is recorded. retired->retiring.store(true, std::memory_order_release); const auto age = std::chrono::duration_cast(session_.association_age(now)); - const bool unusable = session_.on_closed(now, silent); + const auto report = session_.on_closed(now, close); if (session_.may_open(now)) { @@ -649,19 +654,25 @@ namespace proxy dropped_unavailable_ += waiting_.drop_all(); } - if (unusable && (silent || age >= query_ttl)) + switch (report) { - // Queries had time to be answered and none was. + case dns_association_report::no_answer: NETLIB_WARNING("DNS relay: no answer came back through the SOCKS5 UDP association with {}: " "either its UDP relay does not work, or the DNS servers Windows queries cannot be " "reached from the proxy (consider a DNS serverOverride). UDP DNS fails until an " "answer arrives.", upstream_.to_string()); - } - else if (unusable) - { + break; + case dns_association_report::ended_early: NETLIB_WARNING("DNS relay: the SOCKS5 UDP association with {} ended {} s after it opened ({}), " "before any answer arrived. UDP DNS fails until an association works.", upstream_.to_string(), age.count(), reason); + break; + case dns_association_report::relay_unusable: + NETLIB_WARNING("DNS relay: no query could be sent through the SOCKS5 UDP relay of {} (the " + "relay socket failed). UDP DNS fails until an association works.", upstream_.to_string()); + break; + case dns_association_report::none: + break; } lock.unlock(); close_association(std::move(retired)); diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index 9c5cbb0..6485963 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -48,6 +48,8 @@ namespace using table_t = proxy::dns_query_table; const time_point t0{ std::chrono::seconds{ 1000 } }; + constexpr auto silent_close = proxy::dns_association_close::silent; + using report = proxy::dns_association_report; /// Deterministic "random" source returning the given values in order, then repeating the last. struct scripted_random @@ -770,7 +772,7 @@ TEST(DnsAssociationHealth, AssociationRetiredForSilenceBacksOffWhateverItsAge) { proxy::dns_association_health<> health{ 3, 30s }; health.on_opened(t0); - health.on_closed(t0 + 60s, true); + health.on_closed(t0 + 60s, silent_close); EXPECT_EQ(health.consecutive_failures(), 1u); EXPECT_FALSE(health.may_open(t0 + 60s)); EXPECT_TRUE(health.may_open(t0 + 61s)); @@ -784,7 +786,7 @@ TEST(DnsAssociationHealth, AssociationRetiredForSilenceBacksOffWhateverItsAge) health.on_opened(at); at += 40s; ASSERT_TRUE(health.on_unanswered(3, at)); - health.on_closed(at, true); + health.on_closed(at, silent_close); EXPECT_FALSE(health.may_open(at + delay - 1ms)); EXPECT_TRUE(health.may_open(at + delay)); at += delay; @@ -812,7 +814,7 @@ TEST(DnsAssociationHealth, AssociationThatAnsweredBeforeGoingSilentRestartsTheBa health.on_relay_datagram(at + std::chrono::seconds{ i }); // busy for 20 s at += 320s; // idle, then silent ASSERT_TRUE(health.on_unanswered(3, at)) << cycle; - health.on_closed(at, true); + health.on_closed(at, silent_close); EXPECT_FALSE(health.may_open(at + 999ms)) << cycle; EXPECT_TRUE(health.may_open(at + 1s)) << cycle; at += 1s; @@ -828,9 +830,9 @@ TEST(DnsAssociationHealth, FirstOpenFailureSinceAnAssociationLastWorkedIsReporte // An association that works re-arms the report; a silent retirement does not use it up. health.on_opened(t0 + 3s); health.on_relay_datagram(t0 + 4s); - health.on_query_sent(); + health.on_query_sent(t0 + 5s); ASSERT_TRUE(health.on_unanswered(3, t0 + 40s)); - (void)health.on_closed(t0 + 40s, true); + (void)health.on_closed(t0 + 40s, silent_close); EXPECT_TRUE(health.on_open_failed(t0 + 41s)); EXPECT_FALSE(health.on_open_failed(t0 + 43s)); } @@ -848,8 +850,8 @@ TEST(DnsAssociationHealth, FlappingServerThatNeverWorksIsReportedOnce) open_failure_reports += health.on_open_failed(at) ? 1 : 0; at = health.next_attempt(); health.on_opened(at); - health.on_query_sent(); - unusable_reports += health.on_closed(at + 100ms) ? 1 : 0; + health.on_query_sent(at); + unusable_reports += health.on_closed(at + 100ms) != report::none ? 1 : 0; at = health.next_attempt(); } EXPECT_EQ(open_failure_reports, 1); @@ -923,7 +925,7 @@ TEST(DnsAssociationHealth, AssociationThatWorkedThenClosedYoungRestartsTheBackof health.on_opened(at); health.on_relay_datagram(at + 1s); at += 20s; - EXPECT_FALSE(health.on_closed(at)) << cycle; + EXPECT_EQ(health.on_closed(at), report::none) << cycle; EXPECT_FALSE(health.may_open(at + 999ms)) << cycle; EXPECT_TRUE(health.may_open(at + 1s)) << cycle; at += 1s; @@ -949,63 +951,96 @@ TEST(DnsAssociationHealth, AssociationsDyingWithinSecondsStillBackOffFurther) } } -// An association that closes without ever delivering anything is reported once as a warning -// (the relay looks unusable), and again only after some association has delivered something. -TEST(DnsAssociationHealth, UnusableAssociationIsReportedOncePerOutage) +// A closure after sent queries got no answer is reported once per cause until an association +// receives something: "no answer" when the queries had time to be answered (the relay does not +// work, or the queried servers cannot be reached), "ended early" when the server ended the +// association sooner. One cause does not hide the other. +TEST(DnsAssociationHealth, ClosuresWithoutAnswersAreReportedOncePerCause) { - proxy::dns_association_health<> health{ 3, 30s }; - health.on_opened(t0); - health.on_query_sent(); - ASSERT_TRUE(health.on_unanswered(3, t0 + 40s)); - EXPECT_TRUE(health.on_closed(t0 + 40s, true)); - - health.on_opened(t0 + 42s); - health.on_query_sent(); - EXPECT_FALSE(health.on_closed(t0 + 43s)); // still the same outage: not again - - health.on_opened(t0 + 50s); - health.on_query_sent(); - health.on_relay_datagram(t0 + 51s); // it worked - EXPECT_FALSE(health.on_closed(t0 + 90s, true)); // delivered something: not unusable + proxy::dns_association_health<> health{ 3, 30s, 10s }; - health.on_opened(t0 + 91s); - health.on_query_sent(); - EXPECT_TRUE(health.on_closed(t0 + 92s)); // a new outage is reported again + // Ended 3 s after the first query was sent: ended early. + health.on_opened(t0); + health.on_query_sent(t0 + 1s); + EXPECT_EQ(health.on_closed(t0 + 4s), report::ended_early); + + // Then an unreachable resolver: retired for silence. Still reported, as no_answer. + health.on_opened(t0 + 10s); + health.on_query_sent(t0 + 11s); + ASSERT_TRUE(health.on_unanswered(3, t0 + 45s)); + EXPECT_EQ(health.on_closed(t0 + 45s, silent_close), report::no_answer); + + // Each cause is reported once per outage. + health.on_opened(t0 + 60s); + health.on_query_sent(t0 + 61s); + EXPECT_EQ(health.on_closed(t0 + 62s), report::none); + health.on_opened(t0 + 70s); + health.on_query_sent(t0 + 71s); + ASSERT_TRUE(health.on_unanswered(3, t0 + 105s)); + EXPECT_EQ(health.on_closed(t0 + 105s, silent_close), report::none); + + // An association that receives something ends the outage and re-arms both. + health.on_opened(t0 + 110s); + health.on_query_sent(t0 + 111s); + health.on_relay_datagram(t0 + 112s); + EXPECT_EQ(health.on_closed(t0 + 150s, silent_close), report::none); + health.on_opened(t0 + 160s); + health.on_query_sent(t0 + 161s); + EXPECT_EQ(health.on_closed(t0 + 162s), report::ended_early); } -TEST(DnsAssociationHealth, UnusableIsReportedWhateverEndsTheAssociationButOnlyIfQueriesWereSent) +TEST(DnsAssociationHealth, AnswerTimeIsMeasuredFromTheFirstQuerySent) { - // A normal close at any age, after queries got no answer: reported (and the backoff resets). - proxy::dns_association_health<> health{ 3, 30s }; + // Open 21 s, but its first query was sent only 1 s before the close: ended early. + proxy::dns_association_health<> health{ 3, 30s, 10s }; health.on_opened(t0); - health.on_query_sent(); - EXPECT_TRUE(health.on_closed(t0 + 60s)); - EXPECT_TRUE(health.may_open(t0 + 60s)); + health.on_query_sent(t0 + 20s); + health.on_query_sent(t0 + 20500ms); + EXPECT_EQ(health.on_closed(t0 + 21s), report::ended_early); + + // A normal close at any age, 10 s or more after the first query: no answer (and the + // backoff resets for an old association). + proxy::dns_association_health<> other{ 3, 30s, 10s }; + other.on_opened(t0); + other.on_query_sent(t0 + 1s); + EXPECT_EQ(other.on_closed(t0 + 60s), report::no_answer); + EXPECT_TRUE(other.may_open(t0 + 60s)); +} - // No query was sent through it (a restart before the first query): not reported. - proxy::dns_association_health<> idle{ 3, 30s }; +TEST(DnsAssociationHealth, NothingSentIsNotReportedUnlessTheRelaySocketFailed) +{ + // Closed before its first query (a restart): not reported. + proxy::dns_association_health<> idle{ 3, 30s, 10s }; idle.on_opened(t0); - EXPECT_FALSE(idle.on_closed(t0 + 2s)); + EXPECT_EQ(idle.on_closed(t0 + 2s), report::none); idle.on_opened(t0 + 10s); - EXPECT_FALSE(idle.on_closed(t0 + 100s)); + EXPECT_EQ(idle.on_closed(t0 + 100s), report::none); + + // The relay socket failed before any query could be sent: reported, once per outage. + proxy::dns_association_health<> broken{ 3, 30s, 10s }; + broken.on_opened(t0); + EXPECT_EQ(broken.on_closed(t0 + 1s, proxy::dns_association_close::relay_failed), report::relay_unusable); + EXPECT_FALSE(broken.may_open(t0 + 1s)); + broken.on_opened(t0 + 2s); + EXPECT_EQ(broken.on_closed(t0 + 3s, proxy::dns_association_close::relay_failed), report::none); } TEST(DnsRelaySession, ClosureAfterUnansweredQueriesIsReportedButNotAnIdleOne) { auto idle = make_session(); idle.on_opened(t0); - EXPECT_FALSE(idle.on_closed(t0 + 60s)); + EXPECT_EQ(idle.on_closed(t0 + 60s), report::none); // Prepared but never sent (the send failed): not reported either. auto unsent = make_session(); unsent.on_opened(t0); (void)send_query(unsent, { 1, 1 }, 1, "a.example", t0 + 1s, 7); - EXPECT_FALSE(unsent.on_closed(t0 + 60s)); + EXPECT_EQ(unsent.on_closed(t0 + 60s), report::none); auto unanswered = make_session(); unanswered.on_opened(t0); (void)send_query(unanswered, { 1, 1 }, 1, "a.example", t0 + 1s, 7); - unanswered.on_query_sent(); + unanswered.on_query_sent(t0 + 1s); EXPECT_EQ(unanswered.association_age(t0 + 60s), 60s); - EXPECT_TRUE(unanswered.on_closed(t0 + 60s)); + EXPECT_EQ(unanswered.on_closed(t0 + 60s), report::no_answer); } From 0eb081c9a0647f60f0ca6db1bdeb1f3708dd58ef Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 20:02:47 +0000 Subject: [PATCH 52/62] test, docs: cover closure reports in either order; name both causes of an early end Optional review nits: a test for no_answer then ended_early, and for relay_unusable followed by the other reports, in one outage; the enum comment and docs say an early end can be the control connection or the relay socket. No behavior change. --- docs/configuration.md | 2 +- netlib/src/proxy/dns_udp_multiplexer.h | 3 ++- .../test/proxy/dns_udp_multiplexer_test.cpp | 25 +++++++++++++++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index ca6ebeb..75de827 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -195,7 +195,7 @@ UDP DNS of each address family goes through a single SOCKS5 control connection a - **Large answers.** An answer that does not fit in one unfragmented 1,280-byte packet is returned truncated, as a DNS server would: the TC bit is set and only the header and question are kept. Windows then repeats the query over TCP through the same proxy. Without this, the reply from ProxiFyre's local listener would be fragmented and could not be delivered. - **Opening and reopening.** The association is opened when the first query arrives; up to 64 queries wait for it, each for at most 3 seconds (Windows retransmits a query after about a second). It is closed, and reopened on the next query (possibly after a delay, see below), when its control connection closes (TCP keepalive also detects a connection that silently disappeared), its relay socket fails, or it looks silently dead: at least three queries sent after the last datagram from the relay went unanswered, and it has been open for at least 30 seconds. Queries to a resolver that never answers therefore do not close an association that keeps delivering other answers. Queries in flight when the association closes are lost, and Windows retries them. - **When it cannot be opened.** Queries are dropped, never sent directly. The next attempt waits 1 second, doubling after each failure up to 30 seconds; queries arriving meanwhile are dropped. An association that closes less than 30 seconds after opening, or that is closed because queries stopped being answered, also delays the next attempt. If that association worked (it received anything from the relay and lived at least 5 seconds), the delay restarts at 1 second, so a relay whose UDP path dies on idle, or a server that ends associations early, is retried quickly each time. One that received nothing, or died within seconds, makes the delay grow, so a server that accepts `UDP ASSOCIATE` and then fails is not reconnected in a tight loop and a relay that never answers is retried less and less often. The delay also resets once an association has proved itself: something arrived from the relay after it had been open for 30 seconds, or it closed normally at that age. Queries waiting when a failure starts a backoff are dropped. -- **Logging.** Per address family, the first failure to open an association since an association last received something (or since the service started) is logged as a warning and later failures at `Debug`. Every successful open and every close is logged at `Info` with its reason and, when the next attempt is delayed, the delay. When an association closes after queries were sent through it and nothing ever came back, a warning says so. If 10 seconds or more passed since its first query (or it was closed because queries stopped being answered), the warning says that either the SOCKS5 server's UDP relay does not work or the DNS servers Windows queries cannot be reached from the proxy (a local resolver without a `serverOverride`, for example); if the server ended the association sooner, it says that instead; if the relay socket failed before any query could be sent, it says that. Each of these three warnings is given once until an answer arrives, so one does not hide another. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. +- **Logging.** Per address family, the first failure to open an association since an association last received something (or since the service started) is logged as a warning and later failures at `Debug`. Every successful open and every close is logged at `Info` with its reason and, when the next attempt is delayed, the delay. When an association closes after queries were sent through it and nothing ever came back, a warning says so. If 10 seconds or more passed since its first query (or it was closed because queries stopped being answered), the warning says that either the SOCKS5 server's UDP relay does not work or the DNS servers Windows queries cannot be reached from the proxy (a local resolver without a `serverOverride`, for example); if the association ended sooner (its control connection closed or its relay socket failed), it says that instead, with the reason; if the relay socket failed before any query could be sent, it says that. Each of these three warnings is given once until an answer arrives, so one does not hide another. Counts of dropped queries and answers are logged at `Info` at most every 30 seconds, and once more when the service stops. The local listener accepts a datagram only from a source port from which ProxiFyre redirected a UDP DNS query in the last 30 seconds, never from a loopback address, and only if it names port 53 of the address it came from (the server the client queried) or, with a `serverOverride`, the override. So a local process cannot use it to reach other destinations through the proxy. The listener is bound to all local addresses, like the proxy's other local listeners, so another host that guesses an authorized port could still make the proxy send a DNS query to port 53 of whatever source address its datagram claims, or to the override. It never receives the answer, which is delivered to the local client port. When the service stops, the DNS relays stop while packet filtering is still active and stay known to the filter until it has stopped, so answers they send while stopping never leave the computer; new UDP DNS is dropped meanwhile, without a warning. diff --git a/netlib/src/proxy/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h index fd654b3..bf10fbf 100644 --- a/netlib/src/proxy/dns_udp_multiplexer.h +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -543,7 +543,8 @@ namespace proxy none, ///< nothing to report no_answer, ///< queries had time to be answered and none was: the relay does not work, ///< or the DNS servers queried cannot be reached from the proxy - ended_early, ///< the server ended it soon after queries were sent, before any answer + ended_early, ///< it ended (control connection or relay socket) soon after queries were + ///< sent, before any answer relay_unusable ///< its UDP relay socket failed before any query could be sent }; diff --git a/netlib/test/proxy/dns_udp_multiplexer_test.cpp b/netlib/test/proxy/dns_udp_multiplexer_test.cpp index 6485963..b1ae4c7 100644 --- a/netlib/test/proxy/dns_udp_multiplexer_test.cpp +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -989,6 +989,31 @@ TEST(DnsAssociationHealth, ClosuresWithoutAnswersAreReportedOncePerCause) EXPECT_EQ(health.on_closed(t0 + 162s), report::ended_early); } +TEST(DnsAssociationHealth, CausesAreReportedIndependentlyInEitherOrder) +{ + // no_answer first, then ended_early in the same outage. + proxy::dns_association_health<> health{ 3, 30s, 10s }; + health.on_opened(t0); + health.on_query_sent(t0 + 1s); + ASSERT_TRUE(health.on_unanswered(3, t0 + 40s)); + EXPECT_EQ(health.on_closed(t0 + 40s, silent_close), report::no_answer); + health.on_opened(t0 + 42s); + health.on_query_sent(t0 + 43s); + EXPECT_EQ(health.on_closed(t0 + 45s), report::ended_early); + + // relay_unusable, then no_answer, then ended_early in the same outage. + proxy::dns_association_health<> other{ 3, 30s, 10s }; + other.on_opened(t0); + EXPECT_EQ(other.on_closed(t0 + 1s, proxy::dns_association_close::relay_failed), report::relay_unusable); + other.on_opened(t0 + 2s); + other.on_query_sent(t0 + 3s); + ASSERT_TRUE(other.on_unanswered(3, t0 + 40s)); + EXPECT_EQ(other.on_closed(t0 + 40s, silent_close), report::no_answer); + other.on_opened(t0 + 70s); + other.on_query_sent(t0 + 71s); + EXPECT_EQ(other.on_closed(t0 + 72s, proxy::dns_association_close::relay_failed), report::ended_early); +} + TEST(DnsAssociationHealth, AnswerTimeIsMeasuredFromTheFirstQuerySent) { // Open 21 s, but its first query was sent only 1 s before the close: ended early. From 490af89e809dd531866d4efdbd57ad8fc2d792b7 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 20:19:04 +0000 Subject: [PATCH 53/62] test: stop the owner routing tests colliding with the runner's own PID The routing rules never match ProxiFyre's own process (current_process_id), and the OwnerRoutingPolicy tests passed the test runner's real PID while their owners are fakes with fixed PIDs (3000-3900, mostly multiples of 4, like real Windows PIDs). Whenever the runner's PID equalled one of them, that owner was neither proxied nor excluded and the test failed: PidReuseAcrossCapturesDoesNotInheritExclusion failed this way once in CI (netlib-tests Debug), with every PID-3500 owner routed to none. The rules now get a fixed own PID of 2, which is never a real Windows process ID and which no other fake row uses, and a new test pins the own-process rule with it. --- .../test/proxy/owner_routing_policy_test.cpp | 33 ++++++++++++++++++- 1 file changed, 32 insertions(+), 1 deletion(-) diff --git a/netlib/test/proxy/owner_routing_policy_test.cpp b/netlib/test/proxy/owner_routing_policy_test.cpp index dcf5c8f..174028a 100644 --- a/netlib/test/proxy/owner_routing_policy_test.cpp +++ b/netlib/test/proxy/owner_routing_policy_test.cpp @@ -23,6 +23,14 @@ namespace using proxy::proxy_port_action; using proxy::proxy_port_result; + /// ProxiFyre's own process ID as these tests pass it to the routing rules. The router passes + /// ::GetCurrentProcessId(), and its own traffic is never routed. The owners here are fakes + /// with fixed PIDs, so the rules get a fixed "own" PID too: with the test runner's real PID, + /// any test whose fake PID happened to equal it would see that owner neither proxied nor + /// excluded. 2 is never a real Windows process ID (they are multiples of 4), and no fake row + /// uses it except the test of this rule. + constexpr unsigned long own_process_id = 2; + /// One configured proxy: transports, destination families, and its local listeners. struct proxy_offer { @@ -45,7 +53,7 @@ namespace [[nodiscard]] proxy::owner_match_rules rules() const { - return { proxy_to_names, excluded, bypass_unresolved, ::GetCurrentProcessId() }; + return { proxy_to_names, excluded, bypass_unresolved, own_process_id }; } template @@ -464,6 +472,29 @@ namespace EXPECT_FALSE(tcp4(l4, 2000)->excluded); } + TEST_F(OwnerRoutingPolicyTest, OwnProcessIsNeitherProxiedNorExcluded) + { + // ProxiFyre's own connections are never matched: not by a catch-all rule, and not by an + // exclusion that names its image. + os().images[own_process_id] = image(L"BLOCKED.EXE"); + add_everywhere(own_process_id, 1000); + lookup_v4 l4; + + routing_config config; + config.proxies.push_back({}); + config.proxy_to_names.emplace(0, L""); + config.excluded.push_back(L"BLOCKED"); + + const auto t = tcp4(l4, 1000); + const auto u = udp4(l4, 1000); + ASSERT_TRUE(t && u); + EXPECT_EQ(t->id, own_process_id); + expect_route(config.route(t), proxy_port_action::none); + expect_route(config.route(u), proxy_port_action::none); + EXPECT_FALSE(t->excluded); + EXPECT_FALSE(u->excluded); + } + TEST_F(OwnerRoutingPolicyTest, RefreshedCaptureStartsWithFreshRoutingState) { os().images[3900] = image(L"OTHER.EXE"); From 4b1096679806a955da1f011741e138c6a118f2c2 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 21:01:20 +0000 Subject: [PATCH 54/62] fix(config): only fail on a rule id that DNS Proxy mode depends on Earlier releases ignored a rule "id" and a top-level "dns" property, so an upgraded configuration that happened to contain them could stop the service. - An invalid or duplicate rule id is now an error only when dns.proxyId in Proxy mode refers to it; otherwise it is a warning and has no effect. - An empty or whitespace id means no id, matching the normalizer. - A "dns" value that is not an object is reported by name instead of as an anonymous invalid property value; it still stops the service. - The GUI assigns a fresh id when the rule selected as the DNS proxy shares its id with another rule, not only when the id is missing or invalid. - README and configuration reference: upgrade note for the id and dns keys. --- .../ConfigurationSerializer.cs | 12 ++ .../ConfigurationValidator.cs | 61 +++++++--- ProxiFyre.Tests/DnsConfigurationTests.cs | 108 ++++++++++++++++-- ProxiFyreUI/Forms/MainForm.cs | 9 +- README.md | 2 + docs/configuration.md | 9 +- 6 files changed, 171 insertions(+), 30 deletions(-) diff --git a/ProxiFyre.Configuration/ConfigurationSerializer.cs b/ProxiFyre.Configuration/ConfigurationSerializer.cs index 5d7aa04..0d45a45 100644 --- a/ProxiFyre.Configuration/ConfigurationSerializer.cs +++ b/ProxiFyre.Configuration/ConfigurationSerializer.cs @@ -65,6 +65,18 @@ public ProxiFyreConfiguration Deserialize(string json) "The configuration is not a valid JSON object.", ex); } + // Earlier releases kept an unknown top-level "dns" property and ignored it. It now selects + // DNS routing, so a value that is not an object is named in the error rather than + // reported as an anonymous invalid property value. + var dnsProperty = root.Properties().FirstOrDefault( + p => string.Equals(p.Name, "dns", StringComparison.OrdinalIgnoreCase)); + if (dnsProperty != null && dnsProperty.Value.Type != JTokenType.Object && dnsProperty.Value.Type != JTokenType.Null) + { + throw new ConfigurationFormatException( + "The 'dns' property must be an object such as { \"mode\": \"Proxy\", \"proxyId\": \"office\" }, " + + "or be removed to keep DNS Direct."); + } + ProxiFyreConfiguration configuration; try { diff --git a/ProxiFyre.Configuration/ConfigurationValidator.cs b/ProxiFyre.Configuration/ConfigurationValidator.cs index 904aba7..fd44ab8 100644 --- a/ProxiFyre.Configuration/ConfigurationValidator.cs +++ b/ProxiFyre.Configuration/ConfigurationValidator.cs @@ -62,7 +62,7 @@ public ValidationResult Validate(ProxiFyreConfiguration configuration) ValidateCatchAllOrdering(configuration.Proxies, issues); ValidateApplicationOverlap(configuration.Proxies, issues); - ValidateProxyIds(configuration.Proxies, issues); + ValidateProxyIds(configuration.Proxies, configuration.Dns, issues); ValidateDns(configuration.Dns, configuration.Proxies, issues); return new ValidationResult(issues); } @@ -509,36 +509,54 @@ private static string GetPathTail(string value) : lastSlash < 0 ? value : string.Empty; } - private static void ValidateProxyIds(IList rules, ICollection issues) + private static void ValidateProxyIds(IList rules, DnsSettings dns, ICollection issues) { + // Earlier releases ignored a rule "id", so an id only stops the service when DNS Proxy + // mode depends on it. Any other invalid or duplicate id is reported as a warning and has + // no effect. An empty or whitespace id means no id, as the normalizer treats it. + var referencedId = ReferencedProxyId(dns); var seen = new Dictionary(StringComparer.OrdinalIgnoreCase); for (var index = 0; index < rules.Count; index++) { var id = rules[index] == null ? null : rules[index].Id; - if (id == null) + if (string.IsNullOrWhiteSpace(id)) continue; var trimmed = id.Trim(); + var referenced = referencedId != null && + string.Equals(trimmed, referencedId, StringComparison.OrdinalIgnoreCase); if (!DnsConfiguration.IsValidProxyId(trimmed)) { - issues.Add(Error( - "PROXY_ID_INVALID", - "A proxy id must contain 1 to " + DnsConfiguration.MaximumProxyIdLength + - " letters, digits, '-', '_', or '.' characters. Remove the id or give it a valid value.", - RulePath(index) + ".id", - index)); + var message = "A proxy id must contain 1 to " + DnsConfiguration.MaximumProxyIdLength + + " letters, digits, '-', '_', or '.' characters."; + issues.Add(referenced + ? Error("PROXY_ID_INVALID", + message + " dns.proxyId refers to this id; give the rule a valid id and update dns.proxyId.", + RulePath(index) + ".id", + index) + : Warning("PROXY_ID_INVALID", + message + " No DNS setting uses it, so it has no effect; remove it or give it a valid value " + + "before selecting this rule as the DNS proxy.", + RulePath(index) + ".id", + index)); continue; } int firstIndex; if (seen.TryGetValue(trimmed, out firstIndex)) { - issues.Add(Error( - "PROXY_ID_DUPLICATE", - "The proxy id '" + trimmed + "' is already used by rule " + (firstIndex + 1) + - "; proxy ids must be unique (case-insensitive).", - RulePath(index) + ".id", - index)); + var message = "The proxy id '" + trimmed + "' is already used by rule " + (firstIndex + 1) + + "; proxy ids must be unique (case-insensitive)."; + issues.Add(referenced + ? Error("PROXY_ID_DUPLICATE", + message + " dns.proxyId refers to this id, so the DNS proxy would be ambiguous.", + RulePath(index) + ".id", + index) + : Warning("PROXY_ID_DUPLICATE", + message + " No DNS setting uses it, so it has no effect; make it unique before " + + "selecting either rule as the DNS proxy.", + RulePath(index) + ".id", + index)); continue; } @@ -546,6 +564,19 @@ private static void ValidateProxyIds(IList rules, ICollection + /// The trimmed proxy id that DNS Proxy mode routes through, or null when DNS does not + /// reference a rule (DNS omitted, Direct, an unknown mode, or no proxyId). + /// + private static string ReferencedProxyId(DnsSettings dns) + { + DnsRoutingMode mode; + if (dns == null || string.IsNullOrWhiteSpace(dns.ProxyId) || + !DnsConfiguration.TryGetMode(dns.Mode, out mode) || mode != DnsRoutingMode.Proxy) + return null; + return dns.ProxyId.Trim(); + } + private static void ValidateDns(DnsSettings dns, IList rules, ICollection issues) { if (dns == null) diff --git a/ProxiFyre.Tests/DnsConfigurationTests.cs b/ProxiFyre.Tests/DnsConfigurationTests.cs index db7ad2a..74add1f 100644 --- a/ProxiFyre.Tests/DnsConfigurationTests.cs +++ b/ProxiFyre.Tests/DnsConfigurationTests.cs @@ -212,30 +212,71 @@ public void LegacyOmittedProtocolsMeanBothAndAreAccepted() Assert.That(_validator.Validate(configuration).Issues.Any(issue => issue.Code == "DNS_PROXY_PROTOCOLS_UNSUPPORTED"), Is.False); } - [TestCase("")] - [TestCase(" ")] [TestCase("has space")] [TestCase("slash/id")] [TestCase("ünicode")] - public void InvalidProxyIdsAreRejected(string id) + public void InvalidProxyIdReferencedByDnsIsAnError(string id) + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[1].Id = id; + configuration.Dns.ProxyId = id; + + HasError(_validator.Validate(configuration), "PROXY_ID_INVALID", "proxies[1].id"); + } + + [Test] + public void TooLongProxyIdReferencedByDnsIsAnError() + { + var configuration = TwoProxyConfiguration(); + var id = new string('a', DnsConfiguration.MaximumProxyIdLength + 1); + configuration.Proxies[1].Id = id; + configuration.Dns.ProxyId = id; + + HasError(_validator.Validate(configuration), "PROXY_ID_INVALID", "proxies[1].id"); + } + + [TestCase("has space")] + [TestCase("slash/id")] + [TestCase("ünicode")] + public void InvalidProxyIdThatDnsDoesNotUseIsOnlyAWarning(string id) { + // Earlier releases ignored rule ids, so an id DNS does not use must not stop the service. var configuration = TwoProxyConfiguration(); configuration.Proxies[0].Id = id; - HasError(_validator.Validate(configuration), "PROXY_ID_INVALID", "proxies[0].id"); + var result = _validator.Validate(configuration); + Assert.That(result.HasErrors, Is.False, string.Join("; ", result.Errors.Select(issue => issue.Code))); + HasWarning(result, "PROXY_ID_INVALID", "proxies[0].id"); } [Test] - public void TooLongProxyIdIsRejected() + public void InvalidProxyIdIsOnlyAWarningWithoutADnsSection() { var configuration = TwoProxyConfiguration(); + configuration.Dns = null; configuration.Proxies[0].Id = new string('a', DnsConfiguration.MaximumProxyIdLength + 1); - HasError(_validator.Validate(configuration), "PROXY_ID_INVALID", "proxies[0].id"); + var result = _validator.Validate(configuration); + Assert.That(result.HasErrors, Is.False); + HasWarning(result, "PROXY_ID_INVALID", "proxies[0].id"); + } + + [TestCase("")] + [TestCase(" ")] + public void EmptyProxyIdMeansNoId(string id) + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[0].Id = id; + configuration.Proxies[1].Id = id; + configuration.Dns = null; + + var result = _validator.Validate(configuration); + Assert.That(result.Issues.Any(issue => issue.Code.StartsWith("PROXY_ID_")), Is.False); + Assert.That(_normalizer.Normalize(configuration).Proxies[0].Id, Is.Null); } [Test] - public void DuplicateProxyIdsAreRejectedCaseInsensitively() + public void DuplicateProxyIdReferencedByDnsIsAnErrorCaseInsensitively() { var configuration = TwoProxyConfiguration(); configuration.Proxies[1].Id = "OFFICE"; @@ -246,13 +287,50 @@ public void DuplicateProxyIdsAreRejectedCaseInsensitively() } [Test] - public void ProxyIdsAreValidatedInDirectModeToo() + public void DuplicateProxyIdThatDnsDoesNotUseIsOnlyAWarning() { var configuration = TwoProxyConfiguration(); - configuration.Dns = null; configuration.Proxies[1].Id = "office"; + var third = TestModels.ValidRule(); + third.Id = "vpn"; + third.AppNames = new List { "mail" }; + configuration.Proxies.Insert(1, third); + + var result = _validator.Validate(configuration); + Assert.That(result.HasErrors, Is.False, string.Join("; ", result.Errors.Select(issue => issue.Code))); + HasWarning(result, "PROXY_ID_DUPLICATE", "proxies[2].id"); + } + + [TestCase(null)] + [TestCase("Direct")] + public void DuplicateProxyIdIsOnlyAWarningWhenDnsIsDirect(string mode) + { + var configuration = TwoProxyConfiguration(); + configuration.Dns = mode == null ? null : new DnsSettings { Mode = mode, ProxyId = "office" }; + configuration.Proxies[1].Id = "office"; + + var result = _validator.Validate(configuration); + Assert.That(result.HasErrors, Is.False); + HasWarning(result, "PROXY_ID_DUPLICATE", "proxies[1].id"); + } + + [TestCase("\"8.8.8.8\"")] + [TestCase("[]")] + [TestCase("true")] + public void DnsValueThatIsNotAnObjectIsReportedByName(string value) + { + var json = "{ \"logLevel\": \"Info\", \"proxies\": [], \"dns\": " + value + " }"; + + var exception = Assert.Throws(() => _serializer.Deserialize(json)); + StringAssert.Contains("'dns'", exception.Message); + } + + [Test] + public void NullDnsMeansDirect() + { + var configuration = _serializer.Deserialize("{ \"logLevel\": \"Info\", \"proxies\": [], \"dns\": null }"); - HasError(_validator.Validate(configuration), "PROXY_ID_DUPLICATE", "proxies[1].id"); + Assert.That(configuration.Dns, Is.Null); } // ---------------------------------------------------------------- 6. server override @@ -422,6 +500,16 @@ public void NormalizationKeepsAnUnknownModeVisibleForValidation() Assert.That(_normalizer.Normalize(configuration).Dns.Mode, Is.EqualTo("Tunnel")); } + private static ValidationIssue HasWarning(ValidationResult result, string code, string path) + { + var issue = result.Issues.FirstOrDefault(item => item.Code == code); + Assert.That(issue, Is.Not.Null, + "Expected " + code + "; found: " + string.Join(", ", result.Issues.Select(item => item.Code))); + Assert.That(issue.Severity, Is.EqualTo(ValidationSeverity.Warning)); + Assert.That(issue.Path, Is.EqualTo(path)); + return issue; + } + private static ValidationIssue HasError(ValidationResult result, string code, string path) { var issue = result.Issues.FirstOrDefault(item => item.Code == code); diff --git a/ProxiFyreUI/Forms/MainForm.cs b/ProxiFyreUI/Forms/MainForm.cs index 7e1d0b9..1c52228 100644 --- a/ProxiFyreUI/Forms/MainForm.cs +++ b/ProxiFyreUI/Forms/MainForm.cs @@ -319,8 +319,13 @@ private void DnsControlChanged(object sender, EventArgs e) if (ReferenceEquals(sender, dnsProxyComboBox) && dnsProxyComboBox.SelectedItem is DnsProxyChoice choice && choice.Rule != null) { - // Reference the rule by a stable id; assign one when the rule has none yet. - if (!DnsConfiguration.IsValidProxyId(choice.Rule.Id?.Trim())) + // Reference the rule by a stable id; assign a new one when the rule has none, or + // its id is invalid or shared with another rule (either would fail validation). + var currentId = choice.Rule.Id?.Trim(); + var idSharedWithAnotherRule = configuration.Proxies.Any(rule => + rule != null && !ReferenceEquals(rule, choice.Rule) && rule.Id != null && + string.Equals(rule.Id.Trim(), currentId, StringComparison.OrdinalIgnoreCase)); + if (!DnsConfiguration.IsValidProxyId(currentId) || idSharedWithAnotherRule) { choice.Rule.Id = DnsConfiguration.CreateUniqueProxyId( configuration.Proxies.Where(rule => rule != null).Select(rule => rule.Id)); diff --git a/README.md b/README.md index 19c48ad..b0d1e1d 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,8 @@ In `Proxy` mode DNS is not sent directly: if the selected proxy cannot carry a q > [!IMPORTANT] > **Upgrade note — DNS over TCP port 53.** In the default `Direct` DNS mode, which also applies to existing configurations without a `dns` section, DNS over TCP port 53 now always bypasses the proxies, as DNS over UDP port 53 already did. Rules that previously carried TCP port 53 through a proxy, for example a catch-all rule, no longer do so. To route DNS through a proxy, use DNS `Proxy` mode. +> +> **Upgrade note — `id` and `dns` keys.** Earlier releases ignored a rule property named `id` and a top-level property named `dns`; both are now interpreted. An invalid or duplicate `id` is only a warning unless DNS `Proxy` mode refers to it, and an empty `id` means no id. A `dns` value that is not an object, such as `"dns": "8.8.8.8"`, is a configuration error and the service does not start until it is removed or replaced with a DNS policy object. See the [configuration reference](docs/configuration.md) for matching rules, authentication, LAN bypass, DNS routing, logging, TLS options, and complete examples. The repository also includes a ready-to-edit [sample configuration](app-config.sample.json). diff --git a/docs/configuration.md b/docs/configuration.md index 75de827..f8f78f9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -70,7 +70,7 @@ Process ownership lookup is best effort for a standard user. ProxiFyre can route | Property | Description | | --- | --- | -| `id` | Optional stable identifier used to reference this rule's proxy, for example from `dns.proxyId`. 1–64 letters, digits, `-`, `_`, or `.`; unique, case-insensitive. Unlike the rule position it survives reordering. | +| `id` | Optional stable identifier used to reference this rule's proxy, for example from `dns.proxyId`. 1–64 letters, digits, `-`, `_`, or `.`; unique, case-insensitive. Unlike the rule position it survives reordering. An empty or whitespace id means no id. An invalid or duplicate id is an error only when `dns.proxyId` in `Proxy` mode refers to it; otherwise it is reported as a warning and has no effect. | | `appNames` | Application names or paths matched by this rule. An explicit empty string is the catch-all. | | `socks5ProxyEndpoint` | SOCKS5 hostname or IPv4 address plus port, for example `proxy.example.com:1080`. | | `username`, `password` | Optional SOCKS5 authentication. Configure both or neither. | @@ -149,7 +149,10 @@ The optional `dns` object controls conventional DNS: UDP and TCP traffic to dest | `proxyId` | Required in `Proxy` mode: the `id` of the proxy rule whose SOCKS5 proxy carries DNS. That rule must support both `TCP` and `UDP` (omitting `supportedProtocols` means both). | | `serverOverride` | Optional, `Proxy` mode only: an IPv4 or IPv6 literal with an optional port that the SOCKS5 proxy queries instead of the server Windows addressed, for example `1.1.1.1`, `1.1.1.1:53`, `2606:4700:4700::1111`, or `[2606:4700:4700::1111]:53`. Host names are rejected so the override never needs DNS itself. | -Configurations written before DNS routing existed load and save unchanged. The one exception is a configuration that already contained a rule property named `id` or a top-level property named `dns`: these were preserved but ignored by earlier releases and are now interpreted and validated. +Configurations written before DNS routing existed load and save unchanged. The exceptions are configurations that already contained a rule property named `id` or a top-level property named `dns`. Earlier releases preserved and ignored both; they are now interpreted: + +- A rule `id` that is invalid or duplicated is only a warning unless DNS `Proxy` mode refers to it, so such a configuration still starts. An empty `id` means no id. +- A `dns` value must be an object (or `null`). Any other value, such as `"dns": "8.8.8.8"`, is a configuration error that names `dns`, and the service does not start until it is removed or replaced with a DNS policy object. ### Direct mode @@ -184,7 +187,7 @@ Windows retries a failed query and, for UDP answers marked truncated, retries ov If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. -The selection is made by `proxyId`, never by position, so reordering rules does not change the DNS proxy. If the referenced rule is removed or renamed, validation fails with `DNS_PROXY_NOT_FOUND`; ProxiFyre never silently switches to another proxy. The GUI assigns an id such as `proxy-1` to a rule when it is selected as the DNS proxy, and clears the id on a duplicated copy. +The selection is made by `proxyId`, never by position, so reordering rules does not change the DNS proxy. If the referenced rule is removed or renamed, validation fails with `DNS_PROXY_NOT_FOUND`; ProxiFyre never silently switches to another proxy. The GUI assigns an id such as `proxy-1` to a rule when it is selected as the DNS proxy and the rule has no id, an invalid id, or an id another rule also uses, and it clears the id on a duplicated copy. ### Shared UDP association From 16c05790473d1bb2ac331cc2aa1ab14fbf359fd7 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 21:47:33 +0000 Subject: [PATCH 55/62] fix(config, gui): review round 12 for the id and dns upgrade handling - A rule id that is a JSON object or array no longer stops the service: it is kept as its JSON text, which validation reports as an invalid id (a warning unless DNS uses it). A dns value, or a dns mode/proxyId/serverOverride, of the wrong JSON type is reported by its name, for every case variant of the key. - Saving drops ids that only cause warnings (invalid, or a repeat of an earlier rule's id, and not referenced by DNS Proxy mode), so the GUI can clear them; the warning text says so. - GUI: the DNS proxy selector shows the first rule with the referenced id, as validation and the service resolve it; switching to Proxy mode repairs the id of the rule shown; rule rows are refreshed after DNS changes. - Docs: gui.md id assignment, null dns in the README upgrade note. --- .../ConfigurationNormalizer.cs | 32 ++++++++ .../ConfigurationSerializer.cs | 68 ++++++++++++++--- .../ConfigurationValidator.cs | 23 ++---- ProxiFyre.Configuration/DnsConfiguration.cs | 13 ++++ ProxiFyre.Tests/DnsConfigurationTests.cs | 74 +++++++++++++++++++ ProxiFyreUI/Forms/MainForm.cs | 16 +++- README.md | 2 +- docs/configuration.md | 6 +- docs/gui.md | 2 +- 9 files changed, 198 insertions(+), 38 deletions(-) diff --git a/ProxiFyre.Configuration/ConfigurationNormalizer.cs b/ProxiFyre.Configuration/ConfigurationNormalizer.cs index d588ec4..57bb2bc 100644 --- a/ProxiFyre.Configuration/ConfigurationNormalizer.cs +++ b/ProxiFyre.Configuration/ConfigurationNormalizer.cs @@ -32,9 +32,41 @@ public ProxiFyreConfiguration Normalize(ProxiFyreConfiguration configuration) ExtensionData = CloneExtensionData(configuration.ExtensionData) }; + DropUnusedInvalidProxyIds(result.Proxies, DnsConfiguration.GetReferencedProxyId(configuration.Dns)); return result; } + /// + /// Removes ids that the validator reports only as warnings: an invalid id, or a repeat of an + /// earlier rule's id, that DNS Proxy mode does not reference. They have no effect, and + /// dropping them lets a saved configuration clear the warning. An id DNS references is + /// kept, because the validator reports it as an error instead. + /// + private static void DropUnusedInvalidProxyIds(IList rules, string referencedId) + { + if (rules == null) + return; + + var seen = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var rule in rules) + { + if (rule == null || rule.Id == null) + continue; + + var referenced = referencedId != null && + string.Equals(rule.Id, referencedId, StringComparison.OrdinalIgnoreCase); + if (!DnsConfiguration.IsValidProxyId(rule.Id)) + { + if (!referenced) + rule.Id = null; + continue; + } + + if (!seen.Add(rule.Id) && !referenced) + rule.Id = null; + } + } + public DnsSettings NormalizeDns(DnsSettings dns) { if (dns == null) diff --git a/ProxiFyre.Configuration/ConfigurationSerializer.cs b/ProxiFyre.Configuration/ConfigurationSerializer.cs index 0d45a45..77a5c50 100644 --- a/ProxiFyre.Configuration/ConfigurationSerializer.cs +++ b/ProxiFyre.Configuration/ConfigurationSerializer.cs @@ -65,17 +65,7 @@ public ProxiFyreConfiguration Deserialize(string json) "The configuration is not a valid JSON object.", ex); } - // Earlier releases kept an unknown top-level "dns" property and ignored it. It now selects - // DNS routing, so a value that is not an object is named in the error rather than - // reported as an anonymous invalid property value. - var dnsProperty = root.Properties().FirstOrDefault( - p => string.Equals(p.Name, "dns", StringComparison.OrdinalIgnoreCase)); - if (dnsProperty != null && dnsProperty.Value.Type != JTokenType.Object && dnsProperty.Value.Type != JTokenType.Null) - { - throw new ConfigurationFormatException( - "The 'dns' property must be an object such as { \"mode\": \"Proxy\", \"proxyId\": \"office\" }, " + - "or be removed to keep DNS Direct."); - } + PrepareKeysEarlierReleasesIgnored(root); ProxiFyreConfiguration configuration; try @@ -107,6 +97,62 @@ public ProxiFyreConfiguration Deserialize(string json) /// Creates a lossless editable copy, including credentials and unknown extension fields. /// Keeping this operation here prevents UI projects from taking a direct JSON dependency. /// + /// + /// Earlier releases kept a rule "id" and a top-level "dns" property as unknown data and + /// ignored them. A rule id that is an object or array is turned into its JSON text, which + /// the validator then reports as an invalid id (a warning unless DNS uses it), so such a + /// configuration still loads. A "dns" value that is not an object, or a DNS setting that + /// is an object or array, is a configuration error that names the property. + /// + private static void PrepareKeysEarlierReleasesIgnored(JObject root) + { + foreach (var proxies in PropertiesNamed(root, "proxies")) + { + var rules = proxies.Value as JArray; + if (rules == null) + continue; + foreach (var rule in rules.OfType()) + { + foreach (var id in PropertiesNamed(rule, "id")) + { + if (id.Value.Type == JTokenType.Object || id.Value.Type == JTokenType.Array) + id.Value = new JValue(id.Value.ToString(Formatting.None)); + } + } + } + + foreach (var dns in PropertiesNamed(root, "dns")) + { + if (dns.Value.Type == JTokenType.Null) + continue; + var settings = dns.Value as JObject; + if (settings == null) + { + throw new ConfigurationFormatException( + "The '" + dns.Name + "' property must be an object such as " + + "{ \"mode\": \"Proxy\", \"proxyId\": \"office\" }, or be removed to keep DNS Direct."); + } + + foreach (var setting in settings.Properties()) + { + var known = new[] { "mode", "proxyId", "serverOverride" }.FirstOrDefault( + name => string.Equals(name, setting.Name, StringComparison.OrdinalIgnoreCase)); + if (known != null && (setting.Value.Type == JTokenType.Object || setting.Value.Type == JTokenType.Array)) + { + throw new ConfigurationFormatException( + "The '" + dns.Name + "." + setting.Name + "' property must be a string."); + } + } + } + } + + private static JProperty[] PropertiesNamed(JObject parent, string name) + { + return parent.Properties() + .Where(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)) + .ToArray(); + } + public ProxyRule CloneRule(ProxyRule rule) { if (rule == null) diff --git a/ProxiFyre.Configuration/ConfigurationValidator.cs b/ProxiFyre.Configuration/ConfigurationValidator.cs index fd44ab8..906a03b 100644 --- a/ProxiFyre.Configuration/ConfigurationValidator.cs +++ b/ProxiFyre.Configuration/ConfigurationValidator.cs @@ -514,7 +514,7 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC // Earlier releases ignored a rule "id", so an id only stops the service when DNS Proxy // mode depends on it. Any other invalid or duplicate id is reported as a warning and has // no effect. An empty or whitespace id means no id, as the normalizer treats it. - var referencedId = ReferencedProxyId(dns); + var referencedId = DnsConfiguration.GetReferencedProxyId(dns); var seen = new Dictionary(StringComparer.OrdinalIgnoreCase); for (var index = 0; index < rules.Count; index++) { @@ -535,8 +535,8 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC RulePath(index) + ".id", index) : Warning("PROXY_ID_INVALID", - message + " No DNS setting uses it, so it has no effect; remove it or give it a valid value " + - "before selecting this rule as the DNS proxy.", + message + " No DNS setting uses it, so it has no effect and is removed when the " + + "configuration is saved.", RulePath(index) + ".id", index)); continue; @@ -553,8 +553,8 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC RulePath(index) + ".id", index) : Warning("PROXY_ID_DUPLICATE", - message + " No DNS setting uses it, so it has no effect; make it unique before " + - "selecting either rule as the DNS proxy.", + message + " No DNS setting uses it, so it has no effect and is removed from this rule " + + "when the configuration is saved.", RulePath(index) + ".id", index)); continue; @@ -564,19 +564,6 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC } } - /// - /// The trimmed proxy id that DNS Proxy mode routes through, or null when DNS does not - /// reference a rule (DNS omitted, Direct, an unknown mode, or no proxyId). - /// - private static string ReferencedProxyId(DnsSettings dns) - { - DnsRoutingMode mode; - if (dns == null || string.IsNullOrWhiteSpace(dns.ProxyId) || - !DnsConfiguration.TryGetMode(dns.Mode, out mode) || mode != DnsRoutingMode.Proxy) - return null; - return dns.ProxyId.Trim(); - } - private static void ValidateDns(DnsSettings dns, IList rules, ICollection issues) { if (dns == null) diff --git a/ProxiFyre.Configuration/DnsConfiguration.cs b/ProxiFyre.Configuration/DnsConfiguration.cs index fa67abb..ec9688a 100644 --- a/ProxiFyre.Configuration/DnsConfiguration.cs +++ b/ProxiFyre.Configuration/DnsConfiguration.cs @@ -66,6 +66,19 @@ public static class DnsConfiguration /// Maximum length of a proxy rule identifier. public const int MaximumProxyIdLength = 64; + /// + /// The trimmed proxy id that DNS Proxy mode routes through, or null when DNS does not + /// reference a rule (DNS omitted, Direct, an unknown mode, or no proxyId). + /// + public static string GetReferencedProxyId(DnsSettings settings) + { + DnsRoutingMode mode; + if (settings == null || string.IsNullOrWhiteSpace(settings.ProxyId) || + !TryGetMode(settings.Mode, out mode) || mode != DnsRoutingMode.Proxy) + return null; + return settings.ProxyId.Trim(); + } + /// /// Returns the effective mode. A missing DNS section or mode means Direct. /// diff --git a/ProxiFyre.Tests/DnsConfigurationTests.cs b/ProxiFyre.Tests/DnsConfigurationTests.cs index 74add1f..af14d31 100644 --- a/ProxiFyre.Tests/DnsConfigurationTests.cs +++ b/ProxiFyre.Tests/DnsConfigurationTests.cs @@ -325,6 +325,80 @@ public void DnsValueThatIsNotAnObjectIsReportedByName(string value) StringAssert.Contains("'dns'", exception.Message); } + [TestCase("{ \"dns\": {}, \"DNS\": \"8.8.8.8\" }", "'DNS'")] + [TestCase("{ \"dns\": { \"proxyId\": [1] } }", "'dns.proxyId'")] + [TestCase("{ \"dns\": { \"Mode\": {} } }", "'dns.Mode'")] + [TestCase("{ \"dns\": { \"serverOverride\": { \"a\": 1 } } }", "'dns.serverOverride'")] + public void MalformedDnsSettingsAreReportedByName(string json, string name) + { + var exception = Assert.Throws(() => _serializer.Deserialize(json)); + StringAssert.Contains(name, exception.Message); + } + + [TestCase("{}")] + [TestCase("[1]")] + public void RuleIdThatIsNotAStringStillLoadsAndIsOnlyAWarning(string id) + { + var json = "{ \"logLevel\": \"Info\", \"proxies\": [ { \"ID\": " + id + + ", \"appNames\": [\"browser\"], \"socks5ProxyEndpoint\": \"proxy.example.com:1080\" } ] }"; + + var configuration = _serializer.Deserialize(json); + var result = _validator.Validate(configuration); + + Assert.That(result.HasErrors, Is.False, string.Join("; ", result.Errors.Select(issue => issue.Code))); + HasWarning(result, "PROXY_ID_INVALID", "proxies[0].id"); + Assert.That(_normalizer.Normalize(configuration).Proxies[0].Id, Is.Null); + } + + [Test] + public void SavingDropsIdsThatOnlyCauseWarnings() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[0].Id = "has space"; + var third = TestModels.ValidRule(); + third.Id = " VPN "; + third.AppNames = new List { "mail" }; + configuration.Proxies.Insert(1, third); + configuration.Dns.ProxyId = "other"; + configuration.Proxies[2].Id = "other"; + + var normalized = _normalizer.Normalize(configuration); + + Assert.That(normalized.Proxies.Select(rule => rule.Id), Is.EqualTo(new[] { null, "VPN", "other" })); + Assert.That(_validator.Validate(normalized).Issues.Any(issue => issue.Code.StartsWith("PROXY_ID_")), Is.False); + } + + [Test] + public void SavingKeepsIdsTheDnsProxyReferences() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[0].Id = "VPN"; + configuration.Proxies.Add(TestModels.ValidRule()); + configuration.Proxies[2].Id = "bad id"; + configuration.Proxies[2].AppNames = new List { "mail" }; + configuration.Proxies.Insert(2, TestModels.ValidRule()); + configuration.Proxies[2].Id = "bad id"; + configuration.Proxies[2].AppNames = new List { "news" }; + configuration.Dns.ProxyId = "vpn"; + + var normalized = _normalizer.Normalize(configuration); + + // Both copies of the referenced duplicate stay, so the error remains visible; the + // invalid id DNS does not use is removed from both rules. + Assert.That(normalized.Proxies.Select(rule => rule.Id), Is.EqualTo(new[] { "VPN", "vpn", null, null })); + HasError(_validator.Validate(normalized), "PROXY_ID_DUPLICATE", "proxies[1].id"); + } + + [Test] + public void SavingKeepsAnInvalidIdTheDnsProxyReferences() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[1].Id = "has space"; + configuration.Dns.ProxyId = "has space"; + + Assert.That(_normalizer.Normalize(configuration).Proxies[1].Id, Is.EqualTo("has space")); + } + [Test] public void NullDnsMeansDirect() { diff --git a/ProxiFyreUI/Forms/MainForm.cs b/ProxiFyreUI/Forms/MainForm.cs index 1c52228..04157c7 100644 --- a/ProxiFyreUI/Forms/MainForm.cs +++ b/ProxiFyreUI/Forms/MainForm.cs @@ -282,7 +282,8 @@ private void RefreshDnsProxyChoices() " — " + FormatApplications(rule.AppNames) + (string.IsNullOrWhiteSpace(rule.Id) ? string.Empty : " [id: " + rule.Id.Trim() + "]"); var itemIndex = dnsProxyComboBox.Items.Add(new DnsProxyChoice(rule, text)); - if (!string.IsNullOrWhiteSpace(selectedId) && rule.Id != null && + // The first rule with the id, as validation and the service resolve it. + if (selectedIndex < 0 && !string.IsNullOrWhiteSpace(selectedId) && rule.Id != null && string.Equals(rule.Id.Trim(), selectedId.Trim(), StringComparison.OrdinalIgnoreCase)) selectedIndex = itemIndex; } @@ -316,7 +317,11 @@ private void DnsControlChanged(object sender, EventArgs e) if (ReferenceEquals(sender, dnsModeComboBox) && dnsModeComboBox.SelectedIndex >= 0) dns.Mode = dnsModeComboBox.SelectedIndex == 1 ? DnsConfiguration.ProxyMode : DnsConfiguration.DirectMode; - if (ReferenceEquals(sender, dnsProxyComboBox) && + // Choosing a rule, or switching to Proxy mode with a rule shown, (re)establishes the + // reference, so a shown rule whose id cannot be used is repaired without re-selecting it. + var referenceChanged = ReferenceEquals(sender, dnsProxyComboBox) || + (ReferenceEquals(sender, dnsModeComboBox) && dnsModeComboBox.SelectedIndex == 1); + if (referenceChanged && dnsProxyComboBox.SelectedItem is DnsProxyChoice choice && choice.Rule != null) { // Reference the rule by a stable id; assign a new one when the rule has none, or @@ -338,8 +343,11 @@ private void DnsControlChanged(object sender, EventArgs e) configuration.Dns = dns; MarkConfigurationChanged(); - if (ReferenceEquals(sender, dnsProxyComboBox)) - BeginInvoke(new Action(RefreshDnsProxyChoices)); + // Rule rows show id issues, which depend on the DNS settings; rebuilding the grid also + // refreshes the DNS proxy choices. Deferred so the combo box is not rebuilt inside its + // own change event. + if (ReferenceEquals(sender, dnsProxyComboBox) || ReferenceEquals(sender, dnsModeComboBox)) + BeginInvoke(new Action(() => RefreshRoutingGrid(SelectedRuleIndex))); } private void UpdateDnsControlStates() diff --git a/README.md b/README.md index b0d1e1d..b9c488f 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,7 @@ In `Proxy` mode DNS is not sent directly: if the selected proxy cannot carry a q > [!IMPORTANT] > **Upgrade note — DNS over TCP port 53.** In the default `Direct` DNS mode, which also applies to existing configurations without a `dns` section, DNS over TCP port 53 now always bypasses the proxies, as DNS over UDP port 53 already did. Rules that previously carried TCP port 53 through a proxy, for example a catch-all rule, no longer do so. To route DNS through a proxy, use DNS `Proxy` mode. > -> **Upgrade note — `id` and `dns` keys.** Earlier releases ignored a rule property named `id` and a top-level property named `dns`; both are now interpreted. An invalid or duplicate `id` is only a warning unless DNS `Proxy` mode refers to it, and an empty `id` means no id. A `dns` value that is not an object, such as `"dns": "8.8.8.8"`, is a configuration error and the service does not start until it is removed or replaced with a DNS policy object. +> **Upgrade note — `id` and `dns` keys.** Earlier releases ignored a rule property named `id` and a top-level property named `dns`; both are now interpreted. An invalid or duplicate `id` is only a warning unless DNS `Proxy` mode refers to it, and an empty `id` means no id. A `dns` value other than an object or `null`, such as `"dns": "8.8.8.8"`, is a configuration error and the service does not start until it is removed or replaced with a DNS policy object. See the [configuration reference](docs/configuration.md) for matching rules, authentication, LAN bypass, DNS routing, logging, TLS options, and complete examples. The repository also includes a ready-to-edit [sample configuration](app-config.sample.json). diff --git a/docs/configuration.md b/docs/configuration.md index f8f78f9..aa2f3a2 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -70,7 +70,7 @@ Process ownership lookup is best effort for a standard user. ProxiFyre can route | Property | Description | | --- | --- | -| `id` | Optional stable identifier used to reference this rule's proxy, for example from `dns.proxyId`. 1–64 letters, digits, `-`, `_`, or `.`; unique, case-insensitive. Unlike the rule position it survives reordering. An empty or whitespace id means no id. An invalid or duplicate id is an error only when `dns.proxyId` in `Proxy` mode refers to it; otherwise it is reported as a warning and has no effect. | +| `id` | Optional stable identifier used to reference this rule's proxy, for example from `dns.proxyId`. 1–64 letters, digits, `-`, `_`, or `.`; unique, case-insensitive. Unlike the rule position it survives reordering. An empty or whitespace id means no id. An invalid or duplicate id is an error only when `dns.proxyId` in `Proxy` mode refers to it; otherwise it is reported as a warning, has no effect, and is removed when the configuration is saved (the first rule with a duplicated id keeps it). | | `appNames` | Application names or paths matched by this rule. An explicit empty string is the catch-all. | | `socks5ProxyEndpoint` | SOCKS5 hostname or IPv4 address plus port, for example `proxy.example.com:1080`. | | `username`, `password` | Optional SOCKS5 authentication. Configure both or neither. | @@ -151,8 +151,8 @@ The optional `dns` object controls conventional DNS: UDP and TCP traffic to dest Configurations written before DNS routing existed load and save unchanged. The exceptions are configurations that already contained a rule property named `id` or a top-level property named `dns`. Earlier releases preserved and ignored both; they are now interpreted: -- A rule `id` that is invalid or duplicated is only a warning unless DNS `Proxy` mode refers to it, so such a configuration still starts. An empty `id` means no id. -- A `dns` value must be an object (or `null`). Any other value, such as `"dns": "8.8.8.8"`, is a configuration error that names `dns`, and the service does not start until it is removed or replaced with a DNS policy object. +- A rule `id` that is invalid or duplicated, including one that is not a string, is only a warning unless DNS `Proxy` mode refers to it, so such a configuration still starts; the GUI removes it on the next save. An empty `id` means no id. +- A `dns` value must be an object (or `null`, which means `Direct`), and its `mode`, `proxyId`, and `serverOverride` must not be objects or arrays. Anything else, such as `"dns": "8.8.8.8"`, is a configuration error that names the property, and the service does not start until it is removed or replaced with a DNS policy object. ### Direct mode diff --git a/docs/gui.md b/docs/gui.md index d7600fd..1bcd686 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -60,7 +60,7 @@ SOCKS5-over-TLS protects the TCP control connection (including the UDP `ASSOCIAT ### DNS routing -The **DNS routing** group on the **Settings / Diagnostics** tab edits the global `dns` section described in the [configuration reference](configuration.md#dns-routing). **DNS mode** selects `Direct` (default) or `Proxy`. In `Direct` mode the **DNS proxy** and **Server override** fields are disabled but keep their values, so switching modes does not lose them. **DNS proxy** lists the routing rules by position, endpoint, and applications; selecting one stores that rule's stable `id` in `dns.proxyId`, assigning an id such as `proxy-1` to the rule if it has none. The reference therefore survives **Move Up**/**Move Down**, editing, saving, and reloading. **Duplicate** clears the id on the copy. If the referenced rule is removed, the selector shows the missing id and validation fails until another rule is chosen; the GUI never substitutes a different proxy. Validation also requires the selected rule to support both TCP and UDP and checks that the server override is an IP literal whose address family the rule accepts. Like other engine settings, DNS changes take effect after **Apply & Restart**. +The **DNS routing** group on the **Settings / Diagnostics** tab edits the global `dns` section described in the [configuration reference](configuration.md#dns-routing). **DNS mode** selects `Direct` (default) or `Proxy`. In `Direct` mode the **DNS proxy** and **Server override** fields are disabled but keep their values, so switching modes does not lose them. **DNS proxy** lists the routing rules by position, endpoint, and applications; selecting one stores that rule's stable `id` in `dns.proxyId`, assigning an id such as `proxy-1` to the rule if it has none, its id is invalid, or another rule uses the same id. Switching the mode to `Proxy` does the same for the rule already shown. When several rules share the referenced id, the selector shows the first, which is the rule validation and the service use. Ids that DNS does not use and that are invalid or repeated are reported as warnings and removed on the next save. The reference therefore survives **Move Up**/**Move Down**, editing, saving, and reloading. **Duplicate** clears the id on the copy. If the referenced rule is removed, the selector shows the missing id and validation fails until another rule is chosen; the GUI never substitutes a different proxy. Validation also requires the selected rule to support both TCP and UDP and checks that the server override is an IP literal whose address family the rule accepts. Like other engine settings, DNS changes take effect after **Apply & Restart**. ## Save, apply, conflicts, and recovery From 9cec8006eabc696f9b85eb0808b1130bad2c546a Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 21:56:51 +0000 Subject: [PATCH 56/62] fix(config, gui): review round 13 for id handling; read date-like strings verbatim - Saving keeps an id that dns.proxyId names in any mode, so a Direct-mode DNS proxy selection survives a save and a later switch to Proxy mode; the warning for such an id says it is kept. - Error and warning texts name the GUI repair (select the rule as the DNS proxy again) and say ids are removed when the GUI saves. - GUI: opening and closing the DNS proxy list repairs the shown rule's id when Proxy mode cannot use it; moving the selection on gives a rule the id it had before, so passing through the list leaves no ids behind. - The configuration is parsed without date conversion: JObject.Parse turned ISO date-time strings, such as a password, into re-formatted dates (pre-existing). - CloneRule's doc comment is back on CloneRule; docs say which non-string ids are kept as text. --- .../ConfigurationNormalizer.cs | 11 +-- .../ConfigurationSerializer.cs | 19 +++-- .../ConfigurationValidator.cs | 24 +++++-- ProxiFyre.Configuration/DnsConfiguration.cs | 14 +++- ProxiFyre.Tests/DnsConfigurationTests.cs | 59 ++++++++++++++++ ProxiFyreUI/Forms/MainForm.Designer.cs | 2 +- ProxiFyreUI/Forms/MainForm.cs | 70 +++++++++++++++---- docs/configuration.md | 4 +- docs/gui.md | 2 +- 9 files changed, 171 insertions(+), 34 deletions(-) diff --git a/ProxiFyre.Configuration/ConfigurationNormalizer.cs b/ProxiFyre.Configuration/ConfigurationNormalizer.cs index 57bb2bc..c4e9e67 100644 --- a/ProxiFyre.Configuration/ConfigurationNormalizer.cs +++ b/ProxiFyre.Configuration/ConfigurationNormalizer.cs @@ -32,15 +32,16 @@ public ProxiFyreConfiguration Normalize(ProxiFyreConfiguration configuration) ExtensionData = CloneExtensionData(configuration.ExtensionData) }; - DropUnusedInvalidProxyIds(result.Proxies, DnsConfiguration.GetReferencedProxyId(configuration.Dns)); + DropUnusedInvalidProxyIds(result.Proxies, DnsConfiguration.GetNamedProxyId(configuration.Dns)); return result; } /// - /// Removes ids that the validator reports only as warnings: an invalid id, or a repeat of an - /// earlier rule's id, that DNS Proxy mode does not reference. They have no effect, and - /// dropping them lets a saved configuration clear the warning. An id DNS references is - /// kept, because the validator reports it as an error instead. + /// Removes an invalid id, or a repeat of an earlier rule's id, that dns.proxyId does not + /// name. Such ids have no effect, and dropping them lets a saved configuration clear the + /// warning. An id dns.proxyId names is kept in every mode: in Proxy mode the validator + /// reports it as an error, and in Direct mode the selection must survive a later switch + /// to Proxy mode. /// private static void DropUnusedInvalidProxyIds(IList rules, string referencedId) { diff --git a/ProxiFyre.Configuration/ConfigurationSerializer.cs b/ProxiFyre.Configuration/ConfigurationSerializer.cs index 77a5c50..e5359db 100644 --- a/ProxiFyre.Configuration/ConfigurationSerializer.cs +++ b/ProxiFyre.Configuration/ConfigurationSerializer.cs @@ -57,7 +57,16 @@ public ProxiFyreConfiguration Deserialize(string json) JObject root; try { - root = JObject.Parse(json); + // JObject.Parse would turn ISO date-time strings (a password, for example) into + // dates and re-format them; the settings' DateParseHandling does not apply to it. + using (var reader = new JsonTextReader(new StringReader(json)) { DateParseHandling = DateParseHandling.None }) + { + root = JObject.Load(reader); + // Like JObject.Parse: only comments may follow the object. + while (reader.Read()) + { + } + } } catch (JsonException ex) { @@ -93,10 +102,6 @@ public ProxiFyreConfiguration Deserialize(string json) return configuration; } - /// - /// Creates a lossless editable copy, including credentials and unknown extension fields. - /// Keeping this operation here prevents UI projects from taking a direct JSON dependency. - /// /// /// Earlier releases kept a rule "id" and a top-level "dns" property as unknown data and /// ignored them. A rule id that is an object or array is turned into its JSON text, which @@ -153,6 +158,10 @@ private static JProperty[] PropertiesNamed(JObject parent, string name) .ToArray(); } + /// + /// Creates a lossless editable copy, including credentials and unknown extension fields. + /// Keeping this operation here prevents UI projects from taking a direct JSON dependency. + /// public ProxyRule CloneRule(ProxyRule rule) { if (rule == null) diff --git a/ProxiFyre.Configuration/ConfigurationValidator.cs b/ProxiFyre.Configuration/ConfigurationValidator.cs index 906a03b..d7ef226 100644 --- a/ProxiFyre.Configuration/ConfigurationValidator.cs +++ b/ProxiFyre.Configuration/ConfigurationValidator.cs @@ -515,6 +515,7 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC // mode depends on it. Any other invalid or duplicate id is reported as a warning and has // no effect. An empty or whitespace id means no id, as the normalizer treats it. var referencedId = DnsConfiguration.GetReferencedProxyId(dns); + var namedId = DnsConfiguration.GetNamedProxyId(dns); var seen = new Dictionary(StringComparer.OrdinalIgnoreCase); for (var index = 0; index < rules.Count; index++) { @@ -525,18 +526,20 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC var trimmed = id.Trim(); var referenced = referencedId != null && string.Equals(trimmed, referencedId, StringComparison.OrdinalIgnoreCase); + var named = namedId != null && + string.Equals(trimmed, namedId, StringComparison.OrdinalIgnoreCase); if (!DnsConfiguration.IsValidProxyId(trimmed)) { var message = "A proxy id must contain 1 to " + DnsConfiguration.MaximumProxyIdLength + " letters, digits, '-', '_', or '.' characters."; issues.Add(referenced ? Error("PROXY_ID_INVALID", - message + " dns.proxyId refers to this id; give the rule a valid id and update dns.proxyId.", + message + " dns.proxyId refers to this id. Select the rule as the DNS proxy again in " + + "the GUI, which assigns a valid id, or give the rule a valid id and update dns.proxyId.", RulePath(index) + ".id", index) : Warning("PROXY_ID_INVALID", - message + " No DNS setting uses it, so it has no effect and is removed when the " + - "configuration is saved.", + message + UnusedIdConsequence(named), RulePath(index) + ".id", index)); continue; @@ -549,12 +552,13 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC "; proxy ids must be unique (case-insensitive)."; issues.Add(referenced ? Error("PROXY_ID_DUPLICATE", - message + " dns.proxyId refers to this id, so the DNS proxy would be ambiguous.", + message + " dns.proxyId refers to this id, so the DNS proxy would be ambiguous. Select " + + "the intended rule as the DNS proxy again in the GUI, which assigns it a new id, or make " + + "the ids unique.", RulePath(index) + ".id", index) : Warning("PROXY_ID_DUPLICATE", - message + " No DNS setting uses it, so it has no effect and is removed from this rule " + - "when the configuration is saved.", + message + UnusedIdConsequence(named), RulePath(index) + ".id", index)); continue; @@ -564,6 +568,14 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC } } + private static string UnusedIdConsequence(bool namedByDirectModeDns) + { + return namedByDirectModeDns + ? " dns.proxyId names it, so it is kept, but DNS Proxy mode cannot use it as it is; select the rule " + + "as the DNS proxy again in the GUI, which assigns a new id, or fix the id and dns.proxyId." + : " No DNS setting uses it, so it has no effect and is removed when the GUI saves the configuration."; + } + private static void ValidateDns(DnsSettings dns, IList rules, ICollection issues) { if (dns == null) diff --git a/ProxiFyre.Configuration/DnsConfiguration.cs b/ProxiFyre.Configuration/DnsConfiguration.cs index ec9688a..7c59bee 100644 --- a/ProxiFyre.Configuration/DnsConfiguration.cs +++ b/ProxiFyre.Configuration/DnsConfiguration.cs @@ -73,8 +73,18 @@ public static class DnsConfiguration public static string GetReferencedProxyId(DnsSettings settings) { DnsRoutingMode mode; - if (settings == null || string.IsNullOrWhiteSpace(settings.ProxyId) || - !TryGetMode(settings.Mode, out mode) || mode != DnsRoutingMode.Proxy) + if (settings == null || !TryGetMode(settings.Mode, out mode) || mode != DnsRoutingMode.Proxy) + return null; + return GetNamedProxyId(settings); + } + + /// + /// The trimmed dns.proxyId in any mode, or null when it is missing or blank. Direct mode + /// keeps the selection so that switching back to Proxy mode does not lose it. + /// + public static string GetNamedProxyId(DnsSettings settings) + { + if (settings == null || string.IsNullOrWhiteSpace(settings.ProxyId)) return null; return settings.ProxyId.Trim(); } diff --git a/ProxiFyre.Tests/DnsConfigurationTests.cs b/ProxiFyre.Tests/DnsConfigurationTests.cs index af14d31..3a4f9a7 100644 --- a/ProxiFyre.Tests/DnsConfigurationTests.cs +++ b/ProxiFyre.Tests/DnsConfigurationTests.cs @@ -399,6 +399,65 @@ public void SavingKeepsAnInvalidIdTheDnsProxyReferences() Assert.That(_normalizer.Normalize(configuration).Proxies[1].Id, Is.EqualTo("has space")); } + [Test] + public void SavingKeepsTheIdDirectModeStillNames() + { + // Direct mode keeps the DNS proxy selection for a later switch to Proxy mode. + var configuration = TwoProxyConfiguration(); + configuration.Dns = new DnsSettings { Mode = "Direct", ProxyId = " my proxy " }; + configuration.Proxies[1].Id = "my proxy"; + + var result = _validator.Validate(configuration); + Assert.That(result.HasErrors, Is.False); + StringAssert.Contains("dns.proxyId names it", HasWarning(result, "PROXY_ID_INVALID", "proxies[1].id").Message); + + var normalized = _normalizer.Normalize(configuration); + Assert.That(normalized.Proxies[1].Id, Is.EqualTo("my proxy")); + Assert.That(DnsConfiguration.FindProxyRuleIndex(normalized.Proxies, normalized.Dns.ProxyId), Is.EqualTo(1)); + } + + [Test] + public void NormalizingIsIdempotentForIds() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[0].Id = "VPN"; + configuration.Proxies.Add(TestModels.ValidRule()); + configuration.Proxies[2].Id = "bad id"; + + var once = _normalizer.Normalize(configuration); + var twice = _normalizer.Normalize(once); + + Assert.That(twice.Proxies.Select(rule => rule.Id), Is.EqualTo(once.Proxies.Select(rule => rule.Id))); + } + + [Test] + public void DateLikeStringsAreReadVerbatim() + { + var json = "{ \"logLevel\": \"Info\", \"proxies\": [ { \"appNames\": [\"browser\"], " + + "\"socks5ProxyEndpoint\": \"proxy.example.com:1080\", \"username\": \"user\", " + + "\"password\": \"2024-01-15T10:00:00Z\", \"note\": \"2024-01-15T10:00:00+02:00\" } ] }"; + + var configuration = _serializer.Deserialize(json); + + Assert.That(configuration.Proxies[0].Password, Is.EqualTo("2024-01-15T10:00:00Z")); + StringAssert.Contains("\"2024-01-15T10:00:00+02:00\"", + _serializer.Serialize(_normalizer.Normalize(configuration))); + } + + [TestCase("{} {}")] + [TestCase("{} x")] + [TestCase("[]")] + public void ContentOtherThanOneObjectIsRejected(string json) + { + Assert.Throws(() => _serializer.Deserialize(json)); + } + + [Test] + public void CommentsAfterTheObjectAreAccepted() + { + Assert.That(_serializer.Deserialize("{ \"logLevel\": \"Info\" } // trailing comment"), Is.Not.Null); + } + [Test] public void NullDnsMeansDirect() { diff --git a/ProxiFyreUI/Forms/MainForm.Designer.cs b/ProxiFyreUI/Forms/MainForm.Designer.cs index b4e801f..239829c 100644 --- a/ProxiFyreUI/Forms/MainForm.Designer.cs +++ b/ProxiFyreUI/Forms/MainForm.Designer.cs @@ -578,7 +578,7 @@ private void InitializeComponent() this.dnsModeLabel.AutoSize = true; this.dnsModeLabel.Location = new System.Drawing.Point(13, 31); this.dnsModeLabel.TabIndex = 0; this.dnsModeLabel.Text = "DNS &mode:"; this.dnsModeComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.dnsModeComboBox.Items.AddRange(new object[] { "Direct", "Proxy" }); this.dnsModeComboBox.Location = new System.Drawing.Point(122, 27); this.dnsModeComboBox.Size = new System.Drawing.Size(108, 23); this.dnsModeComboBox.TabIndex = 1; this.dnsModeComboBox.SelectedIndexChanged += new System.EventHandler(this.DnsControlChanged); this.dnsProxyLabel.AutoSize = true; this.dnsProxyLabel.Location = new System.Drawing.Point(250, 31); this.dnsProxyLabel.TabIndex = 2; this.dnsProxyLabel.Text = "DNS &proxy:"; - this.dnsProxyComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsProxyComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.dnsProxyComboBox.Location = new System.Drawing.Point(340, 27); this.dnsProxyComboBox.Size = new System.Drawing.Size(723, 23); this.dnsProxyComboBox.TabIndex = 3; this.dnsProxyComboBox.SelectedIndexChanged += new System.EventHandler(this.DnsControlChanged); + this.dnsProxyComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dnsProxyComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.dnsProxyComboBox.Location = new System.Drawing.Point(340, 27); this.dnsProxyComboBox.Size = new System.Drawing.Size(723, 23); this.dnsProxyComboBox.TabIndex = 3; this.dnsProxyComboBox.SelectedIndexChanged += new System.EventHandler(this.DnsControlChanged); this.dnsProxyComboBox.DropDownClosed += new System.EventHandler(this.DnsProxyDropDownClosed); this.dnsServerOverrideLabel.AutoSize = true; this.dnsServerOverrideLabel.Location = new System.Drawing.Point(13, 66); this.dnsServerOverrideLabel.TabIndex = 4; this.dnsServerOverrideLabel.Text = "&Server override:"; this.dnsServerOverrideTextBox.Location = new System.Drawing.Point(122, 62); this.dnsServerOverrideTextBox.Size = new System.Drawing.Size(210, 23); this.dnsServerOverrideTextBox.TabIndex = 5; this.dnsServerOverrideTextBox.TextChanged += new System.EventHandler(this.DnsControlChanged); this.dnsServerOverrideHintLabel.AutoSize = true; this.dnsServerOverrideHintLabel.TabIndex = 6; this.dnsServerOverrideHintLabel.ForeColor = System.Drawing.SystemColors.GrayText; this.dnsServerOverrideHintLabel.Location = new System.Drawing.Point(340, 66); this.dnsServerOverrideHintLabel.Text = "Optional IP literal, e.g. 1.1.1.1 or [2606:4700:4700::1111]:53. Empty keeps the server Windows queried."; diff --git a/ProxiFyreUI/Forms/MainForm.cs b/ProxiFyreUI/Forms/MainForm.cs index 04157c7..ad7cd8c 100644 --- a/ProxiFyreUI/Forms/MainForm.cs +++ b/ProxiFyreUI/Forms/MainForm.cs @@ -31,6 +31,12 @@ internal partial class MainForm : Form private EngineLocation _engineLocation; private ServiceStatusInfo _serviceStatus = new ServiceStatusInfo(ProxiFyreServiceState.Unknown); private bool _suppressChanges; + // The rule the DNS proxy selector last gave a new id, with the id it had before. When the + // selection moves on (arrow keys, mouse wheel), that rule gets its previous id back, so + // passing through the list does not leave an id on every rule. + private ProxyRule _dnsIdAssignedRule; + private string _dnsIdAssignedRulePreviousId; + private string _dnsIdAssigned; private bool _operationInProgress; private bool _applyWorkflowInProgress; private bool _engineStartupFailed; @@ -239,6 +245,7 @@ public DnsProxyChoice(ProxyRule rule, string text) private void BindDnsControls() { var dns = _workspace.Configuration?.Dns; + _dnsIdAssignedRule = null; var previous = _suppressChanges; _suppressChanges = true; try @@ -324,18 +331,7 @@ private void DnsControlChanged(object sender, EventArgs e) if (referenceChanged && dnsProxyComboBox.SelectedItem is DnsProxyChoice choice && choice.Rule != null) { - // Reference the rule by a stable id; assign a new one when the rule has none, or - // its id is invalid or shared with another rule (either would fail validation). - var currentId = choice.Rule.Id?.Trim(); - var idSharedWithAnotherRule = configuration.Proxies.Any(rule => - rule != null && !ReferenceEquals(rule, choice.Rule) && rule.Id != null && - string.Equals(rule.Id.Trim(), currentId, StringComparison.OrdinalIgnoreCase)); - if (!DnsConfiguration.IsValidProxyId(currentId) || idSharedWithAnotherRule) - { - choice.Rule.Id = DnsConfiguration.CreateUniqueProxyId( - configuration.Proxies.Where(rule => rule != null).Select(rule => rule.Id)); - } - dns.ProxyId = choice.Rule.Id.Trim(); + ReferenceDnsProxyRule(configuration, dns, choice.Rule); } var serverOverride = dnsServerOverrideTextBox.Text.Trim(); @@ -350,6 +346,56 @@ private void DnsControlChanged(object sender, EventArgs e) BeginInvoke(new Action(() => RefreshRoutingGrid(SelectedRuleIndex))); } + /// + /// Points dns.proxyId at by its stable id. The rule gets a new id + /// when it has none, or its id is invalid or shared with another rule (either would fail + /// validation). A rule given an id by an earlier selection gets its previous id back. + /// + private void ReferenceDnsProxyRule(ProxiFyreConfiguration configuration, DnsSettings dns, ProxyRule rule) + { + if (_dnsIdAssignedRule != null && !ReferenceEquals(_dnsIdAssignedRule, rule)) + { + if (string.Equals(_dnsIdAssignedRule.Id, _dnsIdAssigned, StringComparison.Ordinal)) + _dnsIdAssignedRule.Id = _dnsIdAssignedRulePreviousId; + _dnsIdAssignedRule = null; + } + + if (!DnsProxyIdUsable(configuration, rule)) + { + var previousId = rule.Id; + rule.Id = DnsConfiguration.CreateUniqueProxyId( + configuration.Proxies.Where(other => other != null).Select(other => other.Id)); + _dnsIdAssignedRule = rule; + _dnsIdAssignedRulePreviousId = previousId; + _dnsIdAssigned = rule.Id; + } + dns.ProxyId = rule.Id.Trim(); + } + + private static bool DnsProxyIdUsable(ProxiFyreConfiguration configuration, ProxyRule rule) + { + var id = rule.Id?.Trim(); + return DnsConfiguration.IsValidProxyId(id) && !configuration.Proxies.Any(other => + other != null && !ReferenceEquals(other, rule) && other.Id != null && + string.Equals(other.Id.Trim(), id, StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Choosing the rule already shown raises no SelectedIndexChanged, so closing the list + /// repairs a shown rule whose id DNS Proxy mode cannot use (for example a duplicate in a + /// loaded file) without making the user pick another rule first. + /// + private void DnsProxyDropDownClosed(object sender, EventArgs e) + { + var configuration = _workspace.Configuration; + if (_suppressChanges || ConfigurationMutationBlocked || configuration?.Proxies == null || + dnsModeComboBox.SelectedIndex != 1) + return; + if (dnsProxyComboBox.SelectedItem is DnsProxyChoice choice && choice.Rule != null && + !DnsProxyIdUsable(configuration, choice.Rule)) + DnsControlChanged(dnsProxyComboBox, e); + } + private void UpdateDnsControlStates() { var editable = !ConfigurationMutationBlocked && _workspace.Configuration != null; diff --git a/docs/configuration.md b/docs/configuration.md index aa2f3a2..3872434 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -70,7 +70,7 @@ Process ownership lookup is best effort for a standard user. ProxiFyre can route | Property | Description | | --- | --- | -| `id` | Optional stable identifier used to reference this rule's proxy, for example from `dns.proxyId`. 1–64 letters, digits, `-`, `_`, or `.`; unique, case-insensitive. Unlike the rule position it survives reordering. An empty or whitespace id means no id. An invalid or duplicate id is an error only when `dns.proxyId` in `Proxy` mode refers to it; otherwise it is reported as a warning, has no effect, and is removed when the configuration is saved (the first rule with a duplicated id keeps it). | +| `id` | Optional stable identifier used to reference this rule's proxy, for example from `dns.proxyId`. 1–64 letters, digits, `-`, `_`, or `.`; unique, case-insensitive. Unlike the rule position it survives reordering. An empty or whitespace id means no id. An invalid or duplicate id is an error only when `dns.proxyId` in `Proxy` mode refers to it; otherwise it is reported as a warning, has no effect, and is removed when the GUI saves the configuration, unless `dns.proxyId` names it (the first rule with a duplicated id keeps it). | | `appNames` | Application names or paths matched by this rule. An explicit empty string is the catch-all. | | `socks5ProxyEndpoint` | SOCKS5 hostname or IPv4 address plus port, for example `proxy.example.com:1080`. | | `username`, `password` | Optional SOCKS5 authentication. Configure both or neither. | @@ -151,7 +151,7 @@ The optional `dns` object controls conventional DNS: UDP and TCP traffic to dest Configurations written before DNS routing existed load and save unchanged. The exceptions are configurations that already contained a rule property named `id` or a top-level property named `dns`. Earlier releases preserved and ignored both; they are now interpreted: -- A rule `id` that is invalid or duplicated, including one that is not a string, is only a warning unless DNS `Proxy` mode refers to it, so such a configuration still starts; the GUI removes it on the next save. An empty `id` means no id. +- A rule `id` that is invalid or duplicated, including one written as a JSON object or array, is only a warning unless DNS `Proxy` mode refers to it, so such a configuration still starts; the GUI removes it on the next save unless `dns.proxyId` names it. An empty `id` means no id. A number or `true`/`false` is read as its text, for example `1.0` as `1`. - A `dns` value must be an object (or `null`, which means `Direct`), and its `mode`, `proxyId`, and `serverOverride` must not be objects or arrays. Anything else, such as `"dns": "8.8.8.8"`, is a configuration error that names the property, and the service does not start until it is removed or replaced with a DNS policy object. ### Direct mode diff --git a/docs/gui.md b/docs/gui.md index 1bcd686..119285d 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -60,7 +60,7 @@ SOCKS5-over-TLS protects the TCP control connection (including the UDP `ASSOCIAT ### DNS routing -The **DNS routing** group on the **Settings / Diagnostics** tab edits the global `dns` section described in the [configuration reference](configuration.md#dns-routing). **DNS mode** selects `Direct` (default) or `Proxy`. In `Direct` mode the **DNS proxy** and **Server override** fields are disabled but keep their values, so switching modes does not lose them. **DNS proxy** lists the routing rules by position, endpoint, and applications; selecting one stores that rule's stable `id` in `dns.proxyId`, assigning an id such as `proxy-1` to the rule if it has none, its id is invalid, or another rule uses the same id. Switching the mode to `Proxy` does the same for the rule already shown. When several rules share the referenced id, the selector shows the first, which is the rule validation and the service use. Ids that DNS does not use and that are invalid or repeated are reported as warnings and removed on the next save. The reference therefore survives **Move Up**/**Move Down**, editing, saving, and reloading. **Duplicate** clears the id on the copy. If the referenced rule is removed, the selector shows the missing id and validation fails until another rule is chosen; the GUI never substitutes a different proxy. Validation also requires the selected rule to support both TCP and UDP and checks that the server override is an IP literal whose address family the rule accepts. Like other engine settings, DNS changes take effect after **Apply & Restart**. +The **DNS routing** group on the **Settings / Diagnostics** tab edits the global `dns` section described in the [configuration reference](configuration.md#dns-routing). **DNS mode** selects `Direct` (default) or `Proxy`. In `Direct` mode the **DNS proxy** and **Server override** fields are disabled but keep their values, so switching modes does not lose them. **DNS proxy** lists the routing rules by position, endpoint, and applications; selecting one stores that rule's stable `id` in `dns.proxyId`, assigning an id such as `proxy-1` to the rule if it has none, its id is invalid, or another rule uses the same id. Switching the mode to `Proxy`, or opening and closing the list, does the same for the rule already shown; moving the selection on gives a rule the id it had before. When several rules share the referenced id, the selector shows the first, which is the rule validation and the service use. Ids that DNS does not use and that are invalid or repeated are reported as warnings and removed on the next save. The reference therefore survives **Move Up**/**Move Down**, editing, saving, and reloading. **Duplicate** clears the id on the copy. If the referenced rule is removed, the selector shows the missing id and validation fails until another rule is chosen; the GUI never substitutes a different proxy. Validation also requires the selected rule to support both TCP and UDP and checks that the server override is an IP literal whose address family the rule accepts. Like other engine settings, DNS changes take effect after **Apply & Restart**. ## Save, apply, conflicts, and recovery From b14a9c00b5b9abd2a1f21029421f4d0634ddbdda Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 22:04:12 +0000 Subject: [PATCH 57/62] fix(gui): keep following a rule given a DNS id across edits; review round 14 nits - The rule editor returns a copy, so the DNS proxy selector now follows the copy (and forgets a removed rule); moving the selection on after an edit restores the rule's previous id instead of leaving the assigned one. - The Direct-mode warning names the repair that works there: switching DNS to Proxy mode in the GUI. - Docs: gui.md states the dns.proxyId exception for dropped ids; the upgrade notes say an existing dns object with an unknown mode, or Proxy mode without a usable proxyId, also stops the service. --- ProxiFyre.Configuration/ConfigurationValidator.cs | 4 ++-- ProxiFyreUI/Forms/MainForm.cs | 6 ++++++ README.md | 2 +- docs/configuration.md | 1 + docs/gui.md | 2 +- 5 files changed, 11 insertions(+), 4 deletions(-) diff --git a/ProxiFyre.Configuration/ConfigurationValidator.cs b/ProxiFyre.Configuration/ConfigurationValidator.cs index d7ef226..99c2ea1 100644 --- a/ProxiFyre.Configuration/ConfigurationValidator.cs +++ b/ProxiFyre.Configuration/ConfigurationValidator.cs @@ -571,8 +571,8 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC private static string UnusedIdConsequence(bool namedByDirectModeDns) { return namedByDirectModeDns - ? " dns.proxyId names it, so it is kept, but DNS Proxy mode cannot use it as it is; select the rule " + - "as the DNS proxy again in the GUI, which assigns a new id, or fix the id and dns.proxyId." + ? " dns.proxyId names it, so it is kept, but DNS Proxy mode cannot use it as it is; switching DNS " + + "to Proxy mode in the GUI assigns the rule a new id, or fix the id and dns.proxyId." : " No DNS setting uses it, so it has no effect and is removed when the GUI saves the configuration."; } diff --git a/ProxiFyreUI/Forms/MainForm.cs b/ProxiFyreUI/Forms/MainForm.cs index ad7cd8c..c87dec1 100644 --- a/ProxiFyreUI/Forms/MainForm.cs +++ b/ProxiFyreUI/Forms/MainForm.cs @@ -527,6 +527,10 @@ private void EditRuleButton_Click(object sender, EventArgs e) return; if (!CanCommitDialogMutation(configuration)) return; + // The editor returns a copy (with the same id); keep following the rule if the DNS + // proxy selector gave it its id, so moving the selection on still restores it. + if (ReferenceEquals(_dnsIdAssignedRule, configuration.Proxies[index])) + _dnsIdAssignedRule = editor.ResultRule; configuration.Proxies[index] = editor.ResultRule; MarkConfigurationChanged(); RefreshRoutingGrid(index); @@ -562,6 +566,8 @@ private void RemoveRuleButton_Click(object sender, EventArgs e) return; if (!CanCommitDialogMutation(configuration)) return; + if (ReferenceEquals(_dnsIdAssignedRule, configuration.Proxies[index])) + _dnsIdAssignedRule = null; configuration.Proxies.RemoveAt(index); MarkConfigurationChanged(); RefreshRoutingGrid(Math.Min(index, configuration.Proxies.Count - 1)); diff --git a/README.md b/README.md index b9c488f..1dde0ba 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,7 @@ In `Proxy` mode DNS is not sent directly: if the selected proxy cannot carry a q > [!IMPORTANT] > **Upgrade note — DNS over TCP port 53.** In the default `Direct` DNS mode, which also applies to existing configurations without a `dns` section, DNS over TCP port 53 now always bypasses the proxies, as DNS over UDP port 53 already did. Rules that previously carried TCP port 53 through a proxy, for example a catch-all rule, no longer do so. To route DNS through a proxy, use DNS `Proxy` mode. > -> **Upgrade note — `id` and `dns` keys.** Earlier releases ignored a rule property named `id` and a top-level property named `dns`; both are now interpreted. An invalid or duplicate `id` is only a warning unless DNS `Proxy` mode refers to it, and an empty `id` means no id. A `dns` value other than an object or `null`, such as `"dns": "8.8.8.8"`, is a configuration error and the service does not start until it is removed or replaced with a DNS policy object. +> **Upgrade note — `id` and `dns` keys.** Earlier releases ignored a rule property named `id` and a top-level property named `dns`; both are now interpreted. An invalid or duplicate `id` is only a warning unless DNS `Proxy` mode refers to it, and an empty `id` means no id. A `dns` value other than an object or `null`, such as `"dns": "8.8.8.8"`, is a configuration error and the service does not start until it is removed or replaced with a DNS policy object. So is a `dns` object with a `mode` other than `Direct` or `Proxy`, or with `Proxy` mode and no `proxyId` naming an existing rule. See the [configuration reference](docs/configuration.md) for matching rules, authentication, LAN bypass, DNS routing, logging, TLS options, and complete examples. The repository also includes a ready-to-edit [sample configuration](app-config.sample.json). diff --git a/docs/configuration.md b/docs/configuration.md index 3872434..37844a7 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -153,6 +153,7 @@ Configurations written before DNS routing existed load and save unchanged. The e - A rule `id` that is invalid or duplicated, including one written as a JSON object or array, is only a warning unless DNS `Proxy` mode refers to it, so such a configuration still starts; the GUI removes it on the next save unless `dns.proxyId` names it. An empty `id` means no id. A number or `true`/`false` is read as its text, for example `1.0` as `1`. - A `dns` value must be an object (or `null`, which means `Direct`), and its `mode`, `proxyId`, and `serverOverride` must not be objects or arrays. Anything else, such as `"dns": "8.8.8.8"`, is a configuration error that names the property, and the service does not start until it is removed or replaced with a DNS policy object. +- A `dns` object is validated like a new one: a `mode` other than `Direct` or `Proxy` (`DNS_MODE_UNKNOWN`), or `Proxy` mode whose `proxyId` is missing or names no rule (`DNS_PROXY_ID_MISSING`, `DNS_PROXY_NOT_FOUND`), also stops the service. ### Direct mode diff --git a/docs/gui.md b/docs/gui.md index 119285d..0dcdef2 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -60,7 +60,7 @@ SOCKS5-over-TLS protects the TCP control connection (including the UDP `ASSOCIAT ### DNS routing -The **DNS routing** group on the **Settings / Diagnostics** tab edits the global `dns` section described in the [configuration reference](configuration.md#dns-routing). **DNS mode** selects `Direct` (default) or `Proxy`. In `Direct` mode the **DNS proxy** and **Server override** fields are disabled but keep their values, so switching modes does not lose them. **DNS proxy** lists the routing rules by position, endpoint, and applications; selecting one stores that rule's stable `id` in `dns.proxyId`, assigning an id such as `proxy-1` to the rule if it has none, its id is invalid, or another rule uses the same id. Switching the mode to `Proxy`, or opening and closing the list, does the same for the rule already shown; moving the selection on gives a rule the id it had before. When several rules share the referenced id, the selector shows the first, which is the rule validation and the service use. Ids that DNS does not use and that are invalid or repeated are reported as warnings and removed on the next save. The reference therefore survives **Move Up**/**Move Down**, editing, saving, and reloading. **Duplicate** clears the id on the copy. If the referenced rule is removed, the selector shows the missing id and validation fails until another rule is chosen; the GUI never substitutes a different proxy. Validation also requires the selected rule to support both TCP and UDP and checks that the server override is an IP literal whose address family the rule accepts. Like other engine settings, DNS changes take effect after **Apply & Restart**. +The **DNS routing** group on the **Settings / Diagnostics** tab edits the global `dns` section described in the [configuration reference](configuration.md#dns-routing). **DNS mode** selects `Direct` (default) or `Proxy`. In `Direct` mode the **DNS proxy** and **Server override** fields are disabled but keep their values, so switching modes does not lose them. **DNS proxy** lists the routing rules by position, endpoint, and applications; selecting one stores that rule's stable `id` in `dns.proxyId`, assigning an id such as `proxy-1` to the rule if it has none, its id is invalid, or another rule uses the same id. Switching the mode to `Proxy`, or opening and closing the list, does the same for the rule already shown; moving the selection on gives a rule the id it had before. When several rules share the referenced id, the selector shows the first, which is the rule validation and the service use. Ids that are invalid or repeated are reported as warnings and, unless `dns.proxyId` names them, removed on the next save. The reference therefore survives **Move Up**/**Move Down**, editing, saving, and reloading. **Duplicate** clears the id on the copy. If the referenced rule is removed, the selector shows the missing id and validation fails until another rule is chosen; the GUI never substitutes a different proxy. Validation also requires the selected rule to support both TCP and UDP and checks that the server override is an IP literal whose address family the rule accepts. Like other engine settings, DNS changes take effect after **Apply & Restart**. ## Save, apply, conflicts, and recovery From f4981eee29591c87fa568ca7f48dec47a5a81e66 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 22:11:56 +0000 Subject: [PATCH 58/62] fix(config): name the rule a repeated id resolves to in id messages - A referenced invalid id that an earlier rule also has is reported as ambiguous and names that rule, like a referenced duplicate, so following the message from the later rule's row does not move DNS to another rule. - The Direct-mode warning for a repeated id names the first rule with it, which is the rule the GUI shows and repairs on a switch to Proxy mode. - Docs: how JSON true/false and numbers become id text; which rule the DNS proxy selector shows for a shared id. --- .../ConfigurationValidator.cs | 40 ++++++++++++++----- ProxiFyre.Tests/DnsConfigurationTests.cs | 28 +++++++++++++ docs/configuration.md | 2 +- docs/gui.md | 2 +- 4 files changed, 60 insertions(+), 12 deletions(-) diff --git a/ProxiFyre.Configuration/ConfigurationValidator.cs b/ProxiFyre.Configuration/ConfigurationValidator.cs index 99c2ea1..5a5f30f 100644 --- a/ProxiFyre.Configuration/ConfigurationValidator.cs +++ b/ProxiFyre.Configuration/ConfigurationValidator.cs @@ -517,6 +517,7 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC var referencedId = DnsConfiguration.GetReferencedProxyId(dns); var namedId = DnsConfiguration.GetNamedProxyId(dns); var seen = new Dictionary(StringComparer.OrdinalIgnoreCase); + var seenInvalid = new Dictionary(StringComparer.OrdinalIgnoreCase); for (var index = 0; index < rules.Count; index++) { var id = rules[index] == null ? null : rules[index].Id; @@ -528,24 +529,38 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC string.Equals(trimmed, referencedId, StringComparison.OrdinalIgnoreCase); var named = namedId != null && string.Equals(trimmed, namedId, StringComparison.OrdinalIgnoreCase); + int firstIndex; if (!DnsConfiguration.IsValidProxyId(trimmed)) { + // A repeated invalid id is reported against the first rule that has it, which is + // the rule the DNS proxy selector, the validator and the service resolve it to. + int? firstInvalidIndex = null; + if (seenInvalid.TryGetValue(trimmed, out firstIndex)) + firstInvalidIndex = firstIndex; + else + seenInvalid.Add(trimmed, index); + var message = "A proxy id must contain 1 to " + DnsConfiguration.MaximumProxyIdLength + " letters, digits, '-', '_', or '.' characters."; + if (firstInvalidIndex.HasValue) + message += " Rule " + (firstInvalidIndex.Value + 1) + " has the same id."; issues.Add(referenced ? Error("PROXY_ID_INVALID", - message + " dns.proxyId refers to this id. Select the rule as the DNS proxy again in " + - "the GUI, which assigns a valid id, or give the rule a valid id and update dns.proxyId.", + message + (firstInvalidIndex.HasValue + ? " dns.proxyId refers to this id, so the DNS proxy would be ambiguous. Select the " + + "intended rule as the DNS proxy again in the GUI, which assigns it a valid id, or " + + "give the rules valid, unique ids and update dns.proxyId." + : " dns.proxyId refers to this id. Select the rule as the DNS proxy again in the GUI, " + + "which assigns a valid id, or give the rule a valid id and update dns.proxyId."), RulePath(index) + ".id", index) : Warning("PROXY_ID_INVALID", - message + UnusedIdConsequence(named), + message + UnusedIdConsequence(named, firstInvalidIndex), RulePath(index) + ".id", index)); continue; } - int firstIndex; if (seen.TryGetValue(trimmed, out firstIndex)) { var message = "The proxy id '" + trimmed + "' is already used by rule " + (firstIndex + 1) + @@ -558,7 +573,7 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC RulePath(index) + ".id", index) : Warning("PROXY_ID_DUPLICATE", - message + UnusedIdConsequence(named), + message + UnusedIdConsequence(named, firstIndex), RulePath(index) + ".id", index)); continue; @@ -568,12 +583,17 @@ private static void ValidateProxyIds(IList rules, DnsSettings dns, IC } } - private static string UnusedIdConsequence(bool namedByDirectModeDns) + /// dns.proxyId names the id while DNS is not in Proxy mode. + /// The first rule with the same id when this rule repeats it; + /// the DNS proxy selector shows, and Proxy mode would use, that rule. + private static string UnusedIdConsequence(bool namedByDirectModeDns, int? firstRuleWithId = null) { - return namedByDirectModeDns - ? " dns.proxyId names it, so it is kept, but DNS Proxy mode cannot use it as it is; switching DNS " + - "to Proxy mode in the GUI assigns the rule a new id, or fix the id and dns.proxyId." - : " No DNS setting uses it, so it has no effect and is removed when the GUI saves the configuration."; + if (!namedByDirectModeDns) + return " No DNS setting uses it, so it has no effect and is removed when the GUI saves the configuration."; + + var repaired = firstRuleWithId.HasValue ? "rule " + (firstRuleWithId.Value + 1) : "the rule"; + return " dns.proxyId names it, so it is kept, but DNS Proxy mode cannot use it as it is; switching DNS " + + "to Proxy mode in the GUI assigns " + repaired + " a new id, or fix the id and dns.proxyId."; } private static void ValidateDns(DnsSettings dns, IList rules, ICollection issues) diff --git a/ProxiFyre.Tests/DnsConfigurationTests.cs b/ProxiFyre.Tests/DnsConfigurationTests.cs index 3a4f9a7..034a530 100644 --- a/ProxiFyre.Tests/DnsConfigurationTests.cs +++ b/ProxiFyre.Tests/DnsConfigurationTests.cs @@ -416,6 +416,34 @@ public void SavingKeepsTheIdDirectModeStillNames() Assert.That(DnsConfiguration.FindProxyRuleIndex(normalized.Proxies, normalized.Dns.ProxyId), Is.EqualTo(1)); } + [Test] + public void RepeatedInvalidReferencedIdIsReportedAsAmbiguous() + { + var configuration = TwoProxyConfiguration(); + configuration.Proxies[0].Id = "bad id"; + configuration.Proxies[1].Id = "BAD ID"; + configuration.Dns.ProxyId = "bad id"; + + var issues = _validator.Validate(configuration).Errors.Where(issue => issue.Code == "PROXY_ID_INVALID").ToList(); + + Assert.That(issues.Select(issue => issue.Path), Is.EqualTo(new[] { "proxies[0].id", "proxies[1].id" })); + StringAssert.DoesNotContain("ambiguous", issues[0].Message); + StringAssert.Contains("Rule 1 has the same id", issues[1].Message); + StringAssert.Contains("ambiguous", issues[1].Message); + } + + [Test] + public void DirectModeDuplicateWarningNamesTheRuleTheGuiRepairs() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns = new DnsSettings { Mode = "Direct", ProxyId = "office" }; + configuration.Proxies[1].Id = "office"; + + var warning = HasWarning(_validator.Validate(configuration), "PROXY_ID_DUPLICATE", "proxies[1].id"); + + StringAssert.Contains("assigns rule 1 a new id", warning.Message); + } + [Test] public void NormalizingIsIdempotentForIds() { diff --git a/docs/configuration.md b/docs/configuration.md index 37844a7..f4c1c39 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -151,7 +151,7 @@ The optional `dns` object controls conventional DNS: UDP and TCP traffic to dest Configurations written before DNS routing existed load and save unchanged. The exceptions are configurations that already contained a rule property named `id` or a top-level property named `dns`. Earlier releases preserved and ignored both; they are now interpreted: -- A rule `id` that is invalid or duplicated, including one written as a JSON object or array, is only a warning unless DNS `Proxy` mode refers to it, so such a configuration still starts; the GUI removes it on the next save unless `dns.proxyId` names it. An empty `id` means no id. A number or `true`/`false` is read as its text, for example `1.0` as `1`. +- A rule `id` that is invalid or duplicated, including one written as a JSON object or array, is only a warning unless DNS `Proxy` mode refers to it, so such a configuration still starts; the GUI removes it on the next save unless `dns.proxyId` names it. An empty `id` means no id. A number or `true`/`false` is read as text the way .NET formats it, for example `1.0` as `1` and `true` as `True`. - A `dns` value must be an object (or `null`, which means `Direct`), and its `mode`, `proxyId`, and `serverOverride` must not be objects or arrays. Anything else, such as `"dns": "8.8.8.8"`, is a configuration error that names the property, and the service does not start until it is removed or replaced with a DNS policy object. - A `dns` object is validated like a new one: a `mode` other than `Direct` or `Proxy` (`DNS_MODE_UNKNOWN`), or `Proxy` mode whose `proxyId` is missing or names no rule (`DNS_PROXY_ID_MISSING`, `DNS_PROXY_NOT_FOUND`), also stops the service. diff --git a/docs/gui.md b/docs/gui.md index 0dcdef2..e6f52f5 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -60,7 +60,7 @@ SOCKS5-over-TLS protects the TCP control connection (including the UDP `ASSOCIAT ### DNS routing -The **DNS routing** group on the **Settings / Diagnostics** tab edits the global `dns` section described in the [configuration reference](configuration.md#dns-routing). **DNS mode** selects `Direct` (default) or `Proxy`. In `Direct` mode the **DNS proxy** and **Server override** fields are disabled but keep their values, so switching modes does not lose them. **DNS proxy** lists the routing rules by position, endpoint, and applications; selecting one stores that rule's stable `id` in `dns.proxyId`, assigning an id such as `proxy-1` to the rule if it has none, its id is invalid, or another rule uses the same id. Switching the mode to `Proxy`, or opening and closing the list, does the same for the rule already shown; moving the selection on gives a rule the id it had before. When several rules share the referenced id, the selector shows the first, which is the rule validation and the service use. Ids that are invalid or repeated are reported as warnings and, unless `dns.proxyId` names them, removed on the next save. The reference therefore survives **Move Up**/**Move Down**, editing, saving, and reloading. **Duplicate** clears the id on the copy. If the referenced rule is removed, the selector shows the missing id and validation fails until another rule is chosen; the GUI never substitutes a different proxy. Validation also requires the selected rule to support both TCP and UDP and checks that the server override is an IP literal whose address family the rule accepts. Like other engine settings, DNS changes take effect after **Apply & Restart**. +The **DNS routing** group on the **Settings / Diagnostics** tab edits the global `dns` section described in the [configuration reference](configuration.md#dns-routing). **DNS mode** selects `Direct` (default) or `Proxy`. In `Direct` mode the **DNS proxy** and **Server override** fields are disabled but keep their values, so switching modes does not lose them. **DNS proxy** lists the routing rules by position, endpoint, and applications; selecting one stores that rule's stable `id` in `dns.proxyId`, assigning an id such as `proxy-1` to the rule if it has none, its id is invalid, or another rule uses the same id. Switching the mode to `Proxy`, or opening and closing the list, does the same for the rule already shown; moving the selection on gives a rule the id it had before. When several rules share the referenced id, the selector shows the first, which is the rule validation and the service resolve the id to. Ids that are invalid or repeated are reported as warnings and, unless `dns.proxyId` names them, removed on the next save. The reference therefore survives **Move Up**/**Move Down**, editing, saving, and reloading. **Duplicate** clears the id on the copy. If the referenced rule is removed, the selector shows the missing id and validation fails until another rule is chosen; the GUI never substitutes a different proxy. Validation also requires the selected rule to support both TCP and UDP and checks that the server override is an IP literal whose address family the rule accepts. Like other engine settings, DNS changes take effect after **Apply & Restart**. ## Save, apply, conflicts, and recovery From e243699a2e22a1016937a14ffd351f3c35cdfa2f Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Fri, 13 Nov 2026 22:20:34 +0000 Subject: [PATCH 59/62] fix(config): report id or dns keys that differ only in case A rule with both "id" and "ID", or a configuration with both "dns" and "DNS", silently kept only one of the values, while earlier releases kept both as unknown data. Both are now a configuration error that names the keys. Docs: which rules keep a repeated or named id when saving. --- .../ConfigurationSerializer.cs | 23 +++++++++++++++++-- ProxiFyre.Tests/DnsConfigurationTests.cs | 11 ++++++++- README.md | 2 +- docs/configuration.md | 3 ++- 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/ProxiFyre.Configuration/ConfigurationSerializer.cs b/ProxiFyre.Configuration/ConfigurationSerializer.cs index e5359db..0bd5902 100644 --- a/ProxiFyre.Configuration/ConfigurationSerializer.cs +++ b/ProxiFyre.Configuration/ConfigurationSerializer.cs @@ -107,17 +107,24 @@ public ProxiFyreConfiguration Deserialize(string json) /// ignored them. A rule id that is an object or array is turned into its JSON text, which /// the validator then reports as an invalid id (a warning unless DNS uses it), so such a /// configuration still loads. A "dns" value that is not an object, or a DNS setting that - /// is an object or array, is a configuration error that names the property. + /// is an object or array, is a configuration error that names the property. So are two + /// "id" (or "dns") keys that differ only in case: earlier releases kept both, and reading + /// one would silently discard the other. /// private static void PrepareKeysEarlierReleasesIgnored(JObject root) { + RejectCaseVariants(root, "dns", "The configuration"); foreach (var proxies in PropertiesNamed(root, "proxies")) { var rules = proxies.Value as JArray; if (rules == null) continue; - foreach (var rule in rules.OfType()) + for (var index = 0; index < rules.Count; index++) { + var rule = rules[index] as JObject; + if (rule == null) + continue; + RejectCaseVariants(rule, "id", "Proxy rule " + (index + 1)); foreach (var id in PropertiesNamed(rule, "id")) { if (id.Value.Type == JTokenType.Object || id.Value.Type == JTokenType.Array) @@ -151,6 +158,18 @@ private static void PrepareKeysEarlierReleasesIgnored(JObject root) } } + private static void RejectCaseVariants(JObject parent, string name, string owner) + { + var variants = PropertiesNamed(parent, name); + if (variants.Length > 1) + { + throw new ConfigurationFormatException( + owner + " has more than one '" + name + "' property (" + + string.Join(", ", variants.Select(p => "'" + p.Name + "'")) + + "); names differ only in case. Keep one of them."); + } + } + private static JProperty[] PropertiesNamed(JObject parent, string name) { return parent.Properties() diff --git a/ProxiFyre.Tests/DnsConfigurationTests.cs b/ProxiFyre.Tests/DnsConfigurationTests.cs index 034a530..5119ff3 100644 --- a/ProxiFyre.Tests/DnsConfigurationTests.cs +++ b/ProxiFyre.Tests/DnsConfigurationTests.cs @@ -325,7 +325,7 @@ public void DnsValueThatIsNotAnObjectIsReportedByName(string value) StringAssert.Contains("'dns'", exception.Message); } - [TestCase("{ \"dns\": {}, \"DNS\": \"8.8.8.8\" }", "'DNS'")] + [TestCase("{ \"DNS\": \"8.8.8.8\" }", "'DNS'")] [TestCase("{ \"dns\": { \"proxyId\": [1] } }", "'dns.proxyId'")] [TestCase("{ \"dns\": { \"Mode\": {} } }", "'dns.Mode'")] [TestCase("{ \"dns\": { \"serverOverride\": { \"a\": 1 } } }", "'dns.serverOverride'")] @@ -335,6 +335,15 @@ public void MalformedDnsSettingsAreReportedByName(string json, string name) StringAssert.Contains(name, exception.Message); } + [TestCase("{ \"proxies\": [ { \"appNames\": [\"a\"] }, { \"ID\": \"x\", \"id\": \"y\" } ] }", "Proxy rule 2", "'ID', 'id'")] + [TestCase("{ \"dns\": { \"mode\": \"Direct\" }, \"Dns\": null }", "The configuration", "'dns', 'Dns'")] + public void KeysDifferingOnlyInCaseAreReportedInsteadOfDiscarded(string json, string owner, string names) + { + var exception = Assert.Throws(() => _serializer.Deserialize(json)); + StringAssert.Contains(owner, exception.Message); + StringAssert.Contains(names, exception.Message); + } + [TestCase("{}")] [TestCase("[1]")] public void RuleIdThatIsNotAStringStillLoadsAndIsOnlyAWarning(string id) diff --git a/README.md b/README.md index 1dde0ba..00b1b20 100644 --- a/README.md +++ b/README.md @@ -98,7 +98,7 @@ In `Proxy` mode DNS is not sent directly: if the selected proxy cannot carry a q > [!IMPORTANT] > **Upgrade note — DNS over TCP port 53.** In the default `Direct` DNS mode, which also applies to existing configurations without a `dns` section, DNS over TCP port 53 now always bypasses the proxies, as DNS over UDP port 53 already did. Rules that previously carried TCP port 53 through a proxy, for example a catch-all rule, no longer do so. To route DNS through a proxy, use DNS `Proxy` mode. > -> **Upgrade note — `id` and `dns` keys.** Earlier releases ignored a rule property named `id` and a top-level property named `dns`; both are now interpreted. An invalid or duplicate `id` is only a warning unless DNS `Proxy` mode refers to it, and an empty `id` means no id. A `dns` value other than an object or `null`, such as `"dns": "8.8.8.8"`, is a configuration error and the service does not start until it is removed or replaced with a DNS policy object. So is a `dns` object with a `mode` other than `Direct` or `Proxy`, or with `Proxy` mode and no `proxyId` naming an existing rule. +> **Upgrade note — `id` and `dns` keys.** Earlier releases ignored a rule property named `id` and a top-level property named `dns`; both are now interpreted. An invalid or duplicate `id` is only a warning unless DNS `Proxy` mode refers to it, and an empty `id` means no id. A `dns` value other than an object or `null`, such as `"dns": "8.8.8.8"`, is a configuration error and the service does not start until it is removed or replaced with a DNS policy object. So is a `dns` object with a `mode` other than `Direct` or `Proxy`, or with `Proxy` mode and no `proxyId` naming an existing rule. Keys that differ only in case, such as `id` and `ID` in one rule, are an error too. See the [configuration reference](docs/configuration.md) for matching rules, authentication, LAN bypass, DNS routing, logging, TLS options, and complete examples. The repository also includes a ready-to-edit [sample configuration](app-config.sample.json). diff --git a/docs/configuration.md b/docs/configuration.md index f4c1c39..951ea82 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -70,7 +70,7 @@ Process ownership lookup is best effort for a standard user. ProxiFyre can route | Property | Description | | --- | --- | -| `id` | Optional stable identifier used to reference this rule's proxy, for example from `dns.proxyId`. 1–64 letters, digits, `-`, `_`, or `.`; unique, case-insensitive. Unlike the rule position it survives reordering. An empty or whitespace id means no id. An invalid or duplicate id is an error only when `dns.proxyId` in `Proxy` mode refers to it; otherwise it is reported as a warning, has no effect, and is removed when the GUI saves the configuration, unless `dns.proxyId` names it (the first rule with a duplicated id keeps it). | +| `id` | Optional stable identifier used to reference this rule's proxy, for example from `dns.proxyId`. 1–64 letters, digits, `-`, `_`, or `.`; unique, case-insensitive. Unlike the rule position it survives reordering. An empty or whitespace id means no id. An invalid or duplicate id is an error only when `dns.proxyId` in `Proxy` mode refers to it; otherwise it is reported as a warning, has no effect, and is removed when the GUI saves the configuration. Two exceptions: every rule with an id that `dns.proxyId` names keeps it, and of rules sharing any other valid id, the first keeps it. | | `appNames` | Application names or paths matched by this rule. An explicit empty string is the catch-all. | | `socks5ProxyEndpoint` | SOCKS5 hostname or IPv4 address plus port, for example `proxy.example.com:1080`. | | `username`, `password` | Optional SOCKS5 authentication. Configure both or neither. | @@ -153,6 +153,7 @@ Configurations written before DNS routing existed load and save unchanged. The e - A rule `id` that is invalid or duplicated, including one written as a JSON object or array, is only a warning unless DNS `Proxy` mode refers to it, so such a configuration still starts; the GUI removes it on the next save unless `dns.proxyId` names it. An empty `id` means no id. A number or `true`/`false` is read as text the way .NET formats it, for example `1.0` as `1` and `true` as `True`. - A `dns` value must be an object (or `null`, which means `Direct`), and its `mode`, `proxyId`, and `serverOverride` must not be objects or arrays. Anything else, such as `"dns": "8.8.8.8"`, is a configuration error that names the property, and the service does not start until it is removed or replaced with a DNS policy object. +- A rule with two `id` keys that differ only in case (`id` and `ID`), or two top-level `dns` keys, is a configuration error that names them, because reading one would discard the other. - A `dns` object is validated like a new one: a `mode` other than `Direct` or `Proxy` (`DNS_MODE_UNKNOWN`), or `Proxy` mode whose `proxyId` is missing or names no rule (`DNS_PROXY_ID_MISSING`, `DNS_PROXY_NOT_FOUND`), also stops the service. ### Direct mode From 216bcf697aaeba496842068b6aa29da535464226 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Sat, 14 Nov 2026 08:00:21 +0100 Subject: [PATCH 60/62] fix(dns): drop ICMP errors that quote a DNS answer in Proxy mode In Proxy mode a DNS answer is written by the DNS proxy's local listener and presented as coming from the server the client queried. When the client's socket has already closed (the answer to a retransmitted query, a client that gave up), Windows reports the datagram with an ICMP "port unreachable" error addressed to that server, and the error quotes the whole answer. The answer then left the adapter in clear, from the computer's own address. Found during Windows validation: 3 such errors in 150 s of browsing, reproducible by closing the socket right after sending a query. - In Proxy mode a REDIRECT driver filter for outbound ICMP and ICMPv6 is placed at the front of the table, ahead of the ICMP PASS and LAN-bypass filters, so the errors reach user mode. A filter that cannot be installed fails the start, like the other Proxy-mode filters. - An outbound ICMP or ICMPv6 error that quotes a UDP datagram or TCP segment sent from port 53 is dropped. Other ICMP, such as ping, is passed, and Direct mode is unchanged. The first drop per run is logged at info level, counts at debug level. - The parsing and the decision are in dns_routing_policy.h and covered by tests: quoted source port for ICMP and ICMPv6 errors (IP options, extension and first-fragment headers, later fragments, truncation, non-error types), the decision per mode, and the filter plan. - Docs: the behaviour in configuration.md, and a capture filter for it in validation step 2 of gui.md. Application UDP through the per-port UDP proxy has the same ICMP behaviour (as on main) and is not changed here. --- docs/configuration.md | 2 + docs/gui.md | 2 +- netlib/src/proxy/dns_routing_policy.h | 165 ++++++++++++++++++ netlib/src/proxy/socks_local_router.h | 107 ++++++++++++ netlib/test/proxy/dns_routing_policy_test.cpp | 160 +++++++++++++++++ 5 files changed, 435 insertions(+), 1 deletion(-) diff --git a/docs/configuration.md b/docs/configuration.md index 951ea82..97e37f5 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -187,6 +187,8 @@ Whether name resolution still succeeds after a drop depends on Windows: it retri Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. +An answer can arrive after the application has closed its socket, for example the answer to a query Windows had already retransmitted. Windows then reports the datagram with an ICMP "port unreachable" error addressed to the DNS server the application queried, and that error quotes the answer. Because the answer came from the DNS proxy and not from that server, ProxiFyre drops outbound ICMP and ICMPv6 errors that quote a packet sent from port 53 in `Proxy` mode, so the answer does not leave the computer in clear. Other ICMP traffic, such as `ping`, is passed. The first such drop after the service starts is logged at `Info` and later ones are counted at `Debug`. + If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. The selection is made by `proxyId`, never by position, so reordering rules does not change the DNS proxy. If the referenced rule is removed or renamed, validation fails with `DNS_PROXY_NOT_FOUND`; ProxiFyre never silently switches to another proxy. The GUI assigns an id such as `proxy-1` to a rule when it is selected as the DNS proxy and the rule has no id, an invalid id, or an id another rule also uses, and it clears the id on a duplicated copy. diff --git a/docs/gui.md b/docs/gui.md index e6f52f5..0b44a1d 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -162,7 +162,7 @@ On a Windows test machine with the appropriate driver and administrator access: The routing policy and the packet rewriting are covered by automated tests (`netlib-tests` and `netlib/test/portable/run-portable-tests.sh`); the end-to-end path through the driver and a live SOCKS5 server needs a Windows test machine. Capture with Wireshark on the physical adapter and use `Resolve-DnsName -Server -DnsOnly` (UDP) and `Resolve-DnsName -TcpOnly` (TCP), running `ipconfig /flushdns` before each step: 1. With no `dns` section (or `Direct`), confirm UDP and TCP queries to the system resolver and to `8.8.8.8` leave the adapter directly for IPv4 and IPv6, including with a catch-all rule. -2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). Browse for a few minutes and confirm the SOCKS5 server sees one control connection and one `UDP ASSOCIATE` per address family for UDP DNS, not one per query. +2. Configure two proxies with ids and select the second in `Proxy` mode. Confirm no port-53 packets leave the adapter, that the second SOCKS5 server receives `UDP ASSOCIATE`/`CONNECT` requests, and that name resolution works from a browser (Dnscache) and from `nslookup 8.8.8.8` (own resolver). Browse for a few minutes and confirm the SOCKS5 server sees one control connection and one `UDP ASSOCIATE` per address family for UDP DNS, not one per query. Also confirm that no ICMP error quoting a DNS answer leaves the adapter (Wireshark: `(icmp.type == 3 && udp.srcport == 53) || (icmpv6.type == 1 && udp.srcport == 53)`); to provoke one, send a query and close the socket before the answer arrives. 3. Enable `bypassLan` with a router resolver (`192.168.x.1`): without an override the SOCKS5 server is asked for the router address; with `serverOverride: "1.1.1.1"` it is asked for `1.1.1.1` and `Resolve-DnsName` still reports answers from the router address. 4. Reorder the rules, Apply & Restart, and confirm DNS still uses the selected proxy. 5. Stop the SOCKS5 server (or block it with a firewall rule) and confirm queries fail and no port-53 packet leaves the adapter; the engine log has one "could not open a SOCKS5 UDP association" warning per address family in use, and attempts back off to about one every 30 seconds (plus the 5-second connect timeout when the server is black-holed). Start the SOCKS5 server again and confirm lookups recover within about 35 seconds. Restart the SOCKS5 server while ProxiFyre runs and confirm the association is reopened ("closing the SOCKS5 UDP association" and "opened" at `Info`) and lookups recover. Configure Windows with a second DNS server the SOCKS5 server cannot reach (for example a LAN address, without `serverOverride`), browse for two minutes, and confirm the log has no "queries stopped being answered" line. Stop the service while the SOCKS5 server is unreachable (black-holed, not refusing) and confirm it stops within a few seconds. Finally, with `serverOverride` removed and Windows using only a resolver the SOCKS5 server cannot reach (a LAN address), confirm one "no answer came back through the SOCKS5 UDP association" warning per address family in use within about a minute, not repeated; then set `serverOverride` and confirm lookups work. Then configure an IPv4-only DNS proxy rule and confirm IPv6 queries are dropped with one DNS routing warning for that cause and a throttled drop count. diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 629b806..5765dfa 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -448,6 +448,171 @@ namespace proxy return translated ? listener_reply_action::revert : listener_reply_action::drop; } + // --------------------------------------------------------------------------------------- + // ICMP errors about DNS answers + // + // In Proxy mode an answer from port 53 that reaches a client was written by the DNS proxy's + // local listener and only presented as coming from the server the client queried. When the + // client's socket has closed by then (the answer to a retransmitted query, a client that + // gave up), the TCP/IP stack reports the datagram with an ICMP error addressed to that + // server, which never sent it. The error quotes the datagram, so the DNS answer would leave + // the adapter in clear and from the computer's own address. Such errors are dropped. + // --------------------------------------------------------------------------------------- + + /// Whether an ICMP (IPv4) message type is an error message, which quotes the packet it is about. + [[nodiscard]] constexpr bool is_icmpv4_error(const uint8_t type) noexcept + { + // Destination unreachable, source quench, redirect, time exceeded, parameter problem. + return type == 3 || type == 4 || type == 5 || type == 11 || type == 12; + } + + /// Whether an ICMPv6 message type is an error message (RFC 4443: types below 128). + [[nodiscard]] constexpr bool is_icmpv6_error(const uint8_t type) noexcept + { + return type < 128; + } + + /** + * @brief The source port of the UDP datagram or TCP segment an ICMP (IPv4) error quotes. + * + * Returns std::nullopt when the message is not an error, quotes another protocol or a later + * fragment (whose first bytes are not ports), or is truncated before the quoted source port. + * + * @param icmp_message The ICMP header followed by the quoted packet. + * @return The quoted source port in host byte order. + */ + [[nodiscard]] constexpr std::optional icmpv4_error_quoted_source_port( + const uint8_t* icmp_message, const std::size_t size) noexcept + { + constexpr std::size_t icmp_header_size = 8, minimum_ipv4_header_size = 20; + constexpr uint8_t tcp = 6, udp = 17; + + if (icmp_message == nullptr || size < icmp_header_size + minimum_ipv4_header_size || + !is_icmpv4_error(icmp_message[0])) + return std::nullopt; + + const auto* const quoted = icmp_message + icmp_header_size; + const auto quoted_size = size - icmp_header_size; + if ((quoted[0] >> 4) != 4) + return std::nullopt; + + const auto header_size = static_cast(quoted[0] & 0x0f) * 4; + if (header_size < minimum_ipv4_header_size || header_size + 2 > quoted_size) + return std::nullopt; + + if (quoted[9] != udp && quoted[9] != tcp) + return std::nullopt; + + const auto flags_and_offset = static_cast((quoted[6] << 8) | quoted[7]); + if (classify_ipv4_fragment(flags_and_offset) == ipv4_fragment::later) + return std::nullopt; + + return static_cast((quoted[header_size] << 8) | quoted[header_size + 1]); + } + + /** + * @brief The source port of the UDP datagram or TCP segment an ICMPv6 error quotes. + * + * Walks the quoted packet's hop-by-hop, routing, destination-options and fragment headers. + * Returns std::nullopt when the message is not an error, quotes another upper-layer protocol + * or a later fragment, or is truncated before the quoted source port. + * + * @param icmp_message The ICMPv6 header followed by the quoted packet. + * @return The quoted source port in host byte order. + */ + [[nodiscard]] constexpr std::optional icmpv6_error_quoted_source_port( + const uint8_t* icmp_message, const std::size_t size) noexcept + { + constexpr std::size_t icmp_header_size = 8, ipv6_header_size = 40; + constexpr uint8_t hop_by_hop = 0, tcp = 6, udp = 17, routing = 43, fragment = 44, destination_options = 60; + + if (icmp_message == nullptr || size < icmp_header_size + ipv6_header_size || + !is_icmpv6_error(icmp_message[0])) + return std::nullopt; + + const auto* const quoted = icmp_message + icmp_header_size; + const auto quoted_size = size - icmp_header_size; + if ((quoted[0] >> 4) != 6) + return std::nullopt; + + uint8_t next = quoted[6]; + std::size_t offset = ipv6_header_size; + + // A bound on the chain length keeps a malformed chain from looping. + for (int headers = 0; headers < 16; ++headers) + { + if (next == hop_by_hop || next == routing || next == destination_options) + { + if (offset + 2 > quoted_size) + return std::nullopt; + const auto length = (static_cast(quoted[offset + 1]) + 1) * 8; + next = quoted[offset]; + offset += length; + continue; + } + + if (next == fragment) + { + if (offset + 8 > quoted_size) + return std::nullopt; + const auto offset_and_flags = static_cast((quoted[offset + 2] << 8) | quoted[offset + 3]); + if ((offset_and_flags >> 3) != 0) + return std::nullopt; // a later fragment: no upper-layer header + next = quoted[offset]; + offset += 8; + continue; + } + + if ((next != udp && next != tcp) || offset + 2 > quoted_size) + return std::nullopt; + + return static_cast((quoted[offset] << 8) | quoted[offset + 1]); + } + + return std::nullopt; + } + + /// What a packet handler does with an outbound ICMP or ICMPv6 message. + enum class icmp_error_action : uint8_t + { + pass, ///< not about a DNS answer, or not in Proxy mode: left alone + drop ///< reports a DNS answer in Proxy mode: it would carry the answer to the DNS server + }; + + /** + * @brief Decides what to do with an outbound ICMP or ICMPv6 message. + * + * Only the quoted source port is used, like the destination port for queries: in Proxy mode + * no query leaves the adapter, so a quoted packet from port 53 is an answer the DNS proxy + * delivered. The few DNS packets the policy passes in Proxy mode (broadcast or multicast + * destinations, ProxiFyre's own traffic to a SOCKS5 server on port 53) lose at most the + * error report for an answer nobody was waiting for. + * + * @param quoted_source_port icmpv4_error_quoted_source_port() or + * icmpv6_error_quoted_source_port() of the message. + */ + [[nodiscard]] constexpr icmp_error_action decide_icmp_error(const dns_routing_mode mode, + const std::optional quoted_source_port) noexcept + { + return mode == dns_routing_mode::proxy && quoted_source_port && *quoted_source_port == dns_port + ? icmp_error_action::drop + : icmp_error_action::pass; + } + + /** + * @brief The address families whose outbound ICMP messages the DNS policy has to see in + * @p mode, as a REDIRECT driver filter at the front of the table. + * + * Without one, ICMP is passed by the driver (the router's ICMP PASS filter, LAN bypass) + * and decide_icmp_error() is never consulted. Direct mode needs none. + */ + [[nodiscard]] inline std::vector plan_dns_icmp_filters(const dns_routing_mode mode) + { + if (mode != dns_routing_mode::proxy) + return {}; + return { dns_family::ipv4, dns_family::ipv6 }; + } + /// What tcp_local_redirect reported for a segment from a local TCP listener. enum class listener_segment_outcome : uint8_t { diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 11288e9..6d00f59 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -333,6 +333,18 @@ namespace proxy */ std::atomic listener_segments_after_reset_{ 0 }; + /** + * @brief Count of outbound ICMP errors about DNS answers dropped in Proxy mode since the + * last throttled report (see decide_icmp_error()). + */ + std::atomic dns_answer_icmp_errors_{ 0 }; + + /** + * @brief Set once the first dropped ICMP error about a DNS answer of this run has been + * reported at info level; later ones are only counted. Reset by start(). + */ + std::atomic_flag dns_answer_icmp_error_logged_{}; + /** * @brief One-shot flags so that each (family, transport, reason) block cause is * described once in the log instead of once per packet. @@ -757,6 +769,21 @@ namespace proxy return enqueue_for_deferred_resolve(buffer); } + if (ip_header->ip_p == IPPROTO_ICMP) + { + // Seen here only in DNS Proxy mode (install_dns_filters()); otherwise + // the driver passes ICMP itself. + const auto ip_header_size = static_cast(ip_header->ip_hl) * sizeof(DWORD); + const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); + if (fragment != ipv4_fragment::later && + buffer.m_Length > ETHER_HEADER_LENGTH + ip_header_size) + { + const auto* const icmp_message = reinterpret_cast(ip_header) + ip_header_size; + return handle_outbound_icmp(icmpv4_error_quoted_source_port(icmp_message, + buffer.m_Length - ETHER_HEADER_LENGTH - ip_header_size)); + } + } + return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; }); @@ -1038,6 +1065,8 @@ namespace proxy untranslated_listener_replies_.store(0, std::memory_order_relaxed); untranslated_listener_reply_logged_.clear(std::memory_order_relaxed); listener_segments_after_reset_.store(0, std::memory_order_relaxed); + dns_answer_icmp_errors_.store(0, std::memory_order_relaxed); + dns_answer_icmp_error_logged_.clear(std::memory_order_relaxed); for (auto& flag : dns_block_reason_logged_) flag.clear(std::memory_order_relaxed); @@ -2364,6 +2393,37 @@ namespace proxy } } + /** + * @brief Applies decide_icmp_error() to an outbound ICMP or ICMPv6 message. + * + * In Proxy mode a DNS answer is written by the DNS proxy's listener and presented as + * coming from the server the client queried. If the client's socket has closed, the + * stack reports the answer to that server with an ICMP error that quotes it; passing the + * error would send the answer to the DNS server in clear, so it is dropped. The lock is + * taken only for a message that quotes a packet from port 53. + * + * @param quoted_source_port Source port of the packet the message quotes, if it is an + * error about a UDP datagram or TCP segment. + */ + packet_filter::packet_action handle_outbound_icmp(const std::optional quoted_source_port) + { + if (decide_icmp_error(dns_routing_mode::proxy, quoted_source_port) == icmp_error_action::pass || + !dns_proxy_mode()) + { + return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; + } + + dns_answer_icmp_errors_.fetch_add(1, std::memory_order_relaxed); + if (!dns_answer_icmp_error_logged_.test_and_set(std::memory_order_relaxed)) + { + NETLIB_LOG(log_level::info, + "DNS routing: dropped an ICMP error about a DNS answer instead of sending it to the DNS server " + "(the client's socket had closed before the answer from the DNS proxy arrived, and the error " + "quotes the answer). Further occurrences are counted."); + } + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + } + /// Maps tcp_local_redirect's result for a listener segment to the policy's outcome. template static listener_segment_outcome to_listener_segment_outcome(const Result result) noexcept @@ -2905,6 +2965,34 @@ namespace proxy } } + // Outbound ICMP has to reach handle_outbound_icmp(): an ICMP error about a DNS answer + // quotes the answer and is addressed to the DNS server. Ahead of the ICMP PASS filter + // and the LAN-bypass PASS filters, like the filters above. + for (const auto family : plan_dns_icmp_filters(mode)) + { + const auto add = [this](auto filter, const uint8_t protocol) -> bool + { + filter.set_direction(ndisapi::direction_t::out) + .set_action(ndisapi::action_t::redirect) + .set_protocol(protocol); + return static_filters_.add_filter_front(filter); + }; + + const bool added = family == dns_family::ipv4 + ? add(ndisapi::filter{}, static_cast(IPPROTO_ICMP)) + : add(ndisapi::filter{}, static_cast(IPPROTO_ICMPV6)); + + if (!added) + { + NETLIB_LOG(log_level::error, + "DNS routing: failed to install the {} driver filter for outbound ICMP errors; refusing to " + "start so a DNS answer cannot leave the computer inside an ICMP error.", + family == dns_family::ipv4 ? "IPv4" : "IPv6"); + remove_dns_filters(); + return false; + } + } + return true; } @@ -3281,6 +3369,17 @@ namespace proxy return enqueue_for_deferred_resolve(buffer); } + if (protocol == IPPROTO_ICMPV6) + { + const auto* const icmp_message = static_cast(transport); + const auto* const packet_end = reinterpret_cast(ethernet_header) + buffer.m_Length; + if (icmp_message < packet_end) + { + return handle_outbound_icmp(icmpv6_error_quoted_source_port(icmp_message, + static_cast(packet_end - icmp_message))); + } + } + return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; } @@ -3612,6 +3711,14 @@ namespace proxy "Dropped {} segment(s) from local TCP listeners for connections that had just been reset " "(expected during aborts).", after_reset); } + if (const auto icmp_errors = dns_answer_icmp_errors_.exchange(0, std::memory_order_relaxed); + icmp_errors != 0) + { + reported = true; + NETLIB_LOG(log_level::debug, + "DNS routing: dropped {} ICMP error(s) about DNS answers delivered to sockets that had closed; " + "they were not sent to the network.", icmp_errors); + } return reported; } diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index bd4f3d4..5ccb4ff 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -681,3 +681,163 @@ TEST(ListenerFragmentPolicy, Ipv4ListenerFirstFragmentsAreNotTranslated) EXPECT_FALSE(ipv4_listener_packet_translatable(classify_ipv4_fragment(0x2000))); EXPECT_FALSE(ipv4_listener_packet_translatable(classify_ipv4_fragment(0x2001))); } + +// ------------------------------------------------------------------ ICMP errors about DNS answers +// +// In Proxy mode a DNS answer delivered to a socket that has closed makes the stack send an ICMP +// error, which quotes the answer, to the server the client queried. It must not leave the adapter. + +namespace +{ + /// Builds an IPv4 packet: a 20-byte header plus @p options, followed by @p payload. + std::vector ipv4_packet(const uint8_t protocol, const uint16_t flags_and_offset, + const std::vector& payload, const std::vector& options = {}) + { + std::vector packet(20, 0); + packet[0] = static_cast(0x40 | ((20 + options.size()) / 4)); + packet[6] = static_cast(flags_and_offset >> 8); + packet[7] = static_cast(flags_and_offset & 0xff); + packet[8] = 64; + packet[9] = protocol; + packet.insert(packet.end(), options.begin(), options.end()); + packet.insert(packet.end(), payload.begin(), payload.end()); + return packet; + } + + /// Builds an ICMP or ICMPv6 message: an 8-byte header followed by the quoted packet. + std::vector icmp_message(const uint8_t type, const uint8_t code, const std::vector& quoted) + { + std::vector message{ type, code, 0, 0, 0, 0, 0, 0 }; + message.insert(message.end(), quoted.begin(), quoted.end()); + return message; + } + + std::optional quoted_v4(const std::vector& message) + { + return proxy::icmpv4_error_quoted_source_port(message.data(), message.size()); + } + + std::optional quoted_v6(const std::vector& message) + { + return proxy::icmpv6_error_quoted_source_port(message.data(), message.size()); + } + + constexpr uint8_t icmpv4_unreachable = 3, icmpv4_port_unreachable = 3, icmpv4_echo_request = 8, icmpv4_echo_reply = 0; + constexpr uint8_t icmpv6_unreachable = 1, icmpv6_port_unreachable = 4, icmpv6_echo_request = 128; + constexpr uint8_t icmpv6_proto = 58, icmp_proto = 1; +} + +TEST(DnsAnswerIcmpPolicy, Icmpv4ErrorExposesTheQuotedSourcePort) +{ + // Port unreachable about a UDP answer from port 53 to a closed client port. + EXPECT_EQ(quoted_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, ipv4_packet(udp_proto, 0, ports(53, 58440)))), + std::optional{ 53 }); + // The quoted header length is honoured (IP options), and TCP is read the same way. + EXPECT_EQ(quoted_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, + ipv4_packet(tcp_proto, 0, ports(53, 58440), { 1, 1, 1, 1 }))), std::optional{ 53 }); + // Every error type quotes the packet; the first fragment of a datagram still carries ports. + for (const uint8_t type : { uint8_t{ 3 }, uint8_t{ 4 }, uint8_t{ 5 }, uint8_t{ 11 }, uint8_t{ 12 } }) + { + EXPECT_EQ(quoted_v4(icmp_message(type, 0, ipv4_packet(udp_proto, 0x2000, ports(443, 50000)))), + std::optional{ 443 }); + } + // The eight bytes RFC 792 requires after the quoted header are enough. + EXPECT_EQ(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, ipv4_packet(udp_proto, 0, ports(53, 1))).size(), 36u); +} + +TEST(DnsAnswerIcmpPolicy, Icmpv4MessagesWithoutAQuotedSourcePortAreNotReported) +{ + // Echo request and reply carry data, not a quoted packet, even if the data looks like one. + EXPECT_FALSE(quoted_v4(icmp_message(icmpv4_echo_request, 0, ipv4_packet(udp_proto, 0, ports(53, 1)))).has_value()); + EXPECT_FALSE(quoted_v4(icmp_message(icmpv4_echo_reply, 0, ipv4_packet(udp_proto, 0, ports(53, 1)))).has_value()); + // Another quoted protocol (ICMP). + EXPECT_FALSE(quoted_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(icmp_proto, 0, ports(53, 1)))).has_value()); + // A later fragment has no transport header: its leading bytes must not be read as ports. + EXPECT_FALSE(quoted_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 185, ports(53, 1)))).has_value()); + // Truncated before the quoted ports, with and without IP options. + EXPECT_FALSE(quoted_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, {}))).has_value()); + EXPECT_FALSE(quoted_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, {}, { 1, 1, 1, 1 }))).has_value()); + // A quoted header that is not IPv4, or whose length field is too small. + auto not_v4 = icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, ports(53, 1))); + not_v4[8] = 0x65; + EXPECT_FALSE(quoted_v4(not_v4).has_value()); + auto short_header = icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, ports(53, 1))); + short_header[8] = 0x44; + EXPECT_FALSE(quoted_v4(short_header).has_value()); + // No data at all. + EXPECT_FALSE(proxy::icmpv4_error_quoted_source_port(nullptr, 100).has_value()); + EXPECT_FALSE(quoted_v4({ icmpv4_unreachable, icmpv4_port_unreachable, 0, 0 }).has_value()); +} + +TEST(DnsAnswerIcmpPolicy, Icmpv6ErrorExposesTheQuotedSourcePort) +{ + EXPECT_EQ(quoted_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, ipv6_packet(udp_proto, ports(53, 58440)))), + std::optional{ 53 }); + EXPECT_EQ(quoted_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, ipv6_packet(tcp_proto, ports(53, 58440)))), + std::optional{ 53 }); + // Extension headers and a first-fragment header in the quoted packet are skipped. + const std::vector hop_by_hop{ fragment_proto, 0, 1, 4, 0, 0, 0, 0 }; + const std::vector destination_options{ udp_proto, 0, 1, 4, 0, 0, 0, 0 }; + EXPECT_EQ(quoted_v6(icmp_message(3, 0, ipv6_packet(hop_proto, + concat({ hop_by_hop, fragment_header(dest_opts_proto, 0, true), destination_options, ports(53, 50001) })))), + std::optional{ 53 }); + // Every type below 128 is an error. + for (const uint8_t type : { uint8_t{ 1 }, uint8_t{ 2 }, uint8_t{ 3 }, uint8_t{ 4 }, uint8_t{ 127 } }) + { + EXPECT_EQ(quoted_v6(icmp_message(type, 0, ipv6_packet(udp_proto, ports(5353, 50000)))), + std::optional{ 5353 }); + } +} + +TEST(DnsAnswerIcmpPolicy, Icmpv6MessagesWithoutAQuotedSourcePortAreNotReported) +{ + // Informational messages (echo, neighbor discovery) are not errors. + EXPECT_FALSE(quoted_v6(icmp_message(icmpv6_echo_request, 0, ipv6_packet(udp_proto, ports(53, 1)))).has_value()); + EXPECT_FALSE(quoted_v6(icmp_message(135, 0, ipv6_packet(udp_proto, ports(53, 1)))).has_value()); + // Another upper-layer protocol, a later fragment, a truncated chain. + EXPECT_FALSE(quoted_v6(icmp_message(icmpv6_unreachable, 0, ipv6_packet(icmpv6_proto, ports(53, 1)))).has_value()); + EXPECT_FALSE(quoted_v6(icmp_message(icmpv6_unreachable, 0, + ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 185, false), ports(53, 1) })))).has_value()); + EXPECT_FALSE(quoted_v6(icmp_message(icmpv6_unreachable, 0, ipv6_packet(udp_proto, {}))).has_value()); + EXPECT_FALSE(quoted_v6(icmp_message(icmpv6_unreachable, 0, + ipv6_packet(fragment_proto, fragment_header(udp_proto, 0, true)))).has_value()); + // Not IPv6, or no data at all. + auto not_v6 = icmp_message(icmpv6_unreachable, 0, ipv6_packet(udp_proto, ports(53, 1))); + not_v6[8] = 0x45; + EXPECT_FALSE(quoted_v6(not_v6).has_value()); + EXPECT_FALSE(proxy::icmpv6_error_quoted_source_port(nullptr, 100).has_value()); +} + +TEST(DnsAnswerIcmpPolicy, OnlyErrorsAboutPort53AnswersAreDroppedAndOnlyInProxyMode) +{ + using proxy::decide_icmp_error; + using proxy::icmp_error_action; + + EXPECT_EQ(decide_icmp_error(proxy_mode, uint16_t{ 53 }), icmp_error_action::drop); + // Direct mode: the answer came from the real server, which may be told. + EXPECT_EQ(decide_icmp_error(direct, uint16_t{ 53 }), icmp_error_action::pass); + // Other traffic, and messages that quote nothing usable, are never touched. + EXPECT_EQ(decide_icmp_error(proxy_mode, uint16_t{ 443 }), icmp_error_action::pass); + EXPECT_EQ(decide_icmp_error(proxy_mode, uint16_t{ 5353 }), icmp_error_action::pass); + EXPECT_EQ(decide_icmp_error(proxy_mode, std::nullopt), icmp_error_action::pass); + EXPECT_EQ(decide_icmp_error(direct, std::nullopt), icmp_error_action::pass); + + // End to end: a port-unreachable error about an answer, for both families. + EXPECT_EQ(decide_icmp_error(proxy_mode, + quoted_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, ipv4_packet(udp_proto, 0, ports(53, 58440))))), + icmp_error_action::drop); + EXPECT_EQ(decide_icmp_error(proxy_mode, + quoted_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, ipv6_packet(udp_proto, ports(53, 58440))))), + icmp_error_action::drop); + // A ping whose data happens to look like a packet from port 53 is passed. + EXPECT_EQ(decide_icmp_error(proxy_mode, + quoted_v4(icmp_message(icmpv4_echo_request, 0, ipv4_packet(udp_proto, 0, ports(53, 1))))), + icmp_error_action::pass); +} + +TEST(DnsFilterPlan, OutboundIcmpIsKeptInUserModeOnlyInProxyMode) +{ + EXPECT_TRUE(proxy::plan_dns_icmp_filters(direct).empty()); + const std::vector both{ dns_family::ipv4, dns_family::ipv6 }; + EXPECT_EQ(proxy::plan_dns_icmp_filters(proxy_mode), both); +} From d26dbbaff3be42991ae07180924b0747e27a4ecd Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Sat, 14 Nov 2026 07:23:24 +0000 Subject: [PATCH 61/62] fix(udp): drop ICMP errors that quote a proxied UDP reply A reply on a UDP flow that a rule proxies reaches the application as if it came from the remote peer: socks5_udp_local_redirect restores the peer named in the SOCKS5 UDP header. If the application's socket has closed when the reply arrives, Windows reports it with an ICMP "port unreachable" (ICMPv6 "destination unreachable") error addressed to that peer. The error leaves the adapter directly, from the computer's own address, and quotes the reply, so the peer learns the real address and sees the reply contents. The previous commit handled this for DNS answers in Proxy mode only. - An outbound ICMP or ICMPv6 error is dropped when the UDP datagram it quotes was addressed to a client port with an active entry in the UDP redirect of that family. This applies in either DNS mode. The redirect is keyed by client port, so a datagram that port received directly is matched too; that sender already knows the address and only loses the error report. Ping, neighbor discovery, TCP quotes and errors about unproxied ports are passed. The first drop per run is logged at info level with the port; later drops are counted at debug level. - The quoted-header parsing in dns_routing_policy.h now returns both quoted ports (icmpv4_error_quote(), icmpv6_error_quote()). The source-port helpers are kept as wrappers. decide_icmp_error() takes the quote and a lookup of redirected client ports, and only calls the lookup (and so takes the redirect's lock) for a quoted UDP datagram with both ports. - socks5_udp_local_redirect::is_active_endpoint() reports whether a client port has an entry that has not timed out (15 minutes, now a named constant). - The REDIRECT filter for outbound ICMP is now needed outside DNS Proxy mode: for IPv4, the router's ICMP PASS filter would otherwise pass the error in the driver. plan_icmp_error_filters() installs it per address family when that family has a UDP listener, and for both families in DNS Proxy mode. install_icmp_error_filters() runs on start() and also when add_socks5_proxy() adds a UDP listener to a running router. It only adds missing filters, so there is never a moment without one. - Tests: quote parsing (both ports, a quote cut between them), the decision in both modes, the lookup only being consulted for quoted UDP, and the filter plan. The portable suite also drives the real redirect: an IPv4 and an IPv6 application flow is redirected, the listener's reply is translated, and the stack's error about the translated reply is dropped, while ping and errors about unredirected ports pass. - Docs: the behaviour and the filter in configuration.md, and a Windows validation step with pktmon/Wireshark in gui.md. --- docs/configuration.md | 7 +- docs/gui.md | 3 +- .../src/ndisapi/socks5_udp_local_redirect.h | 22 +- netlib/src/proxy/dns_routing_policy.h | 149 ++++++++--- netlib/src/proxy/socks_local_router.h | 237 ++++++++++++++---- .../portable/dns_packet_redirect_test.cpp | 109 ++++++++ netlib/test/proxy/dns_routing_policy_test.cpp | 196 +++++++++++++-- 7 files changed, 606 insertions(+), 117 deletions(-) diff --git a/docs/configuration.md b/docs/configuration.md index 97e37f5..49e5d08 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -132,10 +132,13 @@ In DNS `Proxy` mode, DNS takes precedence over LAN bypass: a query addressed to ## Local listener replies and TCP close handling -ProxiFyre redirects a matched connection to a local listener and translates the listener's replies back before the application sees them. Two rules apply to every proxied connection, not only to DNS: +ProxiFyre redirects a matched connection to a local listener and translates the listener's replies back before the application sees them. Three rules apply to every proxied connection, not only to DNS: - **A reply that cannot be translated back is dropped.** A reply from a local listener is addressed to the original server only because redirection swapped the addresses, so it must never reach the network. It is dropped when its TCP connection or UDP endpoint is no longer tracked, when it is the first fragment of a fragmented reply, or when its SOCKS5 relay header is malformed or of the other address family. Earlier releases passed such packets toward the original server. The first such drop after the service starts is logged once as a warning, and a count is logged at `Info` level at most every five seconds while drops continue. Later fragments of a fragmented reply carry no ports, cannot be attributed to a listener, and are still passed. - **A TCP connection is tracked through its whole close.** The FIN/ACK exchange is translated in both directions instead of reaching the real server. A reset (RST) ends the connection immediately; segments the local proxy had already sent when the reset arrived are dropped without the warning and are counted at `Debug` level only. +- **ICMP errors about proxied UDP replies are dropped.** A UDP reply reaches the application as if it came from the remote endpoint, although it came from the proxy. If the application has already closed its socket when the reply arrives, Windows answers with an ICMP "port unreachable" error (ICMPv6 "destination unreachable" for IPv6) addressed to that remote endpoint. The error is sent from the computer's own address, outside the proxy, and quotes the reply, so it would reveal the computer's address and the reply's contents to the remote endpoint. ProxiFyre drops an outbound ICMP or ICMPv6 error when the UDP datagram it quotes was addressed to a local port whose UDP traffic ProxiFyre redirected to a proxy within the last 15 minutes. This applies in either DNS mode, to every rule that proxies `UDP`. It also covers a datagram that port received directly from the network: the sender already knows the computer's address, and only its error report is lost. Other ICMP traffic, such as `ping`, neighbor discovery and errors about unproxied traffic, is passed. The first such drop after the service starts is logged at `Info`, naming the local port, and later ones are counted at `Debug`. Proxied TCP is not affected: Windows answers a TCP segment for a closed connection with a reset, which is translated like any other segment (see above). + +When a rule proxies `UDP` for an address family, or in DNS `Proxy` mode, outbound ICMP of that family (ICMPv6 for IPv6) is filtered by ProxiFyre rather than passed by the driver. The filter is placed ahead of the LAN bypass filters. ICMP that is not dropped is passed unchanged. If the filter cannot be installed, the service does not start; a proxy added while the service runs is then rejected instead. A proxied TCP connection that stays idle for more than 5 minutes loses its redirect entry; see [Limitations](#limitations). @@ -187,7 +190,7 @@ Whether name resolution still succeeds after a drop depends on Windows: it retri Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. -An answer can arrive after the application has closed its socket, for example the answer to a query Windows had already retransmitted. Windows then reports the datagram with an ICMP "port unreachable" error addressed to the DNS server the application queried, and that error quotes the answer. Because the answer came from the DNS proxy and not from that server, ProxiFyre drops outbound ICMP and ICMPv6 errors that quote a packet sent from port 53 in `Proxy` mode, so the answer does not leave the computer in clear. Other ICMP traffic, such as `ping`, is passed. The first such drop after the service starts is logged at `Info` and later ones are counted at `Debug`. +An answer can arrive after the application has closed its socket, for example the answer to a query Windows had already retransmitted. Windows then reports the datagram with an ICMP "port unreachable" error addressed to the DNS server the application queried, and that error quotes the answer. Because the answer came from the DNS proxy and not from that server, ProxiFyre drops outbound ICMP and ICMPv6 errors that quote a packet sent from port 53 in `Proxy` mode, so the answer does not leave the computer in clear. Other ICMP traffic, such as `ping`, is passed. The first such drop after the service starts is logged at `Info` and later ones are counted at `Debug`. The same protection applies to application UDP that a rule proxies, in either mode; see [Local listener replies and TCP close handling](#local-listener-replies-and-tcp-close-handling). If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. diff --git a/docs/gui.md b/docs/gui.md index 0b44a1d..e01026b 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -176,4 +176,5 @@ The routing policy and the packet rewriting are covered by automated tests (`net 13. **Relay source and shared IDs.** If the SOCKS5 server reports an address other than the queried DNS server as the source of UDP replies (for example its own IPv4 address), confirm lookups succeed without and with `serverOverride`, to an IPv4 resolver and to an IPv6 resolver. Run many lookups in parallel (for example `1..200 | ForEach-Object -Parallel { Resolve-DnsName "host$_.example.com" -DnsOnly -ErrorAction SilentlyContinue }` in PowerShell 7) and confirm each one gets its own answer. 14. **SOCKS5 server used as a resolver.** Send a lookup to the SOCKS5 server's own IP address (`Resolve-DnsName example.com -Server -DnsOnly`). Confirm the query goes through the proxy, not directly. If the server listens on TCP port 53 or returns a UDP relay on port 53, also confirm ProxiFyre still reaches it and the one-time `Info` line about the relay appears. 15. **Limited mode.** Repeat step 2 in the optional unelevated console mode. -16. **GUI.** On the **Settings / Diagnostics** tab at 100% and 150% scaling, confirm the DNS routing group and the Uninstall button are reachable (scrolling is expected). Confirm Alt+M, Alt+P, and Alt+S focus the mode, proxy, and override fields; that the DNS proxy selection survives **Move Up**/**Move Down** and a reload; that **Duplicate** does not copy the id; and that removing the selected rule shows the missing id and fails validation. +16. **ICMP errors about proxied UDP replies.** With `Direct` DNS and a rule that proxies `UDP` for a test application, capture on the physical adapter (`pktmon filter add -t ICMP`, `pktmon filter add -t ICMPv6`, `pktmon start --capture --comp nics`, then `pktmon stop` and `pktmon etl2pcap PktMon.etl`; or Wireshark with `icmp.type == 3 || icmpv6.type == 1`). From the application, send a UDP datagram to a server that answers after a delay, over IPv4 and over IPv6, and close the socket before the reply arrives. For example, query a DNS server on a port other than 53 that answers slowly, or use a UDP echo server that delays its reply. Confirm the SOCKS5 server relays the reply, that no ICMP type 3 or ICMPv6 type 1 message addressed to the server leaves the adapter, and that the engine log has one "Dropped an ICMP error about a proxied UDP reply" line naming the client port. Repeat the test with the rule disabled: the error now leaves the adapter, which shows the test provokes it. Confirm `ping` and `ping -6` to the server still work, and that the same check passes in `Proxy` mode. +17. **GUI.** On the **Settings / Diagnostics** tab at 100% and 150% scaling, confirm the DNS routing group and the Uninstall button are reachable (scrolling is expected). Confirm Alt+M, Alt+P, and Alt+S focus the mode, proxy, and override fields; that the DNS proxy selection survives **Move Up**/**Move Down** and a reload; that **Duplicate** does not copy the id; and that removing the selected rule shows the missing id and fails validation. diff --git a/netlib/src/ndisapi/socks5_udp_local_redirect.h b/netlib/src/ndisapi/socks5_udp_local_redirect.h index 049a1b5..43ade4e 100644 --- a/netlib/src/ndisapi/socks5_udp_local_redirect.h +++ b/netlib/src/ndisapi/socks5_udp_local_redirect.h @@ -45,6 +45,9 @@ namespace ndisapi /// std::atomic_bool terminate_{ false }; + /// How long a client endpoint is kept after its last translated datagram. + static constexpr std::chrono::minutes endpoint_timeout{ 15 }; + /** * @brief Starts the background cleanup thread. * @@ -64,8 +67,7 @@ namespace ndisapi tools::generic::erase_if(endpoints_, endpoints_.begin(), endpoints_.end(), [¤t_time, this](auto&& a) { - using namespace std::chrono_literals; - if (current_time - a.second > 15min) + if (current_time - a.second > endpoint_timeout) { NETLIB_DEBUG( "DELETE UDP client endpoint (timeout): : {}", @@ -176,6 +178,22 @@ namespace ndisapi proxy_port_ = htons(proxy_port); } + /** + * @brief Whether @p client_port (host byte order) has an endpoint entry that has not + * timed out, i.e. its datagrams are, or were within endpoint_timeout, redirected + * and replies to it are delivered by a local listener. + * + * Used to recognize an outbound ICMP error about such a reply (decide_icmp_error()): + * the entry outlives the client's socket, which is exactly when the stack reports a + * late reply with an error addressed to the remote peer. + */ + [[nodiscard]] bool is_active_endpoint(const u_short client_port) + { + std::scoped_lock lock(lock_); + const auto it = endpoints_.find(htons(client_port)); + return it != endpoints_.cend() && std::chrono::steady_clock::now() - it->second <= endpoint_timeout; + } + /** * @brief Checks if the UDP session for the given packet is new. * diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 5765dfa..8138791 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -449,14 +449,17 @@ namespace proxy } // --------------------------------------------------------------------------------------- - // ICMP errors about DNS answers + // ICMP errors about datagrams the proxies delivered // - // In Proxy mode an answer from port 53 that reaches a client was written by the DNS proxy's - // local listener and only presented as coming from the server the client queried. When the - // client's socket has closed by then (the answer to a retransmitted query, a client that - // gave up), the TCP/IP stack reports the datagram with an ICMP error addressed to that - // server, which never sent it. The error quotes the datagram, so the DNS answer would leave - // the adapter in clear and from the computer's own address. Such errors are dropped. + // A reply that reaches a client through a proxy was written by a local listener and only + // presented as coming from the remote endpoint: in Proxy mode a DNS answer from the server + // the client queried, and for application UDP that a rule proxies, a datagram from the + // remote peer (socks5_udp_local_redirect restores the peer named in the SOCKS5 UDP header). + // When the client's socket has closed by then (the answer to a retransmitted query, a + // client that gave up or exited), the TCP/IP stack reports the datagram with an ICMP error + // addressed to that remote endpoint, which never sent it to this address. The error quotes + // the datagram, so it would tell the remote endpoint the computer's own address and carry + // the reply in clear. Such errors are dropped. // --------------------------------------------------------------------------------------- /// Whether an ICMP (IPv4) message type is an error message, which quotes the packet it is about. @@ -472,16 +475,40 @@ namespace proxy return type < 128; } + /// The transport header of the UDP datagram or TCP segment an ICMP or ICMPv6 error quotes. + struct icmp_error_quote + { + uint8_t protocol{}; ///< 6 (TCP) or 17 (UDP) + uint16_t source_port{}; ///< host byte order + std::optional destination_port; ///< host byte order; absent when the quote ends before it + }; + + namespace detail + { + /// Reads the ports at @p offset of the quoted packet, if at least the source port is there. + [[nodiscard]] constexpr std::optional quoted_ports(const uint8_t protocol, + const uint8_t* quoted, const std::size_t quoted_size, const std::size_t offset) noexcept + { + if (offset + 2 > quoted_size) + return std::nullopt; + + icmp_error_quote quote{ protocol, static_cast((quoted[offset] << 8) | quoted[offset + 1]), std::nullopt }; + if (offset + 4 <= quoted_size) + quote.destination_port = static_cast((quoted[offset + 2] << 8) | quoted[offset + 3]); + return quote; + } + } + /** - * @brief The source port of the UDP datagram or TCP segment an ICMP (IPv4) error quotes. + * @brief The transport ports of the UDP datagram or TCP segment an ICMP (IPv4) error quotes. * * Returns std::nullopt when the message is not an error, quotes another protocol or a later * fragment (whose first bytes are not ports), or is truncated before the quoted source port. + * The destination port is absent when the quote ends between the two ports. * * @param icmp_message The ICMP header followed by the quoted packet. - * @return The quoted source port in host byte order. */ - [[nodiscard]] constexpr std::optional icmpv4_error_quoted_source_port( + [[nodiscard]] constexpr std::optional icmpv4_error_quote( const uint8_t* icmp_message, const std::size_t size) noexcept { constexpr std::size_t icmp_header_size = 8, minimum_ipv4_header_size = 20; @@ -497,7 +524,7 @@ namespace proxy return std::nullopt; const auto header_size = static_cast(quoted[0] & 0x0f) * 4; - if (header_size < minimum_ipv4_header_size || header_size + 2 > quoted_size) + if (header_size < minimum_ipv4_header_size) return std::nullopt; if (quoted[9] != udp && quoted[9] != tcp) @@ -507,20 +534,20 @@ namespace proxy if (classify_ipv4_fragment(flags_and_offset) == ipv4_fragment::later) return std::nullopt; - return static_cast((quoted[header_size] << 8) | quoted[header_size + 1]); + return detail::quoted_ports(quoted[9], quoted, quoted_size, header_size); } /** - * @brief The source port of the UDP datagram or TCP segment an ICMPv6 error quotes. + * @brief The transport ports of the UDP datagram or TCP segment an ICMPv6 error quotes. * * Walks the quoted packet's hop-by-hop, routing, destination-options and fragment headers. * Returns std::nullopt when the message is not an error, quotes another upper-layer protocol - * or a later fragment, or is truncated before the quoted source port. + * or a later fragment, or is truncated before the quoted source port. The destination port + * is absent when the quote ends between the two ports. * * @param icmp_message The ICMPv6 header followed by the quoted packet. - * @return The quoted source port in host byte order. */ - [[nodiscard]] constexpr std::optional icmpv6_error_quoted_source_port( + [[nodiscard]] constexpr std::optional icmpv6_error_quote( const uint8_t* icmp_message, const std::size_t size) noexcept { constexpr std::size_t icmp_header_size = 8, ipv6_header_size = 40; @@ -563,54 +590,96 @@ namespace proxy continue; } - if ((next != udp && next != tcp) || offset + 2 > quoted_size) + if (next != udp && next != tcp) return std::nullopt; - return static_cast((quoted[offset] << 8) | quoted[offset + 1]); + return detail::quoted_ports(next, quoted, quoted_size, offset); } return std::nullopt; } + /// The source port of the packet an ICMP (IPv4) error quotes (icmpv4_error_quote()). + [[nodiscard]] constexpr std::optional icmpv4_error_quoted_source_port( + const uint8_t* icmp_message, const std::size_t size) noexcept + { + const auto quote = icmpv4_error_quote(icmp_message, size); + return quote ? std::optional{ quote->source_port } : std::nullopt; + } + + /// The source port of the packet an ICMPv6 error quotes (icmpv6_error_quote()). + [[nodiscard]] constexpr std::optional icmpv6_error_quoted_source_port( + const uint8_t* icmp_message, const std::size_t size) noexcept + { + const auto quote = icmpv6_error_quote(icmp_message, size); + return quote ? std::optional{ quote->source_port } : std::nullopt; + } + /// What a packet handler does with an outbound ICMP or ICMPv6 message. enum class icmp_error_action : uint8_t { - pass, ///< not about a DNS answer, or not in Proxy mode: left alone - drop ///< reports a DNS answer in Proxy mode: it would carry the answer to the DNS server + pass, ///< about nothing a proxy delivered: left alone + drop_dns_answer, ///< reports a DNS answer in Proxy mode: it would carry the answer to the DNS server + drop_proxied_udp_reply ///< reports a reply the per-port UDP proxy delivered: it would carry it to the peer }; /** * @brief Decides what to do with an outbound ICMP or ICMPv6 message. * - * Only the quoted source port is used, like the destination port for queries: in Proxy mode - * no query leaves the adapter, so a quoted packet from port 53 is an answer the DNS proxy - * delivered. The few DNS packets the policy passes in Proxy mode (broadcast or multicast - * destinations, ProxiFyre's own traffic to a SOCKS5 server on port 53) lose at most the - * error report for an answer nobody was waiting for. + * - DNS answers: only the quoted source port is used, like the destination port for + * queries: in Proxy mode no query leaves the adapter, so a quoted packet from port 53 is + * an answer the DNS proxy delivered. The few DNS packets the policy passes in Proxy mode + * (broadcast or multicast destinations, ProxiFyre's own traffic to a SOCKS5 server on + * port 53) lose at most the error report for an answer nobody was waiting for. + * - Proxied UDP: a quoted UDP datagram whose destination port is a client port with an + * active entry in the UDP redirect (@p is_redirected_client_port, consulted only for + * such a datagram). Its source is the remote endpoint the reply was presented as coming + * from. The redirect is keyed by the client port, so a datagram the same port received + * directly from the network is matched too; that sender already knows the computer's + * address, and only its error report is lost. * - * @param quoted_source_port icmpv4_error_quoted_source_port() or - * icmpv6_error_quoted_source_port() of the message. + * @param quote icmpv4_error_quote() or icmpv6_error_quote() of the message. + * @param is_redirected_client_port Callable taking a port in host byte order. */ + template [[nodiscard]] constexpr icmp_error_action decide_icmp_error(const dns_routing_mode mode, - const std::optional quoted_source_port) noexcept - { - return mode == dns_routing_mode::proxy && quoted_source_port && *quoted_source_port == dns_port - ? icmp_error_action::drop - : icmp_error_action::pass; + const std::optional& quote, IsRedirectedClientPort&& is_redirected_client_port) + { + constexpr uint8_t udp = 17; + + if (!quote) + return icmp_error_action::pass; + if (mode == dns_routing_mode::proxy && quote->source_port == dns_port) + return icmp_error_action::drop_dns_answer; + if (quote->protocol == udp && quote->destination_port && + std::forward(is_redirected_client_port)(*quote->destination_port)) + return icmp_error_action::drop_proxied_udp_reply; + return icmp_error_action::pass; } /** - * @brief The address families whose outbound ICMP messages the DNS policy has to see in - * @p mode, as a REDIRECT driver filter at the front of the table. + * @brief The address families whose outbound ICMP messages have to be seen in user mode, + * as a REDIRECT driver filter at the front of the table. * * Without one, ICMP is passed by the driver (the router's ICMP PASS filter, LAN bypass) - * and decide_icmp_error() is never consulted. Direct mode needs none. + * and decide_icmp_error() is never consulted. A family needs it in DNS Proxy mode, and + * whenever a UDP listener of that family exists: replies on a proxied UDP flow are + * delivered by the listener whatever the DNS mode. A reply arrives in the packet family of + * its flow, so an IPv4-mapped destination of a dual-stack socket counts as IPv4. + * + * @param ipv4_udp_proxied Whether an IPv4 UDP listener of a proxy exists. + * @param ipv6_udp_proxied Whether an IPv6 UDP listener of a proxy exists. */ - [[nodiscard]] inline std::vector plan_dns_icmp_filters(const dns_routing_mode mode) - { - if (mode != dns_routing_mode::proxy) - return {}; - return { dns_family::ipv4, dns_family::ipv6 }; + [[nodiscard]] inline std::vector plan_icmp_error_filters(const dns_routing_mode mode, + const bool ipv4_udp_proxied, const bool ipv6_udp_proxied) + { + const bool dns_proxy = mode == dns_routing_mode::proxy; + std::vector families; + if (dns_proxy || ipv4_udp_proxied) + families.push_back(dns_family::ipv4); + if (dns_proxy || ipv6_udp_proxied) + families.push_back(dns_family::ipv6); + return families; } /// What tcp_local_redirect reported for a segment from a local TCP listener. diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 6d00f59..056995f 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -345,6 +345,25 @@ namespace proxy */ std::atomic_flag dns_answer_icmp_error_logged_{}; + /** + * @brief Count of outbound ICMP errors about replies the per-port UDP proxy delivered, + * dropped since the last throttled report (see decide_icmp_error()). + */ + std::atomic proxied_udp_icmp_errors_{ 0 }; + + /** + * @brief Set once the first dropped ICMP error about a proxied UDP reply of this run has + * been reported at info level; later ones are only counted. Reset by start(). + */ + std::atomic_flag proxied_udp_icmp_error_logged_{}; + + /** + * @brief Whether the IPv4 and the IPv6 REDIRECT filter for outbound ICMP errors are in + * the driver table (install_icmp_error_filters(); cleared by + * remove_dns_filters()). Under lifecycle_mutex_. + */ + std::array icmp_error_filter_installed_{ false, false }; + /** * @brief One-shot flags so that each (family, transport, reason) block cause is * described once in the log instead of once per packet. @@ -771,15 +790,16 @@ namespace proxy if (ip_header->ip_p == IPPROTO_ICMP) { - // Seen here only in DNS Proxy mode (install_dns_filters()); otherwise - // the driver passes ICMP itself. + // Seen here only while install_icmp_error_filters() has installed the + // IPv4 filter (DNS Proxy mode, or an IPv4 UDP listener); otherwise the + // driver passes ICMP itself. const auto ip_header_size = static_cast(ip_header->ip_hl) * sizeof(DWORD); const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); if (fragment != ipv4_fragment::later && buffer.m_Length > ETHER_HEADER_LENGTH + ip_header_size) { const auto* const icmp_message = reinterpret_cast(ip_header) + ip_header_size; - return handle_outbound_icmp(icmpv4_error_quoted_source_port(icmp_message, + return handle_outbound_icmp(icmpv4_error_quote(icmp_message, buffer.m_Length - ETHER_HEADER_LENGTH - ip_header_size)); } } @@ -1067,6 +1087,8 @@ namespace proxy listener_segments_after_reset_.store(0, std::memory_order_relaxed); dns_answer_icmp_errors_.store(0, std::memory_order_relaxed); dns_answer_icmp_error_logged_.clear(std::memory_order_relaxed); + proxied_udp_icmp_errors_.store(0, std::memory_order_relaxed); + proxied_udp_icmp_error_logged_.clear(std::memory_order_relaxed); for (auto& flag : dns_block_reason_logged_) flag.clear(std::memory_order_relaxed); @@ -1760,6 +1782,27 @@ namespace proxy const bool has_ipv4_listeners = socks_tcp_proxy_server || socks_udp_proxy_server; const bool has_ipv6_listeners = socks_tcp_proxy_server_v6 || socks_udp_proxy_server_v6; + // A running router installed its ICMP error filters for the UDP listeners it had + // at start(); one added now needs them as well (install_icmp_error_filters()). + // Done before the upstream PASS filters: a failure here leaves nothing to roll + // back, and a surplus ICMP filter only passes the messages through user mode. + if ((socks_udp_proxy_server || socks_udp_proxy_server_v6) && is_active_.load(std::memory_order_acquire)) + { + dns_routing_mode mode; + { + std::shared_lock lock(lock_); + mode = dns_mode_; + } + if (!install_icmp_error_filters(mode, socks_udp_proxy_server != nullptr, + socks_udp_proxy_server_v6 != nullptr)) + { + NETLIB_LOG(log_level::error, + "Failed to add SOCKS5 proxy {}: the outbound ICMP filters for its UDP listeners could " + "not be installed.", endpoint); + return {}; + } + } + if ((has_ipv4_listeners || has_ipv6_listeners) && proxy_endpoint->ipv4) { if (!install_upstream_filters(*proxy_endpoint->ipv4)) @@ -2396,32 +2439,58 @@ namespace proxy /** * @brief Applies decide_icmp_error() to an outbound ICMP or ICMPv6 message. * - * In Proxy mode a DNS answer is written by the DNS proxy's listener and presented as - * coming from the server the client queried. If the client's socket has closed, the - * stack reports the answer to that server with an ICMP error that quotes it; passing the - * error would send the answer to the DNS server in clear, so it is dropped. The lock is - * taken only for a message that quotes a packet from port 53. + * A reply delivered by a local listener is presented as coming from the remote endpoint: + * a DNS answer in Proxy mode, or a datagram on a UDP flow the per-port UDP proxy + * redirected. If the client's socket has closed, the stack reports the reply to that + * endpoint with an ICMP error that quotes it; passing the error would send the reply to + * it in clear, from the computer's own address, so it is dropped. The DNS mode lock is + * taken only for a message that quotes a packet from port 53, and the redirect's lock + * only for one that quotes a UDP datagram. * - * @param quoted_source_port Source port of the packet the message quotes, if it is an - * error about a UDP datagram or TCP segment. + * @tparam AddrT Address type of the message's family; selects the UDP redirect. + * @param quote The transport ports of the packet the message quotes, if it is an error + * about a UDP datagram or TCP segment. */ - packet_filter::packet_action handle_outbound_icmp(const std::optional quoted_source_port) + template + packet_filter::packet_action handle_outbound_icmp(const std::optional& quote) { - if (decide_icmp_error(dns_routing_mode::proxy, quoted_source_port) == icmp_error_action::pass || - !dns_proxy_mode()) - { - return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; - } + const auto mode = quote && quote->source_port == dns_port && dns_proxy_mode() + ? dns_routing_mode::proxy + : dns_routing_mode::direct; + + const auto action = decide_icmp_error(mode, quote, + [this](const uint16_t client_port) { return udp_redirect_for().is_active_endpoint(client_port); }); - dns_answer_icmp_errors_.fetch_add(1, std::memory_order_relaxed); - if (!dns_answer_icmp_error_logged_.test_and_set(std::memory_order_relaxed)) + switch (action) { - NETLIB_LOG(log_level::info, - "DNS routing: dropped an ICMP error about a DNS answer instead of sending it to the DNS server " - "(the client's socket had closed before the answer from the DNS proxy arrived, and the error " - "quotes the answer). Further occurrences are counted."); + case icmp_error_action::drop_dns_answer: + dns_answer_icmp_errors_.fetch_add(1, std::memory_order_relaxed); + if (!dns_answer_icmp_error_logged_.test_and_set(std::memory_order_relaxed)) + { + NETLIB_LOG(log_level::info, + "DNS routing: dropped an ICMP error about a DNS answer instead of sending it to the DNS server " + "(the client's socket had closed before the answer from the DNS proxy arrived, and the error " + "quotes the answer). Further occurrences are counted."); + } + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + + case icmp_error_action::drop_proxied_udp_reply: + proxied_udp_icmp_errors_.fetch_add(1, std::memory_order_relaxed); + if (!proxied_udp_icmp_error_logged_.test_and_set(std::memory_order_relaxed)) + { + NETLIB_LOG(log_level::info, + "Dropped an ICMP error about a proxied UDP reply instead of sending it to the remote peer " + "(the application's socket on port {} had closed before the reply from the proxy arrived, " + "and the error quotes the reply). Further occurrences are counted.", + quote->destination_port.value_or(0)); + } + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + + case icmp_error_action::pass: + break; } - return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + + return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; } /// Maps tcp_local_redirect's result for a listener segment to the policy's outcome. @@ -2893,8 +2962,9 @@ namespace proxy } /** - * @brief Removes the DNS policy's driver filters from an earlier start(). They are the - * only REDIRECT filters this router installs; every other static filter is PASS. + * @brief Removes the DNS policy's driver filters from an earlier start(), and the ICMP + * error filters (install_icmp_error_filters()). They are the only REDIRECT filters + * this router installs; every other static filter is PASS. */ void remove_dns_filters() { @@ -2903,6 +2973,76 @@ namespace proxy [&is_dns_filter](const ndisapi::filter& filter) { return is_dns_filter(filter); }); static_filters_.remove_filters_if( [&is_dns_filter](const ndisapi::filter& filter) { return is_dns_filter(filter); }); + icmp_error_filter_installed_ = { false, false }; + } + + /// Whether an IPv4 and an IPv6 UDP listener of a proxy exist. Caller holds lock_. + [[nodiscard]] std::pair udp_listeners_present_locked() const + { + const auto has_udp = [](const auto& servers) + { + return std::ranges::any_of(servers, [](const auto& proxy) { return proxy.second != nullptr; }); + }; + return { has_udp(proxy_servers_), has_udp(proxy_servers_v6_) }; + } + + /** + * @brief Installs the REDIRECT driver filters for outbound ICMP and ICMPv6 that + * plan_icmp_error_filters() asks for and that are not installed yet, at the front + * of the table. + * + * They are ahead of the ICMP PASS filter and the LAN-bypass PASS filters, so an ICMP + * error about a reply a listener delivered reaches handle_outbound_icmp() whatever its + * destination. Called from install_dns_filters() on start(), after remove_dns_filters() + * removed the filters of an earlier run, and from add_socks5_proxy() when a UDP listener + * is added to a running router; a filter already installed is kept, so there is no + * moment without it. Called under lifecycle_mutex_. + * + * @param mode The DNS routing mode the router runs with. + * @param extra_ipv4_udp, extra_ipv6_udp UDP listeners about to be added that are not in + * proxy_servers_ yet. + * @return false when a filter could not be installed. + */ + bool install_icmp_error_filters(const dns_routing_mode mode, const bool extra_ipv4_udp = false, + const bool extra_ipv6_udp = false) + { + std::pair udp_listeners{}; + { + std::shared_lock lock(lock_); + udp_listeners = udp_listeners_present_locked(); + } + + for (const auto family : plan_icmp_error_filters(mode, udp_listeners.first || extra_ipv4_udp, + udp_listeners.second || extra_ipv6_udp)) + { + auto& installed = icmp_error_filter_installed_[family == dns_family::ipv4 ? 0 : 1]; + if (installed) + continue; + + const auto add = [this](auto filter, const uint8_t protocol) -> bool + { + filter.set_direction(ndisapi::direction_t::out) + .set_action(ndisapi::action_t::redirect) + .set_protocol(protocol); + return static_filters_.add_filter_front(filter); + }; + + const bool added = family == dns_family::ipv4 + ? add(ndisapi::filter{}, static_cast(IPPROTO_ICMP)) + : add(ndisapi::filter{}, static_cast(IPPROTO_ICMPV6)); + + if (!added) + { + NETLIB_LOG(log_level::error, + "Failed to install the {} driver filter for outbound ICMP errors; refusing to continue so a " + "DNS answer or a proxied UDP reply cannot leave the computer inside an ICMP error.", + family == dns_family::ipv4 ? "IPv4" : "IPv6"); + return false; + } + installed = true; + } + + return true; } /** @@ -2911,11 +3051,14 @@ namespace proxy * Runs on every start(): the filters from an earlier run are removed and the current plan * is inserted at the front of the table, so the filters stay ahead of LAN-bypass PASS * filters added between runs and use the current listener ports and proxy selection. In - * Direct mode the plan is empty, so earlier filters are only removed. + * Direct mode the plan is empty, so earlier filters are only removed. The ICMP error + * filters (install_icmp_error_filters()) are installed here too: in Proxy mode, and in + * either mode for each address family with a UDP listener. * Called from start() under lifecycle_mutex_. * - * @return false when a filter needed by Proxy mode could not be installed; the caller - * then fails start() rather than running with DNS able to bypass the policy. + * @return false when a filter could not be installed; the caller then fails start() + * rather than running with DNS, or a proxied UDP reply inside an ICMP error, able + * to bypass the proxy. */ bool install_dns_filters() { @@ -2966,31 +3109,11 @@ namespace proxy } // Outbound ICMP has to reach handle_outbound_icmp(): an ICMP error about a DNS answer - // quotes the answer and is addressed to the DNS server. Ahead of the ICMP PASS filter - // and the LAN-bypass PASS filters, like the filters above. - for (const auto family : plan_dns_icmp_filters(mode)) + // or a proxied UDP reply quotes it and is addressed to the remote endpoint. + if (!install_icmp_error_filters(mode)) { - const auto add = [this](auto filter, const uint8_t protocol) -> bool - { - filter.set_direction(ndisapi::direction_t::out) - .set_action(ndisapi::action_t::redirect) - .set_protocol(protocol); - return static_filters_.add_filter_front(filter); - }; - - const bool added = family == dns_family::ipv4 - ? add(ndisapi::filter{}, static_cast(IPPROTO_ICMP)) - : add(ndisapi::filter{}, static_cast(IPPROTO_ICMPV6)); - - if (!added) - { - NETLIB_LOG(log_level::error, - "DNS routing: failed to install the {} driver filter for outbound ICMP errors; refusing to " - "start so a DNS answer cannot leave the computer inside an ICMP error.", - family == dns_family::ipv4 ? "IPv4" : "IPv6"); - remove_dns_filters(); - return false; - } + remove_dns_filters(); + return false; } return true; @@ -3375,7 +3498,7 @@ namespace proxy const auto* const packet_end = reinterpret_cast(ethernet_header) + buffer.m_Length; if (icmp_message < packet_end) { - return handle_outbound_icmp(icmpv6_error_quoted_source_port(icmp_message, + return handle_outbound_icmp(icmpv6_error_quote(icmp_message, static_cast(packet_end - icmp_message))); } } @@ -3719,6 +3842,14 @@ namespace proxy "DNS routing: dropped {} ICMP error(s) about DNS answers delivered to sockets that had closed; " "they were not sent to the network.", icmp_errors); } + if (const auto icmp_errors = proxied_udp_icmp_errors_.exchange(0, std::memory_order_relaxed); + icmp_errors != 0) + { + reported = true; + NETLIB_LOG(log_level::debug, + "Dropped {} ICMP error(s) about proxied UDP replies delivered to sockets that had closed; " + "they were not sent to the network.", icmp_errors); + } return reported; } diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index f5497c8..ac05331 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -1065,3 +1065,112 @@ TEST(DnsPacketRedirect, OversizedUdpAnswerIsDeliveredTruncatedSoTheResolverRetri EXPECT_TRUE(reply->l4_checksum_valid()); } } + +// ------------------------------------------------------------------ ICMP errors about proxied UDP replies +// +// Application UDP that a rule proxies: the per-port UDP proxy's reply is translated by the +// production socks5_udp_local_redirect so that it reaches the client from the remote peer. If the +// client's socket has closed, the stack answers it with an ICMP (or ICMPv6) error addressed to +// that peer which quotes the translated reply. The router recognizes such an error from the quote +// and the redirect's endpoint table (decide_icmp_error(), socks_local_router's +// handle_outbound_icmp()) and drops it, in either DNS mode. + +namespace +{ + /// The stack's ICMP or ICMPv6 error about @p delivered: the 8-byte header, then the + /// datagram from its IP header on (Windows quotes as much of it as fits). + std::vector icmp_error_about(const uint8_t type, const uint8_t code, const frame& delivered) + { + std::vector message{ type, code, 0, 0, 0, 0, 0, 0 }; + message.insert(message.end(), delivered.buffer.m_IBuffer + ETHER_HEADER_LENGTH, + delivered.buffer.m_IBuffer + delivered.buffer.m_Length); + return message; + } + + /// The router's decision for an outbound ICMP message of @p redirect's family. + template + proxy::icmp_error_action router_decision(ndisapi::socks5_udp_local_redirect& redirect, + const proxy::dns_routing_mode mode, const std::vector& message) + { + const auto quote = std::is_same_v + ? proxy::icmpv4_error_quote(message.data(), message.size()) + : proxy::icmpv6_error_quote(message.data(), message.size()); + return proxy::decide_icmp_error(mode, quote, + [&redirect](const uint16_t port) { return redirect.is_active_endpoint(port); }); + } + + constexpr uint16_t peer_port = 3478; +} + +TEST(ProxiedUdpIcmpError, Ipv4ErrorAboutAReplyToAClosedSocketIsDropped) +{ + using proxy::icmp_error_action; + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + EXPECT_FALSE(redirect.is_active_endpoint(client_port)); + + // The application's datagram to the peer is redirected to the UDP proxy's listener. + auto request = frame::udp4("192.168.1.10", "203.0.113.7", client_port, peer_port, std::vector(48, 0xa5)); + EXPECT_TRUE(redirect.is_new_endpoint(request.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(request.buffer, htons(udp_listener))); + EXPECT_TRUE(redirect.is_active_endpoint(client_port)); + + // The listener's reply, carrying the peer in the SOCKS5 header, reaches the client from the peer. + const std::vector response(64, 0x5a); + auto reply = local_proxy_reply("192.168.1.10", "203.0.113.7", v4{ std::string{ "203.0.113.7" } }, peer_port, response); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer)); + ASSERT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "203.0.113.7" } }); + ASSERT_EQ(ntohs(reply.udp()->th_sport), peer_port); + ASSERT_EQ(ntohs(reply.udp()->th_dport), client_port); + ASSERT_EQ(reply.payload(), response); + + // The socket has closed: the port-unreachable error the stack would send to the peer quotes + // the reply, so it is dropped whatever the DNS mode. So is any other error type about it. + const auto unreachable = icmp_error_about(3, 3, reply); + const auto quote = proxy::icmpv4_error_quote(unreachable.data(), unreachable.size()); + ASSERT_TRUE(quote.has_value()); + EXPECT_EQ(quote->source_port, peer_port); + EXPECT_EQ(quote->destination_port, std::optional{ client_port }); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, unreachable), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::proxy, unreachable), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(12, 0, reply)), + icmp_error_action::drop_proxied_udp_reply); + + // A datagram the computer received directly on a port that was never redirected, and a + // ping, are left alone. + auto unproxied = frame::udp4("203.0.113.7", "192.168.1.10", peer_port, client_port + 1, response); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(3, 3, unproxied)), + icmp_error_action::pass); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(8, 0, reply)), + icmp_error_action::pass); +} + +TEST(ProxiedUdpIcmpError, Ipv6ErrorAboutAReplyToAClosedSocketIsDropped) +{ + using proxy::icmp_error_action; + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + + auto request = frame::udp6("2001:db8::10", "2001:db8:1::7", client_port, peer_port, std::vector(48, 0xa5)); + EXPECT_TRUE(redirect.is_new_endpoint(request.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(request.buffer, htons(udp_listener))); + + const std::vector response(200, 0x5a); + auto reply = local_proxy_reply("2001:db8::10", "2001:db8:1::7", v6{ std::string{ "2001:db8:1::7" } }, peer_port, response); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer)); + ASSERT_EQ(v6{ reply.ip6()->ip6_src }, v6{ std::string{ "2001:db8:1::7" } }); + ASSERT_EQ(ntohs(reply.udp()->th_dport), client_port); + + // ICMPv6 destination unreachable, port unreachable (type 1, code 4). + const auto unreachable = icmp_error_about(1, 4, reply); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, unreachable), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::proxy, unreachable), icmp_error_action::drop_proxied_udp_reply); + + // Echo request and neighbor solicitation are informational and pass, as does an error about + // a port that was never redirected. + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(128, 0, reply)), + icmp_error_action::pass); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(135, 0, reply)), + icmp_error_action::pass); + auto unproxied = frame::udp6("2001:db8:1::7", "2001:db8::10", peer_port, client_port + 1, response); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(1, 4, unproxied)), + icmp_error_action::pass); +} diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 5ccb4ff..8f17985 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -13,6 +13,8 @@ #include "pch.h" #include "../../src/proxy/dns_routing_policy.h" +#include +#include #include #include @@ -808,36 +810,192 @@ TEST(DnsAnswerIcmpPolicy, Icmpv6MessagesWithoutAQuotedSourcePortAreNotReported) EXPECT_FALSE(proxy::icmpv6_error_quoted_source_port(nullptr, 100).has_value()); } +namespace +{ + std::optional quote_v4(const std::vector& message) + { + return proxy::icmpv4_error_quote(message.data(), message.size()); + } + + std::optional quote_v6(const std::vector& message) + { + return proxy::icmpv6_error_quote(message.data(), message.size()); + } + + /// A quoted UDP datagram from @p source to @p destination, both ports present. + std::optional udp_quote(const uint16_t source, const uint16_t destination) + { + return proxy::icmp_error_quote{ udp_proto, source, destination }; + } + + /// The UDP redirect's view: which client ports have an active endpoint entry. Records the + /// ports it was asked about, so a test can check that it is consulted only when needed. + struct redirected_ports + { + std::vector active; + mutable std::vector asked; + + bool operator()(const uint16_t port) const + { + asked.push_back(port); + return std::ranges::find(active, port) != active.end(); + } + }; + + proxy::icmp_error_action decide(const proxy::dns_routing_mode mode, + const std::optional& quote, const redirected_ports& redirect = {}) + { + return proxy::decide_icmp_error(mode, quote, std::cref(redirect)); + } +} + TEST(DnsAnswerIcmpPolicy, OnlyErrorsAboutPort53AnswersAreDroppedAndOnlyInProxyMode) { - using proxy::decide_icmp_error; using proxy::icmp_error_action; - EXPECT_EQ(decide_icmp_error(proxy_mode, uint16_t{ 53 }), icmp_error_action::drop); + EXPECT_EQ(decide(proxy_mode, udp_quote(53, 58440)), icmp_error_action::drop_dns_answer); + EXPECT_EQ(decide(proxy_mode, proxy::icmp_error_quote{ tcp_proto, 53, 58440 }), icmp_error_action::drop_dns_answer); // Direct mode: the answer came from the real server, which may be told. - EXPECT_EQ(decide_icmp_error(direct, uint16_t{ 53 }), icmp_error_action::pass); + EXPECT_EQ(decide(direct, udp_quote(53, 58440)), icmp_error_action::pass); // Other traffic, and messages that quote nothing usable, are never touched. - EXPECT_EQ(decide_icmp_error(proxy_mode, uint16_t{ 443 }), icmp_error_action::pass); - EXPECT_EQ(decide_icmp_error(proxy_mode, uint16_t{ 5353 }), icmp_error_action::pass); - EXPECT_EQ(decide_icmp_error(proxy_mode, std::nullopt), icmp_error_action::pass); - EXPECT_EQ(decide_icmp_error(direct, std::nullopt), icmp_error_action::pass); + EXPECT_EQ(decide(proxy_mode, udp_quote(443, 58440)), icmp_error_action::pass); + EXPECT_EQ(decide(proxy_mode, udp_quote(5353, 58440)), icmp_error_action::pass); + EXPECT_EQ(decide(proxy_mode, std::nullopt), icmp_error_action::pass); + EXPECT_EQ(decide(direct, std::nullopt), icmp_error_action::pass); // End to end: a port-unreachable error about an answer, for both families. - EXPECT_EQ(decide_icmp_error(proxy_mode, - quoted_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, ipv4_packet(udp_proto, 0, ports(53, 58440))))), - icmp_error_action::drop); - EXPECT_EQ(decide_icmp_error(proxy_mode, - quoted_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, ipv6_packet(udp_proto, ports(53, 58440))))), - icmp_error_action::drop); + EXPECT_EQ(decide(proxy_mode, + quote_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, ipv4_packet(udp_proto, 0, ports(53, 58440))))), + icmp_error_action::drop_dns_answer); + EXPECT_EQ(decide(proxy_mode, + quote_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, ipv6_packet(udp_proto, ports(53, 58440))))), + icmp_error_action::drop_dns_answer); // A ping whose data happens to look like a packet from port 53 is passed. - EXPECT_EQ(decide_icmp_error(proxy_mode, - quoted_v4(icmp_message(icmpv4_echo_request, 0, ipv4_packet(udp_proto, 0, ports(53, 1))))), + EXPECT_EQ(decide(proxy_mode, + quote_v4(icmp_message(icmpv4_echo_request, 0, ipv4_packet(udp_proto, 0, ports(53, 1))))), icmp_error_action::pass); } -TEST(DnsFilterPlan, OutboundIcmpIsKeptInUserModeOnlyInProxyMode) +// ------------------------------------------------------------------ ICMP errors about proxied UDP replies +// +// A reply on a UDP flow the per-port UDP proxy redirected reaches the client presented as coming +// from the remote peer. If the client's socket has closed, the stack's ICMP error about it quotes +// the reply and is addressed to that peer, from the computer's own address. It must not leave the +// adapter, in either DNS mode. + +TEST(ProxiedUdpIcmpPolicy, QuoteExposesBothPortsOfTheQuotedPacket) +{ + const auto v4 = quote_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, + ipv4_packet(udp_proto, 0, ports(443, 50001), { 1, 1, 1, 1 }))); + ASSERT_TRUE(v4.has_value()); + EXPECT_EQ(v4->protocol, udp_proto); + EXPECT_EQ(v4->source_port, 443); + EXPECT_EQ(v4->destination_port, std::optional{ 50001 }); + + const auto v6 = quote_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, + ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(3478, 50002) })))); + ASSERT_TRUE(v6.has_value()); + EXPECT_EQ(v6->protocol, udp_proto); + EXPECT_EQ(v6->source_port, 3478); + EXPECT_EQ(v6->destination_port, std::optional{ 50002 }); + + const auto tcp = quote_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(tcp_proto, 0, ports(80, 50003)))); + ASSERT_TRUE(tcp.has_value()); + EXPECT_EQ(tcp->protocol, tcp_proto); + + // A quote that ends between the ports has the source port only (it was enough for the DNS + // rule before); the destination port is not guessed. + const auto cut_v4 = quote_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, { 0x01, 0xbb }))); + ASSERT_TRUE(cut_v4.has_value()); + EXPECT_EQ(cut_v4->source_port, 443); + EXPECT_FALSE(cut_v4->destination_port.has_value()); + const auto cut_v6 = quote_v6(icmp_message(icmpv6_unreachable, 0, ipv6_packet(udp_proto, { 0x01, 0xbb, 0xc3 }))); + ASSERT_TRUE(cut_v6.has_value()); + EXPECT_FALSE(cut_v6->destination_port.has_value()); + + // The source-port helpers agree with the quote. + const auto message = icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, ports(443, 50001))); + EXPECT_EQ(proxy::icmpv4_error_quoted_source_port(message.data(), message.size()), std::optional{ 443 }); +} + +TEST(ProxiedUdpIcmpPolicy, ErrorsAboutRepliesToRedirectedClientPortsAreDroppedInEitherMode) +{ + using proxy::icmp_error_action; + const redirected_ports redirect{ { 50001, 50002 }, {} }; + + for (const auto mode : { direct, proxy_mode }) + { + EXPECT_EQ(decide(mode, udp_quote(443, 50001), redirect), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(decide(mode, udp_quote(3478, 50002), redirect), icmp_error_action::drop_proxied_udp_reply); + // A client port without an active redirect entry: its traffic was not proxied. + EXPECT_EQ(decide(mode, udp_quote(443, 50003), redirect), icmp_error_action::pass); + } + + // End to end, for both families, with any error type (not only port unreachable). + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, + ipv4_packet(udp_proto, 0, ports(443, 50001)))), redirect), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(decide(direct, quote_v4(icmp_message(12, 0, ipv4_packet(udp_proto, 0, ports(443, 50001)))), redirect), + icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(decide(direct, quote_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, + ipv6_packet(udp_proto, ports(443, 50002)))), redirect), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(decide(direct, quote_v6(icmp_message(4, 0, ipv6_packet(udp_proto, ports(443, 50002)))), redirect), + icmp_error_action::drop_proxied_udp_reply); + + // In Proxy mode an answer from port 53 is reported as a DNS answer whatever the redirect says. + EXPECT_EQ(decide(proxy_mode, udp_quote(53, 50001), redirect), icmp_error_action::drop_dns_answer); + // In Direct mode a proxied flow's reply from port 53 is still a proxied UDP reply. + EXPECT_EQ(decide(direct, udp_quote(53, 50001), redirect), icmp_error_action::drop_proxied_udp_reply); +} + +TEST(ProxiedUdpIcmpPolicy, OtherIcmpIsPassedAndTheRedirectIsConsultedOnlyForQuotedUdp) { - EXPECT_TRUE(proxy::plan_dns_icmp_filters(direct).empty()); - const std::vector both{ dns_family::ipv4, dns_family::ipv6 }; - EXPECT_EQ(proxy::plan_dns_icmp_filters(proxy_mode), both); + using proxy::icmp_error_action; + const redirected_ports redirect{ { 50001 }, {} }; + + // Ping and neighbor discovery whose data looks like a reply to a redirected port. + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_echo_request, 0, ipv4_packet(udp_proto, 0, ports(443, 50001)))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_echo_reply, 0, ipv4_packet(udp_proto, 0, ports(443, 50001)))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, quote_v6(icmp_message(icmpv6_echo_request, 0, ipv6_packet(udp_proto, ports(443, 50001)))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, quote_v6(icmp_message(135, 0, ipv6_packet(udp_proto, ports(443, 50001)))), redirect), + icmp_error_action::pass); + // A TCP segment to the same port: the UDP redirect does not describe it (proxied TCP is + // answered with a reset, not an ICMP error). + EXPECT_EQ(decide(direct, proxy::icmp_error_quote{ tcp_proto, 443, 50001 }, redirect), icmp_error_action::pass); + // A later fragment, or a quote cut before the destination port. + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 185, ports(443, 50001)))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, { 0x01, 0xbb }))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, proxy::icmp_error_quote{ udp_proto, 443, std::nullopt }, redirect), icmp_error_action::pass); + // A quoted datagram that the redirected port sent rather than received: the port to look up + // is the quoted destination (here the peer's 443), not the source. + EXPECT_EQ(decide(direct, udp_quote(50001, 443), redirect), icmp_error_action::pass); + + // Only that last quote, UDP with both ports, consulted the redirect; ping, neighbor + // discovery, TCP and cut quotes never take its lock. + EXPECT_EQ(redirect.asked, (std::vector{ 443 })); + + // The DNS rule decides without consulting the redirect. + const redirected_ports untouched{ { 50001 }, {} }; + EXPECT_EQ(decide(proxy_mode, udp_quote(53, 50001), untouched), icmp_error_action::drop_dns_answer); + EXPECT_TRUE(untouched.asked.empty()); +} + +TEST(IcmpErrorFilterPlan, OutboundIcmpIsKeptInUserModeForDnsProxyModeAndForEachFamilyWithProxiedUdp) +{ + const std::vector none, v4_only{ dns_family::ipv4 }, v6_only{ dns_family::ipv6 }, + both{ dns_family::ipv4, dns_family::ipv6 }; + + // No UDP is proxied: only DNS Proxy mode needs ICMP in user mode, for both families. + EXPECT_EQ(proxy::plan_icmp_error_filters(direct, false, false), none); + EXPECT_EQ(proxy::plan_icmp_error_filters(proxy_mode, false, false), both); + // A UDP listener of a family needs that family's ICMP in either mode. + EXPECT_EQ(proxy::plan_icmp_error_filters(direct, true, false), v4_only); + EXPECT_EQ(proxy::plan_icmp_error_filters(direct, false, true), v6_only); + EXPECT_EQ(proxy::plan_icmp_error_filters(direct, true, true), both); + EXPECT_EQ(proxy::plan_icmp_error_filters(proxy_mode, true, false), both); + EXPECT_EQ(proxy::plan_icmp_error_filters(proxy_mode, false, true), both); } From 5fddaca866ce0f40209e552d21e52cb1ce11dd03 Mon Sep 17 00:00:00 2001 From: Vadim Smirnov Date: Sat, 14 Nov 2026 09:04:31 +0100 Subject: [PATCH 62/62] docs: say how long to keep the socket open in validation step 16 Step 16 told the tester to close the socket before the reply arrives. A socket closed at once is gone before its datagram can be attributed to the application, so the datagram is sent directly, the server answers directly, and the ICMP error about that direct reply is passed, which looks like the drop not working. Measured on Windows with 12 datagrams per delay: closed after 0 ms, all 12 went out directly; after 2 ms, 9 did; after 10 ms and 30 ms, none. The step now says to keep the socket open for about 50 ms, to use a server that delays its reply when the SOCKS5 server answers faster than that, and to confirm in the capture that no datagram went to the server directly. A STUN binding request is added to the example datagrams. --- docs/gui.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/gui.md b/docs/gui.md index e01026b..8ce88b9 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -176,5 +176,5 @@ The routing policy and the packet rewriting are covered by automated tests (`net 13. **Relay source and shared IDs.** If the SOCKS5 server reports an address other than the queried DNS server as the source of UDP replies (for example its own IPv4 address), confirm lookups succeed without and with `serverOverride`, to an IPv4 resolver and to an IPv6 resolver. Run many lookups in parallel (for example `1..200 | ForEach-Object -Parallel { Resolve-DnsName "host$_.example.com" -DnsOnly -ErrorAction SilentlyContinue }` in PowerShell 7) and confirm each one gets its own answer. 14. **SOCKS5 server used as a resolver.** Send a lookup to the SOCKS5 server's own IP address (`Resolve-DnsName example.com -Server -DnsOnly`). Confirm the query goes through the proxy, not directly. If the server listens on TCP port 53 or returns a UDP relay on port 53, also confirm ProxiFyre still reaches it and the one-time `Info` line about the relay appears. 15. **Limited mode.** Repeat step 2 in the optional unelevated console mode. -16. **ICMP errors about proxied UDP replies.** With `Direct` DNS and a rule that proxies `UDP` for a test application, capture on the physical adapter (`pktmon filter add -t ICMP`, `pktmon filter add -t ICMPv6`, `pktmon start --capture --comp nics`, then `pktmon stop` and `pktmon etl2pcap PktMon.etl`; or Wireshark with `icmp.type == 3 || icmpv6.type == 1`). From the application, send a UDP datagram to a server that answers after a delay, over IPv4 and over IPv6, and close the socket before the reply arrives. For example, query a DNS server on a port other than 53 that answers slowly, or use a UDP echo server that delays its reply. Confirm the SOCKS5 server relays the reply, that no ICMP type 3 or ICMPv6 type 1 message addressed to the server leaves the adapter, and that the engine log has one "Dropped an ICMP error about a proxied UDP reply" line naming the client port. Repeat the test with the rule disabled: the error now leaves the adapter, which shows the test provokes it. Confirm `ping` and `ping -6` to the server still work, and that the same check passes in `Proxy` mode. +16. **ICMP errors about proxied UDP replies.** With `Direct` DNS and a rule that proxies `UDP` for a test application, capture on the physical adapter (`pktmon filter add -t ICMP`, `pktmon filter add -t ICMPv6`, `pktmon start --capture --comp nics`, then `pktmon stop` and `pktmon etl2pcap PktMon.etl`; or Wireshark with `icmp.type == 3 || icmpv6.type == 1`). From the application, send a UDP datagram to a server that answers after a delay, over IPv4 and over IPv6, and close the socket before the reply arrives but not at once: keep it open for about 50 ms after sending. A socket that closes within a few milliseconds is gone before ProxiFyre can attribute its datagram to the application, so the datagram is sent directly, the server answers directly, and the ICMP error about that direct reply is passed. The reply has to arrive after the close, so with a SOCKS5 server that answers faster than that, use a server that delays its reply. For example, query a DNS server on a port other than 53 that answers slowly, send a STUN binding request, or use a UDP echo server that delays its reply. Confirm in the capture that no datagram went from the application to the server directly and that the SOCKS5 server relays the reply, that no ICMP type 3 or ICMPv6 type 1 message addressed to the server leaves the adapter, and that the engine log has one "Dropped an ICMP error about a proxied UDP reply" line naming the client port. Repeat the test with the rule disabled: the error now leaves the adapter, which shows the test provokes it. Confirm `ping` and `ping -6` to the server still work, and that the same check passes in `Proxy` mode. 17. **GUI.** On the **Settings / Diagnostics** tab at 100% and 150% scaling, confirm the DNS routing group and the Uninstall button are reachable (scrolling is expected). Confirm Alt+M, Alt+P, and Alt+S focus the mode, proxy, and override fields; that the DNS proxy selection survives **Move Up**/**Move Down** and a reload; that **Duplicate** does not copy the id; and that removing the selected rule shows the missing id and fails validation.