Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions core/cmd/mistgate-clientd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,8 @@ func run(ctx context.Context, useFake bool, dataDir, verify string, powerEvents
status, err := manager.Status(ctx)
return err == nil && (status.State == "off" || status.State == "error")
}
// a path whose address is IPv6 is marked for the window when the device has none
store.IPv6 = engine.HasIPv6
// the panel's ASN is the network's: note which network the device was in when the sync brought it
store.ASNSeen = func(sub string) {
key, _ := diag.NetworkKey(memory.Salt())
Expand Down
18 changes: 18 additions & 0 deletions core/internal/diag/diag_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,3 +252,21 @@ func TestServerAddressesAreKeptForAWhile(t *testing.T) {
t.Fatalf("after the time ran out: asked %d times, err %v; want a fresh lookup", asked, err)
}
}

// The probes of a server dial in its own family: an IPv6 path is not tried over IPv4 and lost for it.
func TestProbesFollowTheAddressFamily(t *testing.T) {
for host, want := range map[string]string{"192.0.2.1": "tcp4", "2001:db8::1": "tcp6"} {
var network string
dial := func(_ context.Context, n, _ string) (net.Conn, error) {
network = n
return nil, errors.New("down")
}
hostAlive(context.Background(), dial, host, []uint16{443}, 50*time.Millisecond)
if network != want {
t.Errorf("hostAlive(%s) dialed %q, want %q", host, network, want)
}
}
if got := networkFor(netip.MustParseAddr("2001:db8::1"), "udp"); got != "udp6" {
t.Errorf("networkFor(IPv6, udp) = %q", got)
}
}
2 changes: 1 addition & 1 deletion core/internal/diag/network_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func NetworkKey([]byte) (key, kind string) { return "", "" }

func interfaceFor(_ netip.Addr, fallback interfaceInfo) interfaceInfo { return fallback }

func listenPacketBound(context.Context, interfaceInfo) (net.PacketConn, error) {
func listenPacketBound(context.Context, interfaceInfo, string) (net.PacketConn, error) {
return nil, errors.New("physical interface binding is unavailable")
}

Expand Down
19 changes: 12 additions & 7 deletions core/internal/diag/network_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ func interfaceFor(destination netip.Addr, fallback interfaceInfo) interfaceInfo
return fallback
}

