mirror of
https://github.com/juanfont/headscale.git
synced 2026-11-19 11:57:07 +09:00
derp/server: serve STUN with Tailscale's stunserver
Own loop answered IPv4 clients of a dual-stack socket with ::ffff:a.b.c.d. Fixes #3573
This commit is contained in:
1 parent
492c28f5bb
commit
dd4a0edab8
3 files changed
+69
-64
No files matched your search
@@ -191,6 +191,7 @@ is not connected, or refuses is "not found". See [the client docs](https://heads
|
||||
- The NixOS module's `headscale` service now supports `systemctl reload`
|
||||
- DERP map refreshes keep the node order. Clients keep their home relay. [#3649](https://github.com/juanfont/headscale/pull/3649)
|
||||
- A `derp.urls` or `derp.paths` source that fails to load (unreachable, an HTTP status other than 200, or an invalid map) is logged as a warning and skipped instead of stopping headscale from starting. Headscale still refuses to start when no DERP region remains; a refresh with a failing source keeps the previous map [#3142](https://github.com/juanfont/headscale/issues/3142)
|
||||
- Fix the embedded STUN server returning IPv4 addresses as IPv4-mapped IPv6 addresses (`::ffff:a.b.c.d`), and change it to use Tailscale's STUN server implementation [#3573](https://github.com/juanfont/headscale/issues/3573)
|
||||
- Nodes with `disable-ipv4` get their peers over IPv6 only. [#3649](https://github.com/juanfont/headscale/pull/3649)
|
||||
- A node name follows a new hostname at login, unless an administrator set the name. [#3649](https://github.com/juanfont/headscale/pull/3649)
|
||||
- `AllowedIPs` list the node's own addresses first. `tailscale whois` reads them in this order. [#3649](https://github.com/juanfont/headscale/pull/3649)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
@@ -23,7 +22,7 @@ import (
|
||||
"tailscale.com/derp"
|
||||
"tailscale.com/derp/derpserver"
|
||||
"tailscale.com/envknob"
|
||||
"tailscale.com/net/stun"
|
||||
"tailscale.com/net/stunserver"
|
||||
"tailscale.com/net/wsconn"
|
||||
"tailscale.com/tailcfg"
|
||||
"tailscale.com/types/key"
|
||||
@@ -378,70 +377,12 @@ func DERPBootstrapDNSHandler(
|
||||
}
|
||||
}
|
||||
|
||||
// ServeSTUN starts a STUN server on the configured addr.
|
||||
// ServeSTUN starts a STUN server on the configured addr. It uses Tailscale's
|
||||
// stunserver so replies match what Tailscale's own derpers send.
|
||||
func (d *DERPServer) ServeSTUN() {
|
||||
packetConn, err := new(net.ListenConfig).ListenPacket(context.Background(), "udp", string(d.cfg.Server.STUNAddr))
|
||||
err := stunserver.New(context.Background()).ListenAndServe(string(d.cfg.Server.STUNAddr))
|
||||
if err != nil {
|
||||
log.Fatal().Msgf("failed to open STUN listener: %v", err)
|
||||
}
|
||||
|
||||
log.Info().Msgf("stun server started at %s", packetConn.LocalAddr())
|
||||
|
||||
udpConn, ok := packetConn.(*net.UDPConn)
|
||||
if !ok {
|
||||
log.Fatal().Msg("stun listener is not a UDP listener")
|
||||
}
|
||||
|
||||
serverSTUNListener(context.Background(), udpConn)
|
||||
}
|
||||
|
||||
func serverSTUNListener(ctx context.Context, packetConn *net.UDPConn) {
|
||||
var buf [64 << 10]byte
|
||||
|
||||
for {
|
||||
bytesRead, udpAddr, err := packetConn.ReadFromUDP(buf[:])
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return
|
||||
}
|
||||
|
||||
log.Error().Caller().Err(err).Msgf("stun ReadFrom")
|
||||
|
||||
// Rate limit error logging - wait before retrying, but respect context cancellation
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
log.Trace().Caller().Msgf("stun request from %v", udpAddr)
|
||||
|
||||
pkt := buf[:bytesRead]
|
||||
if !stun.Is(pkt) {
|
||||
log.Trace().Caller().Msgf("udp packet is not stun")
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
txid, err := stun.ParseBindingRequest(pkt)
|
||||
if err != nil {
|
||||
log.Trace().Caller().Err(err).Msgf("stun parse error")
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
addr, _ := netip.AddrFromSlice(udpAddr.IP)
|
||||
res := stun.Response(txid, netip.AddrPortFrom(addr, uint16(udpAddr.Port))) //nolint:gosec // port is always <=65535
|
||||
|
||||
_, err = packetConn.WriteTo(res, udpAddr)
|
||||
if err != nil {
|
||||
log.Trace().Caller().Err(err).Msgf("issue writing to UDP")
|
||||
|
||||
continue
|
||||
}
|
||||
log.Fatal().Err(err).Msg("failed to open STUN listener")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,16 +2,20 @@ package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/netip"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/juanfont/headscale/hscontrol/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"tailscale.com/envknob"
|
||||
"tailscale.com/net/stun"
|
||||
"tailscale.com/tailcfg"
|
||||
)
|
||||
|
||||
@@ -85,3 +89,62 @@ func TestDERPBootstrapDNSHandlerFollowsDERPMapUpdates(t *testing.T) {
|
||||
require.NoError(t, json.NewDecoder(rec.Body).Decode(&got))
|
||||
assert.Contains(t, got, "localhost")
|
||||
}
|
||||
|
||||
// TestSTUNServerUnmapsIPv4 pins that an IPv4 client of a dual-stack
|
||||
// listener (what the default "0.0.0.0" opens) gets an IPv4
|
||||
// XOR-MAPPED-ADDRESS, as Tailscale's derpers send. Raw bytes are compared
|
||||
// because stun.ParseResponse unmaps and would hide the bug.
|
||||
// https://github.com/juanfont/headscale/issues/3573
|
||||
func TestSTUNServerUnmapsIPv4(t *testing.T) {
|
||||
// Probe for a free port and whether "0.0.0.0" opens a dual-stack socket.
|
||||
probe, err := new(net.ListenConfig).ListenPacket(t.Context(), "udp", "0.0.0.0:0")
|
||||
require.NoError(t, err)
|
||||
|
||||
local, ok := probe.LocalAddr().(*net.UDPAddr)
|
||||
require.True(t, ok)
|
||||
require.NoError(t, probe.Close())
|
||||
|
||||
if !local.IP.Equal(net.IPv6unspecified) {
|
||||
t.Skipf("listener is not dual-stack: %s", local)
|
||||
}
|
||||
|
||||
d := &DERPServer{cfg: &types.DERPConfig{Server: types.DERPServerConfig{STUNAddr: types.ListenAddr(fmt.Sprintf("0.0.0.0:%d", local.Port))}}}
|
||||
go d.ServeSTUN()
|
||||
|
||||
tests := []struct {
|
||||
network string
|
||||
client netip.Addr
|
||||
}{
|
||||
{network: "udp4", client: netip.MustParseAddr("127.0.0.1")},
|
||||
{network: "udp6", client: netip.MustParseAddr("::1")},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.network, func(t *testing.T) {
|
||||
conn, err := net.DialUDP(tt.network, nil, net.UDPAddrFromAddrPort(netip.AddrPortFrom(tt.client, uint16(local.Port)))) //nolint:gosec // port is always <=65535
|
||||
if err != nil {
|
||||
t.Skipf("no %s loopback: %v", tt.network, err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
txid := stun.NewTxID()
|
||||
buf := make([]byte, 1024)
|
||||
|
||||
var n int
|
||||
|
||||
// Retry until ServeSTUN has bound the port.
|
||||
require.EventuallyWithT(t, func(c *assert.CollectT) {
|
||||
_, err := conn.Write(stun.Request(txid))
|
||||
require.NoError(c, err)
|
||||
require.NoError(c, conn.SetReadDeadline(time.Now().Add(100*time.Millisecond)))
|
||||
|
||||
n, err = conn.Read(buf)
|
||||
require.NoError(c, err)
|
||||
}, 5*time.Second, 10*time.Millisecond)
|
||||
|
||||
clientPort := conn.LocalAddr().(*net.UDPAddr).Port //nolint:forcetypeassert // DialUDP always yields *net.UDPAddr
|
||||
want := stun.Response(txid, netip.AddrPortFrom(tt.client, uint16(clientPort))) //nolint:gosec // port is always <=65535
|
||||
assert.Equal(t, want, buf[:n])
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user