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/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 6e092a9..e97d9f2 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,30 @@ 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 + submodules: true + + - 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 @@ -22,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/ProxiFyre.Configuration/ConfigurationNormalizer.cs b/ProxiFyre.Configuration/ConfigurationNormalizer.cs index 512ea68..c4e9e67 100644 --- a/ProxiFyre.Configuration/ConfigurationNormalizer.cs +++ b/ProxiFyre.Configuration/ConfigurationNormalizer.cs @@ -28,12 +28,73 @@ 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) }; + DropUnusedInvalidProxyIds(result.Proxies, DnsConfiguration.GetNamedProxyId(configuration.Dns)); return result; } + /// + /// 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) + { + 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) + 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 +125,7 @@ public ProxyRule NormalizeRule(ProxyRule rule) var hasCanonicalTransport = TryGetCanonicalTransport(rule.Socks5Transport, out transport); return new ProxyRule { + Id = EmptyToNull(rule.Id), AppNames = appNames, Socks5ProxyEndpoint = rule.Socks5ProxyEndpoint == null ? null : rule.Socks5ProxyEndpoint.Trim(), Username = rule.Username, diff --git a/ProxiFyre.Configuration/ConfigurationSerializer.cs b/ProxiFyre.Configuration/ConfigurationSerializer.cs index 5d7aa04..0bd5902 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) { @@ -65,6 +74,8 @@ public ProxiFyreConfiguration Deserialize(string json) "The configuration is not a valid JSON object.", ex); } + PrepareKeysEarlierReleasesIgnored(root); + ProxiFyreConfiguration configuration; try { @@ -91,6 +102,81 @@ public ProxiFyreConfiguration Deserialize(string json) return configuration; } + /// + /// 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. 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; + 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) + 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 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() + .Where(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)) + .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. diff --git a/ProxiFyre.Configuration/ConfigurationValidator.cs b/ProxiFyre.Configuration/ConfigurationValidator.cs index f980a9e..5a5f30f 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, configuration.Dns, issues); + ValidateDns(configuration.Dns, configuration.Proxies, issues); return new ValidationResult(issues); } @@ -507,6 +509,217 @@ private static string GetPathTail(string value) : lastSlash < 0 ? value : string.Empty; } + 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 = 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; + if (string.IsNullOrWhiteSpace(id)) + continue; + + var trimmed = id.Trim(); + var referenced = referencedId != null && + 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 + (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, firstInvalidIndex), + RulePath(index) + ".id", + index)); + continue; + } + + if (seen.TryGetValue(trimmed, out firstIndex)) + { + 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. 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 + UnusedIdConsequence(named, firstIndex), + RulePath(index) + ".id", + index)); + continue; + } + + seen.Add(trimmed, index); + } + } + + /// 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) + { + 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) + { + 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") + ". Name resolution then relies on Windows " + + "querying a DNS server of the override's address family.", + "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..7c59bee --- /dev/null +++ b/ProxiFyre.Configuration/DnsConfiguration.cs @@ -0,0 +1,292 @@ +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; + + /// + /// 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 || !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(); + } + + /// + /// 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..5119ff3 --- /dev/null +++ b/ProxiFyre.Tests/DnsConfigurationTests.cs @@ -0,0 +1,693 @@ +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("has space")] + [TestCase("slash/id")] + [TestCase("ünicode")] + 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; + + 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 InvalidProxyIdIsOnlyAWarningWithoutADnsSection() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns = null; + configuration.Proxies[0].Id = new string('a', DnsConfiguration.MaximumProxyIdLength + 1); + + 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 DuplicateProxyIdReferencedByDnsIsAnErrorCaseInsensitively() + { + 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 DuplicateProxyIdThatDnsDoesNotUseIsOnlyAWarning() + { + var configuration = TwoProxyConfiguration(); + 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); + } + + [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'")] + public void MalformedDnsSettingsAreReportedByName(string json, string name) + { + var exception = Assert.Throws(() => _serializer.Deserialize(json)); + 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) + { + 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 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 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() + { + 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() + { + var configuration = _serializer.Deserialize("{ \"logLevel\": \"Info\", \"proxies\": [], \"dns\": null }"); + + Assert.That(configuration.Dns, Is.Null); + } + + // ---------------------------------------------------------------- 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); + } + + [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() + { + var configuration = TwoProxyConfiguration(); + configuration.Dns.Mode = "Tunnel"; + + 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); + 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..5bfa691 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, @@ -180,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); } @@ -189,6 +206,68 @@ 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) + { + // 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."); + 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); + var proxyUnavailable = 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 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)) + { + 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; + } + + 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..239829c 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.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.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."; + 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; 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..c87dec1 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; @@ -160,6 +166,7 @@ private void BindConfiguration() bypassLanCheckBox.Checked = configuration.BypassLan; RefreshRoutingGrid(); RefreshExclusionsList(); + BindDnsControls(); } finally { @@ -213,6 +220,193 @@ 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; + _dnsIdAssignedRule = null; + var previous = _suppressChanges; + _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; + dnsModeComboBox.SelectedIndex = !DnsConfiguration.TryGetMode(dns?.Mode, out mode) + ? -1 + : 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)); + // 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; + } + + 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(); + // 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; + + // 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) + { + ReferenceDnsProxyRule(configuration, dns, choice.Rule); + } + + var serverOverride = dnsServerOverrideTextBox.Text.Trim(); + dns.ServerOverride = serverOverride.Length == 0 ? null : serverOverride; + configuration.Dns = dns; + MarkConfigurationChanged(); + + // 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))); + } + + /// + /// 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; + 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) @@ -333,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); @@ -348,6 +546,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); @@ -366,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)); @@ -1759,6 +1961,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..00b1b20 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,20 @@ 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 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. +> +> **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). ## Windows GUI @@ -108,7 +122,8 @@ 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. @@ -124,6 +139,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/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..49e5d08 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. 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. | @@ -106,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. 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 @@ -120,6 +128,137 @@ 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). + +## 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. 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). + +## 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. | + +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 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 + +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 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 + +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, 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. 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. + +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`. + +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 + +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, 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 (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 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. + +### 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 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 + +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. 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 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. + +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 + +- 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. +- 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. +- 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 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..8ce88b9 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, 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 **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. @@ -85,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 @@ -151,3 +156,25 @@ 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). 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. +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,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. **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. 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-tests/netlib-tests.vcxproj b/netlib-tests/netlib-tests.vcxproj index 6b4fd3e..a3a3b0b 100644 --- a/netlib-tests/netlib-tests.vcxproj +++ b/netlib-tests/netlib-tests.vcxproj @@ -111,6 +111,8 @@ + + diff --git a/netlib-tests/pch.h b/netlib-tests/pch.h index bcb3fa0..ebedafc 100644 --- a/netlib-tests/pch.h +++ b/netlib-tests/pch.h @@ -57,5 +57,7 @@ #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" +#include "../netlib/src/proxy/dns_udp_multiplexer.h" #endif // PCH_H diff --git a/netlib/README.md b/netlib/README.md index af56c13..342fa91 100644 --- a/netlib/README.md +++ b/netlib/README.md @@ -87,3 +87,33 @@ 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 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, 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 + 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..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. * @@ -262,9 +280,13 @@ 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. 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 +361,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 +455,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); @@ -678,5 +716,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 3b6c2a8..17bc195 100644 --- a/netlib/src/ndisapi/tcp_local_redirect.h +++ b/netlib/src/ndisapi/tcp_local_redirect.h @@ -18,13 +18,60 @@ 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 + 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 (reset || (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; + } + }; + + /// 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 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 +96,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 +105,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 +203,189 @@ 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() || 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; + } + + /** + * @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_. + * + * 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. + */ + 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(); + + // 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() || it->second.reset) + return false; + + NETLIB_DEBUG("RESET TCP (client RST): {} -> {} : {}", + ntohs(it->first.port), std::string{ it->first.ip }, ntohs(it->second.original_port)); + mark_reset(it->second, now); + return true; + } + + 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 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 }; + return true; + } + + const auto it = redirected_connections_.find(key); + if (it == redirected_connections_.cend() || it->second.reset) + return false; + + if (flags & TH_FIN) + it->second.client_fin = true; + + it->second.last_activity = now; + 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 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. + */ + 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 {}; + + 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("RESET TCP (proxy RST): {} -> {} : {}", + ntohs(it->first.port), std::string{ it->first.ip }, ntohs(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 = now; + return { server_segment_result::translated, original_port }; + } + + public: /** * @brief Redirects a C2S TCP packet to the local proxy and applies NAT to the source port. * @@ -215,58 +425,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 +458,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); @@ -374,17 +488,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) + @@ -395,33 +520,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 it = redirected_connections_.find(net::ip_endpoint{ - T{ ip_header->ip_dst }, tcp_header->th_dport - }); - if (it == redirected_connections_.cend()) - return false; + const auto tracking = track_server_segment( + net::ip_endpoint{ T{ ip_header->ip_dst }, tcp_header->th_dport }, tcp_header->th_flags); + if (tracking.result != server_segment_result::translated) + return tracking.result; - 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 = tracking.original_port; // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -432,47 +540,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 it = redirected_connections_.find(net::ip_endpoint{ - T{ ip_header->ip6_dst }, tcp_header->th_dport - }); - if (it == redirected_connections_.cend()) - 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)); + const auto tracking = track_server_segment( + net::ip_endpoint{ T{ ip_header->ip6_dst }, tcp_header->th_dport }, tcp_header->th_flags); + if (tracking.result != server_segment_result::translated) + return tracking.result; - redirected_connections_.erase(it); - } - else - { - it->second.second = std::chrono::steady_clock::now(); - } + tcp_header->th_sport = tracking.original_port; // Swap Ethernet addresses std::swap(eth_header->h_dest, eth_header->h_source); @@ -483,10 +574,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; } /** @@ -518,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/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h new file mode 100644 index 0000000..8138791 --- /dev/null +++ b/netlib/src/proxy/dns_routing_policy.h @@ -0,0 +1,934 @@ +#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 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 + +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 + 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. + 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) + 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 + }; + + /// 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 + }; + + /// 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 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. + * The only ProxiFyre UDP traffic to a SOCKS5 server's address that can reach the recursion + * 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. + * + * @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. + * + * 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 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 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 || guard == dns_upstream_guard::exempt) + 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 (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) + 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, " + "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::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: + 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"; + } + } + + // --------------------------------------------------------------------------------------- + // 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 + // + // 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 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 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. + */ + [[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 + uint16_t source_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]), + static_cast((ipv6_packet[offset] << 8) | ipv6_packet[offset + 1]) }; + } + + 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 + { + 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. + * + * @param translated The redirect translated the packet back to its client. + */ + [[nodiscard]] constexpr listener_reply_action decide_listener_reply(const bool translated) noexcept + { + return translated ? listener_reply_action::revert : listener_reply_action::drop; + } + + // --------------------------------------------------------------------------------------- + // ICMP errors about datagrams the proxies delivered + // + // 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. + [[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; + } + + /// 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 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. + */ + [[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; + 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) + 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 detail::quoted_ports(quoted[9], quoted, quoted_size, header_size); + } + + /** + * @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. The destination port + * is absent when the quote ends between the two ports. + * + * @param icmp_message The ICMPv6 header followed by the quoted packet. + */ + [[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; + 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) + return std::nullopt; + + 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, ///< 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. + * + * - 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 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& 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 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. 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_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. + 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 + { + 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 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). + * + * 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 + { + 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 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 + { + if (payload == nullptr || size < dns_header_size) + return std::nullopt; + return static_cast((static_cast(payload[0]) << 8) | payload[1]); + } + + /// 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; + } + + // 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."); + 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/dns_udp_multiplexer.h b/netlib/src/proxy/dns_udp_multiplexer.h new file mode 100644 index 0000000..bf10fbf --- /dev/null +++ b/netlib/src/proxy/dns_udp_multiplexer.h @@ -0,0 +1,962 @@ +#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 +#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); + } + + /// 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 + * 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 Walks the question section of a DNS message (RFC 1035 section 4.1.2). + * + * @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. + * + * @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. + */ + 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 < dns_header_size) + return std::nullopt; + + const auto question_count = static_cast((message[4] << 8) | message[5]); + std::size_t end = dns_header_size; + 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) + 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 || size - end < 1 + length) + return std::nullopt; + visit(message + end, 1, false); + visit(message + end + 1, length, true); + end += 1 + length; + } + 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; + } + + /** + * @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; + 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. + * + * 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. + * 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. + */ + [[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 + truncate_dns_answer(out + header_size, relayed.data_size, + 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. 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 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. + */ + 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{}; + uint64_t question{}; + }; + + 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 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 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; + } + + // 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, 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. + */ + 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, it->second.question }; + erase(it); + if (expired) + return std::nullopt; + return result; + } + + /** + * @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 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); + } + else + { + ++it; + } + } + return counted; + } + + 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{}; + uint64_t question{}; + 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_; + }; + + /// 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, ///< 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 + }; + + /** + * @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 association that + * 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 + * 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 + * 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 caller serializes access. + */ + template + class dns_association_health + { + 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 }, + 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) + { + } + + /// 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_; + } + + /** + * @brief Records a failed attempt to open an association and backs off. + * @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 + { + back_off(now); + const bool first = !open_failure_reported_; + open_failure_reported_ = true; + return first; + } + + void on_opened(const time_point now) noexcept + { + unanswered_ = 0; + opened_at_ = now; + last_datagram_.reset(); + query_sent_ = false; + } + + /// 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, 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, 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 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. + */ + 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 (!silent && age >= minimum_age_) + failures_ = 0; + else + { + if (delivered && age >= minimum_working_life) + failures_ = 0; + back_off(now); + } + + 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 + /// 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; + reported_ = {}; + open_failure_reported_ = false; + if (now - opened_at_ >= minimum_age_) + failures_ = 0; + } + + /// 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 + { + 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 }; + + /// 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 + { + ++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::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_{}; + 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, query_ttl) + { + } + + /** + * @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); } + /// 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 + { + 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); } + + /// The association closed: its queries in flight can no longer be answered. See + /// 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, close); + } + + 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_; + }; + + /** + * @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 new file mode 100644 index 0000000..145dce3 --- /dev/null +++ b/netlib/src/proxy/socks5_dns_udp_relay.h @@ -0,0 +1,886 @@ +#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 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 +// 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. stop() also interrupts an association being opened. + +#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 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. + 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; + + /// 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::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; + + /// 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 }; + + /** + * @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 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. + */ + 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, + 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)), + 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_) + { + } + + ~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 or a thread could not be created. + */ + bool start() + { + if (running_) + return true; + + if (!create_listener_socket()) + 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; + 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); + + // 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(); + } + + 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_); + dropped_unavailable_ += waiting_.drop_all(); + 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: + /// 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; + static constexpr std::chrono::seconds report_interval{ 30 }; + + // --- Configuration ------------------------------------------------------------------- + + 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_; + + // --- State (lock_ protects everything below except the atomics and the listener) ----- + + std::mutex lock_; + std::condition_variable maintenance_cv_; + std::unique_ptr association_; + 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_; + + /// 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 }; + 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_refused_{ 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); + } + + /// 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. + void enable_keepalive(const SOCKET socket) const noexcept + { + 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, + 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). + [[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) + { + 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) + { + 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; + } + + if (send(association_->relay, reinterpret_cast(datagram.data()), + static_cast(datagram.size()), 0) != SOCKET_ERROR) + { + session_.on_query_sent(std::chrono::steady_clock::now()); + } + else + { + ++dropped_send_failures_; + if (!transient_udp_error(WSAGetLastError())) + { + 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) + { + // 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; + } + if (received <= 0) + continue; + + try + { + handle_listener_datagram(buffer, static_cast(received), sender); + } + catch (const std::exception& e) + { + ++dropped_unavailable_; + NETLIB_DEBUG("DNS relay: dropped a query: {}", e.what()); + } + } + } + + 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; + } + + // 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* override_address = server_override_ + ? reinterpret_cast(&server_override_->ip) + : nullptr; + 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_refused_; + 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. + 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; + } + + 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 (transient_udp_error(WSAGetLastError())) + continue; + owner->failed.store(true, std::memory_order_release); + { + std::scoped_lock lock(lock_); + maintenance_cv_.notify_all(); + } + return; + } + + 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) + { + return std::pair{ reinterpret_cast(&client.endpoint.ip), own_address_size }; + }, + answer.data(), answer.size(), std::chrono::steady_clock::now()); + } + + if (result.outcome != dns_relay_answer::deliver) + { + ++dropped_unmatched_answers_; + continue; + } + + 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_; + } + } + } + + 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() && session_.may_open(std::chrono::steady_clock::now())); + }); + if (stopping_.load(std::memory_order_acquire)) + break; + + try + { + maintain(lock); + } + catch (const std::exception& e) + { + if (!lock.owns_lock()) + lock.lock(); + NETLIB_ERROR("DNS relay: maintenance failed: {}", e.what()); + } + } + } + + /// 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(); + + // Retire an association whose relay or control connection failed, or that has + // stopped answering. + if (association_) + { + const char* reason = nullptr; + 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"; + close = dns_association_close::silent; + } + + 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 auto age = std::chrono::duration_cast(session_.association_age(now)); + const auto report = session_.on_closed(now, close); + + 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); + 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(); + } + + switch (report) + { + 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()); + 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)); + lock.lock(); + return; + } + } + else + { + session_.expire_closed(now); + } + + dropped_unavailable_ += waiting_.drop_stale(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 + /// 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)) + { + 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)) + { + if (opened) + { + lock.unlock(); + close_association(std::move(opened)); + lock.lock(); + return; + } + + if (stopping_.load(std::memory_order_acquire)) + return; + + 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 (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()); + } + else + { + NETLIB_DEBUG("DNS relay: SOCKS5 UDP association attempt failed again; next attempt in {} s", + retry.count()); + } + return; + } + + NETLIB_INFO("DNS relay: SOCKS5 UDP association with {} opened", upstream_.to_string()); + session_.on_opened(now); + association_ = std::move(opened); + + // Opening can take seconds; queries Windows has given up on are not sent late. + dropped_unavailable_ += waiting_.drop_stale(now); + for (auto& query : waiting_.take_all()) + send_query_locked(query.client, query.datagram); + } + + /// 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, &stopping_); + if (control == INVALID_SOCKET) + return nullptr; + + { + 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 (const std::exception& e) + { + NETLIB_DEBUG("DNS relay: SOCKS5 UDP ASSOCIATE failed: {}", e.what()); + relay_endpoint.reset(); + } + + { + std::scoped_lock lock(handshake_lock_); + handshake_socket_ = INVALID_SOCKET; + } + + if (!relay_endpoint || stopping_.load(std::memory_order_acquire)) + { + closesocket(control); + return nullptr; + } + + enable_keepalive(control); + + 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, and on stop(). + 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 + 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, {} naming a destination other than the queried server or the " + "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/socks5_local_udp_proxy_server.h b/netlib/src/proxy/socks5_local_udp_proxy_server.h index 0bd1892..7f7f6ad 100644 --- a/netlib/src/proxy/socks5_local_udp_proxy_server.h +++ b/netlib/src/proxy/socks5_local_udp_proxy_server.h @@ -84,6 +84,19 @@ 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. Apart from the + * 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&); + private: /** * @brief Maximum number of simultaneous proxy connections. @@ -93,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; @@ -211,6 +216,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. */ @@ -234,6 +244,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 }; @@ -244,32 +257,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 { @@ -520,12 +507,15 @@ 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), - proxy_port_(proxy_port) + relay_endpoint_observed_(relay_endpoint_observed_fn), + proxy_port_(proxy_port), + association_(log_level, logger::log_stream_) { if (!create_server_socket()) { @@ -1071,7 +1061,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) { @@ -1139,574 +1129,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. * @@ -1770,7 +1192,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( @@ -1784,7 +1206,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 (...) { @@ -1809,124 +1231,19 @@ namespace proxy udp_endpoint->ip, udp_endpoint->port); - auto remote_socket = WSASocket(address_type_t::af_type, SOCK_DGRAM, IPPROTO_UDP, nullptr, 0, - WSA_FLAG_OVERLAPPED); + // 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); + 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..ea3d747 --- /dev/null +++ b/netlib/src/proxy/socks5_udp_association.h @@ -0,0 +1,788 @@ +#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. + * @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, + 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); + + 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, cancel)) + { + 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, cancel)) + { + 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, const std::atomic_bool* const cancel = nullptr) 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) + { + // 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) + { + 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)) + { + 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; + } + } + + // 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/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index c8a2392..056995f 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,128 @@ 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 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 + * 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 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 + * 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 }; + + /** + * @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_. + */ + 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() 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 }; + + /** + * @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. + */ + 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. + */ + 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 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 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 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 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. + */ + 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 +648,51 @@ 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_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 + { + if constexpr (std::is_same_v) + return dns_udp_relay_v4_; + else + return dns_udp_relay_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. @@ -600,6 +788,22 @@ namespace proxy return enqueue_for_deferred_resolve(buffer); } + if (ip_header->ip_p == IPPROTO_ICMP) + { + // 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_quote(icmp_message, + buffer.m_Length - ETHER_HEADER_LENGTH - ip_header_size)); + } + } + return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; }); @@ -689,6 +893,9 @@ namespace proxy GetLastError()); } + stop_dns_udp_relays(); + release_dns_udp_relays(); + std::vector> proxies_to_stop; std::vector> proxies_to_stop_v6; { @@ -857,6 +1064,43 @@ namespace proxy if (udp) udp->stop(); + // 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(); + + { + 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); + 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); + 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); + + // 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(); + return false; + } + process_resolve_thread_ = std::thread(&socks_local_router::process_resolve_thread_proc, this); // Update network configuration and start filter @@ -914,7 +1158,13 @@ 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. 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(); @@ -933,6 +1183,14 @@ 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(); + // 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"); @@ -1064,6 +1322,8 @@ namespace proxy { add_lan_passover_filters_v4(); add_lan_passover_filters_v6(); + // 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. } /** @@ -1193,6 +1453,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; @@ -1278,6 +1542,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) { @@ -1420,6 +1685,8 @@ 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); + proxy_session_settings_.reserve(proxy_session_settings_.size() + 1); } // Install PASS filters only for upstream addresses selected by @@ -1515,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)) @@ -1536,6 +1824,8 @@ 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); + proxy_session_settings_.push_back(std::move(session_settings)); return proxy_servers_.size() - 1; // Return the index of the added proxy server } @@ -1637,6 +1927,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 @@ -1858,8 +2293,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) @@ -1885,12 +2323,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) @@ -1899,84 +2341,893 @@ namespace proxy }); } + // --------------------------------------------------------------------------------- + // Global DNS policy (see set_dns_routing() and dns_routing_policy.h) + // --------------------------------------------------------------------------------- + /** - * @brief Processes a UDP packet for possible redirection through a proxy. - * - * This function inspects the provided intermediate_buffer, attempts to resolve the associated process, - * and determines if the UDP packet should be redirected to a proxy port, passed through, or reverted. - * If the process cannot be resolved and @p postponed is false, the function returns std::nullopt, - * indicating that the packet should be queued for later processing. If @p postponed is true, a - * second attempt is made to resolve the process using an updated process table. - * - * If the process is associated with a UDP proxy, and the packet is from a new endpoint, the source - * port is recorded and a redirection is logged. The function then attempts to process the packet for - * client-to-server redirection. If the packet is from a known proxy port, it attempts to process it - * for server-to-client redirection. - * - * @param buffer Reference to the intermediate_buffer containing the packet data. - * @param postponed If false, only the current process table is used for lookup. If true, the process - * table is refreshed and a second lookup is attempted. - * @return std::optional indicating the action to take: - * - std::nullopt: process could not be resolved (should be queued for later) - * - packet_action::revert: packet should be reverted (redirected) - * - packet_action::pass: packet should be passed through + * @brief Local listener port of the DNS proxy for @p Transport and family @p AddrT. + * The caller holds lock_. */ - std::optional process_udp_packet(netlib::ndisapi::intermediate_buffer& buffer, const bool postponed) + template + std::optional dns_listener_port_locked() const { - auto* const ethernet_header = reinterpret_cast(buffer.m_IBuffer); - auto* const ip_header = reinterpret_cast(ethernet_header + 1); - const auto* const udp_header = reinterpret_cast(reinterpret_cast(ip_header) - + sizeof(DWORD) * ip_header->ip_hl); + if (!dns_proxy_id_) + return std::nullopt; - // 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) + if constexpr (Transport == dns_transport::udp) { - return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; + // 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 && !dns_udp_relays_stopping_ + ? std::optional{ relay->listener_port() } + : std::nullopt; } - - // If the packet is from a known proxy port, process for server-to-client redirection - if (is_udp_proxy_port(ntohs(udp_header->th_sport))) + else { - if (udp_redirect_->process_server_to_client_packet(buffer)) + const auto listener = [id = *dns_proxy_id_](const auto& servers) -> std::optional { - log_packet_to_pcap(buffer); - return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; - } - } + if (id >= servers.size() || !servers[id].first) + return std::nullopt; + return servers[id].first->proxy_port(); + }; - auto process = process_lookup_v4_. - lookup_process_for_udp(net::ip_endpoint{ - ip_header->ip_src, ntohs(udp_header->th_sport) - }); + if constexpr (std::is_same_v) + return listener(proxy_servers_); + else + return listener(proxy_servers_v6_); + } + } - if (!process) + /** + * @brief True when @p destination (and, for TCP, @p port) is one of ProxiFyre's own + * 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 + { + return std::ranges::any_of(proxy_upstreams_, [&](const net::ip_endpoint& upstream) { - if (postponed) + if (Transport == dns_transport::tcp && upstream.port != port) + return false; + + if constexpr (std::is_same_v) { - process = process_lookup_v4_. - lookup_process_for_udp(net::ip_endpoint{ - ip_header->ip_src, ntohs(udp_header->th_sport) - }); + return destination == upstream.ip; } else { - return std::nullopt; + // 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; } - } + }); + } - // Excluded or bypassing owners pass; a selection of none marks the owner as bypassing. - const auto proxy_lookup = route_owner(*process, - [&] { return get_proxy_port(process); }); + /// 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 + }; - if (proxy_lookup.action == proxy_port_action::proxy) + /** + * @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)) { - const auto is_new_endpoint = udp_redirect_->is_new_endpoint(buffer); - const auto source_address = net::ip_address_v4(ip_header->ip_src); - const auto source_port = ntohs(udp_header->th_sport); - const auto destination_address = net::ip_address_v4(ip_header->ip_dst); - const auto destination_port = ntohs(udp_header->th_dport); - + 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."); + } + } + + /** + * @brief Applies decide_icmp_error() to an outbound ICMP or ICMPv6 message. + * + * 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. + * + * @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. + */ + template + packet_filter::packet_action handle_outbound_icmp(const std::optional& quote) + { + 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); }); + + switch (action) + { + 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::pass }; + } + + /// 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 }; + } + + /// 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() + { + 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). + * + * The owner comes from process_lookup's cached tables, which are replaced only by + * 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 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"). + */ + 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, const bool postponed, + SenderLookup&& sender_lookup) + { + if (destination_port != dns_port) + return {}; + + constexpr auto v4 = std::is_same_v; + + dns_proxy_target target; + bool destination_matches_upstream = false; + bool relays_stopping = false; + std::optional> server_override; + { + 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.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(); + } + + 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(); + 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(exemption_candidate, + exemption_candidate ? sender_lookup(postponed) : std::optional{}, postponed); + + 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 }; + } + + /** + * @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) + { + // 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; + 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 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 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 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, + 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.decision.action != dns_route_action::proxy) + { + // 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 }; + } + + // 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::not_dns_message); + return packet_filter::packet_action{ action_type::drop }; + } + + 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(dns_udp_clients_lock_); + dns_udp_clients_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 (route.decision.action != dns_route_action::proxy) + { + // 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 }; + } + + 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 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 + * 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, + const proxy_session_settings& settings, const std::optional>& server_override) + { + try + { + auto relay = std::make_unique>(upstream, settings.credentials, + settings.upstream_options, server_override, + [this](const uint16_t port) + { + 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) + { + note_udp_relay_endpoint(relay_endpoint.port); + }, + log_level_, log_stream_); + + 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; + } + + 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() + { + // 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; + std::optional> override_v4; + std::optional> override_v6; + bool ipv4 = false; + bool ipv6 = false; + { + 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]; + 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; + ipv4 = family_supports_ipv4(families); + 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, 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); + dns_udp_relay_v6_ = std::move(relay_v6); + } + + /** + * @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() + { + socks5_dns_udp_relay* relay_v4; + socks5_dns_udp_relay* relay_v6; + { + std::unique_lock lock(lock_); + 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(); + } + + /** + * @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() + { + std::unique_ptr> released_v4; + std::unique_ptr> released_v6; + { + std::unique_lock lock(lock_); + released_v4 = std::move(dns_udp_relay_v4_); + released_v6 = std::move(dns_udp_relay_v6_); + dns_udp_relays_stopping_ = false; + } + } + + /** + * @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() + { + 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); }); + 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; + } + + /** + * @brief (Re)installs the static driver filters the DNS policy needs (plan_dns_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. 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 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() + { + dns_routing_mode mode; + dns_listener_ports listeners; + { + std::shared_lock lock(lock_); + 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(); + } + + remove_dns_filters(); + + for (const auto& spec : plan_dns_filters(mode, listeners)) + { + 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; + } + } + + // Outbound ICMP has to reach handle_outbound_icmp(): an ICMP error about a DNS answer + // or a proxied UDP reply quotes it and is addressed to the remote endpoint. + if (!install_icmp_error_filters(mode)) + { + remove_dns_filters(); + return false; + } + + return true; + } + + /** + * @brief Processes a UDP packet for possible redirection through a proxy. + * + * This function inspects the provided intermediate_buffer, attempts to resolve the associated process, + * and determines if the UDP packet should be redirected to a proxy port, passed through, or reverted. + * If the process cannot be resolved and @p postponed is false, the function returns std::nullopt, + * indicating that the packet should be queued for later processing. If @p postponed is true, a + * second attempt is made to resolve the process using an updated process table. + * + * If the process is associated with a UDP proxy, and the packet is from a new endpoint, the source + * port is recorded and a redirection is logged. The function then attempts to process the packet for + * client-to-server redirection. If the packet is from a known proxy port, it attempts to process it + * for server-to-client redirection. + * + * @param buffer Reference to the intermediate_buffer containing the packet data. + * @param postponed If false, only the current process table is used for lookup. If true, the process + * table is refreshed and a second lookup is attempted. + * @return std::optional indicating the action to take: + * - std::nullopt: process could not be resolved (should be queued for later) + * - packet_action::revert: packet should be reverted (redirected) + * - packet_action::pass: packet should be passed through + */ + std::optional process_udp_packet(netlib::ndisapi::intermediate_buffer& buffer, const bool postponed) + { + auto* const ethernet_header = reinterpret_cast(buffer.m_IBuffer); + auto* const ip_header = reinterpret_cast(ethernet_header + 1); + 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 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))) + { + // A listener reply never belongs on the wire: drop it when it cannot be translated. + 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 }; + } + + 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. 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, + [&](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_. + lookup_process_for_udp(net::ip_endpoint{ + ip_header->ip_src, ntohs(udp_header->th_sport) + }); + + if (!process) + { + if (postponed) + { + process = process_lookup_v4_. + lookup_process_for_udp(net::ip_endpoint{ + ip_header->ip_src, ntohs(udp_header->th_sport) + }); + } + else + { + return std::nullopt; + } + } + + // Excluded or bypassing owners pass; a selection of none marks the owner as bypassing. + const auto proxy_lookup = route_owner(*process, + [&] { return get_proxy_port(process); }); + + if (proxy_lookup.action == proxy_port_action::proxy) + { + const auto is_new_endpoint = udp_redirect_->is_new_endpoint(buffer); + const auto source_address = net::ip_address_v4(ip_header->ip_src); + const auto source_port = ntohs(udp_header->th_sport); + const auto destination_address = net::ip_address_v4(ip_header->ip_dst); + const auto destination_port = ntohs(udp_header->th_dport); + if (udp_redirect_->process_client_to_server_packet(buffer, htons(proxy_lookup.port))) { // Refresh authorization for every datagram that was actually redirected. A @@ -2037,13 +3288,51 @@ 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))) { - 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. + // A first fragment cannot be translated on its own (the TCP redirect does not check). + if (!ipv4_listener_packet_translatable(fragment)) { - 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 + // now unconditionally direct (previously it was routed like any other TCP traffic of + // 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, + [&](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); } } @@ -2133,6 +3422,36 @@ namespace proxy if (transport == nullptr) { + // 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) + { + 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)); + + 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(); + 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; + } + } + // 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 @@ -2173,6 +3492,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_quote(icmp_message, + static_cast(packet_end - icmp_message))); + } + } + return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; } @@ -2199,21 +3529,39 @@ 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 + // 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))) { - if (udp_redirect_v6_->process_server_to_client_packet(buffer)) + // A listener reply never belongs on the wire: drop it when it cannot be translated. + 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 }; } + + note_untranslated_listener_reply(); + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + } + + // 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), 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)); } auto process = process_lookup_v6_. @@ -2307,11 +3655,30 @@ 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)) - { - log_packet_to_pcap(buffer); - return packet_filter::packet_action{ packet_filter::packet_action::action_type::revert }; - } + // 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. + 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). + if (const auto dns = decide_dns( + 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); } auto process = process_lookup_v6_. @@ -2434,6 +3801,58 @@ 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); + } + 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); + } + 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; + } + /** * @brief Thread procedure for deferred process resolution and packet forwarding. * @@ -2468,11 +3887,18 @@ 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; while (true) { @@ -2488,7 +3914,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; @@ -2579,6 +4005,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_ && report_listener_and_dns_drops()) + { + last_dns_block_log = now; } // 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..ac05331 --- /dev/null +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -0,0 +1,1176 @@ +// 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()), 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 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" + +#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 }; + + /// 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, + 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; + } + + 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); + } + + /// 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 + { + 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_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(); + + // 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) }; + + 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, const char* local_address) + { + 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(result.size); + + const std::string server{ result.client->ip }; + if constexpr (std::is_same_v) + 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, result.client->port, out); + } + }; + + /// 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::vector relay_answer(const Addr& source, const uint16_t port, std::vector answer, + const uint16_t relay_id) + { + 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 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 }; + dns_relay relay; + 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(): 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)); + + // 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); + EXPECT_TRUE(packet.ip4_checksum_valid()); + EXPECT_TRUE(packet.l4_checksum_valid()); + + // 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); + 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; the client sees the original server and ID. + const auto answer = dns_message(0xabcd, 40); + 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 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 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 = 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 }; + 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()); + + 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); + 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_EQ(proxy::dns_message_id(view->data, view->data_size), std::optional{ 0x4321 }); + + const auto answer = dns_message(0x7777, 64); + 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()); +} + +// 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 }; + dns_relay relay; + const auto answer = dns_message(0x1111, 12); + + 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 + }; + + 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()); + } + + // 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")); + + 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. 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 }; + 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. 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 }; + dns_relay relay; + auto query = frame::udp6("fd00::10", "2001:4860:4860::8888", client_port, 53, dns_message(0x6363)); + 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, 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 }; + dns_relay relay; + auto query = frame::udp4("192.168.1.10", "8.8.8.8", client_port, 53, dns_message(0x6363)); + 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, 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 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::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 +// 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 }; + // 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))); + + // 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))); +} + +// ------------------------------------------------------------------ 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(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(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 }; + dns_relay relay; + const net::ip_endpoint server_override{ v4{ std::string{ "1.1.1.1" } }, 53 }; + + // 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)); + 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 = 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; + 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))); +} + +// 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()); + } +} + +// ------------------------------------------------------------------ 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)); + + // 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)); + 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); +} + +// 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()); +} + +// 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()); + } +} + +// ------------------------------------------------------------------ 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/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..29eaf43 --- /dev/null +++ b/netlib/test/portable/run-portable-tests.sh @@ -0,0 +1,57 @@ +#!/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 +# * ../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 +# +# 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. +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 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 ""}' \ + "$ndisapi_cpp" +} > "$checksums" +if [[ "$(grep -c '^void CNdisApi::Recalculate' "$checksums")" != "3" ]]; then + echo "Failed to extract the CNdisApi checksum routines from external/ndisapi/ndisapi/ndisapi.cpp" >&2 + exit 1 +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 \ + -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..7bdfe34 --- /dev/null +++ b/netlib/test/portable/winshim/packet_env.h @@ -0,0 +1,25 @@ +// 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 "../../../../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. +#define u_long winshim_u_long +#define long int +#include "../../../src/iphlp.h" +#undef long +#include "../../../../external/ndisapi/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" +#include "../../../src/proxy/dns_udp_multiplexer.h" diff --git a/netlib/test/portable/winshim/winshim.h b/netlib/test/portable/winshim/winshim.h new file mode 100644 index 0000000..fc74203 --- /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 the ndisapi submodule (external/ndisapi) 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..8f17985 --- /dev/null +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -0,0 +1,1001 @@ +// 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. 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). + +#include "pch.h" +#include "../../src/proxy/dns_routing_policy.h" + +#include +#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; + 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. + 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, 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, apply, 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, 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); + 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. 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{}; + for (const auto& c : all_cases) + { + 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); + } + } + } +} + +// 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, apply, 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, 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, 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, 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, apply, 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, apply, with_v4_override.target(transport, dns_family::ipv4)).action, + dns_route_action::proxy); + + 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, 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, apply, with_v6_override.target(dns_transport::udp, dns_family::ipv4)).action, + dns_route_action::block); +} + +// 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) + { + 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); + } +} + +// 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, apply, p.target(dns_transport::udp, dns_family::ipv4)).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; + } + } +} + +// 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) +{ + 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) +{ + 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()); +} + +// 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) +{ + using proxy::decide_listener_reply; + using proxy::listener_reply_action; + + 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; +// 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()); +} + +// 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); +} + +// ------------------------------------------------------------------ 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))); +} + +// 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); +} + +// 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); + } + } +} + +// 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))); +} + +// ------------------------------------------------------------------ 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()); +} + +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::icmp_error_action; + + 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(direct, udp_quote(53, 58440)), icmp_error_action::pass); + // Other traffic, and messages that quote nothing usable, are never touched. + 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(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(proxy_mode, + quote_v4(icmp_message(icmpv4_echo_request, 0, ipv4_packet(udp_proto, 0, ports(53, 1))))), + icmp_error_action::pass); +} + +// ------------------------------------------------------------------ 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) +{ + 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); +} 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..b1ae4c7 --- /dev/null +++ b/netlib/test/proxy/dns_udp_multiplexer_test.cpp @@ -0,0 +1,1071 @@ +// 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 } }; + 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 + { + 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)); + } + + // 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, AssociationThatDeliversOnceOldEnoughResetsTheBackoff) +{ + proxy::dns_association_health<> health{ 3, 30s }; + (void)health.on_open_failed(t0); + (void)health.on_open_failed(t0); + health.on_opened(t0 + 2s); + // 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); +} + +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, 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(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, 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 + // 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); +} + +// --- 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)); +} + +// --- 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)); +} + +// --- 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, silent_close); + EXPECT_EQ(health.consecutive_failures(), 1u); + 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, silent_close); + 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(at); + health.on_closed(at + 140s); + EXPECT_EQ(health.consecutive_failures(), 0u); + 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, silent_close); + EXPECT_FALSE(health.may_open(at + 999ms)) << cycle; + EXPECT_TRUE(health.may_open(at + 1s)) << cycle; + at += 1s; + } +} + +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)); + + // 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(t0 + 5s); + ASSERT_TRUE(health.on_unanswered(3, t0 + 40s)); + (void)health.on_closed(t0 + 40s, silent_close); + 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(at); + unusable_reports += health.on_closed(at + 100ms) != report::none ? 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) +{ + 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)); +} + +// 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_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; + } +} + +// 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; + } +} + +// 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, 10s }; + + // 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, 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. + proxy::dns_association_health<> health{ 3, 30s, 10s }; + health.on_opened(t0); + 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)); +} + +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_EQ(idle.on_closed(t0 + 2s), report::none); + idle.on_opened(t0 + 10s); + 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_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_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(t0 + 1s); + EXPECT_EQ(unanswered.association_age(t0 + 60s), 60s); + EXPECT_EQ(unanswered.on_closed(t0 + 60s), report::no_answer); +} 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"); 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..a610fe7 100644 --- a/socksify/socksify.vcxproj +++ b/socksify/socksify.vcxproj @@ -268,6 +268,10 @@ + + + + diff --git a/socksify/socksify.vcxproj.filters b/socksify/socksify.vcxproj.filters index 0e70381..3e5c0ba 100644 --- a/socksify/socksify.vcxproj.filters +++ b/socksify/socksify.vcxproj.filters @@ -141,6 +141,18 @@ Header Files\netlib\proxy + + Header Files\netlib\proxy + + + Header Files\netlib\proxy + + + 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. diff --git a/socksify/unmanaged.h b/socksify/unmanaged.h index 0e45541..bb892c0 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" @@ -69,7 +69,9 @@ #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/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"