Compare commits
10 commits
master
...
outboundip
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89fc43b398 | ||
|
|
e54c45a936 | ||
|
|
9b47cbc1ed | ||
|
|
9c2aae3785 | ||
|
|
0164137a36 | ||
|
|
2e50b58f8b | ||
|
|
40b87f8414 | ||
|
|
4b14040ce1 | ||
|
|
7d57216d30 | ||
|
|
7a14419d10 |
17 changed files with 1160 additions and 39 deletions
|
|
@ -33,6 +33,8 @@ type Config struct {
|
|||
LocalDoH LocalDoHConfig `toml:"local_doh"`
|
||||
MonitoringUI MonitoringUIConfig `toml:"monitoring_ui"`
|
||||
UserName string `toml:"user_name"`
|
||||
OutboundSourceIPv4 string `toml:"outbound_source_ipv4"`
|
||||
OutboundSourceIPv6 string `toml:"outbound_source_ipv6"`
|
||||
ForceTCP bool `toml:"force_tcp"`
|
||||
HTTP3 bool `toml:"http3"`
|
||||
HTTP3Probe bool `toml:"http3_probe"`
|
||||
|
|
@ -380,7 +382,11 @@ func ConfigLoad(proxy *Proxy, flags *ConfigFlags) error {
|
|||
proxy.userName = config.UserName
|
||||
proxy.child = *flags.Child
|
||||
proxy.enableHotReload = config.EnableHotReload
|
||||
proxy.xTransport = NewXTransport()
|
||||
proxy.outboundSource, err = parseOutboundSources(config.OutboundSourceIPv4, config.OutboundSourceIPv6)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
proxy.xTransport = NewXTransport(&proxy.outboundSource)
|
||||
|
||||
// Configure logging
|
||||
configureLogging(proxy, flags, &config)
|
||||
|
|
@ -392,6 +398,7 @@ func ConfigLoad(proxy *Proxy, flags *ConfigFlags) error {
|
|||
if err := configureXTransport(proxy, &config); err != nil {
|
||||
return err
|
||||
}
|
||||
logOutboundSources(&proxy.outboundSource, proxy.xTransport.ignoreSystemDNS)
|
||||
|
||||
// Configure DoH client authentication
|
||||
if err := configureDoHClientAuth(proxy, &config); err != nil {
|
||||
|
|
|
|||
|
|
@ -71,6 +71,22 @@ func configureLogging(proxy *Proxy, flags *ConfigFlags, config *Config) {
|
|||
}
|
||||
}
|
||||
|
||||
// logOutboundSources reports missing source families and effective system DNS exclusions.
|
||||
func logOutboundSources(policy *outboundSourcePolicy, ignoreSystemDNS bool) {
|
||||
if !policy.enabled() {
|
||||
return
|
||||
}
|
||||
if !policy.ipv4.IsValid() {
|
||||
dlog.Info("No outbound IPv4 source is configured. Covered non-local IPv4 connections will fail.")
|
||||
}
|
||||
if !policy.ipv6.IsValid() {
|
||||
dlog.Info("No outbound IPv6 source is configured. Covered non-local IPv6 connections will fail.")
|
||||
}
|
||||
if !ignoreSystemDNS {
|
||||
dlog.Info("Native system DNS does not use outbound source binding.")
|
||||
}
|
||||
}
|
||||
|
||||
// configureXTransport - Configures the XTransport
|
||||
func configureXTransport(proxy *Proxy, config *Config) error {
|
||||
proxy.xTransport.tlsDisableSessionTickets = config.TLSDisableSessionTickets
|
||||
|
|
@ -123,7 +139,11 @@ func configureXTransport(proxy *Proxy, config *Config) error {
|
|||
if err != nil {
|
||||
return fmt.Errorf("Unable to parse the proxy URL [%v]", config.Proxy)
|
||||
}
|
||||
proxyDialer, err := netproxy.FromURL(proxyDialerURL, netproxy.Direct)
|
||||
forwardDialer := netproxy.Dialer(netproxy.Direct)
|
||||
if proxy.outboundSource.enabled() {
|
||||
forwardDialer = &proxyDialer{xTransport: proxy.xTransport}
|
||||
}
|
||||
proxyDialer, err := netproxy.FromURL(proxyDialerURL, forwardDialer)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Unable to use the proxy: [%v]", err)
|
||||
}
|
||||
|
|
|
|||
66
dnscrypt-proxy/config_outbound_source_test.go
Normal file
66
dnscrypt-proxy/config_outbound_source_test.go
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
)
|
||||
|
||||
func TestOutboundSourceConfig(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
toml string
|
||||
wantIPv4 string
|
||||
wantIPv6 string
|
||||
wantError string
|
||||
}{
|
||||
{name: "empty", toml: "outbound_source_ipv4 = ''\noutbound_source_ipv6 = ''"},
|
||||
{name: "IPv4", toml: "outbound_source_ipv4 = '192.0.2.10'", wantIPv4: "192.0.2.10"},
|
||||
{name: "mapped IPv4", toml: "outbound_source_ipv4 = '::ffff:192.0.2.10'", wantIPv4: "192.0.2.10"},
|
||||
{name: "IPv6", toml: "outbound_source_ipv6 = '2001:db8::10'", wantIPv6: "2001:db8::10"},
|
||||
{name: "scoped IPv6", toml: "outbound_source_ipv6 = 'fe80::1%eth0'", wantIPv6: "fe80::1%eth0"},
|
||||
{name: "dual stack", toml: "outbound_source_ipv4 = '192.0.2.10'\noutbound_source_ipv6 = '2001:db8::10'", wantIPv4: "192.0.2.10", wantIPv6: "2001:db8::10"},
|
||||
{name: "wrong IPv4 family", toml: "outbound_source_ipv4 = '2001:db8::10'", wantError: "expected an IPv4"},
|
||||
{name: "wrong IPv6 family", toml: "outbound_source_ipv6 = '192.0.2.10'", wantError: "expected an IPv6"},
|
||||
{name: "CIDR", toml: "outbound_source_ipv4 = '192.0.2.10/24'", wantError: "literal"},
|
||||
{name: "hostname", toml: "outbound_source_ipv4 = 'example.org'", wantError: "literal"},
|
||||
{name: "interface", toml: "outbound_source_ipv6 = 'eth0'", wantError: "literal"},
|
||||
{name: "port", toml: "outbound_source_ipv4 = '192.0.2.10:53'", wantError: "literal"},
|
||||
{name: "malformed", toml: "outbound_source_ipv6 = '2001:db8:::1'", wantError: "literal"},
|
||||
{name: "unspecified IPv4", toml: "outbound_source_ipv4 = '0.0.0.0'", wantError: "unspecified"},
|
||||
{name: "unspecified IPv6", toml: "outbound_source_ipv6 = '::'", wantError: "unspecified"},
|
||||
{name: "multicast IPv4", toml: "outbound_source_ipv4 = '224.0.0.1'", wantError: "multicast"},
|
||||
{name: "multicast IPv6", toml: "outbound_source_ipv6 = 'ff02::1%eth0'", wantError: "multicast"},
|
||||
{name: "broadcast", toml: "outbound_source_ipv4 = '255.255.255.255'", wantError: "limited broadcast"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
config := newConfig()
|
||||
if _, err := toml.Decode(test.toml, &config); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
policy, err := parseOutboundSources(config.OutboundSourceIPv4, config.OutboundSourceIPv6)
|
||||
if test.wantError != "" {
|
||||
if err == nil || !strings.Contains(err.Error(), test.wantError) {
|
||||
t.Fatalf("error = %v, want containing %q", err, test.wantError)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gotIPv4 := ""
|
||||
if policy.ipv4.IsValid() {
|
||||
gotIPv4 = policy.ipv4.String()
|
||||
}
|
||||
gotIPv6 := ""
|
||||
if policy.ipv6.IsValid() {
|
||||
gotIPv6 = policy.ipv6.String()
|
||||
}
|
||||
if gotIPv4 != test.wantIPv4 || gotIPv6 != test.wantIPv6 {
|
||||
t.Fatalf("got IPv4=%q IPv6=%q", gotIPv4, gotIPv6)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
@ -512,7 +512,7 @@ func _dnsExchange(
|
|||
proxy.prepareForRelay(udpAddr.IP, udpAddr.Port, &binQuery)
|
||||
upstreamAddr = relay.RelayUDPAddr
|
||||
}
|
||||
pc, err := net.DialTimeout("udp", upstreamAddr.String(), proxy.timeout)
|
||||
pc, err := proxy.outboundSource.dialUDP(upstreamAddr)
|
||||
if err != nil {
|
||||
return DNSExchangeResponse{err: err}
|
||||
}
|
||||
|
|
@ -558,7 +558,7 @@ func _dnsExchange(
|
|||
var pc net.Conn
|
||||
proxyDialer := proxy.xTransport.proxyDialer
|
||||
if proxyDialer == nil {
|
||||
pc, err = net.DialTimeout("tcp", upstreamAddr.String(), proxy.timeout)
|
||||
pc, err = proxy.outboundSource.dialTCP(upstreamAddr.AddrPort(), proxy.timeout, 0)
|
||||
} else {
|
||||
pc, err = (*proxyDialer).Dial("tcp", upstreamAddr.String())
|
||||
}
|
||||
|
|
|
|||
114
dnscrypt-proxy/dnsutils_outbound_source_test.go
Normal file
114
dnscrypt-proxy/dnsutils_outbound_source_test.go
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"codeberg.org/miekg/dns"
|
||||
)
|
||||
|
||||
func TestDNSExchangeOutboundSource(t *testing.T) {
|
||||
sourceIP := nonLoopbackIPv4(t)
|
||||
policy, err := parseOutboundSources(sourceIP.String(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
proxy := &Proxy{timeout: 2 * time.Second, outboundSource: policy}
|
||||
proxy.xTransport = NewXTransport(&proxy.outboundSource)
|
||||
|
||||
for _, proto := range []string{"udp", "tcp"} {
|
||||
for _, relayed := range []bool{false, true} {
|
||||
name := proto + "-direct"
|
||||
if relayed {
|
||||
name = proto + "-relayed"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
relayAddress, peerCh, closeServer := startTestDNS(t, proto, sourceIP, relayed, nil)
|
||||
serverAddress := relayAddress.String()
|
||||
if relayed {
|
||||
serverAddress = "9.9.9.9:53"
|
||||
}
|
||||
defer closeServer()
|
||||
var relay *DNSCryptRelay
|
||||
if relayed {
|
||||
relay = &DNSCryptRelay{}
|
||||
if proto == "udp" {
|
||||
relay.RelayUDPAddr = relayAddress.(*net.UDPAddr)
|
||||
} else {
|
||||
relay.RelayTCPAddr = relayAddress.(*net.TCPAddr)
|
||||
}
|
||||
}
|
||||
query := dns.NewMsg("example.org.", dns.TypeA)
|
||||
response := _dnsExchange(proxy, proto, query, serverAddress, relay, 0)
|
||||
if response.err != nil {
|
||||
t.Fatal(response.err)
|
||||
}
|
||||
peer := <-peerCh
|
||||
if !peer.Equal(sourceIP) {
|
||||
t.Fatalf("peer source = %s, want %s", peer, sourceIP)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func startTestDNS(t *testing.T, proto string, destinationIP net.IP, relayed bool, answer func(*dns.Msg)) (net.Addr, <-chan net.IP, func()) {
|
||||
t.Helper()
|
||||
peerCh := make(chan net.IP, 1)
|
||||
respond := func(packet []byte) []byte {
|
||||
if relayed {
|
||||
packet = packet[anonymizedDNSHeaderSize:]
|
||||
}
|
||||
msg := dns.Msg{Data: packet}
|
||||
if msg.Unpack() != nil {
|
||||
return nil
|
||||
}
|
||||
msg.Response = true
|
||||
if answer != nil {
|
||||
answer(&msg)
|
||||
}
|
||||
if msg.Pack() != nil {
|
||||
return nil
|
||||
}
|
||||
return msg.Data
|
||||
}
|
||||
if proto == "udp" {
|
||||
listener, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go func() {
|
||||
packet := make([]byte, MaxDNSPacketSize)
|
||||
length, peer, err := listener.ReadFromUDP(packet)
|
||||
if err == nil {
|
||||
peerCh <- peer.IP
|
||||
_, _ = listener.WriteToUDP(respond(packet[:length]), peer)
|
||||
}
|
||||
}()
|
||||
port := listener.LocalAddr().(*net.UDPAddr).Port
|
||||
return &net.UDPAddr{IP: destinationIP, Port: port}, peerCh, func() { _ = listener.Close() }
|
||||
}
|
||||
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4zero})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go func() {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.Close()
|
||||
peerCh <- conn.RemoteAddr().(*net.TCPAddr).IP
|
||||
packet, err := ReadPrefixed(conn)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
packet, err = PrefixWithSize(respond(packet))
|
||||
if err == nil {
|
||||
_, _ = conn.Write(packet)
|
||||
}
|
||||
}()
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
return &net.TCPAddr{IP: destinationIP, Port: port}, peerCh, func() { _ = listener.Close() }
|
||||
}
|
||||
|
|
@ -94,6 +94,23 @@ disabled_server_names = []
|
|||
# Connection Settings #
|
||||
###############################################################################
|
||||
|
||||
## Optional local source IPs for upstream DNS, resolver downloads, and
|
||||
## connections to proxies. Use literal IPv4/IPv6 addresses.
|
||||
## Leave both unset to let the OS choose. If either is set, covered
|
||||
## connections fail when their source is unavailable or their family has
|
||||
## no configured source; they are never retried unbound.
|
||||
##
|
||||
## Excludes direct forwarding, native system DNS, netprobe, `-resolve`,
|
||||
## local logging, and local/loopback sockets. Private destinations are covered.
|
||||
## Set `ignore_system_dns = true` to also disable native DNS fallback.
|
||||
##
|
||||
## Changes require a restart. These settings do not select routes or
|
||||
## interfaces; policy routing or NAT exemptions may be needed.
|
||||
|
||||
# outbound_source_ipv4 = '192.0.2.10'
|
||||
# outbound_source_ipv6 = '2001:db8::10'
|
||||
|
||||
|
||||
## Always use TCP to connect to upstream servers.
|
||||
## This can be useful if you need to route everything through Tor.
|
||||
## Otherwise, leave this to `false`, as it doesn't improve security
|
||||
|
|
|
|||
181
dnscrypt-proxy/outbound_source.go
Normal file
181
dnscrypt-proxy/outbound_source.go
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"time"
|
||||
|
||||
"codeberg.org/miekg/dns"
|
||||
)
|
||||
|
||||
type outboundSourcePolicy struct {
|
||||
ipv4 netip.Addr
|
||||
ipv6 netip.Addr
|
||||
}
|
||||
|
||||
// outboundTarget selects source binding for a destination; an invalid source leaves it unbound.
|
||||
type outboundTarget struct {
|
||||
destination netip.Addr
|
||||
source netip.Addr
|
||||
}
|
||||
|
||||
func parseOutboundSources(ipv4Str, ipv6Str string) (outboundSourcePolicy, error) {
|
||||
var policy outboundSourcePolicy
|
||||
for _, field := range []struct {
|
||||
family int
|
||||
value string
|
||||
addr *netip.Addr
|
||||
}{
|
||||
{4, ipv4Str, &policy.ipv4},
|
||||
{6, ipv6Str, &policy.ipv6},
|
||||
} {
|
||||
if field.value == "" {
|
||||
continue
|
||||
}
|
||||
addr, err := netip.ParseAddr(field.value)
|
||||
if err != nil {
|
||||
return outboundSourcePolicy{}, fmt.Errorf("invalid outbound_source_ipv%d value %q: expected an IP address literal", field.family, field.value)
|
||||
}
|
||||
if field.family == 4 {
|
||||
addr = addr.Unmap()
|
||||
}
|
||||
if addr.IsUnspecified() || addr.IsMulticast() || addr == netip.AddrFrom4([4]byte{255, 255, 255, 255}) {
|
||||
return outboundSourcePolicy{}, fmt.Errorf("invalid outbound_source_ipv%d value %q: address cannot be unspecified, multicast, or limited broadcast", field.family, field.value)
|
||||
}
|
||||
if addr.Is4In6() || addr.Is4() != (field.family == 4) {
|
||||
return outboundSourcePolicy{}, fmt.Errorf("invalid outbound_source_ipv%d value %q: expected an IPv%d address", field.family, field.value, field.family)
|
||||
}
|
||||
*field.addr = addr
|
||||
}
|
||||
return policy, nil
|
||||
}
|
||||
|
||||
func (policy *outboundSourcePolicy) enabled() bool {
|
||||
return policy != nil && (policy.ipv4.IsValid() || policy.ipv6.IsValid())
|
||||
}
|
||||
|
||||
func (target outboundTarget) family() string {
|
||||
if target.destination.Is4() {
|
||||
return "4"
|
||||
}
|
||||
return "6"
|
||||
}
|
||||
|
||||
// sourceFor applies an enabled policy, leaving loopback and unspecified destinations unbound.
|
||||
func (policy *outboundSourcePolicy) sourceFor(destination netip.Addr) (outboundTarget, error) {
|
||||
if !destination.IsValid() {
|
||||
return outboundTarget{}, fmt.Errorf("invalid outbound destination address")
|
||||
}
|
||||
target := outboundTarget{destination: destination.Unmap()}
|
||||
if target.destination.IsLoopback() || target.destination.IsUnspecified() {
|
||||
return target, nil
|
||||
}
|
||||
target.source = policy.ipv6
|
||||
if target.destination.Is4() {
|
||||
target.source = policy.ipv4
|
||||
}
|
||||
if !target.source.IsValid() {
|
||||
return outboundTarget{}, fmt.Errorf("outbound_source_ipv%s is not configured for destination %s", target.family(), target.destination)
|
||||
}
|
||||
return target, nil
|
||||
}
|
||||
|
||||
func (target outboundTarget) udpAddr() *net.UDPAddr {
|
||||
if !target.source.IsValid() {
|
||||
return nil
|
||||
}
|
||||
return net.UDPAddrFromAddrPort(netip.AddrPortFrom(target.source, 0))
|
||||
}
|
||||
|
||||
// wrapDialError adds the source setting to errors from covered connections.
|
||||
func (target *outboundTarget) wrapDialError(proto string, err error) error {
|
||||
if target == nil || err == nil || !target.source.IsValid() {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("outbound_source_ipv%s=%s: %s connection to %s failed: %w", target.family(), target.source, proto+target.family(), target.destination, err)
|
||||
}
|
||||
|
||||
// configureDialer applies source binding and normalizes the destination's address family.
|
||||
func (policy *outboundSourcePolicy) configureDialer(dialer *net.Dialer, proto, address string) (string, string, *outboundTarget, error) {
|
||||
if !policy.enabled() {
|
||||
return proto, address, nil, nil
|
||||
}
|
||||
endpoint, err := netip.ParseAddrPort(address)
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
}
|
||||
target, err := policy.sourceFor(endpoint.Addr())
|
||||
if err != nil {
|
||||
return "", "", nil, err
|
||||
}
|
||||
dialer.LocalAddr = nil
|
||||
if target.source.IsValid() {
|
||||
if proto == "udp" {
|
||||
dialer.LocalAddr = target.udpAddr()
|
||||
} else {
|
||||
dialer.LocalAddr = net.TCPAddrFromAddrPort(netip.AddrPortFrom(target.source, 0))
|
||||
}
|
||||
}
|
||||
remote := netip.AddrPortFrom(target.destination, endpoint.Port())
|
||||
return proto + target.family(), remote.String(), &target, nil
|
||||
}
|
||||
|
||||
func (policy *outboundSourcePolicy) dialTCPContext(ctx context.Context, destination netip.AddrPort, timeout, keepAlive time.Duration) (net.Conn, error) {
|
||||
if !destination.IsValid() {
|
||||
return nil, fmt.Errorf("invalid TCP destination")
|
||||
}
|
||||
destination = netip.AddrPortFrom(destination.Addr().Unmap(), destination.Port())
|
||||
dialer := net.Dialer{Timeout: timeout, KeepAlive: keepAlive}
|
||||
network, remote, target, err := policy.configureDialer(&dialer, "tcp", destination.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
conn, err := dialer.DialContext(ctx, network, remote)
|
||||
return conn, target.wrapDialError("tcp", err)
|
||||
}
|
||||
|
||||
func (policy *outboundSourcePolicy) dialTCP(destination netip.AddrPort, timeout, keepAlive time.Duration) (net.Conn, error) {
|
||||
return policy.dialTCPContext(context.Background(), destination, timeout, keepAlive)
|
||||
}
|
||||
|
||||
// dialUDP binds a connected UDP socket without waiting for the peer.
|
||||
func (policy *outboundSourcePolicy) dialUDP(destination *net.UDPAddr) (*net.UDPConn, error) {
|
||||
if destination == nil {
|
||||
return nil, fmt.Errorf("nil UDP destination")
|
||||
}
|
||||
if !policy.enabled() {
|
||||
return net.DialUDP("udp", nil, destination)
|
||||
}
|
||||
target, err := policy.sourceFor(destination.AddrPort().Addr())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
remote := netip.AddrPortFrom(target.destination, destination.AddrPort().Port())
|
||||
conn, err := net.DialUDP("udp"+target.family(), target.udpAddr(), net.UDPAddrFromAddrPort(remote))
|
||||
return conn, target.wrapDialError("udp", err)
|
||||
}
|
||||
|
||||
// listenUDP binds an unconnected socket and keeps its destination in the same address family.
|
||||
func (policy *outboundSourcePolicy) listenUDP(destination netip.Addr) (*net.UDPConn, string, netip.Addr, error) {
|
||||
if !policy.enabled() {
|
||||
conn, err := net.ListenUDP("udp", nil)
|
||||
return conn, "udp", destination, err
|
||||
}
|
||||
target, err := policy.sourceFor(destination)
|
||||
if err != nil {
|
||||
return nil, "", netip.Addr{}, err
|
||||
}
|
||||
network := "udp" + target.family()
|
||||
conn, err := net.ListenUDP(network, target.udpAddr())
|
||||
return conn, network, target.destination, target.wrapDialError("udp", err)
|
||||
}
|
||||
|
||||
// newDNSTransport isolates dialer changes from the shared DNS defaults.
|
||||
func newDNSTransport() *dns.Transport {
|
||||
transport := dns.NewTransport()
|
||||
dialer := *transport.Dialer
|
||||
transport.Dialer = &dialer
|
||||
return transport
|
||||
}
|
||||
165
dnscrypt-proxy/outbound_source_test.go
Normal file
165
dnscrypt-proxy/outbound_source_test.go
Normal file
|
|
@ -0,0 +1,165 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func nonLoopbackIPv4(t *testing.T) net.IP {
|
||||
t.Helper()
|
||||
addrs, err := net.InterfaceAddrs()
|
||||
if err != nil {
|
||||
t.Skipf("unable to enumerate interface addresses: %v", err)
|
||||
}
|
||||
for _, interfaceAddr := range addrs {
|
||||
ip, _, err := net.ParseCIDR(interfaceAddr.String())
|
||||
if err == nil && ip.To4() != nil && !ip.IsLoopback() && !ip.IsUnspecified() && !ip.IsMulticast() {
|
||||
return ip.To4()
|
||||
}
|
||||
}
|
||||
t.Skip("host has no usable non-loopback IPv4 address")
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestListenUDPLoopback(t *testing.T) {
|
||||
policy, err := parseOutboundSources("192.0.2.10", "2001:db8::10")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ipv4Loopback := netip.MustParseAddr("127.0.0.1")
|
||||
unconnected, network, destination, err := policy.listenUDP(ipv4Loopback)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer unconnected.Close()
|
||||
if network != "udp4" || destination != ipv4Loopback {
|
||||
t.Fatalf("got network=%s destination=%s", network, destination)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutboundSourceFor(t *testing.T) {
|
||||
policy, err := parseOutboundSources("192.0.2.10", "2001:db8::10")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
destination netip.Addr
|
||||
wantDest string
|
||||
wantSource string
|
||||
}{
|
||||
{name: "IPv4", destination: netip.MustParseAddr("9.9.9.9"), wantDest: "9.9.9.9", wantSource: "192.0.2.10"},
|
||||
{name: "mapped IPv4", destination: netip.MustParseAddr("::ffff:9.9.9.9"), wantDest: "9.9.9.9", wantSource: "192.0.2.10"},
|
||||
{name: "IPv6", destination: netip.MustParseAddr("2001:4860:4860::8888"), wantDest: "2001:4860:4860::8888", wantSource: "2001:db8::10"},
|
||||
{name: "loopback IPv4", destination: netip.MustParseAddr("127.0.0.1"), wantDest: "127.0.0.1"},
|
||||
{name: "mapped loopback", destination: netip.MustParseAddr("::ffff:127.0.0.1"), wantDest: "127.0.0.1"},
|
||||
{name: "loopback IPv6", destination: netip.IPv6Loopback(), wantDest: "::1"},
|
||||
{name: "unspecified IPv4", destination: netip.IPv4Unspecified(), wantDest: "0.0.0.0"},
|
||||
{name: "mapped unspecified", destination: netip.MustParseAddr("::ffff:0.0.0.0"), wantDest: "0.0.0.0"},
|
||||
{name: "unspecified IPv6", destination: netip.IPv6Unspecified(), wantDest: "::"},
|
||||
{name: "private IPv4 is covered", destination: netip.MustParseAddr("10.0.0.1"), wantDest: "10.0.0.1", wantSource: "192.0.2.10"},
|
||||
{name: "ULA is covered", destination: netip.MustParseAddr("fd00::1"), wantDest: "fd00::1", wantSource: "2001:db8::10"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
target, err := policy.sourceFor(test.destination)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gotSource := ""
|
||||
if target.source.IsValid() {
|
||||
gotSource = target.source.String()
|
||||
}
|
||||
if target.destination.String() != test.wantDest || gotSource != test.wantSource {
|
||||
t.Fatalf("got destination=%s source=%s", target.destination, target.source)
|
||||
}
|
||||
})
|
||||
}
|
||||
if _, err := policy.sourceFor(netip.Addr{}); err == nil {
|
||||
t.Fatal("invalid destination was accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceDialerOptions(t *testing.T) {
|
||||
policy, err := parseOutboundSources("192.0.2.10", "fe80::1%en0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dialer := net.Dialer{Timeout: time.Second, KeepAlive: 2 * time.Second}
|
||||
network, remote, _, err := policy.configureDialer(&dialer, "tcp", "[fe80::2%en0]:53")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if network != "tcp6" || remote != "[fe80::2%en0]:53" || dialer.Timeout != time.Second || dialer.KeepAlive != 2*time.Second {
|
||||
t.Fatalf("unexpected dialer: %s %s %+v", network, remote, dialer)
|
||||
}
|
||||
local, ok := dialer.LocalAddr.(*net.TCPAddr)
|
||||
if !ok {
|
||||
t.Fatalf("unexpected local address type: %T", dialer.LocalAddr)
|
||||
}
|
||||
if local.Port != 0 || local.Zone != "en0" || !local.IP.Equal(net.ParseIP("fe80::1")) {
|
||||
t.Fatalf("unexpected local address: %#v", local)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDNSTransportDialerIsolation(t *testing.T) {
|
||||
first := newDNSTransport()
|
||||
second := newDNSTransport()
|
||||
if first.Dialer.Timeout != 5*time.Second || first.Dialer.KeepAlive != 3*time.Second {
|
||||
t.Fatalf("unexpected DNS dialer defaults: %+v", first.Dialer)
|
||||
}
|
||||
first.Dialer.Timeout = time.Second
|
||||
if second.Dialer.Timeout != 5*time.Second {
|
||||
t.Fatal("mutating one DNS dialer changed another")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceDialer(t *testing.T) {
|
||||
policy, err := parseOutboundSources("192.0.2.10", "2001:db8::10")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
transport := newDNSTransport()
|
||||
network, resolver, _, err := policy.configureDialer(transport.Dialer, "udp", "[::ffff:9.9.9.9]:53")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if network != "udp4" || resolver != "9.9.9.9:53" {
|
||||
t.Fatalf("got %q %q", network, resolver)
|
||||
}
|
||||
local, ok := transport.Dialer.LocalAddr.(*net.UDPAddr)
|
||||
if !ok || !local.IP.Equal(net.ParseIP("192.0.2.10")) || local.Port != 0 {
|
||||
t.Fatalf("unexpected DNS local address: %#v", transport.Dialer.LocalAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceDNSError(t *testing.T) {
|
||||
policy, err := parseOutboundSources("192.0.2.10", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, _, target, err := policy.configureDialer(newDNSTransport().Dialer, "udp", "9.9.9.9:53")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wrapped := target.wrapDialError("udp", net.ErrClosed)
|
||||
for _, want := range []string{"outbound_source_ipv4", "192.0.2.10", "udp4", "9.9.9.9"} {
|
||||
if !strings.Contains(wrapped.Error(), want) {
|
||||
t.Fatalf("error %q does not contain %q", wrapped, want)
|
||||
}
|
||||
}
|
||||
_, _, local, err := policy.configureDialer(newDNSTransport().Dialer, "udp", "127.0.0.1:53")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := local.wrapDialError("udp", net.ErrClosed); got != net.ErrClosed {
|
||||
t.Fatalf("local error was wrapped: %v", got)
|
||||
}
|
||||
var uncovered *outboundTarget
|
||||
if got := uncovered.wrapDialError("udp", net.ErrClosed); got != net.ErrClosed {
|
||||
t.Fatalf("uncovered error was wrapped: %v", got)
|
||||
}
|
||||
}
|
||||
|
|
@ -332,6 +332,7 @@ func (plugin *PluginCloak) Eval(pluginsState *PluginsState, msg *dns.Msg) error
|
|||
pluginsState.xTransport.mainProto,
|
||||
target,
|
||||
pluginsState.xTransport.internalResolvers,
|
||||
false,
|
||||
returnIPv4,
|
||||
returnIPv6,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -200,13 +200,18 @@ func translateToIPv6(ipv4 net.IP, prefix *net.IPNet) net.IP {
|
|||
func (plugin *PluginDNS64) fetchPref64(resolver string) error {
|
||||
msg := dns.NewMsg(rfc7050WKN, dns.TypeAAAA)
|
||||
|
||||
client := new(dns.Client)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
resp, _, err := client.Exchange(ctx, msg, "udp", resolver)
|
||||
transport := newDNSTransport()
|
||||
network, resolver, target, err := plugin.proxy.outboundSource.configureDialer(transport.Dialer, "udp", resolver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
client := &dns.Client{Transport: transport}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
resp, _, err := client.Exchange(ctx, msg, network, resolver)
|
||||
if err != nil {
|
||||
return target.wrapDialError("udp", err)
|
||||
}
|
||||
|
||||
if resp == nil || resp.Rcode != dns.RcodeSuccess {
|
||||
return errors.New("Unable to fetch Pref64")
|
||||
|
|
|
|||
36
dnscrypt-proxy/plugin_dns64_outbound_source_test.go
Normal file
36
dnscrypt-proxy/plugin_dns64_outbound_source_test.go
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"codeberg.org/miekg/dns"
|
||||
"codeberg.org/miekg/dns/rdata"
|
||||
)
|
||||
|
||||
func TestDNS64SourceBinding(t *testing.T) {
|
||||
sourceIP := nonLoopbackIPv4(t)
|
||||
policy, err := parseOutboundSources(sourceIP.String(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resolver, peerCh, closeServer := startTestDNS(t, "udp", sourceIP, false, func(msg *dns.Msg) {
|
||||
msg.Answer = []dns.RR{&dns.AAAA{
|
||||
Hdr: dns.Header{Name: rfc7050WKN, Class: dns.ClassINET, TTL: 60},
|
||||
AAAA: rdata.AAAA{Addr: netip.MustParseAddr("64:ff9b::c000:aa")},
|
||||
}}
|
||||
})
|
||||
defer closeServer()
|
||||
|
||||
plugin := PluginDNS64{pref64Mutex: new(sync.RWMutex), proxy: &Proxy{outboundSource: policy}}
|
||||
if err := plugin.fetchPref64(resolver.String()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if peer := <-peerCh; !peer.Equal(sourceIP) {
|
||||
t.Fatalf("DNS64 peer source = %s, want %s", peer, sourceIP)
|
||||
}
|
||||
if len(plugin.pref64) != 1 || plugin.pref64[0].String() != "64:ff9b::/96" {
|
||||
t.Fatalf("prefixes = %v", plugin.pref64)
|
||||
}
|
||||
}
|
||||
|
|
@ -113,6 +113,7 @@ type Proxy struct {
|
|||
ipCryptConfig *IPCryptConfig
|
||||
udpConnPool *UDPConnPool
|
||||
netMonitor *networkMonitor
|
||||
outboundSource outboundSourcePolicy
|
||||
}
|
||||
|
||||
func (proxy *Proxy) registerUDPListener(conn *net.UDPConn) {
|
||||
|
|
@ -716,7 +717,7 @@ func (proxy *Proxy) exchangeWithTCPServer(
|
|||
var pc net.Conn
|
||||
proxyDialer := proxy.xTransport.proxyDialer
|
||||
if proxyDialer == nil {
|
||||
pc, err = net.DialTimeout("tcp", upstreamAddr.String(), serverInfo.Timeout)
|
||||
pc, err = proxy.outboundSource.dialTCP(upstreamAddr.AddrPort(), serverInfo.Timeout, 0)
|
||||
} else {
|
||||
pc, err = (*proxyDialer).Dial("tcp", upstreamAddr.String())
|
||||
}
|
||||
|
|
@ -939,8 +940,7 @@ func() (*ServerInfo, bool) {
|
|||
}
|
||||
|
||||
func NewProxy() *Proxy {
|
||||
return &Proxy{
|
||||
serversInfo: NewServersInfo(),
|
||||
udpConnPool: NewUDPConnPool(),
|
||||
}
|
||||
proxy := &Proxy{serversInfo: NewServersInfo()}
|
||||
proxy.udpConnPool = NewUDPConnPool(&proxy.outboundSource)
|
||||
return proxy
|
||||
}
|
||||
|
|
|
|||
|
|
@ -231,7 +231,7 @@ func checkTestServer(c *check.C, d *SourceTestData) {
|
|||
}
|
||||
|
||||
func setupSourceTest(t *testing.T) (func(), *SourceTestData) {
|
||||
d := &SourceTestData{n: -1, xTransport: NewXTransport()}
|
||||
d := &SourceTestData{n: -1, xTransport: NewXTransport(nil)}
|
||||
d.cacheTests = map[string]SourceTestState{ // determines cache files written to disk before each call
|
||||
"correct": TestStateCorrect,
|
||||
"expired": TestStateExpired,
|
||||
|
|
|
|||
|
|
@ -31,11 +31,13 @@ type UDPConnPool struct {
|
|||
closed int32 // atomic
|
||||
stopOnce sync.Once
|
||||
stopCh chan struct{}
|
||||
policy *outboundSourcePolicy
|
||||
}
|
||||
|
||||
func NewUDPConnPool() *UDPConnPool {
|
||||
func NewUDPConnPool(policy *outboundSourcePolicy) *UDPConnPool {
|
||||
pool := &UDPConnPool{
|
||||
stopCh: make(chan struct{}),
|
||||
policy: policy,
|
||||
}
|
||||
for i := range pool.shards {
|
||||
pool.shards[i].conns = make(map[string][]*pooledConn)
|
||||
|
|
@ -107,7 +109,7 @@ func (p *UDPConnPool) Get(addr *net.UDPAddr) (*net.UDPConn, error) {
|
|||
}
|
||||
shard.Unlock()
|
||||
|
||||
return net.DialUDP("udp", nil, addr)
|
||||
return p.policy.dialUDP(addr)
|
||||
}
|
||||
|
||||
func (p *UDPConnPool) Put(addr *net.UDPAddr, conn *net.UDPConn) {
|
||||
|
|
|
|||
|
|
@ -3,13 +3,114 @@
|
|||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestUDPConnPool_SourceBinding(t *testing.T) {
|
||||
sourceIP := nonLoopbackIPv4(t)
|
||||
policy, err := parseOutboundSources(sourceIP.String(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listener, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4zero})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
destination := listener.LocalAddr().(*net.UDPAddr)
|
||||
// net.ParseIP intentionally supplies the 16-byte mapped representation.
|
||||
destination = &net.UDPAddr{IP: net.ParseIP(sourceIP.String()), Port: destination.Port}
|
||||
|
||||
pool := NewUDPConnPool(&policy)
|
||||
defer pool.Close()
|
||||
conn, err := pool.Get(destination)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := conn.Write([]byte{1}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
packet := make([]byte, 1)
|
||||
if err := listener.SetReadDeadline(time.Now().Add(time.Second)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, peer, err := listener.ReadFromUDP(packet)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !peer.IP.Equal(sourceIP) {
|
||||
t.Fatalf("peer source = %s, want %s", peer.IP, sourceIP)
|
||||
}
|
||||
|
||||
pool.Put(destination, conn)
|
||||
reused, err := pool.Get(destination)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if reused != conn {
|
||||
t.Fatal("pooled connection was not reused")
|
||||
}
|
||||
pool.Discard(reused)
|
||||
replacement, err := pool.Get(destination)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if replacement == reused {
|
||||
t.Fatal("discarded connection was reused")
|
||||
}
|
||||
pool.Discard(replacement)
|
||||
}
|
||||
|
||||
func TestUDPConnPool_Loopback(t *testing.T) {
|
||||
policy, err := parseOutboundSources("192.0.2.1", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listener, err := net.ListenUDP("udp4", &net.UDPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
pool := NewUDPConnPool(&policy)
|
||||
defer pool.Close()
|
||||
conn, err := pool.Get(listener.LocalAddr().(*net.UDPAddr))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Discard(conn)
|
||||
if !conn.LocalAddr().(*net.UDPAddr).IP.IsLoopback() {
|
||||
t.Fatalf("loopback destination used configured source: %s", conn.LocalAddr())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUDPConnPool_BindFailure(t *testing.T) {
|
||||
destinationIP := nonLoopbackIPv4(t)
|
||||
configured := "192.0.2.1"
|
||||
if destinationIP.Equal(net.ParseIP(configured)) {
|
||||
configured = "198.51.100.1"
|
||||
}
|
||||
policy, err := parseOutboundSources(configured, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pool := NewUDPConnPool(&policy)
|
||||
defer pool.Close()
|
||||
_, err = pool.Get(&net.UDPAddr{IP: destinationIP, Port: 53})
|
||||
if err == nil {
|
||||
t.Skipf("host permits binding non-local test address %s", configured)
|
||||
}
|
||||
for _, want := range []string{"outbound_source_ipv4", configured, "udp4", destinationIP.String()} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("error %q does not contain %q", err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUDPConnPool_Basic(t *testing.T) {
|
||||
pool := NewUDPConnPool()
|
||||
pool := NewUDPConnPool(nil)
|
||||
defer pool.Close()
|
||||
|
||||
addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:53")
|
||||
|
|
@ -47,7 +148,7 @@ func TestUDPConnPool_Basic(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestUDPConnPool_MaxConns(t *testing.T) {
|
||||
pool := NewUDPConnPool()
|
||||
pool := NewUDPConnPool(nil)
|
||||
defer pool.Close()
|
||||
|
||||
addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:53")
|
||||
|
|
@ -72,7 +173,7 @@ func TestUDPConnPool_MaxConns(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestUDPConnPool_Discard(t *testing.T) {
|
||||
pool := NewUDPConnPool()
|
||||
pool := NewUDPConnPool(nil)
|
||||
defer pool.Close()
|
||||
|
||||
addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:53")
|
||||
|
|
@ -91,7 +192,7 @@ func TestUDPConnPool_Discard(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestUDPConnPool_Concurrent(t *testing.T) {
|
||||
pool := NewUDPConnPool()
|
||||
pool := NewUDPConnPool(nil)
|
||||
defer pool.Close()
|
||||
|
||||
addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:53")
|
||||
|
|
@ -122,7 +223,7 @@ func TestUDPConnPool_Concurrent(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestUDPConnPool_MultipleAddresses(t *testing.T) {
|
||||
pool := NewUDPConnPool()
|
||||
pool := NewUDPConnPool(nil)
|
||||
defer pool.Close()
|
||||
|
||||
addr1, _ := net.ResolveUDPAddr("udp", "127.0.0.1:53")
|
||||
|
|
@ -144,7 +245,7 @@ func TestUDPConnPool_MultipleAddresses(t *testing.T) {
|
|||
}
|
||||
|
||||
func TestUDPConnPool_Close(t *testing.T) {
|
||||
pool := NewUDPConnPool()
|
||||
pool := NewUDPConnPool(nil)
|
||||
|
||||
addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:53")
|
||||
|
||||
|
|
@ -167,7 +268,7 @@ func TestUDPConnPool_Close(t *testing.T) {
|
|||
}
|
||||
|
||||
func BenchmarkUDPConnPool_GetPut(b *testing.B) {
|
||||
pool := NewUDPConnPool()
|
||||
pool := NewUDPConnPool(nil)
|
||||
defer pool.Close()
|
||||
|
||||
addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:53")
|
||||
|
|
@ -193,7 +294,7 @@ func BenchmarkUDPDial_NoPool(b *testing.B) {
|
|||
}
|
||||
|
||||
func BenchmarkUDPConnPool_Contention(b *testing.B) {
|
||||
pool := NewUDPConnPool()
|
||||
pool := NewUDPConnPool(nil)
|
||||
defer pool.Close()
|
||||
|
||||
addr, _ := net.ResolveUDPAddr("udp", "127.0.0.1:53")
|
||||
|
|
@ -211,7 +312,7 @@ func BenchmarkUDPConnPool_Contention(b *testing.B) {
|
|||
}
|
||||
|
||||
func BenchmarkUDPConnPool_MultiAddrContention(b *testing.B) {
|
||||
pool := NewUDPConnPool()
|
||||
pool := NewUDPConnPool(nil)
|
||||
defer pool.Close()
|
||||
|
||||
addrs := make([]*net.UDPAddr, 16)
|
||||
|
|
|
|||
|
|
@ -10,10 +10,12 @@
|
|||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
|
|
@ -101,9 +103,66 @@ type XTransport struct {
|
|||
httpProxyFunction func(*http.Request) (*url.URL, error)
|
||||
tlsClientCreds DOHClientCreds
|
||||
keyLogWriter io.Writer
|
||||
outboundSource *outboundSourcePolicy
|
||||
}
|
||||
|
||||
func NewXTransport() *XTransport {
|
||||
type proxyDialer struct {
|
||||
xTransport *XTransport
|
||||
}
|
||||
|
||||
var _ netproxy.Dialer = (*proxyDialer)(nil)
|
||||
var _ netproxy.ContextDialer = (*proxyDialer)(nil)
|
||||
|
||||
func (dialer *proxyDialer) Dial(network, address string) (net.Conn, error) {
|
||||
return dialer.DialContext(context.Background(), network, address)
|
||||
}
|
||||
|
||||
func (dialer *proxyDialer) DialContext(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if network != "tcp" && network != "tcp4" && network != "tcp6" {
|
||||
return nil, fmt.Errorf("unsupported proxy forward network %q", network)
|
||||
}
|
||||
host, portStr, err := net.SplitHostPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
port, err := strconv.Atoi(portStr)
|
||||
if err != nil || port < 0 || port > 65535 {
|
||||
return nil, fmt.Errorf("invalid proxy endpoint port %q", portStr)
|
||||
}
|
||||
var addresses []netip.Addr
|
||||
if literal, err := netip.ParseAddr(host); err == nil {
|
||||
addresses = []netip.Addr{literal}
|
||||
} else {
|
||||
ips, _, err := dialer.xTransport.resolveProxy(host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to resolve proxy endpoint %q: %w", host, err)
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if addr, ok := netip.AddrFromSlice(ip); ok {
|
||||
addresses = append(addresses, addr)
|
||||
}
|
||||
}
|
||||
}
|
||||
var lastErr error
|
||||
for _, addr := range addresses {
|
||||
conn, err := dialer.xTransport.outboundSource.dialTCPContext(
|
||||
ctx,
|
||||
netip.AddrPortFrom(addr, uint16(port)),
|
||||
dialer.xTransport.timeout,
|
||||
dialer.xTransport.keepAlive,
|
||||
)
|
||||
if err == nil {
|
||||
return conn, nil
|
||||
}
|
||||
lastErr = err
|
||||
}
|
||||
if lastErr == nil {
|
||||
lastErr = fmt.Errorf("proxy endpoint %q has no usable IP addresses", host)
|
||||
}
|
||||
return nil, lastErr
|
||||
}
|
||||
|
||||
func NewXTransport(outboundSource *outboundSourcePolicy) *XTransport {
|
||||
if err := isIPAndPort(DefaultBootstrapResolver); err != nil {
|
||||
panic("DefaultBootstrapResolver does not parse")
|
||||
}
|
||||
|
|
@ -121,6 +180,7 @@ func NewXTransport() *XTransport {
|
|||
tlsDisableSessionTickets: false,
|
||||
tlsPreferRSA: false,
|
||||
keyLogWriter: nil,
|
||||
outboundSource: outboundSource,
|
||||
}
|
||||
return &xTransport
|
||||
}
|
||||
|
|
@ -312,6 +372,13 @@ func (xTransport *XTransport) rebuildTransport() {
|
|||
}
|
||||
|
||||
cachedIPs, _, _ := xTransport.loadCachedIPs(host)
|
||||
if xTransport.outboundSource.enabled() && xTransport.proxyDialer == nil && len(cachedIPs) == 0 {
|
||||
resolved, err := xTransport.resolveDialIPs(host, "HTTP")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cachedIPs = resolved
|
||||
}
|
||||
targets := make([]string, 0, len(cachedIPs))
|
||||
for _, ip := range cachedIPs {
|
||||
targets = append(targets, formatEndpoint(ip))
|
||||
|
|
@ -322,11 +389,21 @@ func (xTransport *XTransport) rebuildTransport() {
|
|||
}
|
||||
|
||||
dial := func(address string) (net.Conn, error) {
|
||||
if xTransport.proxyDialer == nil {
|
||||
dialer := &net.Dialer{Timeout: timeout, KeepAlive: xTransport.keepAlive, DualStack: true}
|
||||
if xTransport.proxyDialer != nil {
|
||||
if contextDialer, ok := (*xTransport.proxyDialer).(netproxy.ContextDialer); ok {
|
||||
return contextDialer.DialContext(ctx, network, address)
|
||||
}
|
||||
return (*xTransport.proxyDialer).Dial(network, address)
|
||||
}
|
||||
if !xTransport.outboundSource.enabled() {
|
||||
dialer := &net.Dialer{Timeout: timeout, KeepAlive: xTransport.keepAlive}
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
}
|
||||
return (*xTransport.proxyDialer).Dial(network, address)
|
||||
endpoint, err := netip.ParseAddrPort(address)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return xTransport.outboundSource.dialTCPContext(ctx, endpoint, timeout, xTransport.keepAlive)
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
|
|
@ -460,6 +537,13 @@ type udpTarget struct {
|
|||
}
|
||||
|
||||
cachedIPs, _, _ := xTransport.loadCachedIPs(host)
|
||||
if xTransport.outboundSource.enabled() && len(cachedIPs) == 0 {
|
||||
resolved, err := xTransport.resolveDialIPs(host, "HTTP/3")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cachedIPs = resolved
|
||||
}
|
||||
targets := make([]udpTarget, 0, len(cachedIPs))
|
||||
for _, ip := range cachedIPs {
|
||||
targets = append(targets, buildAddr(ip))
|
||||
|
|
@ -479,7 +563,17 @@ type udpTarget struct {
|
|||
}
|
||||
continue
|
||||
}
|
||||
udpConn, err := net.ListenUDP(target.network, nil)
|
||||
var udpConn *net.UDPConn
|
||||
if xTransport.outboundSource.enabled() {
|
||||
addrPort := udpAddr.AddrPort()
|
||||
var normalized netip.Addr
|
||||
udpConn, target.network, normalized, err = xTransport.outboundSource.listenUDP(addrPort.Addr())
|
||||
if err == nil {
|
||||
udpAddr = net.UDPAddrFromAddrPort(netip.AddrPortFrom(normalized, addrPort.Port()))
|
||||
}
|
||||
} else {
|
||||
udpConn, err = net.ListenUDP(target.network, nil)
|
||||
}
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
if idx < len(targets)-1 {
|
||||
|
|
@ -505,6 +599,29 @@ type udpTarget struct {
|
|||
}
|
||||
}
|
||||
|
||||
// resolveDialIPs resolves through the configured DNS policy before source binding.
|
||||
func (xTransport *XTransport) resolveDialIPs(host, kind string) ([]net.IP, error) {
|
||||
if literal := ParseIP(host); literal != nil {
|
||||
return []net.IP{literal}, nil
|
||||
}
|
||||
var ips []net.IP
|
||||
var ttl time.Duration
|
||||
var err error
|
||||
if xTransport.httpProxyFunction != nil && kind == "HTTP" {
|
||||
ips, ttl, err = xTransport.resolveProxy(host)
|
||||
} else {
|
||||
ips, ttl, err = xTransport.resolve(host, xTransport.useIPv4, xTransport.useIPv6)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("unable to resolve covered %s destination %q: %w", kind, host, err)
|
||||
}
|
||||
if len(ips) == 0 {
|
||||
return nil, fmt.Errorf("covered %s destination %q has no usable IP addresses", kind, host)
|
||||
}
|
||||
xTransport.saveCachedIPs(host, ips, ttl)
|
||||
return ips, nil
|
||||
}
|
||||
|
||||
func (xTransport *XTransport) resolveUsingSystem(host string, returnIPv4, returnIPv6 bool) ([]net.IP, time.Duration, error) {
|
||||
ipa, err := net.LookupIP(host)
|
||||
if returnIPv4 && returnIPv6 {
|
||||
|
|
@ -526,10 +643,19 @@ func (xTransport *XTransport) resolveUsingSystem(host string, returnIPv4, return
|
|||
func (xTransport *XTransport) resolveUsingResolver(
|
||||
proto, host string,
|
||||
resolver string,
|
||||
covered bool,
|
||||
returnIPv4, returnIPv6 bool,
|
||||
) (ips []net.IP, ttl time.Duration, err error) {
|
||||
transport := dns.NewTransport()
|
||||
transport := newDNSTransport()
|
||||
transport.ReadTimeout = ResolverReadTimeout
|
||||
policy := xTransport.outboundSource
|
||||
if !covered {
|
||||
policy = nil
|
||||
}
|
||||
network, resolver, target, err := policy.configureDialer(transport.Dialer, proto, resolver)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
dnsClient := dns.Client{Transport: transport}
|
||||
queryType := make([]uint16, 0, 2)
|
||||
if returnIPv4 {
|
||||
|
|
@ -552,7 +678,7 @@ func (xTransport *XTransport) resolveUsingResolver(
|
|||
msg.UDPSize = uint16(MaxDNSPacketSize)
|
||||
msg.Security = true
|
||||
var in *dns.Msg
|
||||
if in, _, err = dnsClient.Exchange(ctx, msg, proto, resolver); err == nil {
|
||||
if in, _, err = dnsClient.Exchange(ctx, msg, network, resolver); err == nil {
|
||||
for _, answer := range in.Answer {
|
||||
if dns.RRToType(answer) == rrType {
|
||||
switch rrType {
|
||||
|
|
@ -568,7 +694,7 @@ func (xTransport *XTransport) resolveUsingResolver(
|
|||
}
|
||||
}
|
||||
} else {
|
||||
lastErr = err
|
||||
lastErr = target.wrapDialError(proto, err)
|
||||
}
|
||||
}
|
||||
if len(ips) > 0 {
|
||||
|
|
@ -581,6 +707,7 @@ func (xTransport *XTransport) resolveUsingResolver(
|
|||
func (xTransport *XTransport) resolveUsingServers(
|
||||
proto, host string,
|
||||
resolvers []string,
|
||||
covered bool,
|
||||
returnIPv4, returnIPv6 bool,
|
||||
) (ips []net.IP, ttl time.Duration, err error) {
|
||||
if len(resolvers) == 0 {
|
||||
|
|
@ -590,7 +717,7 @@ func (xTransport *XTransport) resolveUsingServers(
|
|||
for i, resolver := range resolvers {
|
||||
delay := resolverRetryInitialBackoff
|
||||
for attempt := 1; attempt <= resolverRetryCount; attempt++ {
|
||||
ips, ttl, err = xTransport.resolveUsingResolver(proto, host, resolver, returnIPv4, returnIPv6)
|
||||
ips, ttl, err = xTransport.resolveUsingResolver(proto, host, resolver, covered, returnIPv4, returnIPv6)
|
||||
if err == nil && len(ips) > 0 {
|
||||
if i > 0 {
|
||||
dlog.Infof("Resolution succeeded with resolver %s[%s]", proto, resolver)
|
||||
|
|
@ -621,15 +748,26 @@ func (xTransport *XTransport) resolveUsingServers(
|
|||
return nil, 0, lastErr
|
||||
}
|
||||
|
||||
func (xTransport *XTransport) resolve(host string, returnIPv4, returnIPv6 bool) (ips []net.IP, ttl time.Duration, err error) {
|
||||
func (xTransport *XTransport) resolve(host string, returnIPv4, returnIPv6 bool) ([]net.IP, time.Duration, error) {
|
||||
return xTransport.resolveHost(host, returnIPv4, returnIPv6, true)
|
||||
}
|
||||
|
||||
// resolveProxy avoids depending on the proxy to resolve its own address.
|
||||
func (xTransport *XTransport) resolveProxy(host string) ([]net.IP, time.Duration, error) {
|
||||
return xTransport.resolveHost(host, xTransport.useIPv4, xTransport.useIPv6, false)
|
||||
}
|
||||
|
||||
func (xTransport *XTransport) resolveHost(host string, returnIPv4, returnIPv6, useInternal bool) (ips []net.IP, ttl time.Duration, err error) {
|
||||
protos := []string{"udp", "tcp"}
|
||||
if xTransport.mainProto == "tcp" {
|
||||
protos = []string{"tcp", "udp"}
|
||||
}
|
||||
if xTransport.ignoreSystemDNS {
|
||||
if xTransport.internalResolverReady.Load() {
|
||||
if !useInternal {
|
||||
err = errors.New("proxy endpoint requires bootstrap resolution")
|
||||
} else if xTransport.internalResolverReady.Load() {
|
||||
for _, proto := range protos {
|
||||
ips, ttl, err = xTransport.resolveUsingServers(proto, host, xTransport.internalResolvers, returnIPv4, returnIPv6)
|
||||
ips, ttl, err = xTransport.resolveUsingServers(proto, host, xTransport.internalResolvers, false, returnIPv4, returnIPv6)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
|
|
@ -654,13 +792,13 @@ func (xTransport *XTransport) resolve(host string, returnIPv4, returnIPv6 bool)
|
|||
proto,
|
||||
)
|
||||
}
|
||||
ips, ttl, err = xTransport.resolveUsingServers(proto, host, xTransport.bootstrapResolvers, returnIPv4, returnIPv6)
|
||||
ips, ttl, err = xTransport.resolveUsingServers(proto, host, xTransport.bootstrapResolvers, true, returnIPv4, returnIPv6)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil && xTransport.ignoreSystemDNS {
|
||||
if err != nil && xTransport.ignoreSystemDNS && !xTransport.outboundSource.enabled() {
|
||||
dlog.Noticef("Bootstrap resolvers didn't respond - Trying with the system resolver as a last resort")
|
||||
ips, ttl, err = xTransport.resolveUsingSystem(host, returnIPv4, returnIPv6)
|
||||
}
|
||||
|
|
|
|||
268
dnscrypt-proxy/xtransport_outbound_source_test.go
Normal file
268
dnscrypt-proxy/xtransport_outbound_source_test.go
Normal file
|
|
@ -0,0 +1,268 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"codeberg.org/miekg/dns"
|
||||
"codeberg.org/miekg/dns/rdata"
|
||||
)
|
||||
|
||||
func TestXTransportSourceBinding(t *testing.T) {
|
||||
sourceIP := nonLoopbackIPv4(t)
|
||||
policy, err := parseOutboundSources(sourceIP.String(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4zero})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
peerCh := make(chan net.IP, 1)
|
||||
go func() {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err == nil {
|
||||
peerCh <- conn.RemoteAddr().(*net.TCPAddr).IP
|
||||
_ = conn.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
xTransport := NewXTransport(&policy)
|
||||
xTransport.timeout = time.Second
|
||||
xTransport.saveCachedIPs("ordered.test", []net.IP{
|
||||
net.ParseIP("127.0.0.2"),
|
||||
net.ParseIP(sourceIP.String()),
|
||||
}, time.Hour)
|
||||
xTransport.rebuildTransport()
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
conn, err := xTransport.transport.DialContext(context.Background(), "tcp", net.JoinHostPort("ordered.test", strconv.Itoa(port)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = conn.Close()
|
||||
if peer := <-peerCh; !peer.Equal(sourceIP) {
|
||||
t.Fatalf("peer source = %s, want %s", peer, sourceIP)
|
||||
}
|
||||
}
|
||||
|
||||
func TestXTransportMissingSource(t *testing.T) {
|
||||
policy, err := parseOutboundSources("192.0.2.10", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xTransport := NewXTransport(&policy)
|
||||
xTransport.rebuildTransport()
|
||||
_, err = xTransport.transport.DialContext(context.Background(), "tcp", "[2001:db8::1]:443")
|
||||
if err == nil || !strings.Contains(err.Error(), "outbound_source_ipv6") {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyDialer(t *testing.T) {
|
||||
sourceIP := nonLoopbackIPv4(t)
|
||||
policy, err := parseOutboundSources(sourceIP.String(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xTransport := NewXTransport(&policy)
|
||||
xTransport.timeout = time.Second
|
||||
forward := &proxyDialer{xTransport: xTransport}
|
||||
|
||||
t.Run("remote", func(t *testing.T) {
|
||||
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4zero})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
peerCh := make(chan net.IP, 1)
|
||||
go func() {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err == nil {
|
||||
peerCh <- conn.RemoteAddr().(*net.TCPAddr).IP
|
||||
_ = conn.Close()
|
||||
}
|
||||
}()
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
conn, err := forward.DialContext(context.Background(), "tcp", net.JoinHostPort(sourceIP.String(), strconv.Itoa(port)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = conn.Close()
|
||||
if peer := <-peerCh; !peer.Equal(sourceIP) {
|
||||
t.Fatalf("peer source = %s, want %s", peer, sourceIP)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("local bypass", func(t *testing.T) {
|
||||
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
go func() {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err == nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}()
|
||||
conn, err := forward.DialContext(context.Background(), "tcp", listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !conn.LocalAddr().(*net.TCPAddr).IP.IsLoopback() {
|
||||
t.Fatalf("local proxy used configured source: %s", conn.LocalAddr())
|
||||
}
|
||||
_ = conn.Close()
|
||||
})
|
||||
|
||||
t.Run("canceled context", func(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
_, err := forward.DialContext(ctx, "tcp", net.JoinHostPort(sourceIP.String(), "9"))
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("error = %v, want context canceled", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestResolverSourceBinding(t *testing.T) {
|
||||
sourceIP := nonLoopbackIPv4(t)
|
||||
policy, err := parseOutboundSources(sourceIP.String(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xTransport := NewXTransport(&policy)
|
||||
for _, proto := range []string{"udp", "tcp"} {
|
||||
t.Run(proto, func(t *testing.T) {
|
||||
resolver, peerCh, closeServer := startTestResolver(t, proto, sourceIP)
|
||||
defer closeServer()
|
||||
ips, _, err := xTransport.resolveUsingResolver(proto, "example.org", resolver, true, true, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(ips) != 1 || !ips[0].Equal(net.ParseIP("203.0.113.5")) {
|
||||
t.Fatalf("resolved IPs = %v", ips)
|
||||
}
|
||||
if peer := <-peerCh; !peer.Equal(sourceIP) {
|
||||
t.Fatalf("resolver peer source = %s, want %s", peer, sourceIP)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func startTestResolver(t *testing.T, proto string, destinationIP net.IP) (string, <-chan net.IP, func()) {
|
||||
t.Helper()
|
||||
return startTestResolverWithIP(t, proto, destinationIP, netip.MustParseAddr("203.0.113.5"))
|
||||
}
|
||||
|
||||
func startTestResolverWithIP(t *testing.T, proto string, destinationIP net.IP, answer netip.Addr) (string, <-chan net.IP, func()) {
|
||||
t.Helper()
|
||||
addr, peers, closeServer := startTestDNS(t, proto, destinationIP, false, func(msg *dns.Msg) {
|
||||
msg.Answer = []dns.RR{&dns.A{
|
||||
Hdr: dns.Header{Name: msg.Question[0].Header().Name, Class: dns.ClassINET, TTL: 60},
|
||||
A: rdata.A{Addr: answer},
|
||||
}}
|
||||
})
|
||||
return addr.String(), peers, closeServer
|
||||
}
|
||||
|
||||
func TestProxyResolveNoRecursion(t *testing.T) {
|
||||
for _, kind := range []string{"SOCKS", "HTTP"} {
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
loopback := net.IPv4(127, 0, 0, 1)
|
||||
answer := netip.MustParseAddr("127.0.0.1")
|
||||
internal, internalQueries, closeInternal := startTestResolverWithIP(t, "udp", loopback, answer)
|
||||
defer closeInternal()
|
||||
bootstrap, bootstrapQueries, closeBootstrap := startTestResolverWithIP(t, "udp", loopback, answer)
|
||||
defer closeBootstrap()
|
||||
listener, err := net.ListenTCP("tcp4", &net.TCPAddr{IP: loopback})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer listener.Close()
|
||||
go func() {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err == nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}()
|
||||
policy, err := parseOutboundSources("192.0.2.10", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xTransport := NewXTransport(&policy)
|
||||
xTransport.ignoreSystemDNS = true
|
||||
xTransport.useIPv6 = false
|
||||
xTransport.internalResolverReady.Store(true)
|
||||
xTransport.internalResolvers = []string{internal}
|
||||
xTransport.bootstrapResolvers = []string{bootstrap}
|
||||
endpoint := net.JoinHostPort("proxy.test", strconv.Itoa(listener.Addr().(*net.TCPAddr).Port))
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
var conn net.Conn
|
||||
if kind == "SOCKS" {
|
||||
forward := &proxyDialer{xTransport: xTransport}
|
||||
conn, err = forward.DialContext(ctx, "tcp", endpoint)
|
||||
} else {
|
||||
proxyURL, parseErr := url.Parse("http://" + endpoint)
|
||||
if parseErr != nil {
|
||||
t.Fatal(parseErr)
|
||||
}
|
||||
xTransport.httpProxyFunction = http.ProxyURL(proxyURL)
|
||||
xTransport.rebuildTransport()
|
||||
conn, err = xTransport.transport.DialContext(ctx, "tcp", endpoint)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = conn.Close()
|
||||
select {
|
||||
case <-internalQueries:
|
||||
t.Fatal("proxy endpoint lookup used the proxy itself, creating a circular dependency")
|
||||
default:
|
||||
}
|
||||
select {
|
||||
case <-bootstrapQueries:
|
||||
default:
|
||||
t.Fatal("proxy endpoint lookup did not use the bootstrap resolver")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestProxyDialerIPv6Zone(t *testing.T) {
|
||||
listener, err := net.ListenTCP("tcp6", &net.TCPAddr{IP: net.IPv6loopback})
|
||||
if err != nil {
|
||||
t.Skipf("IPv6 loopback is unavailable: %v", err)
|
||||
}
|
||||
defer listener.Close()
|
||||
go func() {
|
||||
conn, err := listener.AcceptTCP()
|
||||
if err == nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}()
|
||||
policy, err := parseOutboundSources("192.0.2.10", "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
xTransport := NewXTransport(&policy)
|
||||
xTransport.ignoreSystemDNS = true
|
||||
xTransport.bootstrapResolvers = nil
|
||||
forward := &proxyDialer{xTransport: xTransport}
|
||||
endpoint := net.JoinHostPort("::1%1", strconv.Itoa(listener.Addr().(*net.TCPAddr).Port))
|
||||
conn, err := forward.DialContext(context.Background(), "tcp", endpoint)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_ = conn.Close()
|
||||
}
|
||||
Loading…
Reference in a new issue