func listenPacketBound(ctx context.Context, physical interfaceInfo) (net.PacketConn, error) {
func listenPacketBound(ctx context.Context, physical interfaceInfo, network string) (net.PacketConn, error) {
var config net.ListenConfig
config.Control = netcfg.SocketControl(physical.Index)
return config.ListenPacket(ctx, "udp4", ":0")
return config.ListenPacket(ctx, network, ":0")
}

func boundDialer(physical interfaceInfo) *net.Dialer {
Expand Down Expand Up @@ -160,7 +160,7 @@ func dnsExchange(ctx context.Context, server netip.Addr, query []byte, physical
if !server.Is4() {
return nil, errors.New("physical resolver is not IPv4")
}
conn, err := listenPacketBound(ctx, physical)
conn, err := listenPacketBound(ctx, physical, "udp4") // the resolvers are IPv4
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -235,6 +235,7 @@ func attemptProfile(ctx context.Context, p profile.Profile, endpoint netip.AddrP
type hy2BoundFactory struct {
ctx context.Context
physical interfaceInfo
network string // udp4 or udp6, by the server's address
kind string
password []byte
mu sync.Mutex
Expand All @@ -246,7 +247,7 @@ type hy2BoundFactory struct {
}

func (f *hy2BoundFactory) New(net.Addr) (net.PacketConn, error) {
conn, err := listenPacketBound(f.ctx, f.physical)
conn, err := listenPacketBound(f.ctx, f.physical, f.network)
if err != nil {
f.mu.Lock()
f.err = err
Expand Down Expand Up @@ -339,7 +340,7 @@ func attemptHy2(ctx context.Context, p *profile.Hy2, endpoint netip.AddrPort, ph
return 0, errNoAnswer
}
started := time.Now()
factory := &hy2BoundFactory{ctx: ctx, physical: physical, kind: p.Obfs, password: []byte(p.ObfsPassword)}
factory := &hy2BoundFactory{ctx: ctx, physical: physical, network: networkFor(endpoint.Addr(), "udp"), kind: p.Obfs, password: []byte(p.ObfsPassword)}
tlsConfig := client.TLSConfig{ServerName: p.ServerName, InsecureSkipVerify: p.Insecure}
if p.HasPin {
pin := p.PinSHA256
Expand Down Expand Up @@ -406,7 +407,7 @@ func attemptVLESS(ctx context.Context, p *profile.VLESS, endpoint netip.AddrPort
return 0, errNoAnswer
}
started := time.Now()
conn, err := dialBound(ctx, "tcp4", endpoint.String(), physical)
conn, err := dialBound(ctx, networkFor(endpoint.Addr(), "tcp"), endpoint.String(), physical)
if err != nil {
return 0, errNoAnswer
}
Expand Down Expand Up @@ -501,7 +502,11 @@ func attemptAWG(ctx context.Context, p *profile.AWG, endpoint netip.AddrPort, ph
if !ok {
return 0, errors.New("AmneziaWG bind cannot select an interface")
}
if err := interfaceBind.BindSocketToInterface4(physical.Index, false); err != nil {
bindTo := interfaceBind.BindSocketToInterface4
if endpoint.Addr().Is6() {
bindTo = interfaceBind.BindSocketToInterface6
}
if err := bindTo(physical.Index, false); err != nil {
return 0, err
}
keyBytes, err := hex.DecodeString(p.ServerKey)
Expand Down
2 changes: 1 addition & 1 deletion core/internal/diag/probes.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ func checkSTUN(ctx context.Context, physical interfaceInfo, config Config) []uin
if len(config.STUNServers) == 0 {
return nil
}
conn, err := listenPacketBound(ctx, physical)
conn, err := listenPacketBound(ctx, physical, "udp4")
if err != nil {
return nil
}
Expand Down
11 changes: 10 additions & 1 deletion core/internal/diag/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -655,7 +655,8 @@ func hostAlive(ctx context.Context, dial dialContextFunc, host string, ports []u
defer func() { results <- result }()
dialCtx, stop := context.WithTimeout(checkCtx, timeout)
defer stop()
conn, err := dial(dialCtx, "tcp4", net.JoinHostPort(host, strconv.Itoa(int(port))))
address, _ := netip.ParseAddr(host)
conn, err := dial(dialCtx, networkFor(address, "tcp"), net.JoinHostPort(host, strconv.Itoa(int(port))))
if conn != nil {
_ = conn.Close()
}
Expand Down Expand Up @@ -748,3 +749,11 @@ func numericAddress(host string) (netip.Addr, bool) {
ip, err := netip.ParseAddr(strings.Trim(host, "[]"))
return ip, err == nil && ip.Is4()
}

// networkFor is proto4 or proto6 by the address's family (an unparsed address is taken for IPv4).
func networkFor(address netip.Addr, proto string) string {
if address.Is6() {
return proto + "6"
}
return proto + "4"
}
29 changes: 27 additions & 2 deletions core/internal/engine/gvisor_bridge_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"log/slog"
"net"
"net/netip"
"slices"
"sync"
"sync/atomic"
"time"
Expand Down Expand Up @@ -1020,14 +1021,16 @@ func (f countedFlow) ReadFrom() ([]byte, netip.AddrPort, error) {

var direct6 struct{ at, ok atomic.Int64 }

// directIPv6 says whether this machine reaches IPv6 beside the tunnel; the routing table is asked at most once in 30 s.
// directIPv6 says whether this machine reaches IPv6 beside the tunnel: a route outside the tunnel to a global address,
// whose interface has a global address of its own (Teredo and 6to4 add a ::/0 route of their own, and with it a false
// yes). The routing table is asked at most once in 30 s.
var directIPv6 = func() bool { // a variable for the tests
now := time.Now().Unix()
if now-direct6.at.Load() < 30 {
return direct6.ok.Load() == 1
}
var ok int64
if _, err := netcfg.PhysicalInterfaceIndexFor(netip.MustParseAddr("2001:4860:4860::8888")); err == nil {
if index, err := netcfg.PhysicalInterfaceIndexFor(netip.MustParseAddr("2001:4860:4860::8888")); err == nil && hasGlobalIPv6(index) {
ok = 1
}
direct6.ok.Store(ok)
Expand All @@ -1039,3 +1042,25 @@ func directAddressAllowed(address netip.Addr) bool {
return address.IsValid() && !address.IsPrivate() && !address.IsLoopback() && !address.IsLinkLocalUnicast() &&
!address.IsLinkLocalMulticast() && !address.IsMulticast() && !address.IsUnspecified()
}

// hasGlobalIPv6 says whether the interface has an address that IPv6 on the Internet can use.
func hasGlobalIPv6(index uint32) bool {
iface, err := net.InterfaceByIndex(int(index))
if err != nil {
return false
}
addrs, _ := iface.Addrs()
return slices.ContainsFunc(addrs, func(a net.Addr) bool {
prefix, err := netip.ParsePrefix(a.String())
return err == nil && globalIPv6(prefix.Addr())
})
}

var tunnelingIPv6 = []netip.Prefix{netip.MustParsePrefix("2001::/32"), netip.MustParsePrefix("2002::/16")} // Teredo, 6to4

func globalIPv6(a netip.Addr) bool {
return a.Is6() && !a.Is4In6() && a.IsGlobalUnicast() && !a.IsPrivate() && !slices.ContainsFunc(tunnelingIPv6, func(p netip.Prefix) bool { return p.Contains(a) })
}

// HasIPv6 says whether this machine reaches IPv6 outside any tunnel.
func HasIPv6() bool { return directIPv6() }
63 changes: 63 additions & 0 deletions core/internal/engine/ipv6_paths_windows_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
//go:build windows

package engine

import (
"context"
"net/netip"
"slices"
"testing"

"github.com/mistgate/mistgate-client/core/internal/profile"
)

func v6Paths() []profile.Profile {
return []profile.Profile{
{ID: "v4", Protocol: "hysteria2", Sub: "s", Hy2: &profile.Hy2{Host: "192.0.2.1", Port: 443}},
{ID: "v6", Protocol: "vless", Sub: "s", VLESS: &profile.VLESS{Host: "2001:db8::1", Port: 443}},
}
}

func withIPv6(t *testing.T, has bool) {
t.Helper()
real := directIPv6
t.Cleanup(func() { directIPv6 = real })
directIPv6 = func() bool { return has }
}

// Without IPv6 on the device Auto's choices (Select's order, the background probes) leave IPv6 paths out; the one asked
// for by name stays, and its connect is refused at once with its own code.
func TestIPv6PathsOnADeviceWithoutIPv6(t *testing.T) {
r := &Real{load: func() ([]profile.Profile, error) { return v6Paths(), nil }}
withIPv6(t, false)
if selection, _ := r.Select(Target{Server: "auto"}); !slices.Equal(selection.Order, []string{"v4"}) {
t.Errorf("Auto's order = %v, want the IPv4 path only", selection.Order)
}
if selection, _ := r.Select(Target{Server: "v6"}); !slices.Contains(selection.Order, "v6") {
t.Errorf("a path asked for by name left the order: %v", selection.Order)
}
rtts, skipped := r.Measure(context.Background(), []string{"v6"})
if len(rtts) != 0 || !slices.Equal(skipped, []string{"v6"}) {
t.Errorf("Measure of an IPv6 path = %v, skipped %v; want it skipped, not dialed", rtts, skipped)
}
err := ipv6Refusal(v6Paths()[1])
if ErrorCode(err) != "no_ipv6" || ipv6Refusal(v6Paths()[0]) != nil {
t.Errorf("refusals = %v / %v", err, ipv6Refusal(v6Paths()[0]))
}
withIPv6(t, true)
if selection, _ := r.Select(Target{Server: "auto"}); len(selection.Order) != 2 || ipv6Refusal(v6Paths()[1]) != nil {
t.Errorf("with IPv6 the order is %v and the path refused", selection.Order)
}
}

// Teredo, 6to4 and local addresses are no sign of IPv6 on the Internet.
func TestGlobalIPv6(t *testing.T) {
for address, want := range map[string]bool{
"2001:db8::1": true, "2a00:1450::1": true, "fe80::1": false, "fd00::1": false, "2001:0:4136:e378::1": false,
"2002:c000:204::1": false, "::1": false, "192.0.2.1": false, "::ffff:192.0.2.1": false,
} {
if got := globalIPv6(netip.MustParseAddr(address)); got != want {
t.Errorf("globalIPv6(%s) = %v, want %v", address, got, want)
}
}
}
3 changes: 3 additions & 0 deletions core/internal/engine/real_other.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,6 @@ func (*Real) Measure(context.Context, []string) (map[string]time.Duration, []str

func (*Real) DialVPN(context.Context, string, uint16) (net.Conn, error) { return nil, ErrNoTunnel }
func (*Real) HomeAddr() string { return "" }

// HasIPv6: off Windows nothing says otherwise.
func HasIPv6() bool { return true }
40 changes: 38 additions & 2 deletions core/internal/engine/real_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -540,6 +540,17 @@ func (r *Real) Start(ctx context.Context, target Target, report func(Step)) (inf
// the first wave.
if target.Server == "" || target.Server == "auto" {
_, ring, _ := profile.Ring(profiles, target.Server, target.Protocol, target.Sub, configured.Protocol, configured.Game)
ipv6 := directIPv6()
if !ipv6 { // none on the device: a path whose address is an IPv6 literal is not Auto's to take, so none is noted either
left := dropIPv6(target, ring)
if len(left) < len(ring) {
slog.Info("auto: IPv6 paths left out count=" + strconv.Itoa(len(ring)-len(left)))
}
if len(left) == 0 && len(ring) > 0 {
return Info{}, failure("no_ipv6", "every path needs IPv6")
}
ring = left
}
candidates := ring[:0:0]
for _, p := range ring {
if !configured.Game || p.Protocol == selected.Protocol { // Game mode has chosen the protocol
Expand All @@ -549,7 +560,7 @@ func (r *Real) Start(ctx context.Context, target Target, report func(Step)) (inf
if !slices.ContainsFunc(candidates, func(p profile.Profile) bool { return !slices.Contains(target.Avoid, p.ID) }) {
candidates = ring // the chosen protocol failed on every path: the others may be tried
}
waves := profile.AutoWaves(candidates, target.Avoid)
waves := profile.AutoWaves(candidates, target.Avoid, ipv6)
answered := false
if i := slices.IndexFunc(candidates, func(p profile.Profile) bool { return target.takes(p.ID) }); i >= 0 {
selected, answered, waves = candidates[i], true, nil // the path that worked lately here: no race
Expand All @@ -573,6 +584,9 @@ func (r *Real) Start(ctx context.Context, target Target, report func(Step)) (inf
selected = waves[0][0]
}
}
if err := ipv6Refusal(selected); err != nil {
return Info{}, err
}
started := selected // as the subscriptions gave it: the override below is not theirs
if r.verify != "" {
selected.Verify = r.verify
Expand Down Expand Up @@ -1000,6 +1014,7 @@ func (r *Real) Next(target Target, after string) (string, bool) {
return "", false
}
configured := r.settings()
profiles = dropIPv6(target, profiles)
return profile.Next(profiles, target.Server, target.Protocol, target.Sub, configured.Protocol, configured.Game, after)
}

Expand All @@ -1016,6 +1031,7 @@ func (r *Real) Select(target Target) (Selection, bool) {
if !ok {
return Selection{}, false
}
ring = dropIPv6(target, ring)
name := home.Name
if name == "" {
name = home.ID
Expand Down Expand Up @@ -1123,6 +1139,8 @@ func (r *Real) Measure(ctx context.Context, ids []string) (map[string]time.Durat
for _, p := range profiles {
switch _, live := diag.LiveGuard(p); {
case !slices.Contains(ids, p.ID):
case p.NeedsIPv6() && !directIPv6(): // nothing to dial; the session leaves it out of the memory
skipped = append(skipped, p.ID)
case live:
skipped = append(skipped, p.ID)
default:
Expand All @@ -1149,7 +1167,7 @@ func (r *Real) Fastest(ctx context.Context, target Target, except string) (strin
configured := r.settings()
others := profile.Others(profiles, target.Server, target.Protocol, target.Sub, configured.Protocol, configured.Game, except)
others = slices.DeleteFunc(others, func(p profile.Profile) bool { return slices.Contains(target.Avoid, p.ID) }) // Auto's own
for _, wave := range profile.AutoWaves(others, nil) {
for _, wave := range profile.AutoWaves(others, nil, directIPv6()) {
if best := quickestOf(ctx, wave); best >= 0 {
return wave[best].ID, true
}
Expand Down Expand Up @@ -1992,3 +2010,21 @@ func awgHandshakeSeen(text, serverKey string) bool {
func awgNeedsStack(useForwarder bool, p profile.Profile) bool {
return useForwarder || p.PanelBlockAds || p.NoIPv6 || slices.ContainsFunc(p.AWG.Addresses, func(a netip.Prefix) bool { return a.Addr().Is6() })
}

// dropIPv6 leaves out the paths a device without IPv6 cannot reach: those whose address is an IPv6 literal. The path
// asked for by name stays (ipv6Refusal turns it away at the connect).
func dropIPv6(target Target, paths []profile.Profile) []profile.Profile {
if directIPv6() {
return paths
}
return slices.DeleteFunc(slices.Clone(paths), func(p profile.Profile) bool { return p.NeedsIPv6() && p.ID != target.Server })
}

// ipv6Refusal is the answer to a path of an IPv6 address on a device without IPv6: at once, not after the wait for a
// server that cannot be reached.
func ipv6Refusal(p profile.Profile) error {
if p.NeedsIPv6() && !directIPv6() {
return failure("no_ipv6", "the path's address is IPv6, this device has none")
}
return nil
}
Loading
Loading