diff --git a/docs/configuration.md b/docs/configuration.md index 97e37f5..49e5d08 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -132,10 +132,13 @@ In DNS `Proxy` mode, DNS takes precedence over LAN bypass: a query addressed to ## Local listener replies and TCP close handling -ProxiFyre redirects a matched connection to a local listener and translates the listener's replies back before the application sees them. Two rules apply to every proxied connection, not only to DNS: +ProxiFyre redirects a matched connection to a local listener and translates the listener's replies back before the application sees them. Three rules apply to every proxied connection, not only to DNS: - **A reply that cannot be translated back is dropped.** A reply from a local listener is addressed to the original server only because redirection swapped the addresses, so it must never reach the network. It is dropped when its TCP connection or UDP endpoint is no longer tracked, when it is the first fragment of a fragmented reply, or when its SOCKS5 relay header is malformed or of the other address family. Earlier releases passed such packets toward the original server. The first such drop after the service starts is logged once as a warning, and a count is logged at `Info` level at most every five seconds while drops continue. Later fragments of a fragmented reply carry no ports, cannot be attributed to a listener, and are still passed. - **A TCP connection is tracked through its whole close.** The FIN/ACK exchange is translated in both directions instead of reaching the real server. A reset (RST) ends the connection immediately; segments the local proxy had already sent when the reset arrived are dropped without the warning and are counted at `Debug` level only. +- **ICMP errors about proxied UDP replies are dropped.** A UDP reply reaches the application as if it came from the remote endpoint, although it came from the proxy. If the application has already closed its socket when the reply arrives, Windows answers with an ICMP "port unreachable" error (ICMPv6 "destination unreachable" for IPv6) addressed to that remote endpoint. The error is sent from the computer's own address, outside the proxy, and quotes the reply, so it would reveal the computer's address and the reply's contents to the remote endpoint. ProxiFyre drops an outbound ICMP or ICMPv6 error when the UDP datagram it quotes was addressed to a local port whose UDP traffic ProxiFyre redirected to a proxy within the last 15 minutes. This applies in either DNS mode, to every rule that proxies `UDP`. It also covers a datagram that port received directly from the network: the sender already knows the computer's address, and only its error report is lost. Other ICMP traffic, such as `ping`, neighbor discovery and errors about unproxied traffic, is passed. The first such drop after the service starts is logged at `Info`, naming the local port, and later ones are counted at `Debug`. Proxied TCP is not affected: Windows answers a TCP segment for a closed connection with a reset, which is translated like any other segment (see above). + +When a rule proxies `UDP` for an address family, or in DNS `Proxy` mode, outbound ICMP of that family (ICMPv6 for IPv6) is filtered by ProxiFyre rather than passed by the driver. The filter is placed ahead of the LAN bypass filters. ICMP that is not dropped is passed unchanged. If the filter cannot be installed, the service does not start; a proxy added while the service runs is then rejected instead. A proxied TCP connection that stays idle for more than 5 minutes loses its redirect entry; see [Limitations](#limitations). @@ -187,7 +190,7 @@ Whether name resolution still succeeds after a drop depends on Windows: it retri Windows retries a failed query and, for UDP answers marked truncated, retries over TCP; both go through the same proxy. ProxiFyre does not inspect payloads to decide what is DNS: only destination port 53 is classified. -An answer can arrive after the application has closed its socket, for example the answer to a query Windows had already retransmitted. Windows then reports the datagram with an ICMP "port unreachable" error addressed to the DNS server the application queried, and that error quotes the answer. Because the answer came from the DNS proxy and not from that server, ProxiFyre drops outbound ICMP and ICMPv6 errors that quote a packet sent from port 53 in `Proxy` mode, so the answer does not leave the computer in clear. Other ICMP traffic, such as `ping`, is passed. The first such drop after the service starts is logged at `Info` and later ones are counted at `Debug`. +An answer can arrive after the application has closed its socket, for example the answer to a query Windows had already retransmitted. Windows then reports the datagram with an ICMP "port unreachable" error addressed to the DNS server the application queried, and that error quotes the answer. Because the answer came from the DNS proxy and not from that server, ProxiFyre drops outbound ICMP and ICMPv6 errors that quote a packet sent from port 53 in `Proxy` mode, so the answer does not leave the computer in clear. Other ICMP traffic, such as `ping`, is passed. The first such drop after the service starts is logged at `Info` and later ones are counted at `Debug`. The same protection applies to application UDP that a rule proxies, in either mode; see [Local listener replies and TCP close handling](#local-listener-replies-and-tcp-close-handling). If the selected proxy cannot be created when the service starts (for example its host name does not resolve or its listeners cannot be opened), the service still starts but **all DNS is blocked until the service is restarted** after the cause is fixed. The engine log says so explicitly. An unknown `mode` value stops the service from starting instead of being treated as `Direct`. diff --git a/docs/gui.md b/docs/gui.md index 0b44a1d..8ce88b9 100644 --- a/docs/gui.md +++ b/docs/gui.md @@ -176,4 +176,5 @@ The routing policy and the packet rewriting are covered by automated tests (`net 13. **Relay source and shared IDs.** If the SOCKS5 server reports an address other than the queried DNS server as the source of UDP replies (for example its own IPv4 address), confirm lookups succeed without and with `serverOverride`, to an IPv4 resolver and to an IPv6 resolver. Run many lookups in parallel (for example `1..200 | ForEach-Object -Parallel { Resolve-DnsName "host$_.example.com" -DnsOnly -ErrorAction SilentlyContinue }` in PowerShell 7) and confirm each one gets its own answer. 14. **SOCKS5 server used as a resolver.** Send a lookup to the SOCKS5 server's own IP address (`Resolve-DnsName example.com -Server -DnsOnly`). Confirm the query goes through the proxy, not directly. If the server listens on TCP port 53 or returns a UDP relay on port 53, also confirm ProxiFyre still reaches it and the one-time `Info` line about the relay appears. 15. **Limited mode.** Repeat step 2 in the optional unelevated console mode. -16. **GUI.** On the **Settings / Diagnostics** tab at 100% and 150% scaling, confirm the DNS routing group and the Uninstall button are reachable (scrolling is expected). Confirm Alt+M, Alt+P, and Alt+S focus the mode, proxy, and override fields; that the DNS proxy selection survives **Move Up**/**Move Down** and a reload; that **Duplicate** does not copy the id; and that removing the selected rule shows the missing id and fails validation. +16. **ICMP errors about proxied UDP replies.** With `Direct` DNS and a rule that proxies `UDP` for a test application, capture on the physical adapter (`pktmon filter add -t ICMP`, `pktmon filter add -t ICMPv6`, `pktmon start --capture --comp nics`, then `pktmon stop` and `pktmon etl2pcap PktMon.etl`; or Wireshark with `icmp.type == 3 || icmpv6.type == 1`). From the application, send a UDP datagram to a server that answers after a delay, over IPv4 and over IPv6, and close the socket before the reply arrives 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/netlib/src/ndisapi/socks5_udp_local_redirect.h b/netlib/src/ndisapi/socks5_udp_local_redirect.h index 049a1b5..43ade4e 100644 --- a/netlib/src/ndisapi/socks5_udp_local_redirect.h +++ b/netlib/src/ndisapi/socks5_udp_local_redirect.h @@ -45,6 +45,9 @@ namespace ndisapi /// std::atomic_bool terminate_{ false }; + /// How long a client endpoint is kept after its last translated datagram. + static constexpr std::chrono::minutes endpoint_timeout{ 15 }; + /** * @brief Starts the background cleanup thread. * @@ -64,8 +67,7 @@ namespace ndisapi tools::generic::erase_if(endpoints_, endpoints_.begin(), endpoints_.end(), [¤t_time, this](auto&& a) { - using namespace std::chrono_literals; - if (current_time - a.second > 15min) + if (current_time - a.second > endpoint_timeout) { NETLIB_DEBUG( "DELETE UDP client endpoint (timeout): : {}", @@ -176,6 +178,22 @@ namespace ndisapi proxy_port_ = htons(proxy_port); } + /** + * @brief Whether @p client_port (host byte order) has an endpoint entry that has not + * timed out, i.e. its datagrams are, or were within endpoint_timeout, redirected + * and replies to it are delivered by a local listener. + * + * Used to recognize an outbound ICMP error about such a reply (decide_icmp_error()): + * the entry outlives the client's socket, which is exactly when the stack reports a + * late reply with an error addressed to the remote peer. + */ + [[nodiscard]] bool is_active_endpoint(const u_short client_port) + { + std::scoped_lock lock(lock_); + const auto it = endpoints_.find(htons(client_port)); + return it != endpoints_.cend() && std::chrono::steady_clock::now() - it->second <= endpoint_timeout; + } + /** * @brief Checks if the UDP session for the given packet is new. * diff --git a/netlib/src/proxy/dns_routing_policy.h b/netlib/src/proxy/dns_routing_policy.h index 5765dfa..8138791 100644 --- a/netlib/src/proxy/dns_routing_policy.h +++ b/netlib/src/proxy/dns_routing_policy.h @@ -449,14 +449,17 @@ namespace proxy } // --------------------------------------------------------------------------------------- - // ICMP errors about DNS answers + // ICMP errors about datagrams the proxies delivered // - // In Proxy mode an answer from port 53 that reaches a client was written by the DNS proxy's - // local listener and only presented as coming from the server the client queried. When the - // client's socket has closed by then (the answer to a retransmitted query, a client that - // gave up), the TCP/IP stack reports the datagram with an ICMP error addressed to that - // server, which never sent it. The error quotes the datagram, so the DNS answer would leave - // the adapter in clear and from the computer's own address. Such errors are dropped. + // A reply that reaches a client through a proxy was written by a local listener and only + // presented as coming from the remote endpoint: in Proxy mode a DNS answer from the server + // the client queried, and for application UDP that a rule proxies, a datagram from the + // remote peer (socks5_udp_local_redirect restores the peer named in the SOCKS5 UDP header). + // When the client's socket has closed by then (the answer to a retransmitted query, a + // client that gave up or exited), the TCP/IP stack reports the datagram with an ICMP error + // addressed to that remote endpoint, which never sent it to this address. The error quotes + // the datagram, so it would tell the remote endpoint the computer's own address and carry + // the reply in clear. Such errors are dropped. // --------------------------------------------------------------------------------------- /// Whether an ICMP (IPv4) message type is an error message, which quotes the packet it is about. @@ -472,16 +475,40 @@ namespace proxy return type < 128; } + /// The transport header of the UDP datagram or TCP segment an ICMP or ICMPv6 error quotes. + struct icmp_error_quote + { + uint8_t protocol{}; ///< 6 (TCP) or 17 (UDP) + uint16_t source_port{}; ///< host byte order + std::optional destination_port; ///< host byte order; absent when the quote ends before it + }; + + namespace detail + { + /// Reads the ports at @p offset of the quoted packet, if at least the source port is there. + [[nodiscard]] constexpr std::optional quoted_ports(const uint8_t protocol, + const uint8_t* quoted, const std::size_t quoted_size, const std::size_t offset) noexcept + { + if (offset + 2 > quoted_size) + return std::nullopt; + + icmp_error_quote quote{ protocol, static_cast((quoted[offset] << 8) | quoted[offset + 1]), std::nullopt }; + if (offset + 4 <= quoted_size) + quote.destination_port = static_cast((quoted[offset + 2] << 8) | quoted[offset + 3]); + return quote; + } + } + /** - * @brief The source port of the UDP datagram or TCP segment an ICMP (IPv4) error quotes. + * @brief The transport ports of the UDP datagram or TCP segment an ICMP (IPv4) error quotes. * * Returns std::nullopt when the message is not an error, quotes another protocol or a later * fragment (whose first bytes are not ports), or is truncated before the quoted source port. + * The destination port is absent when the quote ends between the two ports. * * @param icmp_message The ICMP header followed by the quoted packet. - * @return The quoted source port in host byte order. */ - [[nodiscard]] constexpr std::optional icmpv4_error_quoted_source_port( + [[nodiscard]] constexpr std::optional icmpv4_error_quote( const uint8_t* icmp_message, const std::size_t size) noexcept { constexpr std::size_t icmp_header_size = 8, minimum_ipv4_header_size = 20; @@ -497,7 +524,7 @@ namespace proxy return std::nullopt; const auto header_size = static_cast(quoted[0] & 0x0f) * 4; - if (header_size < minimum_ipv4_header_size || header_size + 2 > quoted_size) + if (header_size < minimum_ipv4_header_size) return std::nullopt; if (quoted[9] != udp && quoted[9] != tcp) @@ -507,20 +534,20 @@ namespace proxy if (classify_ipv4_fragment(flags_and_offset) == ipv4_fragment::later) return std::nullopt; - return static_cast((quoted[header_size] << 8) | quoted[header_size + 1]); + return detail::quoted_ports(quoted[9], quoted, quoted_size, header_size); } /** - * @brief The source port of the UDP datagram or TCP segment an ICMPv6 error quotes. + * @brief The transport ports of the UDP datagram or TCP segment an ICMPv6 error quotes. * * Walks the quoted packet's hop-by-hop, routing, destination-options and fragment headers. * Returns std::nullopt when the message is not an error, quotes another upper-layer protocol - * or a later fragment, or is truncated before the quoted source port. + * or a later fragment, or is truncated before the quoted source port. The destination port + * is absent when the quote ends between the two ports. * * @param icmp_message The ICMPv6 header followed by the quoted packet. - * @return The quoted source port in host byte order. */ - [[nodiscard]] constexpr std::optional icmpv6_error_quoted_source_port( + [[nodiscard]] constexpr std::optional icmpv6_error_quote( const uint8_t* icmp_message, const std::size_t size) noexcept { constexpr std::size_t icmp_header_size = 8, ipv6_header_size = 40; @@ -563,54 +590,96 @@ namespace proxy continue; } - if ((next != udp && next != tcp) || offset + 2 > quoted_size) + if (next != udp && next != tcp) return std::nullopt; - return static_cast((quoted[offset] << 8) | quoted[offset + 1]); + return detail::quoted_ports(next, quoted, quoted_size, offset); } return std::nullopt; } + /// The source port of the packet an ICMP (IPv4) error quotes (icmpv4_error_quote()). + [[nodiscard]] constexpr std::optional icmpv4_error_quoted_source_port( + const uint8_t* icmp_message, const std::size_t size) noexcept + { + const auto quote = icmpv4_error_quote(icmp_message, size); + return quote ? std::optional{ quote->source_port } : std::nullopt; + } + + /// The source port of the packet an ICMPv6 error quotes (icmpv6_error_quote()). + [[nodiscard]] constexpr std::optional icmpv6_error_quoted_source_port( + const uint8_t* icmp_message, const std::size_t size) noexcept + { + const auto quote = icmpv6_error_quote(icmp_message, size); + return quote ? std::optional{ quote->source_port } : std::nullopt; + } + /// What a packet handler does with an outbound ICMP or ICMPv6 message. enum class icmp_error_action : uint8_t { - pass, ///< not about a DNS answer, or not in Proxy mode: left alone - drop ///< reports a DNS answer in Proxy mode: it would carry the answer to the DNS server + pass, ///< about nothing a proxy delivered: left alone + drop_dns_answer, ///< reports a DNS answer in Proxy mode: it would carry the answer to the DNS server + drop_proxied_udp_reply ///< reports a reply the per-port UDP proxy delivered: it would carry it to the peer }; /** * @brief Decides what to do with an outbound ICMP or ICMPv6 message. * - * Only the quoted source port is used, like the destination port for queries: in Proxy mode - * no query leaves the adapter, so a quoted packet from port 53 is an answer the DNS proxy - * delivered. The few DNS packets the policy passes in Proxy mode (broadcast or multicast - * destinations, ProxiFyre's own traffic to a SOCKS5 server on port 53) lose at most the - * error report for an answer nobody was waiting for. + * - DNS answers: only the quoted source port is used, like the destination port for + * queries: in Proxy mode no query leaves the adapter, so a quoted packet from port 53 is + * an answer the DNS proxy delivered. The few DNS packets the policy passes in Proxy mode + * (broadcast or multicast destinations, ProxiFyre's own traffic to a SOCKS5 server on + * port 53) lose at most the error report for an answer nobody was waiting for. + * - Proxied UDP: a quoted UDP datagram whose destination port is a client port with an + * active entry in the UDP redirect (@p is_redirected_client_port, consulted only for + * such a datagram). Its source is the remote endpoint the reply was presented as coming + * from. The redirect is keyed by the client port, so a datagram the same port received + * directly from the network is matched too; that sender already knows the computer's + * address, and only its error report is lost. * - * @param quoted_source_port icmpv4_error_quoted_source_port() or - * icmpv6_error_quoted_source_port() of the message. + * @param quote icmpv4_error_quote() or icmpv6_error_quote() of the message. + * @param is_redirected_client_port Callable taking a port in host byte order. */ + template [[nodiscard]] constexpr icmp_error_action decide_icmp_error(const dns_routing_mode mode, - const std::optional quoted_source_port) noexcept - { - return mode == dns_routing_mode::proxy && quoted_source_port && *quoted_source_port == dns_port - ? icmp_error_action::drop - : icmp_error_action::pass; + const std::optional& quote, IsRedirectedClientPort&& is_redirected_client_port) + { + constexpr uint8_t udp = 17; + + if (!quote) + return icmp_error_action::pass; + if (mode == dns_routing_mode::proxy && quote->source_port == dns_port) + return icmp_error_action::drop_dns_answer; + if (quote->protocol == udp && quote->destination_port && + std::forward(is_redirected_client_port)(*quote->destination_port)) + return icmp_error_action::drop_proxied_udp_reply; + return icmp_error_action::pass; } /** - * @brief The address families whose outbound ICMP messages the DNS policy has to see in - * @p mode, as a REDIRECT driver filter at the front of the table. + * @brief The address families whose outbound ICMP messages have to be seen in user mode, + * as a REDIRECT driver filter at the front of the table. * * Without one, ICMP is passed by the driver (the router's ICMP PASS filter, LAN bypass) - * and decide_icmp_error() is never consulted. Direct mode needs none. + * and decide_icmp_error() is never consulted. A family needs it in DNS Proxy mode, and + * whenever a UDP listener of that family exists: replies on a proxied UDP flow are + * delivered by the listener whatever the DNS mode. A reply arrives in the packet family of + * its flow, so an IPv4-mapped destination of a dual-stack socket counts as IPv4. + * + * @param ipv4_udp_proxied Whether an IPv4 UDP listener of a proxy exists. + * @param ipv6_udp_proxied Whether an IPv6 UDP listener of a proxy exists. */ - [[nodiscard]] inline std::vector plan_dns_icmp_filters(const dns_routing_mode mode) - { - if (mode != dns_routing_mode::proxy) - return {}; - return { dns_family::ipv4, dns_family::ipv6 }; + [[nodiscard]] inline std::vector plan_icmp_error_filters(const dns_routing_mode mode, + const bool ipv4_udp_proxied, const bool ipv6_udp_proxied) + { + const bool dns_proxy = mode == dns_routing_mode::proxy; + std::vector families; + if (dns_proxy || ipv4_udp_proxied) + families.push_back(dns_family::ipv4); + if (dns_proxy || ipv6_udp_proxied) + families.push_back(dns_family::ipv6); + return families; } /// What tcp_local_redirect reported for a segment from a local TCP listener. diff --git a/netlib/src/proxy/socks_local_router.h b/netlib/src/proxy/socks_local_router.h index 6d00f59..056995f 100644 --- a/netlib/src/proxy/socks_local_router.h +++ b/netlib/src/proxy/socks_local_router.h @@ -345,6 +345,25 @@ namespace proxy */ std::atomic_flag dns_answer_icmp_error_logged_{}; + /** + * @brief Count of outbound ICMP errors about replies the per-port UDP proxy delivered, + * dropped since the last throttled report (see decide_icmp_error()). + */ + std::atomic proxied_udp_icmp_errors_{ 0 }; + + /** + * @brief Set once the first dropped ICMP error about a proxied UDP reply of this run has + * been reported at info level; later ones are only counted. Reset by start(). + */ + std::atomic_flag proxied_udp_icmp_error_logged_{}; + + /** + * @brief Whether the IPv4 and the IPv6 REDIRECT filter for outbound ICMP errors are in + * the driver table (install_icmp_error_filters(); cleared by + * remove_dns_filters()). Under lifecycle_mutex_. + */ + std::array icmp_error_filter_installed_{ false, false }; + /** * @brief One-shot flags so that each (family, transport, reason) block cause is * described once in the log instead of once per packet. @@ -771,15 +790,16 @@ namespace proxy if (ip_header->ip_p == IPPROTO_ICMP) { - // Seen here only in DNS Proxy mode (install_dns_filters()); otherwise - // the driver passes ICMP itself. + // Seen here only while install_icmp_error_filters() has installed the + // IPv4 filter (DNS Proxy mode, or an IPv4 UDP listener); otherwise the + // driver passes ICMP itself. const auto ip_header_size = static_cast(ip_header->ip_hl) * sizeof(DWORD); const auto fragment = classify_ipv4_fragment(ntohs(ip_header->ip_off)); if (fragment != ipv4_fragment::later && buffer.m_Length > ETHER_HEADER_LENGTH + ip_header_size) { const auto* const icmp_message = reinterpret_cast(ip_header) + ip_header_size; - return handle_outbound_icmp(icmpv4_error_quoted_source_port(icmp_message, + return handle_outbound_icmp(icmpv4_error_quote(icmp_message, buffer.m_Length - ETHER_HEADER_LENGTH - ip_header_size)); } } @@ -1067,6 +1087,8 @@ namespace proxy listener_segments_after_reset_.store(0, std::memory_order_relaxed); dns_answer_icmp_errors_.store(0, std::memory_order_relaxed); dns_answer_icmp_error_logged_.clear(std::memory_order_relaxed); + proxied_udp_icmp_errors_.store(0, std::memory_order_relaxed); + proxied_udp_icmp_error_logged_.clear(std::memory_order_relaxed); for (auto& flag : dns_block_reason_logged_) flag.clear(std::memory_order_relaxed); @@ -1760,6 +1782,27 @@ namespace proxy const bool has_ipv4_listeners = socks_tcp_proxy_server || socks_udp_proxy_server; const bool has_ipv6_listeners = socks_tcp_proxy_server_v6 || socks_udp_proxy_server_v6; + // A running router installed its ICMP error filters for the UDP listeners it had + // at start(); one added now needs them as well (install_icmp_error_filters()). + // Done before the upstream PASS filters: a failure here leaves nothing to roll + // back, and a surplus ICMP filter only passes the messages through user mode. + if ((socks_udp_proxy_server || socks_udp_proxy_server_v6) && is_active_.load(std::memory_order_acquire)) + { + dns_routing_mode mode; + { + std::shared_lock lock(lock_); + mode = dns_mode_; + } + if (!install_icmp_error_filters(mode, socks_udp_proxy_server != nullptr, + socks_udp_proxy_server_v6 != nullptr)) + { + NETLIB_LOG(log_level::error, + "Failed to add SOCKS5 proxy {}: the outbound ICMP filters for its UDP listeners could " + "not be installed.", endpoint); + return {}; + } + } + if ((has_ipv4_listeners || has_ipv6_listeners) && proxy_endpoint->ipv4) { if (!install_upstream_filters(*proxy_endpoint->ipv4)) @@ -2396,32 +2439,58 @@ namespace proxy /** * @brief Applies decide_icmp_error() to an outbound ICMP or ICMPv6 message. * - * In Proxy mode a DNS answer is written by the DNS proxy's listener and presented as - * coming from the server the client queried. If the client's socket has closed, the - * stack reports the answer to that server with an ICMP error that quotes it; passing the - * error would send the answer to the DNS server in clear, so it is dropped. The lock is - * taken only for a message that quotes a packet from port 53. + * A reply delivered by a local listener is presented as coming from the remote endpoint: + * a DNS answer in Proxy mode, or a datagram on a UDP flow the per-port UDP proxy + * redirected. If the client's socket has closed, the stack reports the reply to that + * endpoint with an ICMP error that quotes it; passing the error would send the reply to + * it in clear, from the computer's own address, so it is dropped. The DNS mode lock is + * taken only for a message that quotes a packet from port 53, and the redirect's lock + * only for one that quotes a UDP datagram. * - * @param quoted_source_port Source port of the packet the message quotes, if it is an - * error about a UDP datagram or TCP segment. + * @tparam AddrT Address type of the message's family; selects the UDP redirect. + * @param quote The transport ports of the packet the message quotes, if it is an error + * about a UDP datagram or TCP segment. */ - packet_filter::packet_action handle_outbound_icmp(const std::optional quoted_source_port) + template + packet_filter::packet_action handle_outbound_icmp(const std::optional& quote) { - if (decide_icmp_error(dns_routing_mode::proxy, quoted_source_port) == icmp_error_action::pass || - !dns_proxy_mode()) - { - return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; - } + const auto mode = quote && quote->source_port == dns_port && dns_proxy_mode() + ? dns_routing_mode::proxy + : dns_routing_mode::direct; + + const auto action = decide_icmp_error(mode, quote, + [this](const uint16_t client_port) { return udp_redirect_for().is_active_endpoint(client_port); }); - dns_answer_icmp_errors_.fetch_add(1, std::memory_order_relaxed); - if (!dns_answer_icmp_error_logged_.test_and_set(std::memory_order_relaxed)) + switch (action) { - NETLIB_LOG(log_level::info, - "DNS routing: dropped an ICMP error about a DNS answer instead of sending it to the DNS server " - "(the client's socket had closed before the answer from the DNS proxy arrived, and the error " - "quotes the answer). Further occurrences are counted."); + case icmp_error_action::drop_dns_answer: + dns_answer_icmp_errors_.fetch_add(1, std::memory_order_relaxed); + if (!dns_answer_icmp_error_logged_.test_and_set(std::memory_order_relaxed)) + { + NETLIB_LOG(log_level::info, + "DNS routing: dropped an ICMP error about a DNS answer instead of sending it to the DNS server " + "(the client's socket had closed before the answer from the DNS proxy arrived, and the error " + "quotes the answer). Further occurrences are counted."); + } + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + + case icmp_error_action::drop_proxied_udp_reply: + proxied_udp_icmp_errors_.fetch_add(1, std::memory_order_relaxed); + if (!proxied_udp_icmp_error_logged_.test_and_set(std::memory_order_relaxed)) + { + NETLIB_LOG(log_level::info, + "Dropped an ICMP error about a proxied UDP reply instead of sending it to the remote peer " + "(the application's socket on port {} had closed before the reply from the proxy arrived, " + "and the error quotes the reply). Further occurrences are counted.", + quote->destination_port.value_or(0)); + } + return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + + case icmp_error_action::pass: + break; } - return packet_filter::packet_action{ packet_filter::packet_action::action_type::drop }; + + return packet_filter::packet_action{ packet_filter::packet_action::action_type::pass }; } /// Maps tcp_local_redirect's result for a listener segment to the policy's outcome. @@ -2893,8 +2962,9 @@ namespace proxy } /** - * @brief Removes the DNS policy's driver filters from an earlier start(). They are the - * only REDIRECT filters this router installs; every other static filter is PASS. + * @brief Removes the DNS policy's driver filters from an earlier start(), and the ICMP + * error filters (install_icmp_error_filters()). They are the only REDIRECT filters + * this router installs; every other static filter is PASS. */ void remove_dns_filters() { @@ -2903,6 +2973,76 @@ namespace proxy [&is_dns_filter](const ndisapi::filter& filter) { return is_dns_filter(filter); }); static_filters_.remove_filters_if( [&is_dns_filter](const ndisapi::filter& filter) { return is_dns_filter(filter); }); + icmp_error_filter_installed_ = { false, false }; + } + + /// Whether an IPv4 and an IPv6 UDP listener of a proxy exist. Caller holds lock_. + [[nodiscard]] std::pair udp_listeners_present_locked() const + { + const auto has_udp = [](const auto& servers) + { + return std::ranges::any_of(servers, [](const auto& proxy) { return proxy.second != nullptr; }); + }; + return { has_udp(proxy_servers_), has_udp(proxy_servers_v6_) }; + } + + /** + * @brief Installs the REDIRECT driver filters for outbound ICMP and ICMPv6 that + * plan_icmp_error_filters() asks for and that are not installed yet, at the front + * of the table. + * + * They are ahead of the ICMP PASS filter and the LAN-bypass PASS filters, so an ICMP + * error about a reply a listener delivered reaches handle_outbound_icmp() whatever its + * destination. Called from install_dns_filters() on start(), after remove_dns_filters() + * removed the filters of an earlier run, and from add_socks5_proxy() when a UDP listener + * is added to a running router; a filter already installed is kept, so there is no + * moment without it. Called under lifecycle_mutex_. + * + * @param mode The DNS routing mode the router runs with. + * @param extra_ipv4_udp, extra_ipv6_udp UDP listeners about to be added that are not in + * proxy_servers_ yet. + * @return false when a filter could not be installed. + */ + bool install_icmp_error_filters(const dns_routing_mode mode, const bool extra_ipv4_udp = false, + const bool extra_ipv6_udp = false) + { + std::pair udp_listeners{}; + { + std::shared_lock lock(lock_); + udp_listeners = udp_listeners_present_locked(); + } + + for (const auto family : plan_icmp_error_filters(mode, udp_listeners.first || extra_ipv4_udp, + udp_listeners.second || extra_ipv6_udp)) + { + auto& installed = icmp_error_filter_installed_[family == dns_family::ipv4 ? 0 : 1]; + if (installed) + continue; + + const auto add = [this](auto filter, const uint8_t protocol) -> bool + { + filter.set_direction(ndisapi::direction_t::out) + .set_action(ndisapi::action_t::redirect) + .set_protocol(protocol); + return static_filters_.add_filter_front(filter); + }; + + const bool added = family == dns_family::ipv4 + ? add(ndisapi::filter{}, static_cast(IPPROTO_ICMP)) + : add(ndisapi::filter{}, static_cast(IPPROTO_ICMPV6)); + + if (!added) + { + NETLIB_LOG(log_level::error, + "Failed to install the {} driver filter for outbound ICMP errors; refusing to continue so a " + "DNS answer or a proxied UDP reply cannot leave the computer inside an ICMP error.", + family == dns_family::ipv4 ? "IPv4" : "IPv6"); + return false; + } + installed = true; + } + + return true; } /** @@ -2911,11 +3051,14 @@ namespace proxy * Runs on every start(): the filters from an earlier run are removed and the current plan * is inserted at the front of the table, so the filters stay ahead of LAN-bypass PASS * filters added between runs and use the current listener ports and proxy selection. In - * Direct mode the plan is empty, so earlier filters are only removed. + * Direct mode the plan is empty, so earlier filters are only removed. The ICMP error + * filters (install_icmp_error_filters()) are installed here too: in Proxy mode, and in + * either mode for each address family with a UDP listener. * Called from start() under lifecycle_mutex_. * - * @return false when a filter needed by Proxy mode could not be installed; the caller - * then fails start() rather than running with DNS able to bypass the policy. + * @return false when a filter could not be installed; the caller then fails start() + * rather than running with DNS, or a proxied UDP reply inside an ICMP error, able + * to bypass the proxy. */ bool install_dns_filters() { @@ -2966,31 +3109,11 @@ namespace proxy } // Outbound ICMP has to reach handle_outbound_icmp(): an ICMP error about a DNS answer - // quotes the answer and is addressed to the DNS server. Ahead of the ICMP PASS filter - // and the LAN-bypass PASS filters, like the filters above. - for (const auto family : plan_dns_icmp_filters(mode)) + // or a proxied UDP reply quotes it and is addressed to the remote endpoint. + if (!install_icmp_error_filters(mode)) { - const auto add = [this](auto filter, const uint8_t protocol) -> bool - { - filter.set_direction(ndisapi::direction_t::out) - .set_action(ndisapi::action_t::redirect) - .set_protocol(protocol); - return static_filters_.add_filter_front(filter); - }; - - const bool added = family == dns_family::ipv4 - ? add(ndisapi::filter{}, static_cast(IPPROTO_ICMP)) - : add(ndisapi::filter{}, static_cast(IPPROTO_ICMPV6)); - - if (!added) - { - NETLIB_LOG(log_level::error, - "DNS routing: failed to install the {} driver filter for outbound ICMP errors; refusing to " - "start so a DNS answer cannot leave the computer inside an ICMP error.", - family == dns_family::ipv4 ? "IPv4" : "IPv6"); - remove_dns_filters(); - return false; - } + remove_dns_filters(); + return false; } return true; @@ -3375,7 +3498,7 @@ namespace proxy const auto* const packet_end = reinterpret_cast(ethernet_header) + buffer.m_Length; if (icmp_message < packet_end) { - return handle_outbound_icmp(icmpv6_error_quoted_source_port(icmp_message, + return handle_outbound_icmp(icmpv6_error_quote(icmp_message, static_cast(packet_end - icmp_message))); } } @@ -3719,6 +3842,14 @@ namespace proxy "DNS routing: dropped {} ICMP error(s) about DNS answers delivered to sockets that had closed; " "they were not sent to the network.", icmp_errors); } + if (const auto icmp_errors = proxied_udp_icmp_errors_.exchange(0, std::memory_order_relaxed); + icmp_errors != 0) + { + reported = true; + NETLIB_LOG(log_level::debug, + "Dropped {} ICMP error(s) about proxied UDP replies delivered to sockets that had closed; " + "they were not sent to the network.", icmp_errors); + } return reported; } diff --git a/netlib/test/portable/dns_packet_redirect_test.cpp b/netlib/test/portable/dns_packet_redirect_test.cpp index f5497c8..ac05331 100644 --- a/netlib/test/portable/dns_packet_redirect_test.cpp +++ b/netlib/test/portable/dns_packet_redirect_test.cpp @@ -1065,3 +1065,112 @@ TEST(DnsPacketRedirect, OversizedUdpAnswerIsDeliveredTruncatedSoTheResolverRetri EXPECT_TRUE(reply->l4_checksum_valid()); } } + +// ------------------------------------------------------------------ ICMP errors about proxied UDP replies +// +// Application UDP that a rule proxies: the per-port UDP proxy's reply is translated by the +// production socks5_udp_local_redirect so that it reaches the client from the remote peer. If the +// client's socket has closed, the stack answers it with an ICMP (or ICMPv6) error addressed to +// that peer which quotes the translated reply. The router recognizes such an error from the quote +// and the redirect's endpoint table (decide_icmp_error(), socks_local_router's +// handle_outbound_icmp()) and drops it, in either DNS mode. + +namespace +{ + /// The stack's ICMP or ICMPv6 error about @p delivered: the 8-byte header, then the + /// datagram from its IP header on (Windows quotes as much of it as fits). + std::vector icmp_error_about(const uint8_t type, const uint8_t code, const frame& delivered) + { + std::vector message{ type, code, 0, 0, 0, 0, 0, 0 }; + message.insert(message.end(), delivered.buffer.m_IBuffer + ETHER_HEADER_LENGTH, + delivered.buffer.m_IBuffer + delivered.buffer.m_Length); + return message; + } + + /// The router's decision for an outbound ICMP message of @p redirect's family. + template + proxy::icmp_error_action router_decision(ndisapi::socks5_udp_local_redirect& redirect, + const proxy::dns_routing_mode mode, const std::vector& message) + { + const auto quote = std::is_same_v + ? proxy::icmpv4_error_quote(message.data(), message.size()) + : proxy::icmpv6_error_quote(message.data(), message.size()); + return proxy::decide_icmp_error(mode, quote, + [&redirect](const uint16_t port) { return redirect.is_active_endpoint(port); }); + } + + constexpr uint16_t peer_port = 3478; +} + +TEST(ProxiedUdpIcmpError, Ipv4ErrorAboutAReplyToAClosedSocketIsDropped) +{ + using proxy::icmp_error_action; + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + EXPECT_FALSE(redirect.is_active_endpoint(client_port)); + + // The application's datagram to the peer is redirected to the UDP proxy's listener. + auto request = frame::udp4("192.168.1.10", "203.0.113.7", client_port, peer_port, std::vector(48, 0xa5)); + EXPECT_TRUE(redirect.is_new_endpoint(request.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(request.buffer, htons(udp_listener))); + EXPECT_TRUE(redirect.is_active_endpoint(client_port)); + + // The listener's reply, carrying the peer in the SOCKS5 header, reaches the client from the peer. + const std::vector response(64, 0x5a); + auto reply = local_proxy_reply("192.168.1.10", "203.0.113.7", v4{ std::string{ "203.0.113.7" } }, peer_port, response); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer)); + ASSERT_EQ(v4{ reply.ip4()->ip_src }, v4{ std::string{ "203.0.113.7" } }); + ASSERT_EQ(ntohs(reply.udp()->th_sport), peer_port); + ASSERT_EQ(ntohs(reply.udp()->th_dport), client_port); + ASSERT_EQ(reply.payload(), response); + + // The socket has closed: the port-unreachable error the stack would send to the peer quotes + // the reply, so it is dropped whatever the DNS mode. So is any other error type about it. + const auto unreachable = icmp_error_about(3, 3, reply); + const auto quote = proxy::icmpv4_error_quote(unreachable.data(), unreachable.size()); + ASSERT_TRUE(quote.has_value()); + EXPECT_EQ(quote->source_port, peer_port); + EXPECT_EQ(quote->destination_port, std::optional{ client_port }); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, unreachable), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::proxy, unreachable), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(12, 0, reply)), + icmp_error_action::drop_proxied_udp_reply); + + // A datagram the computer received directly on a port that was never redirected, and a + // ping, are left alone. + auto unproxied = frame::udp4("203.0.113.7", "192.168.1.10", peer_port, client_port + 1, response); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(3, 3, unproxied)), + icmp_error_action::pass); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(8, 0, reply)), + icmp_error_action::pass); +} + +TEST(ProxiedUdpIcmpError, Ipv6ErrorAboutAReplyToAClosedSocketIsDropped) +{ + using proxy::icmp_error_action; + ndisapi::socks5_udp_local_redirect redirect{ log_level::error }; + + auto request = frame::udp6("2001:db8::10", "2001:db8:1::7", client_port, peer_port, std::vector(48, 0xa5)); + EXPECT_TRUE(redirect.is_new_endpoint(request.buffer)); + ASSERT_TRUE(redirect.process_client_to_server_packet(request.buffer, htons(udp_listener))); + + const std::vector response(200, 0x5a); + auto reply = local_proxy_reply("2001:db8::10", "2001:db8:1::7", v6{ std::string{ "2001:db8:1::7" } }, peer_port, response); + ASSERT_TRUE(redirect.process_server_to_client_packet(reply.buffer)); + ASSERT_EQ(v6{ reply.ip6()->ip6_src }, v6{ std::string{ "2001:db8:1::7" } }); + ASSERT_EQ(ntohs(reply.udp()->th_dport), client_port); + + // ICMPv6 destination unreachable, port unreachable (type 1, code 4). + const auto unreachable = icmp_error_about(1, 4, reply); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, unreachable), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::proxy, unreachable), icmp_error_action::drop_proxied_udp_reply); + + // Echo request and neighbor solicitation are informational and pass, as does an error about + // a port that was never redirected. + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(128, 0, reply)), + icmp_error_action::pass); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(135, 0, reply)), + icmp_error_action::pass); + auto unproxied = frame::udp6("2001:db8:1::7", "2001:db8::10", peer_port, client_port + 1, response); + EXPECT_EQ(router_decision(redirect, proxy::dns_routing_mode::direct, icmp_error_about(1, 4, unproxied)), + icmp_error_action::pass); +} diff --git a/netlib/test/proxy/dns_routing_policy_test.cpp b/netlib/test/proxy/dns_routing_policy_test.cpp index 5ccb4ff..8f17985 100644 --- a/netlib/test/proxy/dns_routing_policy_test.cpp +++ b/netlib/test/proxy/dns_routing_policy_test.cpp @@ -13,6 +13,8 @@ #include "pch.h" #include "../../src/proxy/dns_routing_policy.h" +#include +#include #include #include @@ -808,36 +810,192 @@ TEST(DnsAnswerIcmpPolicy, Icmpv6MessagesWithoutAQuotedSourcePortAreNotReported) EXPECT_FALSE(proxy::icmpv6_error_quoted_source_port(nullptr, 100).has_value()); } +namespace +{ + std::optional quote_v4(const std::vector& message) + { + return proxy::icmpv4_error_quote(message.data(), message.size()); + } + + std::optional quote_v6(const std::vector& message) + { + return proxy::icmpv6_error_quote(message.data(), message.size()); + } + + /// A quoted UDP datagram from @p source to @p destination, both ports present. + std::optional udp_quote(const uint16_t source, const uint16_t destination) + { + return proxy::icmp_error_quote{ udp_proto, source, destination }; + } + + /// The UDP redirect's view: which client ports have an active endpoint entry. Records the + /// ports it was asked about, so a test can check that it is consulted only when needed. + struct redirected_ports + { + std::vector active; + mutable std::vector asked; + + bool operator()(const uint16_t port) const + { + asked.push_back(port); + return std::ranges::find(active, port) != active.end(); + } + }; + + proxy::icmp_error_action decide(const proxy::dns_routing_mode mode, + const std::optional& quote, const redirected_ports& redirect = {}) + { + return proxy::decide_icmp_error(mode, quote, std::cref(redirect)); + } +} + TEST(DnsAnswerIcmpPolicy, OnlyErrorsAboutPort53AnswersAreDroppedAndOnlyInProxyMode) { - using proxy::decide_icmp_error; using proxy::icmp_error_action; - EXPECT_EQ(decide_icmp_error(proxy_mode, uint16_t{ 53 }), icmp_error_action::drop); + EXPECT_EQ(decide(proxy_mode, udp_quote(53, 58440)), icmp_error_action::drop_dns_answer); + EXPECT_EQ(decide(proxy_mode, proxy::icmp_error_quote{ tcp_proto, 53, 58440 }), icmp_error_action::drop_dns_answer); // Direct mode: the answer came from the real server, which may be told. - EXPECT_EQ(decide_icmp_error(direct, uint16_t{ 53 }), icmp_error_action::pass); + EXPECT_EQ(decide(direct, udp_quote(53, 58440)), icmp_error_action::pass); // Other traffic, and messages that quote nothing usable, are never touched. - EXPECT_EQ(decide_icmp_error(proxy_mode, uint16_t{ 443 }), icmp_error_action::pass); - EXPECT_EQ(decide_icmp_error(proxy_mode, uint16_t{ 5353 }), icmp_error_action::pass); - EXPECT_EQ(decide_icmp_error(proxy_mode, std::nullopt), icmp_error_action::pass); - EXPECT_EQ(decide_icmp_error(direct, std::nullopt), icmp_error_action::pass); + EXPECT_EQ(decide(proxy_mode, udp_quote(443, 58440)), icmp_error_action::pass); + EXPECT_EQ(decide(proxy_mode, udp_quote(5353, 58440)), icmp_error_action::pass); + EXPECT_EQ(decide(proxy_mode, std::nullopt), icmp_error_action::pass); + EXPECT_EQ(decide(direct, std::nullopt), icmp_error_action::pass); // End to end: a port-unreachable error about an answer, for both families. - EXPECT_EQ(decide_icmp_error(proxy_mode, - quoted_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, ipv4_packet(udp_proto, 0, ports(53, 58440))))), - icmp_error_action::drop); - EXPECT_EQ(decide_icmp_error(proxy_mode, - quoted_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, ipv6_packet(udp_proto, ports(53, 58440))))), - icmp_error_action::drop); + EXPECT_EQ(decide(proxy_mode, + quote_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, ipv4_packet(udp_proto, 0, ports(53, 58440))))), + icmp_error_action::drop_dns_answer); + EXPECT_EQ(decide(proxy_mode, + quote_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, ipv6_packet(udp_proto, ports(53, 58440))))), + icmp_error_action::drop_dns_answer); // A ping whose data happens to look like a packet from port 53 is passed. - EXPECT_EQ(decide_icmp_error(proxy_mode, - quoted_v4(icmp_message(icmpv4_echo_request, 0, ipv4_packet(udp_proto, 0, ports(53, 1))))), + EXPECT_EQ(decide(proxy_mode, + quote_v4(icmp_message(icmpv4_echo_request, 0, ipv4_packet(udp_proto, 0, ports(53, 1))))), icmp_error_action::pass); } -TEST(DnsFilterPlan, OutboundIcmpIsKeptInUserModeOnlyInProxyMode) +// ------------------------------------------------------------------ ICMP errors about proxied UDP replies +// +// A reply on a UDP flow the per-port UDP proxy redirected reaches the client presented as coming +// from the remote peer. If the client's socket has closed, the stack's ICMP error about it quotes +// the reply and is addressed to that peer, from the computer's own address. It must not leave the +// adapter, in either DNS mode. + +TEST(ProxiedUdpIcmpPolicy, QuoteExposesBothPortsOfTheQuotedPacket) +{ + const auto v4 = quote_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, + ipv4_packet(udp_proto, 0, ports(443, 50001), { 1, 1, 1, 1 }))); + ASSERT_TRUE(v4.has_value()); + EXPECT_EQ(v4->protocol, udp_proto); + EXPECT_EQ(v4->source_port, 443); + EXPECT_EQ(v4->destination_port, std::optional{ 50001 }); + + const auto v6 = quote_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, + ipv6_packet(fragment_proto, concat({ fragment_header(udp_proto, 0, true), ports(3478, 50002) })))); + ASSERT_TRUE(v6.has_value()); + EXPECT_EQ(v6->protocol, udp_proto); + EXPECT_EQ(v6->source_port, 3478); + EXPECT_EQ(v6->destination_port, std::optional{ 50002 }); + + const auto tcp = quote_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(tcp_proto, 0, ports(80, 50003)))); + ASSERT_TRUE(tcp.has_value()); + EXPECT_EQ(tcp->protocol, tcp_proto); + + // A quote that ends between the ports has the source port only (it was enough for the DNS + // rule before); the destination port is not guessed. + const auto cut_v4 = quote_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, { 0x01, 0xbb }))); + ASSERT_TRUE(cut_v4.has_value()); + EXPECT_EQ(cut_v4->source_port, 443); + EXPECT_FALSE(cut_v4->destination_port.has_value()); + const auto cut_v6 = quote_v6(icmp_message(icmpv6_unreachable, 0, ipv6_packet(udp_proto, { 0x01, 0xbb, 0xc3 }))); + ASSERT_TRUE(cut_v6.has_value()); + EXPECT_FALSE(cut_v6->destination_port.has_value()); + + // The source-port helpers agree with the quote. + const auto message = icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, ports(443, 50001))); + EXPECT_EQ(proxy::icmpv4_error_quoted_source_port(message.data(), message.size()), std::optional{ 443 }); +} + +TEST(ProxiedUdpIcmpPolicy, ErrorsAboutRepliesToRedirectedClientPortsAreDroppedInEitherMode) +{ + using proxy::icmp_error_action; + const redirected_ports redirect{ { 50001, 50002 }, {} }; + + for (const auto mode : { direct, proxy_mode }) + { + EXPECT_EQ(decide(mode, udp_quote(443, 50001), redirect), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(decide(mode, udp_quote(3478, 50002), redirect), icmp_error_action::drop_proxied_udp_reply); + // A client port without an active redirect entry: its traffic was not proxied. + EXPECT_EQ(decide(mode, udp_quote(443, 50003), redirect), icmp_error_action::pass); + } + + // End to end, for both families, with any error type (not only port unreachable). + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_unreachable, icmpv4_port_unreachable, + ipv4_packet(udp_proto, 0, ports(443, 50001)))), redirect), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(decide(direct, quote_v4(icmp_message(12, 0, ipv4_packet(udp_proto, 0, ports(443, 50001)))), redirect), + icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(decide(direct, quote_v6(icmp_message(icmpv6_unreachable, icmpv6_port_unreachable, + ipv6_packet(udp_proto, ports(443, 50002)))), redirect), icmp_error_action::drop_proxied_udp_reply); + EXPECT_EQ(decide(direct, quote_v6(icmp_message(4, 0, ipv6_packet(udp_proto, ports(443, 50002)))), redirect), + icmp_error_action::drop_proxied_udp_reply); + + // In Proxy mode an answer from port 53 is reported as a DNS answer whatever the redirect says. + EXPECT_EQ(decide(proxy_mode, udp_quote(53, 50001), redirect), icmp_error_action::drop_dns_answer); + // In Direct mode a proxied flow's reply from port 53 is still a proxied UDP reply. + EXPECT_EQ(decide(direct, udp_quote(53, 50001), redirect), icmp_error_action::drop_proxied_udp_reply); +} + +TEST(ProxiedUdpIcmpPolicy, OtherIcmpIsPassedAndTheRedirectIsConsultedOnlyForQuotedUdp) { - EXPECT_TRUE(proxy::plan_dns_icmp_filters(direct).empty()); - const std::vector both{ dns_family::ipv4, dns_family::ipv6 }; - EXPECT_EQ(proxy::plan_dns_icmp_filters(proxy_mode), both); + using proxy::icmp_error_action; + const redirected_ports redirect{ { 50001 }, {} }; + + // Ping and neighbor discovery whose data looks like a reply to a redirected port. + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_echo_request, 0, ipv4_packet(udp_proto, 0, ports(443, 50001)))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_echo_reply, 0, ipv4_packet(udp_proto, 0, ports(443, 50001)))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, quote_v6(icmp_message(icmpv6_echo_request, 0, ipv6_packet(udp_proto, ports(443, 50001)))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, quote_v6(icmp_message(135, 0, ipv6_packet(udp_proto, ports(443, 50001)))), redirect), + icmp_error_action::pass); + // A TCP segment to the same port: the UDP redirect does not describe it (proxied TCP is + // answered with a reset, not an ICMP error). + EXPECT_EQ(decide(direct, proxy::icmp_error_quote{ tcp_proto, 443, 50001 }, redirect), icmp_error_action::pass); + // A later fragment, or a quote cut before the destination port. + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 185, ports(443, 50001)))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, quote_v4(icmp_message(icmpv4_unreachable, 0, ipv4_packet(udp_proto, 0, { 0x01, 0xbb }))), + redirect), icmp_error_action::pass); + EXPECT_EQ(decide(direct, proxy::icmp_error_quote{ udp_proto, 443, std::nullopt }, redirect), icmp_error_action::pass); + // A quoted datagram that the redirected port sent rather than received: the port to look up + // is the quoted destination (here the peer's 443), not the source. + EXPECT_EQ(decide(direct, udp_quote(50001, 443), redirect), icmp_error_action::pass); + + // Only that last quote, UDP with both ports, consulted the redirect; ping, neighbor + // discovery, TCP and cut quotes never take its lock. + EXPECT_EQ(redirect.asked, (std::vector{ 443 })); + + // The DNS rule decides without consulting the redirect. + const redirected_ports untouched{ { 50001 }, {} }; + EXPECT_EQ(decide(proxy_mode, udp_quote(53, 50001), untouched), icmp_error_action::drop_dns_answer); + EXPECT_TRUE(untouched.asked.empty()); +} + +TEST(IcmpErrorFilterPlan, OutboundIcmpIsKeptInUserModeForDnsProxyModeAndForEachFamilyWithProxiedUdp) +{ + const std::vector none, v4_only{ dns_family::ipv4 }, v6_only{ dns_family::ipv6 }, + both{ dns_family::ipv4, dns_family::ipv6 }; + + // No UDP is proxied: only DNS Proxy mode needs ICMP in user mode, for both families. + EXPECT_EQ(proxy::plan_icmp_error_filters(direct, false, false), none); + EXPECT_EQ(proxy::plan_icmp_error_filters(proxy_mode, false, false), both); + // A UDP listener of a family needs that family's ICMP in either mode. + EXPECT_EQ(proxy::plan_icmp_error_filters(direct, true, false), v4_only); + EXPECT_EQ(proxy::plan_icmp_error_filters(direct, false, true), v6_only); + EXPECT_EQ(proxy::plan_icmp_error_filters(direct, true, true), both); + EXPECT_EQ(proxy::plan_icmp_error_filters(proxy_mode, true, false), both); + EXPECT_EQ(proxy::plan_icmp_error_filters(proxy_mode, false, true), both); }