Repository navigation
Add configurable DNS routing (Direct and Proxy modes) - #190
Merged
Merged
Conversation
Add a global DNS policy for conventional DNS (UDP and TCP port 53): - Direct (default, also for configurations without a dns section): port-53 traffic bypasses every proxy for IPv4 and IPv6. TCP/53 is now unconditionally direct as well (previously only UDP/53 was). - Proxy: all captured port-53 traffic, whatever process sends it (including the Windows DNS Client service), goes through one selected SOCKS5 proxy via the existing UDP ASSOCIATE and TCP CONNECT paths. The policy fails closed: DNS the proxy cannot carry is dropped, never sent direct, and takes precedence over LAN bypass through front-of-table driver REDIRECT filters. - Optional serverOverride (IPv4/IPv6 literal): only the SOCKS5 destination changes; UDP answers are restored to the server the resolver queried (tracked by client port and DNS message ID). Queries to servers of the other family are blocked. - The DNS proxy is referenced by a new stable per-rule "id", which survives reordering, editing and reload; invalid or dangling references and proxies without TCP+UDP are rejected by validation. Native: dns_routing_policy.h holds the platform-independent decisions, override syntax, reply classification and origin tracker; the router applies them before process attribution. socks5_udp_local_redirect gains optional SOCKS destination / source-restore parameters. ProxiFyre's own upstream traffic is never captured. Managed: DnsSettings model, DnsConfiguration helpers, validator and normalizer rules, service wiring (fail closed when the selected proxy could not be created), and a DNS routing group in the GUI settings tab. Tests: GoogleTest policy suite (also in netlib-tests), a portable packet round-trip suite that runs the real redirect headers and the product checksum routines on Linux (new CI job), and NUnit DNS configuration tests. Docs: configuration reference, GUI guide, README, sample configuration.
wiresock
force-pushed
the
claude/proxifyre-dns-routing-f94k1o
branch
from
November 12, 2026 13:11
bc7d528 to
e0d9c8b
Compare
…loses A packet sourced from a local proxy listener is addressed to the original server only because redirection swapped its addresses. When process_server_to_client_packet could not translate it, all four handlers fell through and passed it; for the DNS listener that sent the SOCKS5 header and the DNS answer toward the original resolver in clear (for example an answer large enough to fragment, or a relay replying with another ATYP). Such packets are now dropped (decide_listener_reply) and counted, with a throttled debug report. This must land together with the TCP close tracking: tcp_local_redirect erased its entry on the first FIN or RST, so the rest of an ordinary close found no entry. On the application path those segments reached the real server and provoked a RST, which is what tore the connection down; on the DNS path they were dropped and reported as blocked DNS. The entry is now kept through the close in both directions (half-closed 2 min, 10 s linger after both FINs, 5 min idle while open) and removed immediately on RST. A SYN on a closing key starts a new connection. This changes the application path too: trailing close segments are now translated instead of being passed to the real server. Tests: TCP client- and listener-initiated closes, FIN retransmits, RST from either side, the timeouts, key reuse, and the listener-drop rule.
…DNS policy The recursion guard matched UDP by destination address only, so when a host was both the SOCKS5 server and the resolver every UDP query to it went direct, ignoring serverOverride, with no log line. The address (and, for TCP, port) match is now only a cheap pre-filter. A matching port-53 packet is exempt only when its owner is ProxiFyre's own process. The process lookup runs only for such packets and without holding lock_. An owner that cannot be resolved inline defers the packet to the existing deferred-resolve path; if it is still unknown there, the packet is dropped and counted (upstream_sender_unknown): passing it could leak a query and redirecting ProxiFyre's own traffic would loop. The TCP guard uses the same sender check. The decision is in decide_dns_upstream_guard() and decide_dns_route() (dns_routing_policy.h) and covered by the policy tests. The stated limitation is removed from docs/configuration.md.
…Proxy mode IPv6 fragments returned pass before any DNS check, and the IPv4 handlers read "ports" from the payload of non-first fragments. - IPv4: a later fragment (non-zero offset) is no longer classified as DNS. A first fragment addressed to port 53 that Proxy mode would redirect is dropped (reason "fragmented"): a fragmented datagram cannot be redirected and passing its first fragment would send DNS directly. - IPv6: in Proxy mode, a first fragment (offset 0) whose upper-layer header is UDP or TCP with destination port 53 is dropped. A new parse_ipv6_first_fragment() reads that header from raw bytes instead of changing what find_transport_header() returns to existing callers. - Later fragments carry no ports and are left alone, so unrelated fragmented traffic is unaffected. The helpers (classify_ipv4_fragment, apply_fragmentation, parse_ipv6_first_fragment) are in dns_routing_policy.h with tests. docs/configuration.md now states exactly what is and is not dropped.
install_dns_filters() ran once per router and only logged when a filter could not be inserted. - Every start() now removes the DNS filters installed earlier (the only REDIRECT filters the router installs) and inserts the current plan at the front again, so they stay ahead of LAN-bypass PASS filters added between runs and use the current listener ports and proxy selection. In Direct mode they are only removed. - If any filter Proxy mode needs cannot be inserted, start() fails through the existing failure cleanup instead of running with DNS able to bypass the policy. - No source-port filter is installed for a listener that is not running or reports port 0. The filter set is computed by plan_dns_filters() in dns_routing_policy.h and covered by tests.
With a serverOverride, a reply whose SOCKS5 header did not name the override server was left unchanged and then discarded by the resolver, so relays that report another source (for example their own address) broke DNS. classify_dns_override_reply() now restores any reply on the DNS listener whose (client port, DNS message ID) matches a tracked query, whatever its header source. Replies that name the override but match no query are still dropped, and unmatched replies from other sources are still left unchanged. The header's address type must still match the listener's family, since the redirect strips a header of that size. Tests cover a relay reporting another source end to end; the "Server override" section of docs/configuration.md is updated.
… active dns_udp_reply_origin() took lock_ for every reply leaving any local UDP listener, in every mode. set_dns_routing() now sets an atomic flag only in Proxy mode with a usable proxy and a server override (dns_reply_restore_needed()), and the reply path returns early without locking when it is clear, so Direct mode and override-free Proxy mode add no locking to application UDP replies.
When the table was full of live entries, each insert on the packet thread ran a full sweep plus a linear min_element under the mutex. Entries are now also recorded in an insertion-ordered queue: expiry and eviction of the oldest entry pop from its front (amortized O(1)), stale records left by refreshed or resolved-and-expired keys are skipped, and the queue is compacted when stale records outnumber live entries. Semantics are unchanged: lookups do not consume entries, re-remembering a key refreshes its time, the TTL is 30 seconds and the table is bounded. Tests cover refresh-aware eviction, the queue bound, and the cost of inserting into a full table (about 10 ms for 200k inserts, versus about 6.7 s before).
Direct mode, which also applies to configurations without a dns section, now always sends TCP port 53 directly. Add a clearly marked upgrade note to README.md and extend the docs/configuration.md callout: rules that previously carried TCP port 53 through a proxy no longer do so, and Proxy mode is the way to route DNS through a proxy.
…wn DNS modes When the selected DNS proxy cannot be created at startup, the service keeps running and blocks all DNS by design. The error log now says explicitly that all DNS is blocked until the service is restarted after the cause is fixed, logs it once instead of twice, and the Proxy mode section of docs/configuration.md states the same. ConfigureDnsRouting() now uses DnsConfiguration.TryGetMode() and fails the service start on an unknown mode instead of relying on GetMode(), which maps any unknown value to Direct.
The one-warning-per-cause and throttled drop count apply only to packets the DNS policy itself blocks. SOCKS5 connection, authentication, TLS and UDP ASSOCIATE failures, and proxy disconnects, happen after a successful redirect and are reported by the local proxy server. Separate the two in the Proxy mode section of docs/configuration.md and in manual validation step 5 of docs/gui.md, list the new drop causes (fragments, unknown sender to a SOCKS5 server), and stop promising that Windows falls back to other DNS servers.
- ConfigurationNormalizer turns a whitespace-only rule id into null instead of an empty string, so a saved configuration does not gain an "id": "" property. - DNS_SERVER_OVERRIDE_OTHER_FAMILY_BLOCKED no longer promises that Windows falls back to other DNS servers; it says name resolution relies on Windows querying a server of the override's family. NUnit cases cover both, and that TryGetMode rejects an unknown mode.
…e field Each DNS label now has the TabIndex immediately before its control (&mode -> DNS mode, &proxy -> DNS proxy, &Server override -> server override text box), and the Uninstall button gets an explicit tab position after the DNS group. The layout is unchanged: the DNS group plus the Uninstall button do not fit the 487-pixel design height of the Settings tab without rearranging other groups, so the page relies on its existing AutoScroll. This needs a visual check on Windows.
- DecisionDoesNotDependOnTheSendingProcess called the same pure function repeatedly. It is replaced by SenderNeverAffectsQueriesToOrdinaryResolvers, which fails if the recursion guard's sender check ever applies to queries that are not addressed to a SOCKS5 server (an unresolved Dnscache owner would then be deferred or dropped). - TruncatedUdpAnswerTcpRetryUsesTheSameProxy compared two listener ports from the same fixture. It is replaced by TcpRetryIsRedirectedOrBlockedNeverPassed (TCP/53 is redirected to the proxy's TCP listener, or blocked when the proxy has no TCP, for both families) and by a packet-level test that sends a truncated UDP answer and the TCP retry through the real redirects, checking the TC bit, restored source, listener replies through the close, and checksums.
Three related problems in how packets from local proxy listeners are handled: 1. A fragmented IPv6 listener reply was passed to the wire. When the stack fragments a reply (a DNS answer over about 1430 bytes), find_transport_header() returns null, and the first-fragment check only looked for destination port 53, which a reply never has. The first fragment, carrying the SOCKS5 header and the start of the answer, went toward the original resolver. parse_ipv6_first_fragment() now also returns the source port, and decide_ipv6_fragment() drops a first fragment whose source port is an IPv6 listener port of its protocol, in every mode, counted with the other untranslated listener replies. The Proxy-mode port-53 drop is kept. 2. Later IPv4 fragments of unrelated traffic could be dropped: the listener-port check ran before fragment classification, so a later fragment whose first payload bytes equalled a listener port was treated as an untranslatable listener reply. Both IPv4 handlers now classify the fragment first and skip the listener check and DNS classification for later fragments (ipv4_transport_header_present()), which are passed as before. 3. Listener-reply drops were invisible at the default log level, and the UDP override-classification drop was not counted. Both UDP drop paths now go through decide_udp_listener_reply() and are counted; the first drop per run is logged at warning level and the throttled count at info level. The one-shot flag is reset in start(). Tests cover each decision and fail when it is reverted.
…time The full-table test asserted that 200,000 inserts finish in 2 seconds. It measured 13 ms in a plain gcc build and 436 ms under ASan/UBSan, was never measured in an MSVC Debug build, and its comment overstated the headroom. The tracker now counts every table entry and queue record it examines (expiry, eviction, compaction and sweeps all go through the counter; visits() exposes it for tests). The test fills the table with live entries and asserts that 100,000 further inserts examine at most 4 per insert; a per-insert sweep examines the whole table (8193 per insert) and fails. A second test bounds the work of repeated refreshes. No test in this suite depends on wall-clock time any more.
A segment with both SYN and RST was treated as a SYN and restarted tracking. tcp_local_redirect now checks RST first: on a tracked key it ends tracking (the segment is still translated), and on an untracked key it neither creates an entry nor is rewritten. A portable test covers both cases and fails with the previous ordering.
…; document idle and recursion limits - ProxiFyre/Program.cs: when the engine fails to start in DNS Proxy mode, the message now says that a driver filter needed to keep DNS in the DNS proxy may have failed to install and that the engine log has the cause, instead of naming only the driver. - docs/configuration.md: state that a proxied TCP connection idle for more than 5 minutes loses its redirect entry, after which segments the local proxy sends first are dropped instead of reaching the real server, so the connection stalls rather than being reset. In "Recursion and ProxiFyre's own traffic", give examples of senders that cannot be determined: traffic forwarded for virtual machines or containers, and kernel- or driver-owned sockets.
… tables The recursion guard exempts a port-53 packet addressed to a SOCKS5 server when process_lookup's cached tables say its owner is ProxiFyre. Those tables are replaced only by actualize(), which runs when the resolver thread processes deferred packets, so a row for a ProxiFyre socket that has since closed can survive until the next refresh. A packet that hits the stale row is answered inline and does not trigger a refresh itself. The race is real but narrow: it needs another process to reuse the exact local UDP port (TCP rows are keyed by the full 4-tuple, which TIME_WAIT normally protects) and to send DNS to the SOCKS5 server's own address before any other deferral refreshes the table. The exact fix, tracking ProxiFyre's own upstream sockets, would have to cover about 70 close paths across the proxy servers and sockets, where sockets change owners. That is not a contained change, and a missed removal would recreate the same stale-entry problem. Deferring every such packet instead was ruled out. The race, its preconditions and how to avoid it are documented in "Recursion and ProxiFyre's own traffic", and at sender_is_proxifyre().
…g a fault tcp_local_redirect erased a connection's entry as soon as an RST was seen, so when an application aborted a proxied connection while the local proxy was still sending, the proxy's in-flight segments found no entry and were reported like any untranslatable listener packet: a warning per run plus an info-level count, making an ordinary abort look like a fault. - An RST now ends the connection but keeps its key as a short-lived record (connection_state::reset) for closed_linger. Nothing on that key is translated after the RST, except that a new SYN starts a new connection as it does on a closing key. Client-to-server segments on a reset key behave exactly as on an untracked key. - process_server_to_client_segment() reports translated, recently_reset or unknown; process_server_to_client_packet() keeps its bool contract. - The router's TCP handlers map the result through decide_tcp_listener_segment(): a recently-reset segment is dropped without the warning or the info-level count and counted separately at debug level; unknown segments keep today's reporting. Tests cover a listener segment after a client RST and after a listener RST, client segments on a reset key, expiry of the record, a new SYN on a reset key, and the pure decision.
The recursion guard exempted a port-53 packet addressed to a configured
SOCKS5 server when the cached connection table said its sender was
ProxiFyre. The table is refreshed only when a packet is deferred, so a
stale row for a closed ProxiFyre UDP socket could send another
process's UDP query to a host that is both SOCKS5 server and resolver
directly.
ProxiFyre has two UDP sockets per UDP proxy server: the local listener,
which only sends to local clients, and the relay socket, which is
connected to the endpoint associate_to_socks5_proxy() returns,
{socks_server_address, BND.PORT}, and sends nothing else. So ProxiFyre
sends UDP to a SOCKS5 server's address on port 53 only if a relay
endpoint has port 53.
- socks5_local_udp_proxy_server reports each relay endpoint through a
new optional callback, before the relay socket is created; the router
passes it like its other callbacks (both address families) and sets an
atomic flag, never cleared, when a relay uses port 53 (logged once).
- is_upstream_exemption_candidate(): for UDP, a destination matching a
SOCKS5 server is a candidate for exemption only when the flag is set;
otherwise the packet follows the DNS policy with no sender lookup and
no deferral. TCP is unchanged (it already requires a server configured
on port 53).
- The comment at sender_is_proxifyre() and "Recursion and ProxiFyre's own
traffic" now limit the residual race to a SOCKS5 server on TCP port 53
or with a UDP relay on port 53.
Policy tests cover the flag in both states for UDP and TCP with a known,
unknown and ProxiFyre sender, and fail when the flag is ignored.
The tracker cost test bounds visits(), but each loop incremented the counter itself, so a scan added without the increment (for example in evict_oldest_locked) went unnoticed. Every iteration over the table now goes through for_each_entry_locked() and every examination of the queue through consume_front_locked(); both count each element they visit, and the existing expiry, eviction, compaction and sweep loops are rewritten on top of them. A loop copied from any of them is therefore counted: a linear search added through the helper in evict_oldest_locked fails the test at 8194 visits per insert. The test comment states the remaining limitation: it bounds counted work and cannot see a raw loop that bypasses the helpers. No time-based assertion is reintroduced.
…istener first fragments - Every parsed IPv6 first fragment called dns_proxy_mode(), which takes lock_. ipv6_fragment_needs_dns_mode() now limits that to a first fragment that is not from a listener and is addressed to port 53; decide_ipv6_fragment() behaves exactly as before. - tcp_local_redirect does not check fragmentation, so the first fragment of an IPv4 TCP listener segment was translated on its own, leaving the later fragments untranslated. The IPv4 TCP handler now drops and reports it (ipv4_listener_packet_translatable()), as the UDP path already did because the UDP redirect rejects fragments. Tests cover both predicates and fail when either is reverted.
A listener segment that pushed the reset record's time forward passed every reset-tracking test. tcp_local_redirect now exposes the reset record's expiry for tests (reset_record_expiry(), like is_recently_reset()), and ResetRecordExpiresAfterTheLinger asserts that listener and client segments on a reset key leave it unchanged. Making either a listener or a client segment refresh the record, even to the current time, now fails the test. No wall-clock assertion is added.
- The docs and comments said ProxiFyre's only UDP traffic to a SOCKS5 server's address goes to the UDP ASSOCIATE relay. The local UDP listener's replies can also be addressed to a SOCKS5 host; they are handled as listener replies before any DNS decision and never passed. The claim now says the relay is the only such traffic that can reach the recursion guard (docs/configuration.md, the relay-callback comment in socks5_local_udp_proxy_server.h, and the router and policy comments). - ipv6_fragment_needs_dns_mode() had been inserted between decide_ipv6_fragment()'s doc comment and its declaration; each comment now sits on its own function.
…server override A resolver discards an answer that does not come from the server it queried. Answers were restored to that server only when a server override was configured, so in Proxy mode without an override a SOCKS5 relay that reports another source (for example its own address) broke UDP DNS. Every redirected UDP query that carries a DNS header is now tracked, and an answer matching a tracked query is restored whatever source the relay reports. A datagram too short to carry a DNS header is still redirected untracked without an override, and still dropped with one. Without an override nothing is dropped for matching no query. Also drop the listener decision's unused "not a listener" outcome: every caller has already established that the source port is a listener port.
…ows checklist - configuration.md: a section on local listener replies and TCP close handling, which apply to all proxied traffic; answer restoration with or without a server override; the two remaining unclassified pass paths (broadcast/multicast link-layer destinations, unwalkable IPv6 extension chains); previously ignored `id` and `dns` properties are now interpreted. - README.md and configuration.md: fragmented IPv6 is no longer passed without exception. - gui.md: manual validation steps for the upgrade path, restarts, a DNS proxy unavailable at start, TCP closes, aborts, large answers, relay sources, a SOCKS5 server used as a resolver, limited mode, and the GUI.
… address family A relay that reports its own address as the source of a UDP answer reports an IPv4 address even for an IPv6 query, because SOCKS5 servers are reached over IPv4. Such an answer matched a tracked query but was still dropped: the classifier ignored a header of the other family, and the UDP redirect rejected it. The classifier now restores a tracked answer whatever family its header has. The UDP redirect strips a header of the other family by its real size, but only when the caller supplies the source to present; without it such a header is rejected as before, so application traffic is unchanged. Also: - rename classify_dns_override_reply() to classify_dns_reply() and update comments that still tied restoration to a server override; - tests call the classifier with the arguments the router passes (no override address, the family's address size, port 0), so the null-address guard is covered; add IPv6 and truncated-header cases. Notes on the previous commit, which its message left out: it changed dns_reply_restore_needed() to two parameters, and in Proxy mode without an override every UDP listener reply now takes lock_ (shared) once more, and every reply from the DNS proxy's listener does one tracker lookup. Direct mode is unaffected.
…steps - configuration.md: restoration covers either address family; state what matching on client port and message ID implies (the last-queried server wins, and when a non-DNS datagram can be re-sourced); an unmatched datagram that names the server override is dropped, not delivered, and is one of the listener-reply drop causes. - gui.md: the large-answer step needs a server that sends large UDP answers and a tool that sets the EDNS buffer size, and the warning is logged once per service run; the relay-source step covers IPv6 resolvers; the SOCKS5-as-resolver command now names a host.
… match The fail-closed fallback in handle_dns_udp() and handle_dns_tcp() cannot be reached (decide_dns() returns only pass, block, proxy or defer for port 53, and defer is handled by the caller); it was reported as an unattributable sender and is now reported as a failed redirect. On the IPv6 path the recursion guard compared destinations with the IPv4-mapped form of each SOCKS5 server, which no IPv6 packet carries because mapped addresses leave the host as IPv4; it now says so and returns false. No behavior change.
…ver TCP An answer too large for one unfragmented packet left the DNS relay's listener fragmented, and the first fragment of a listener reply is dropped, so such lookups failed every time and, the answer not being marked truncated, Windows never retried over TCP. The relay now returns an answer larger than fits a 1280-byte packet (the IPv6 minimum MTU) the way a server does when an answer does not fit: TC set, header and question kept, record counts zeroed. The resolver then repeats the query over TCP through the proxy.
…wers docs/configuration.md gains a "Shared UDP association" section: one control connection and UDP ASSOCIATE per address family, relay message IDs, answers presented from the queried server, truncation of answers that do not fit an unfragmented 1280-byte packet, opening and reopening with backoff, and logging. The listener-reply rule, the server override, the recursion guard and the limitations are updated to match: the per-query handshake limitation is replaced by the shared source port and the queries lost on a reopen. README.md no longer says flatly that DNS is never sent directly and links to the limitations. The Windows checklist covers the association count, recovery after a SOCKS5 restart, truncated large answers and parallel lookups. netlib/README.md lists the new test suite.
…stion Review findings on the shared UDP association: - Health. An answer from the relay reset the unanswered count at once, but queries are counted as unanswered only when they expire 10 s later, so queries to a resolver the proxy cannot reach still retired an association that kept delivering other answers, every 30 s. A query now counts as unanswered only if it was sent after the last datagram from the relay. - Backoff. An association that closes less than 30 s after opening counts as a failed open, so a server that accepts UDP ASSOCIATE and drops the connection is not reconnected about once a second. The backoff resets once an association has stayed open for 30 s. - Matching. Answers were matched by the 16-bit relay ID alone, so a late or forged answer could reach another client. Each query now keeps a fingerprint of its question section (names compared without regard to ASCII case); an answer must carry the same question, or be a question-less error response, and a mismatch does not consume the query. Queries without a parsable question are dropped. - Stop. stop() interrupts an association being opened: the connect wait polls the stop flag (connect_to_socks5_proxy() takes an optional cancel flag; without it the wait is unchanged) and a connected control socket is shut down so a blocked negotiation returns. - Robustness. TCP keepalive on the control connection; ICMP-induced and other transient UDP errors no longer retire the association or spin the listener; thread creation failures are handled instead of terminating; the last drop counts are logged on stop; every successful open is logged at Info. The relay's per-datagram logic moves into dns_relay_session (dns_udp_multiplexer.h), which the relay and the packet tests now share, so the tests exercise the shipped logic instead of a copy. New tests cover the two-resolver scenario, silence after answers, early-close backoff, the question check and question-less error responses.
- stop() stopped the packet filter before the DNS relays, so answers a relay sent while stopping left the host unfiltered. The relays now stop first. New UDP DNS is blocked while they stop, but their listener ports stay recognized so their last answers are still translated. - The relay accepted any source port in the shared UDP source-port mapper, including ports of application UDP redirected to the per-port listeners, and an application UDP association could erase a DNS port's entry. UDP DNS source ports are now recorded in their own map, which the relay checks and the resolver thread sweeps. - The last DNS and listener drop counts are reported on stop(). - A comment that had drifted away from install_dns_filters() is back with it.
Waiting queries, the question check, when an association is retired (only queries sent after the last datagram from the relay count), the early-close backoff, keepalive, logging per address family (every open and close at Info, final counts on stop), which source ports the listener accepts, and the stop order. The Windows checklist adds the two-resolver case and a service stop while the SOCKS5 server is black-holed.
…close the stop window Review findings on the shared UDP association and its shutdown: - Queued queries. Queries queued after the association failed could wait through a backoff of up to 30 s and then be sent long after Windows gave up. A query now waits at most 3 s, and the queue is dropped when a failure starts a backoff. - Listener access. The relay checked only the sender's source port. It now also refuses loopback senders and accepts only a SOCKS5 destination of port 53 of the sender's address (the server the client queried) or, with a server override, the override, which the router now passes to each relay (dns_relay_destination_allowed()). - Stop window. stop() unregistered the relays right after stopping them, before the packet filter stopped, so an answer sent at the last moment could no longer be recognized as a listener reply. The stopped relays now stay registered until the filter has stopped (release_dns_udp_relays()). UDP DNS blocked during that window uses a new service_stopping reason, which is neither counted nor warned about. - Silent association. An association retired because queries stopped being answered now starts a backoff whatever its age, instead of reopening at once every 30 to 40 s while the relay is unreachable. - Keepalive is set with SIO_KEEPALIVE_VALS (60 s idle, 10 s interval), which every supported Windows version honors, instead of options an older SDK or Windows may lack. - A misplaced member comment is fixed.
…ck and the stop order
…e warning Review findings on the previous round's fixes: - A silent association was retired only once at least 30 s old, and at that age the backoff had already been reset, so it always backed off 1 s and reopened every 31 to 41 s. The backoff now resets only when an association proves itself: a datagram arrives from the relay once it is 30 s old, or it closes normally at that age. Silent associations now back off 1, 2, 4 ... 30 s. - After a silent retirement the first failed reopen was logged at Debug only, because the warning was keyed to the first consecutive failure. It is now keyed to the first failed open since the last successful one. - The queue of queries waiting for an association moves into a portable, tested dns_waiting_queue (bounded, at most 3 s per query, arrival order). - The router releases the stopped relays only after the resolver thread has been joined, so deferred DNS packets processed during stop are also blocked quietly, and start clears the stopping flag in case an earlier stop() did not finish. - The listener's drop report counts refused destinations separately; the SOCKS5 header is parsed once; keepalive uses SIO_KEEPALIVE_VALS and tcp_keepalive from <mstcpip.h>, which socksify already includes. - Tests: silent-retirement escalation through the normal path, the warning rule, the waiting queue, and IPv6 (including link-local) destinations. - Docs: when the backoff resets, the warning rule, and that another host guessing an authorized port can only make the proxy query its own port 53 or the override, never seeing the answer.
… goes silent Review findings on the previous fix: - An association that answered only during its first 30 s (a UDP path that dies whenever the machine idles, while keepalive holds the control connection) never proved itself, so each idle period escalated the backoff towards 30 s and every return from idle dropped UDP DNS for longer. A silent retirement of an association that delivered anything now starts a new outage: the backoff restarts at 1 s. A relay that never answers still backs off 1, 2, 4 ... 30 s, and early closes still escalate. - start_dns_udp_relays() now releases relays left registered by a stop() that did not finish, not just the stopping flag. - Log text: the repeated-failure Debug line no longer prints a misleading attempt number, and the malformed-query count says what it counts. - A test ran its clock backwards; fixed. New test for the idle scenario. - Docs: when the backoff restarts, that another host can only make the proxy query port 53 of the source address its datagram claims (or the override) and never sees the answer, and the black-holed server timing in the Windows checklist.
…rn when unusable Review findings on the previous fix: - A server that ends every UDP association after less than 30 s (an early idle timeout or a fixed lifetime) would push the backoff towards 30 s, because each association answered and then closed young. Any closure of an association that received something from the relay and lived at least 5 s now restarts the backoff at 1 s, whether it was retired for silence or closed young. Associations that received nothing, or died within seconds, still make it grow, so failing servers are not reconnected in a tight loop. - A SOCKS5 server whose relay never answers produced only Info lines. A close of an association that received nothing is now logged as a warning, once until an association works again. - The close log no longer says the association is reopened on the next query when the next attempt is delayed; it gives the delay instead. - Tests pin both close rules and the warning; docs describe them.
…server once Review findings on the previous fix: - The new warning blamed the SOCKS5 relay, while the commonest cause is a DNS server the proxy cannot reach (a local resolver without serverOverride). It now names both causes and suggests serverOverride. - That warning was skipped when an association that never received anything closed normally at 30 s or older. It is now given whatever ends the association, but only if queries were sent through it, so an association closed before its first query is not reported. - The "could not open" warning was re-armed by every successful open, so a server alternating between refusing and accepting without ever working repeated it about once a minute. It is now re-armed only when an association receives something. - A retired association's reader could still hand one late datagram to the session after the closure was recorded, cancelling the backoff just set. The association is marked retiring under the lock before the closure is recorded, and the reader checks that under the lock. - Docs: reopening may be delayed; the logging rules above. Class comment tightened. Tests for each rule.
…; tidy Review findings on the previous fix: - When the server ended an association within seconds, the warning still suggested an unreachable resolver and serverOverride. That diagnosis is now given only when queries had time to be answered (an association retired for silence, or open at least the query lifetime); otherwise the warning says the server ended the association N s after it opened. It now says UDP DNS fails, not that it is dropped, and follows the Info close line instead of preceding it. - A query counts as sent through the association only once send() succeeds. - An overlong comment line is reflowed; trailing whitespace carried over with the moved SOCKS5 association code is removed. - Docs: the two warning texts; a Windows checklist step for the unreachable-resolver warning.
…on unusable relay sockets
Review findings on the previous fix:
- The "ended N s after it opened" and the "no answer came back (consider a
DNS serverOverride)" warnings shared one once-per-outage flag, so an early
close (for example at boot) hid the more useful diagnosis for an
unreachable resolver. dns_association_health::on_closed() now returns
which report applies, and each has its own flag, re-armed when an
association receives something.
- Whether queries had time to be answered is measured from the first query
actually sent, not from when the association opened.
- An association whose relay socket failed before any query could be sent
produced no warning, so UDP DNS could fail permanently with only Info
lines. It now gets its own warning ("no query could be sent through the
SOCKS5 UDP relay").
- The decision moved into the portable class, with tests for each cause,
both orders, the timing rule and the relay-socket case.
- Docs: the three warnings; the checklist says "per address family in use".
…f an early end Optional review nits: a test for no_answer then ended_early, and for relay_unusable followed by the other reports, in one outage; the enum comment and docs say an early end can be the control connection or the relay socket. No behavior change.
The routing rules never match ProxiFyre's own process (current_process_id), and the OwnerRoutingPolicy tests passed the test runner's real PID while their owners are fakes with fixed PIDs (3000-3900, mostly multiples of 4, like real Windows PIDs). Whenever the runner's PID equalled one of them, that owner was neither proxied nor excluded and the test failed: PidReuseAcrossCapturesDoesNotInheritExclusion failed this way once in CI (netlib-tests Debug), with every PID-3500 owner routed to none. The rules now get a fixed own PID of 2, which is never a real Windows process ID and which no other fake row uses, and a new test pins the own-process rule with it.
Earlier releases ignored a rule "id" and a top-level "dns" property, so an upgraded configuration that happened to contain them could stop the service. - An invalid or duplicate rule id is now an error only when dns.proxyId in Proxy mode refers to it; otherwise it is a warning and has no effect. - An empty or whitespace id means no id, matching the normalizer. - A "dns" value that is not an object is reported by name instead of as an anonymous invalid property value; it still stops the service. - The GUI assigns a fresh id when the rule selected as the DNS proxy shares its id with another rule, not only when the id is missing or invalid. - README and configuration reference: upgrade note for the id and dns keys.
- A rule id that is a JSON object or array no longer stops the service: it is kept as its JSON text, which validation reports as an invalid id (a warning unless DNS uses it). A dns value, or a dns mode/proxyId/serverOverride, of the wrong JSON type is reported by its name, for every case variant of the key. - Saving drops ids that only cause warnings (invalid, or a repeat of an earlier rule's id, and not referenced by DNS Proxy mode), so the GUI can clear them; the warning text says so. - GUI: the DNS proxy selector shows the first rule with the referenced id, as validation and the service resolve it; switching to Proxy mode repairs the id of the rule shown; rule rows are refreshed after DNS changes. - Docs: gui.md id assignment, null dns in the README upgrade note.
…ings verbatim - Saving keeps an id that dns.proxyId names in any mode, so a Direct-mode DNS proxy selection survives a save and a later switch to Proxy mode; the warning for such an id says it is kept. - Error and warning texts name the GUI repair (select the rule as the DNS proxy again) and say ids are removed when the GUI saves. - GUI: opening and closing the DNS proxy list repairs the shown rule's id when Proxy mode cannot use it; moving the selection on gives a rule the id it had before, so passing through the list leaves no ids behind. - The configuration is parsed without date conversion: JObject.Parse turned ISO date-time strings, such as a password, into re-formatted dates (pre-existing). - CloneRule's doc comment is back on CloneRule; docs say which non-string ids are kept as text.
…ound 14 nits - The rule editor returns a copy, so the DNS proxy selector now follows the copy (and forgets a removed rule); moving the selection on after an edit restores the rule's previous id instead of leaving the assigned one. - The Direct-mode warning names the repair that works there: switching DNS to Proxy mode in the GUI. - Docs: gui.md states the dns.proxyId exception for dropped ids; the upgrade notes say an existing dns object with an unknown mode, or Proxy mode without a usable proxyId, also stops the service.
- A referenced invalid id that an earlier rule also has is reported as ambiguous and names that rule, like a referenced duplicate, so following the message from the later rule's row does not move DNS to another rule. - The Direct-mode warning for a repeated id names the first rule with it, which is the rule the GUI shows and repairs on a switch to Proxy mode. - Docs: how JSON true/false and numbers become id text; which rule the DNS proxy selector shows for a shared id.
A rule with both "id" and "ID", or a configuration with both "dns" and "DNS", silently kept only one of the values, while earlier releases kept both as unknown data. Both are now a configuration error that names the keys. Docs: which rules keep a repeated or named id when saving.
In Proxy mode a DNS answer is written by the DNS proxy's local listener and presented as coming from the server the client queried. When the client's socket has already closed (the answer to a retransmitted query, a client that gave up), Windows reports the datagram with an ICMP "port unreachable" error addressed to that server, and the error quotes the whole answer. The answer then left the adapter in clear, from the computer's own address. Found during Windows validation: 3 such errors in 150 s of browsing, reproducible by closing the socket right after sending a query. - In Proxy mode a REDIRECT driver filter for outbound ICMP and ICMPv6 is placed at the front of the table, ahead of the ICMP PASS and LAN-bypass filters, so the errors reach user mode. A filter that cannot be installed fails the start, like the other Proxy-mode filters. - An outbound ICMP or ICMPv6 error that quotes a UDP datagram or TCP segment sent from port 53 is dropped. Other ICMP, such as ping, is passed, and Direct mode is unchanged. The first drop per run is logged at info level, counts at debug level. - The parsing and the decision are in dns_routing_policy.h and covered by tests: quoted source port for ICMP and ICMPv6 errors (IP options, extension and first-fragment headers, later fragments, truncation, non-error types), the decision per mode, and the filter plan. - Docs: the behaviour in configuration.md, and a capture filter for it in validation step 2 of gui.md. Application UDP through the per-port UDP proxy has the same ICMP behaviour (as on main) and is not changed here.
3 tasks done
A reply on a UDP flow that a rule proxies reaches the application as if it came from the remote peer: socks5_udp_local_redirect restores the peer named in the SOCKS5 UDP header. If the application's socket has closed when the reply arrives, Windows reports it with an ICMP "port unreachable" (ICMPv6 "destination unreachable") error addressed to that peer. The error leaves the adapter directly, from the computer's own address, and quotes the reply, so the peer learns the real address and sees the reply contents. The previous commit handled this for DNS answers in Proxy mode only. - An outbound ICMP or ICMPv6 error is dropped when the UDP datagram it quotes was addressed to a client port with an active entry in the UDP redirect of that family. This applies in either DNS mode. The redirect is keyed by client port, so a datagram that port received directly is matched too; that sender already knows the address and only loses the error report. Ping, neighbor discovery, TCP quotes and errors about unproxied ports are passed. The first drop per run is logged at info level with the port; later drops are counted at debug level. - The quoted-header parsing in dns_routing_policy.h now returns both quoted ports (icmpv4_error_quote(), icmpv6_error_quote()). The source-port helpers are kept as wrappers. decide_icmp_error() takes the quote and a lookup of redirected client ports, and only calls the lookup (and so takes the redirect's lock) for a quoted UDP datagram with both ports. - socks5_udp_local_redirect::is_active_endpoint() reports whether a client port has an entry that has not timed out (15 minutes, now a named constant). - The REDIRECT filter for outbound ICMP is now needed outside DNS Proxy mode: for IPv4, the router's ICMP PASS filter would otherwise pass the error in the driver. plan_icmp_error_filters() installs it per address family when that family has a UDP listener, and for both families in DNS Proxy mode. install_icmp_error_filters() runs on start() and also when add_socks5_proxy() adds a UDP listener to a running router. It only adds missing filters, so there is never a moment without one. - Tests: quote parsing (both ports, a quote cut between them), the decision in both modes, the lookup only being consulted for quoted UDP, and the filter plan. The portable suite also drives the real redirect: an IPv4 and an IPv6 application flow is redirected, the listener's reply is translated, and the stack's error about the translated reply is dropped, while ping and errors about unredirected ports pass. - Docs: the behaviour and the filter in configuration.md, and a Windows validation step with pktmon/Wireshark in gui.md.
Step 16 told the tester to close the socket before the reply arrives. A socket closed at once is gone before its datagram can be attributed to the application, so the datagram is sent directly, the server answers directly, and the ICMP error about that direct reply is passed, which looks like the drop not working. Measured on Windows with 12 datagrams per delay: closed after 0 ms, all 12 went out directly; after 2 ms, 9 did; after 10 ms and 30 ms, none. The step now says to keep the socket open for about 50 ms, to use a server that delays its reply when the SOCKS5 server answers faster than that, and to confirm in the capture that no datagram went to the server directly. A STUN binding request is added to the example datagrams.
Drop ICMP errors that quote a proxied UDP reply
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds a global DNS policy for conventional DNS (UDP and TCP port 53), with two modes:
dnssection): port-53 traffic bypasses every proxy, for IPv4 and IPv6.svchost.exe). Proxy mode never falls back to sending DNS directly. UDP DNS shares one SOCKS5 association per address family; TCP DNS uses aCONNECTper connection.The goal is optional DNS leak prevention without changing Windows DNS settings and without adding a resolver or cache.
It also replaces the copied Windows Packet Filter API sources with a submodule of
wiresock/ndisapi(see "Windows Packet Filter API as a submodule").Behavior change on upgrade
TCP/53 is now always direct in Direct mode, which also applies to existing configurations. Previously only UDP/53 was bypassed, and TCP/53 was routed like any other traffic of the owning process, so rules that carried TCP/53 through a proxy no longer do. Proxy mode is the way to route DNS through a proxy.
A rule property named
idand a top-level property nameddnswere previously preserved but ignored. They are now interpreted:id(including one written as a JSON object or array) is only a warning unless DNS Proxy mode refers to it, so such configurations still start. An emptyidmeans no id. The GUI removes such ids on the next save, unlessdns.proxyIdnames them.dnsvalue other than an object ornull(for example"dns": "8.8.8.8"), adnssetting that is an object or array, twoidkeys in one rule or twodnskeys that differ only in case, an unknownmode, or Proxy mode without a usableproxyIdis a configuration error that names the property, and the service does not start.Both are in the README upgrade notes and
docs/configuration.md.Windows validation required before merge
Nothing in this PR has run through the packet-filter driver or against a live SOCKS5 server. No automated test exercises the router class or the DNS relay's sockets and threads; the relay's per-datagram logic, health and backoff rules are unit tested. Run the steps below before merging, on a Windows machine with the driver installed, a SOCKS5 server that supports
UDP ASSOCIATE, and Wireshark (or pktmon) capturing on the physical adapter. Runipconfig /flushdnsbefore each step. UseResolve-DnsName -Server <server> -DnsOnlyfor UDP andResolve-DnsName -TcpOnlyfor TCP.Step numbers refer to "DNS routing manual validation" in
docs/gui.md, which has the full instructions.Validation status (2026-11-14). Run on Windows 11 x64 with Windows Packet Filter 3.6.2.1 and a live SOCKS5-over-TLS server, capturing at the physical NIC with pktmon, against head
e243699, and re-run for the affected items with the fix in216bcf6. #192, which extends that fix to application UDP, was validated the same way ond26dbbaand is merged here ine0493f9. All 22 items are ticked. The last two were closed by the maintainer:e0493f9.Notes on ticked items: Proxy mode passed its criteria on
e243699, but that run found that a DNS answer delivered to a socket that has already closed left the adapter inside an ICMP "port unreachable" error addressed to the DNS server the client queried, quoting the answer (3 times in 150 s of browsing).216bcf6drops outbound ICMP and ICMPv6 errors that quote a packet from port 53 in Proxy mode; with it, 2,090 queries, 200 parallel lookups per family and 40 deliberately closed sockets produced no port-53 packet and no such ICMP error at the adapter. The machine has no native IPv6, so IPv6 was exercised with a temporary address and route (in Direct mode IPv6 queries were seen leaving the adapter but could not be answered). The port-53 server/relay sub-case of step 14 does not apply to the test server. Limited mode ran with a restricted token (Administrators deny-only). Ordinary proxied traffic was checked on this branch only, not side by side withmain.Core behavior
dnssection and a catch-all rule, UDP and TCP port 53 leave the adapter directly for IPv4 and IPv6, and the rule's other traffic is still proxied.nslookup <name> 8.8.8.8, over IPv4 and IPv6. After a few minutes of browsing, the SOCKS5 server has seen one control connection and oneUDP ASSOCIATEper address family for UDP DNS, not one per query.serverOverride: "1.1.1.1"the SOCKS5 server is asked for1.1.1.1and answers appear to come from the server Windows queried. With an IPv4 override, queries to IPv6 resolvers are dropped.Fail closed, recovery and diagnostics (step 5)
serverOverridefixes lookups.Driver filters and stop
bypassLanand a router resolver, DNS to the router is proxied while other LAN traffic stays direct, also after Apply & Restart.taskkill /fofProxiFyre.exein Proxy mode, DNS still works.Shared-code changes, which also affect non-DNS traffic
main.Directand inProxymode; without the rule the error does leave;pingstill works. Validated in Drop ICMP errors that quote a proxied UDP reply #192: 60 datagrams over IPv4 and IPv6 all proxied and no error on the adapter, against 12 IPv4 and 12 IPv6 errors on216bcf6.Edge cases
serverOverride, IPv4 and IPv6; 200 parallel lookups each get their own answer. Include a link-local IPv6 resolver if available.GUI and build
dns.modeshows no selection and is not saved as Direct./W3warnings in the x86, x64, and ARM64 builds (CI shows none).Design
CONNECTpath, as application TCP does.socks5_dns_udp_relay.h) with one SOCKS5 control connection and oneUDP ASSOCIATEshared by every query. The SOCKS5 connect and handshake code is shared with the per-port UDP proxy (socks5_udp_association.h). There is no resolver or cache.id, anddns.proxyIdrefers to it (trimmed, case-insensitive, first matching rule), so reordering, editing or reloading rules doesn't change the DNS proxy. Validation rejects an invalid or duplicate id thatdns.proxyIdrefers to in Proxy mode (any other invalid or duplicate id is a warning), a reference to a missing rule, and a selected proxy without both TCP and UDP. ProxiFyre never substitutes another proxy. Messages for a repeated id name the rule it resolves to.dns_relay_session,dns_udp_multiplexer.h):serverOverride.stop()interrupts a handshake in progress. The relays stop while packets are still processed and stay registered until processing has ended, so their last answers are still translated; new UDP DNS is quietly blocked meanwhile.serverOverride(optional IPv4/IPv6 literal with an optional port): only the destination sent to the SOCKS5 server changes; the packets the application sees keep the original server address. Queries addressed to servers of the other address family are blocked.192.168.1.1:53is still proxied while other LAN traffic stays direct.UDP ASSOCIATErelay on port 53 (both the per-port UDP proxy and the DNS relay report their relay endpoints). Only then is it exempt, and only when the cached connection table says its sender is ProxiFyre. An unattributable sender is deferred, then dropped if still unknown.Shared-code changes that also affect non-DNS traffic
mainpassed it untranslated (TCP replies were already translated).tcp_local_redirectkeeps a connection's entry through the whole close; trailing FIN/ACK segments are translated in both directions. An RST (which takes precedence over SYN) ends the connection immediately; its key is kept a few seconds as a record so the proxy's segments still in flight are dropped quietly. A SYN on a still-tracked key takes the new destination port. The redirects' cleanup threads restart when the router starts again in the same process.216bcf6), and in either mode when the UDP datagram it quotes was addressed to a client port the UDP redirect used within the last 15 minutes (Drop ICMP errors that quote a proxied UDP reply #192). Ping and other ICMP are passed. For this, a REDIRECT filter for outbound ICMP of a family is placed at the front of the driver table in Proxy mode and whenever a rule proxies UDP for that family; if it cannot be installed, the engine does not start.socks5_udp_association.h(the connect wait can now be cancelled; without a cancel flag it behaves as before). DNS source ports no longer go into its source-port map.main). The configuration was parsed withJObject.Parse, which turned ISO date-time strings into dates and re-formatted them: a password such as2024-01-15T10:00:00Zwas read as01/15/2024 10:00:00, sent to the proxy that way, and written back by a GUI save. Strings are now read verbatim. Accepted and rejected inputs are otherwise unchanged, except that text after a trailing comment is now rejected.Windows Packet Filter API as a submodule
The copied
include/andndisapi/sources are replaced by a submodule ofwiresock/ndisapiatexternal/ndisapi, pinned tofc03ee7(upstreammaster: the 3.6.2 SDK line with the 3.8.2 user-mode backports).Common.hdiffers only inNDISRD_VERSION, comments, one SDK-side macro and the opt-inUSER_IOCTLSblock; driver-facing structures and IOCTL codes are unchanged.ndisapi.cppgains the upstream SDK fixes.ndisapi.libproject (the upstream one links the static CRT and names its output after the solution).socksify, the portable test harness and its checksum extraction read from the submodule.git clone --recurse-submodulesorgit submodule update --init. GitHub's "Download ZIP" archives don't include submodules.Configuration
A missing
dnssection means Direct. Nodnssection and no ids are added to existing configurations; configurations that already hadidordnskeys are covered under "Behavior change on upgrade".Changed components
netlib/src/proxy/dns_routing_policy.h(new, portable): routing decisions, recursion guard, listener/fragment handling, the driver filter plan, ICMP error parsing and the ICMP drop decision, override syntax, SOCKS5 UDP header parsing.netlib/src/proxy/dns_udp_multiplexer.h(new, portable): relay IDs, queries in flight, question check, answers to the client, truncation, the destination check, association health and backoff, closure reports, the waiting queue, anddns_relay_session.netlib/src/proxy/socks5_dns_udp_relay.h(new): the DNS relay's sockets and threads.netlib/src/proxy/socks5_udp_association.h(new): SOCKS5 connect (cancellable), authentication,UDP ASSOCIATE, relay socket.socks_local_router.h:set_dns_routing(), the packet handlers, the DNS relays' lifecycle and client ports, driver filter (re)installation, throttled diagnostics.socks5_udp_local_redirect.h: an optional SOCKS5 destination for queries (the override);is_active_endpoint()for the ICMP drop decision; the answer path is as onmain.tcp_local_redirect.h: close tracking, reset records, a three-way result for listener segments, cleanup-thread restart.socks5_local_udp_proxy_server.h: uses the shared association helper; reports relay endpoints.external/ndisapisubmodule.SetDnsRoutinginsocksify/.ProxiFyre/Program.cslooks up the selected rule byid.DnsConfiguration.cs;DnsSettingsandProxyRule.Id; validator rules (id severity depends on whether DNS Proxy mode uses it); the normalizer drops ids that only cause warnings unlessdns.proxyIdnames them; the serializer reads strings verbatim, names malformeddns/idkeys, and keeps object/array ids as text.docs/configuration.md,docs/gui.md,docs/installer.md,README.md,netlib/README.md, the sample config; a Linux job innative-tests.yml; submodule checkout in the build and test jobs.Tests
dns_routing_policy_test.cppanddns_udp_multiplexer_test.cppare also part ofnetlib-tests.dns_packet_redirect_test.cppruns real IPv4/IPv6 UDP and TCP frames through the shipped redirect headers, the shippeddns_relay_sessionand the product checksum routines.kernel32.dllfail there).socksify.sln(x86, x64, ARM64) with no compiler warnings,netlib-tests(Debug and Release) and the portable suite.Limitations
ipconfig /flushdnsafter switching modes.