Compare commits

..
Author SHA1 Message Date
Ryan Huber 6826c04103 tun: Separate inside-packet filtering from sending 2026-10-16 21:21:03 +00:00
6 changed files with 224 additions and 107 deletions

No files matched your search

+17 -22
View File
@@ -65,7 +65,7 @@ type HandshakeManager struct {
lightHouse *LightHouse
outside udp.Conn
config HandshakeConfig
OutboundHandshakeTimer *LockingTimerWheel[*HandshakeHostInfo]
OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
messageMetrics *MessageMetrics
metricInitiated metrics.Counter
metricTimedOut metrics.Counter
@@ -81,7 +81,6 @@ type HandshakeHostInfo struct {
startTime time.Time // Time that we first started trying with this handshake
ready bool // Is the handshake ready
deleted bool // Has the handshake been removed from the pending maps, deleters hold the lock
initiatingVersionOverride cert.Version // Should we use a non-default cert version for this handshake?
counter int64 // How many attempts have we made so far
lastRemotes []netip.AddrPort // Remotes that we sent to during the previous attempt
@@ -126,7 +125,7 @@ func NewHandshakeManager(l *slog.Logger, mainHostMap *HostMap, lightHouse *Light
outside: outside,
config: config,
trigger: make(chan netip.Addr, config.triggerBuffer),
OutboundHandshakeTimer: NewLockingTimerWheel[*HandshakeHostInfo](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
OutboundHandshakeTimer: NewLockingTimerWheel[netip.Addr](config.tryInterval, hsTimeout(config.retries, config.tryInterval)),
messageMetrics: config.messageMetrics,
metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
@@ -143,9 +142,7 @@ func (hm *HandshakeManager) Run(ctx context.Context) {
case <-ctx.Done():
return
case vpnIP := <-hm.trigger:
if hh := hm.queryVpnIp(vpnIP); hh != nil {
hm.handleOutbound(hh, true)
}
hm.handleOutbound(vpnIP, true)
case now := <-clockSource.C:
hm.NextOutboundHandshakeTimerTick(now)
}
@@ -200,25 +197,23 @@ func (hm *HandshakeManager) HandleIncoming(via ViaSender, packet []byte, h *head
func (hm *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time) {
hm.OutboundHandshakeTimer.Advance(now)
for {
hh, has := hm.OutboundHandshakeTimer.Purge()
vpnIp, has := hm.OutboundHandshakeTimer.Purge()
if !has {
break
}
hm.handleOutbound(hh, false)
hm.handleOutbound(vpnIp, false)
}
}
func (hm *HandshakeManager) handleOutbound(hh *HandshakeHostInfo, lighthouseTriggered bool) {
func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered bool) {
hh := hm.queryVpnIp(vpnIp)
if hh == nil {
return
}
hh.Lock()
defer hh.Unlock()
// Timer entries outlive their handshake. A new handshake for the same vpn addr runs its own timer chain.
if hh.deleted {
return
}
hostinfo := hh.hostinfo
vpnIp := hostinfo.vpnAddrs[0]
// If we are out of time, clean up
if hh.counter >= hm.config.retries {
fields := []any{
@@ -244,14 +239,10 @@ func (hm *HandshakeManager) handleOutbound(hh *HandshakeHostInfo, lighthouseTrig
// Increment the counter to increase our delay, linear backoff
hh.counter++
// A lighthouse triggered attempt is still in the timer wheel, adding it again would start a second retry chain
if !lighthouseTriggered {
defer hm.OutboundHandshakeTimer.Add(hh, hm.config.tryInterval*time.Duration(hh.counter))
}
// Check if we have a handshake packet to transmit yet
if !hh.ready {
if !hm.buildStage0Packet(hh) {
hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
return
}
}
@@ -332,6 +323,11 @@ func (hm *HandshakeManager) handleOutbound(hh *HandshakeHostInfo, lighthouseTrig
}
hm.f.relayManager.StartRelays(hm.f, vpnIp, hh, stage0)
// If a lighthouse triggered this attempt then we are still in the timer wheel and do not need to re-add
if !lighthouseTriggered {
hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
}
}
// GetOrHandshake will try to find a hostinfo with a fully formed tunnel or start a new handshake if one is not present
@@ -384,7 +380,7 @@ func (hm *HandshakeManager) StartHandshake(vpnAddr netip.Addr, cacheCb func(*Han
}
hm.vpnIps[vpnAddr] = hh
hm.metricInitiated.Inc(1)
hm.OutboundHandshakeTimer.Add(hh, hm.config.tryInterval)
hm.OutboundHandshakeTimer.Add(vpnAddr, hm.config.tryInterval)
if cacheCb != nil {
cacheCb(hh)
@@ -536,7 +532,6 @@ func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
for _, addr := range hostinfo.vpnAddrs {
if cur, ok := hm.vpnIps[addr]; ok && cur.hostinfo == hostinfo {
cur.deleted = true
delete(hm.vpnIps, addr)
}
}
+1 -63
View File
@@ -65,69 +65,7 @@ func Test_NewHandshakeManagerVpnIp(t *testing.T) {
assert.NotContains(t, blah.vpnIps, ip)
}
// newTestHandshakeManager returns a manager whose handshakes never build a stage 0 packet (the cert has no key), so
// every attempt just bumps the counter and schedules the next one. tick advances its timer wheel by one tryInterval.
func newTestHandshakeManager() (hm *HandshakeManager, tick func()) {
l := test.NewLogger()
mainHM := newHostMap(l)
mainHM.preferredRanges.Store(&[]netip.Prefix{})
hm = NewHandshakeManager(l, mainHM, newTestLighthouse(), &udp.NoopConn{}, defaultHandshakeConfig)
hm.f = &Interface{handshakeManager: hm, pki: &PKI{}, l: l}
hm.f.pki.cs.Store(&CertState{
initiatingVersion: cert.Version1,
privateKey: []byte{},
v1Cert: &dummyCert{version: cert.Version1},
})
now := time.Now()
hm.NextOutboundHandshakeTimerTick(now)
return hm, func() {
now = now.Add(DefaultHandshakeTryInterval)
hm.NextOutboundHandshakeTimerTick(now)
}
}
func Test_HandshakeManager_RestartDropsOldTimer(t *testing.T) {
ip := netip.MustParseAddr("172.1.1.2")
hm, tick := newTestHandshakeManager()
hm.StartHandshake(ip, nil)
old := hm.queryVpnIp(ip)
tick()
tick()
require.Equal(t, int64(1), old.counter)
// Restart the handshake while the old one still has a retry queued
hm.DeleteHostInfo(old.hostinfo)
hm.StartHandshake(ip, nil)
hh := hm.queryVpnIp(ip)
require.NotSame(t, old, hh)
// An entry for timeout d fires d/tryInterval+1 ticks after it is added, so linear backoff lands attempts on ticks
// 2, 4 and 7
var counters []int64
for range 7 {
tick()
counters = append(counters, hh.counter)
}
assert.Equal(t, []int64{0, 1, 1, 2, 2, 2, 3}, counters)
// The old handshake's queued retry ended its chain instead of retrying a deleted handshake
assert.Equal(t, int64(1), old.counter)
assert.Equal(t, 1, testCountTimerWheelEntries(hm.OutboundHandshakeTimer))
}
func Test_HandshakeManager_LighthouseTriggerKeepsOneTimer(t *testing.T) {
ip := netip.MustParseAddr("172.1.1.2")
hm, _ := newTestHandshakeManager()
hm.StartHandshake(ip, nil)
hm.handleOutbound(hm.queryVpnIp(ip), true)
assert.Equal(t, 1, testCountTimerWheelEntries(hm.OutboundHandshakeTimer))
}
func testCountTimerWheelEntries(tw *LockingTimerWheel[*HandshakeHostInfo]) (c int) {
func testCountTimerWheelEntries(tw *LockingTimerWheel[netip.Addr]) (c int) {
for _, i := range tw.t.wheel {
n := i.Head
for n != nil {
+23 -14
View File
@@ -18,12 +18,20 @@ import (
)
func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, nb []byte, sendBatch *batch.SendBatch, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
if hostinfo := f.filterInsidePacket(pkt, fwPacket, rejectBuf, q, localCache); hostinfo != nil {
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
}
}
// filterInsidePacket parses and filters pkt, handling local traffic, destination lookup, pending handshakes and
// the outbound firewall. It returns the hostinfo to send pkt to, or nil when pkt was dropped, rejected, forwarded
// to self or cached for a pending handshake.
func (f *Interface) filterInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, rejectBuf []byte, q int, localCache firewall.ConntrackCache) *HostInfo {
// borrowed: pkt.Bytes is owned by the originating tio.Queue and is
// only valid until the next Read on that queue. Every consumer below
// (parse, self-forward, handshake cache, sendInsideMessage) reads it
// synchronously; do not retain pkt outside this call. If a future
// caller needs to keep the packet, use pkt.Clone() to detach it from
// the borrow.
// only valid until the next Read on that queue. Filtering and sending
// must finish before then. Self-forwarding writes synchronously and the
// handshake cache copies each segment. To retain the packet beyond the
// next Read, use pkt.Clone() to detach it from the borrow.
//
// pkt.Bytes is either one IP datagram (GSO zero) or a TSO/USO
// superpacket. In both cases the L3+L4 headers at the start describe
@@ -38,13 +46,13 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
"error", err,
)
}
return
return nil
}
// Ignore local broadcast packets
if f.dropLocalBroadcast {
if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
return
return nil
}
}
@@ -71,12 +79,12 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
}
// Otherwise, drop. On linux, we should never see these packets - Linux
// routes packets from the nebula addr to the nebula addr through the loopback device.
return
return nil
}
// Ignore multicast packets
if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
return
return nil
}
hostinfo, ready := f.getOrHandshakeConsiderRouting(&fwPacket.Packet, func(hh *HandshakeHostInfo) {
@@ -103,17 +111,18 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
"fwPacket", fwPacket,
)
}
return
return nil
}
if !ready {
return
return nil
}
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
if dropReason == nil {
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
} else {
return hostinfo
}
f.rejectInside(packet, rejectBuf, q)
if f.l.Enabled(context.Background(), slog.LevelDebug) {
hostinfo.logger(f.l).Debug("dropping outbound packet",
@@ -121,7 +130,7 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
"reason", dropReason,
)
}
}
return nil
}
func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, seg, scratch, nb []byte) []byte {
+180
View File
@@ -0,0 +1,180 @@
package nebula
import (
"net/netip"
"testing"
"time"
"github.com/gaissmai/bart"
"github.com/slackhq/nebula/cert"
"github.com/slackhq/nebula/firewall"
"github.com/slackhq/nebula/header"
"github.com/slackhq/nebula/overlay/batch"
"github.com/slackhq/nebula/overlay/overlaytest"
"github.com/slackhq/nebula/overlay/tio"
"github.com/slackhq/nebula/udp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newInsideFilterTestInterface(t *testing.T, allow bool) (*Interface, *HostInfo, *capturingTun) {
t.Helper()
local := netip.MustParseAddr("192.0.2.1")
remote := netip.MustParseAddr("192.0.2.2")
f, tun := newSelfForwardInterface(local)
f.inside = overlaytest.NoopTun{}
f.myVpnNetworksTable = &bart.Lite{}
f.myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.0/24"))
f.myBroadcastAddrsTable.Insert(netip.MustParsePrefix("192.0.2.255/32"))
f.dropLocalBroadcast, f.dropMulticast = true, true
localCert := &dummyCert{version: cert.Version1, networks: []netip.Prefix{netip.PrefixFrom(local, 24)}}
peerCert := &dummyCert{version: cert.Version1, networks: []netip.Prefix{netip.PrefixFrom(remote, 24)}}
f.firewall = NewFirewall(f.l, time.Minute, time.Minute, time.Minute, localCert)
if allow {
require.NoError(t, f.firewall.AddRule(false, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
}
f.pki = &PKI{}
f.pki.caPool.Store(cert.NewCAPool())
f.hostMap = newHostMap(f.l)
f.lightHouse = newTestLighthouse()
f.lightHouse.amLighthouse = true // Keep destination lookup from probing other remotes.
f.handshakeManager = NewHandshakeManager(f.l, f.hostMap, f.lightHouse, udp.NoopConn{}, defaultHandshakeConfig)
f.handshakeManager.f = f
f.connectionManager = &connectionManager{intf: f}
h := &HostInfo{
vpnAddrs: []netip.Addr{remote},
ConnectionState: &ConnectionState{
peerCert: &cert.CachedCertificate{Certificate: peerCert},
},
}
f.hostMap.Hosts[remote] = h
return f, h, tun
}
func TestFilterInsidePacket(t *testing.T) {
local := netip.MustParseAddr("192.0.2.1")
remote := netip.MustParseAddr("192.0.2.2")
for _, tt := range []struct {
name string
packet []byte
allow bool
reject bool
ready bool
writes int
}{
{name: "allowed", packet: buildIPv4(local, remote, tcpSyn), allow: true, ready: true},
{name: "malformed", packet: []byte{0x45}, allow: true},
{name: "broadcast", packet: buildIPv4(local, netip.MustParseAddr("192.0.2.255"), udpDatagram), allow: true},
{name: "multicast", packet: buildIPv4(local, netip.MustParseAddr("224.0.0.1"), udpDatagram), allow: true},
{name: "firewall drop", packet: buildIPv4(local, remote, tcpSyn)},
{name: "firewall reject", packet: buildIPv4(local, remote, tcpSyn), reject: true, writes: 1},
{name: "unroutable drop", packet: buildIPv4(local, netip.MustParseAddr("198.51.100.1"), tcpSyn), allow: true},
{name: "unroutable reject", packet: buildIPv4(local, netip.MustParseAddr("198.51.100.1"), tcpSyn), allow: true, reject: true, writes: 1},
} {
t.Run(tt.name, func(t *testing.T) {
f, h, tun := newInsideFilterTestInterface(t, tt.allow)
f.firewall.OutboundSendReject = tt.reject
fp := &firewall.ParsedPacket{}
got := f.filterInsidePacket(tio.Packet{Bytes: tt.packet}, fp, make([]byte, mtu), 0, nil)
if tt.ready {
require.Same(t, h, got)
assert.Equal(t, local, fp.LocalAddr)
assert.Equal(t, remote, fp.RemoteAddr)
} else {
require.Nil(t, got)
}
assert.Zero(t, h.ConnectionState.messageCounter.Load(), "filtering must not allocate encryption counters")
assert.False(t, h.sentSinceCheck(), "filtering must not mark outbound traffic")
require.Len(t, tun.writes, tt.writes)
if tt.writes > 0 {
require.GreaterOrEqual(t, len(tun.writes[0]), 40)
assert.Equal(t, tt.packet[16:20], tun.writes[0][12:16])
assert.Equal(t, tt.packet[12:16], tun.writes[0][16:20])
assert.NotZero(t, tun.writes[0][33]&0x04, "reject must carry a TCP reset")
}
})
}
}
func TestFilterInsidePacketSelf(t *testing.T) {
local := netip.MustParseAddr("192.0.2.1")
f, _, tun := newInsideFilterTestInterface(t, true)
pkt := buildIPv4(local, local, tcpSyn)
require.Nil(t, f.filterInsidePacket(tio.Packet{Bytes: pkt}, &firewall.ParsedPacket{}, nil, 0, nil))
if immediatelyForwardToSelf {
require.Len(t, tun.writes, 1)
assert.Equal(t, pkt, tun.writes[0])
} else {
assert.Empty(t, tun.writes)
}
}
func TestFilterInsidePacketPendingHandshake(t *testing.T) {
f, h, tun := newInsideFilterTestInterface(t, true)
remote := h.vpnAddrs[0]
delete(f.hostMap.Hosts, remote)
hh := &HandshakeHostInfo{hostinfo: h}
f.handshakeManager.vpnIps[remote] = hh
pkt := buildIPv4(netip.MustParseAddr("192.0.2.1"), remote, udpDatagram)
want := append([]byte(nil), pkt...)
require.Nil(t, f.filterInsidePacket(tio.Packet{Bytes: pkt}, &firewall.ParsedPacket{}, nil, 0, nil))
require.Len(t, hh.packetStore, 1)
clear(pkt)
assert.Equal(t, want, hh.packetStore[0].packet, "the handshake cache must own its packet")
assert.Equal(t, header.Message, hh.packetStore[0].messageType)
assert.Empty(t, tun.writes)
assert.Zero(t, h.ConnectionState.messageCounter.Load())
}
type insideFilterConn struct {
udp.NoopConn
packets [][]byte
}
func (c *insideFilterConn) WriteBatch(bufs [][]byte, _ []netip.AddrPort) (int, error) {
for _, b := range bufs {
c.packets = append(c.packets, append([]byte(nil), b...))
}
return len(bufs), nil
}
func TestConsumeInsidePacketFilterAndSend(t *testing.T) {
for _, allow := range []bool{false, true} {
t.Run(map[bool]string{false: "denied", true: "allowed"}[allow], func(t *testing.T) {
f, h, _ := newInsideFilterTestInterface(t, allow)
initR, respR := runTestHandshake(t)
ci, err := newConnectionStateFromResult(initR)
require.NoError(t, err)
rci, err := newConnectionStateFromResult(respR)
require.NoError(t, err)
ci.peerCert = h.ConnectionState.peerCert
h.ConnectionState = ci
h.remoteIndexId = 100
remote := netip.MustParseAddrPort("198.51.100.2:4242")
h.remote.Store(&remote)
conn := &insideFilterConn{}
sb := batch.NewSendBatch(conn, 1, mtu)
pkt := buildIPv4(netip.MustParseAddr("192.0.2.1"), h.vpnAddrs[0], udpDatagram)
before := ci.messageCounter.Load()
f.consumeInsidePacket(tio.Packet{Bytes: pkt}, &firewall.ParsedPacket{}, make([]byte, 12), sb, nil, 0, nil)
_, err = sb.Flush()
require.NoError(t, err)
if !allow {
assert.Empty(t, conn.packets)
assert.Equal(t, before, ci.messageCounter.Load())
assert.False(t, h.sentSinceCheck())
return
}
require.Len(t, conn.packets, 1)
assert.True(t, h.sentSinceCheck())
hdr := &header.H{}
require.NoError(t, hdr.Parse(conn.packets[0]))
assert.Equal(t, header.Message, hdr.Type)
assert.Equal(t, h.remoteIndexId, hdr.RemoteIndex)
assert.Equal(t, before+1, hdr.MessageCounter)
plain, err := rci.Decrypt(f.l, hdr.MessageCounter, conn.packets[0], make([]byte, 12))
require.NoError(t, err)
assert.Equal(t, pkt, plain)
})
}
}
+2 -5
View File
@@ -147,10 +147,7 @@ func (tw *TimerWheel[T]) Purge() (T, bool) {
tw.expired.Tail = nil
}
// Clear out the items references, a cached item must not keep its value alive
v := ti.Item
var zero T
ti.Item = zero
// Clear out the items references
ti.Next = nil
// Maybe cache it for later
@@ -160,7 +157,7 @@ func (tw *TimerWheel[T]) Purge() (T, bool) {
tw.itemsCached++
}
return v, true
return ti.Item, true
}
// findWheel find the next position in the wheel for the provided timeout given the current tick
+1 -3
View File
@@ -7,7 +7,6 @@ import (
"github.com/slackhq/nebula/firewall"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewTimerWheel(t *testing.T) {
@@ -151,8 +150,7 @@ func TestTimerWheel_Purge(t *testing.T) {
assert.Equal(t, 4, tw.itemsCached)
ci := tw.itemCache
for range 4 {
require.NotNil(t, ci)
assert.Zero(t, ci.Item)
assert.NotNil(t, ci)
ci = ci.Next
}
assert.Nil(t, ci)