mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 08:36:52 +01:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6826c04103 |
No files matched your search
+17
-22
@@ -65,7 +65,7 @@ type HandshakeManager struct {
|
|||||||
lightHouse *LightHouse
|
lightHouse *LightHouse
|
||||||
outside udp.Conn
|
outside udp.Conn
|
||||||
config HandshakeConfig
|
config HandshakeConfig
|
||||||
OutboundHandshakeTimer *LockingTimerWheel[*HandshakeHostInfo]
|
OutboundHandshakeTimer *LockingTimerWheel[netip.Addr]
|
||||||
messageMetrics *MessageMetrics
|
messageMetrics *MessageMetrics
|
||||||
metricInitiated metrics.Counter
|
metricInitiated metrics.Counter
|
||||||
metricTimedOut metrics.Counter
|
metricTimedOut metrics.Counter
|
||||||
@@ -81,7 +81,6 @@ type HandshakeHostInfo struct {
|
|||||||
|
|
||||||
startTime time.Time // Time that we first started trying with this handshake
|
startTime time.Time // Time that we first started trying with this handshake
|
||||||
ready bool // Is the handshake ready
|
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?
|
initiatingVersionOverride cert.Version // Should we use a non-default cert version for this handshake?
|
||||||
counter int64 // How many attempts have we made so far
|
counter int64 // How many attempts have we made so far
|
||||||
lastRemotes []netip.AddrPort // Remotes that we sent to during the previous attempt
|
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,
|
outside: outside,
|
||||||
config: config,
|
config: config,
|
||||||
trigger: make(chan netip.Addr, config.triggerBuffer),
|
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,
|
messageMetrics: config.messageMetrics,
|
||||||
metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
|
metricInitiated: metrics.GetOrRegisterCounter("handshake_manager.initiated", nil),
|
||||||
metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
|
metricTimedOut: metrics.GetOrRegisterCounter("handshake_manager.timed_out", nil),
|
||||||
@@ -143,9 +142,7 @@ func (hm *HandshakeManager) Run(ctx context.Context) {
|
|||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
return
|
return
|
||||||
case vpnIP := <-hm.trigger:
|
case vpnIP := <-hm.trigger:
|
||||||
if hh := hm.queryVpnIp(vpnIP); hh != nil {
|
hm.handleOutbound(vpnIP, true)
|
||||||
hm.handleOutbound(hh, true)
|
|
||||||
}
|
|
||||||
case now := <-clockSource.C:
|
case now := <-clockSource.C:
|
||||||
hm.NextOutboundHandshakeTimerTick(now)
|
hm.NextOutboundHandshakeTimerTick(now)
|
||||||
}
|
}
|
||||||
@@ -200,25 +197,23 @@ func (hm *HandshakeManager) HandleIncoming(via ViaSender, packet []byte, h *head
|
|||||||
func (hm *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time) {
|
func (hm *HandshakeManager) NextOutboundHandshakeTimerTick(now time.Time) {
|
||||||
hm.OutboundHandshakeTimer.Advance(now)
|
hm.OutboundHandshakeTimer.Advance(now)
|
||||||
for {
|
for {
|
||||||
hh, has := hm.OutboundHandshakeTimer.Purge()
|
vpnIp, has := hm.OutboundHandshakeTimer.Purge()
|
||||||
if !has {
|
if !has {
|
||||||
break
|
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()
|
hh.Lock()
|
||||||
defer hh.Unlock()
|
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
|
hostinfo := hh.hostinfo
|
||||||
vpnIp := hostinfo.vpnAddrs[0]
|
|
||||||
// If we are out of time, clean up
|
// If we are out of time, clean up
|
||||||
if hh.counter >= hm.config.retries {
|
if hh.counter >= hm.config.retries {
|
||||||
fields := []any{
|
fields := []any{
|
||||||
@@ -244,14 +239,10 @@ func (hm *HandshakeManager) handleOutbound(hh *HandshakeHostInfo, lighthouseTrig
|
|||||||
// Increment the counter to increase our delay, linear backoff
|
// Increment the counter to increase our delay, linear backoff
|
||||||
hh.counter++
|
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
|
// Check if we have a handshake packet to transmit yet
|
||||||
if !hh.ready {
|
if !hh.ready {
|
||||||
if !hm.buildStage0Packet(hh) {
|
if !hm.buildStage0Packet(hh) {
|
||||||
|
hm.OutboundHandshakeTimer.Add(vpnIp, hm.config.tryInterval*time.Duration(hh.counter))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -332,6 +323,11 @@ func (hm *HandshakeManager) handleOutbound(hh *HandshakeHostInfo, lighthouseTrig
|
|||||||
}
|
}
|
||||||
|
|
||||||
hm.f.relayManager.StartRelays(hm.f, vpnIp, hh, stage0)
|
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
|
// 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.vpnIps[vpnAddr] = hh
|
||||||
hm.metricInitiated.Inc(1)
|
hm.metricInitiated.Inc(1)
|
||||||
hm.OutboundHandshakeTimer.Add(hh, hm.config.tryInterval)
|
hm.OutboundHandshakeTimer.Add(vpnAddr, hm.config.tryInterval)
|
||||||
|
|
||||||
if cacheCb != nil {
|
if cacheCb != nil {
|
||||||
cacheCb(hh)
|
cacheCb(hh)
|
||||||
@@ -536,7 +532,6 @@ func (hm *HandshakeManager) DeleteHostInfo(hostinfo *HostInfo) {
|
|||||||
func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
|
func (hm *HandshakeManager) unlockedDeleteHostInfo(hostinfo *HostInfo) {
|
||||||
for _, addr := range hostinfo.vpnAddrs {
|
for _, addr := range hostinfo.vpnAddrs {
|
||||||
if cur, ok := hm.vpnIps[addr]; ok && cur.hostinfo == hostinfo {
|
if cur, ok := hm.vpnIps[addr]; ok && cur.hostinfo == hostinfo {
|
||||||
cur.deleted = true
|
|
||||||
delete(hm.vpnIps, addr)
|
delete(hm.vpnIps, addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -65,69 +65,7 @@ func Test_NewHandshakeManagerVpnIp(t *testing.T) {
|
|||||||
assert.NotContains(t, blah.vpnIps, ip)
|
assert.NotContains(t, blah.vpnIps, ip)
|
||||||
}
|
}
|
||||||
|
|
||||||
// newTestHandshakeManager returns a manager whose handshakes never build a stage 0 packet (the cert has no key), so
|
func testCountTimerWheelEntries(tw *LockingTimerWheel[netip.Addr]) (c int) {
|
||||||
// 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) {
|
|
||||||
for _, i := range tw.t.wheel {
|
for _, i := range tw.t.wheel {
|
||||||
n := i.Head
|
n := i.Head
|
||||||
for n != nil {
|
for n != nil {
|
||||||
|
|||||||
@@ -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) {
|
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
|
// borrowed: pkt.Bytes is owned by the originating tio.Queue and is
|
||||||
// only valid until the next Read on that queue. Every consumer below
|
// only valid until the next Read on that queue. Filtering and sending
|
||||||
// (parse, self-forward, handshake cache, sendInsideMessage) reads it
|
// must finish before then. Self-forwarding writes synchronously and the
|
||||||
// synchronously; do not retain pkt outside this call. If a future
|
// handshake cache copies each segment. To retain the packet beyond the
|
||||||
// caller needs to keep the packet, use pkt.Clone() to detach it from
|
// next Read, use pkt.Clone() to detach it from the borrow.
|
||||||
// the borrow.
|
|
||||||
//
|
//
|
||||||
// pkt.Bytes is either one IP datagram (GSO zero) or a TSO/USO
|
// 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
|
// 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,
|
"error", err,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ignore local broadcast packets
|
// Ignore local broadcast packets
|
||||||
if f.dropLocalBroadcast {
|
if f.dropLocalBroadcast {
|
||||||
if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
|
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
|
// 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.
|
// routes packets from the nebula addr to the nebula addr through the loopback device.
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ignore multicast packets
|
// Ignore multicast packets
|
||||||
if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
|
if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
hostinfo, ready := f.getOrHandshakeConsiderRouting(&fwPacket.Packet, func(hh *HandshakeHostInfo) {
|
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,
|
"fwPacket", fwPacket,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if !ready {
|
if !ready {
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
|
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
|
||||||
if dropReason == nil {
|
if dropReason == nil {
|
||||||
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
|
return hostinfo
|
||||||
} else {
|
}
|
||||||
|
|
||||||
f.rejectInside(packet, rejectBuf, q)
|
f.rejectInside(packet, rejectBuf, q)
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
hostinfo.logger(f.l).Debug("dropping outbound packet",
|
hostinfo.logger(f.l).Debug("dropping outbound packet",
|
||||||
@@ -121,7 +130,7 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
"reason", dropReason,
|
"reason", dropReason,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, seg, scratch, nb []byte) []byte {
|
func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, seg, scratch, nb []byte) []byte {
|
||||||
|
|||||||
@@ -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
@@ -147,10 +147,7 @@ func (tw *TimerWheel[T]) Purge() (T, bool) {
|
|||||||
tw.expired.Tail = nil
|
tw.expired.Tail = nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Clear out the items references, a cached item must not keep its value alive
|
// Clear out the items references
|
||||||
v := ti.Item
|
|
||||||
var zero T
|
|
||||||
ti.Item = zero
|
|
||||||
ti.Next = nil
|
ti.Next = nil
|
||||||
|
|
||||||
// Maybe cache it for later
|
// Maybe cache it for later
|
||||||
@@ -160,7 +157,7 @@ func (tw *TimerWheel[T]) Purge() (T, bool) {
|
|||||||
tw.itemsCached++
|
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
|
// findWheel find the next position in the wheel for the provided timeout given the current tick
|
||||||
|
|||||||
+1
-3
@@ -7,7 +7,6 @@ import (
|
|||||||
|
|
||||||
"github.com/slackhq/nebula/firewall"
|
"github.com/slackhq/nebula/firewall"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestNewTimerWheel(t *testing.T) {
|
func TestNewTimerWheel(t *testing.T) {
|
||||||
@@ -151,8 +150,7 @@ func TestTimerWheel_Purge(t *testing.T) {
|
|||||||
assert.Equal(t, 4, tw.itemsCached)
|
assert.Equal(t, 4, tw.itemsCached)
|
||||||
ci := tw.itemCache
|
ci := tw.itemCache
|
||||||
for range 4 {
|
for range 4 {
|
||||||
require.NotNil(t, ci)
|
assert.NotNil(t, ci)
|
||||||
assert.Zero(t, ci.Item)
|
|
||||||
ci = ci.Next
|
ci = ci.Next
|
||||||
}
|
}
|
||||||
assert.Nil(t, ci)
|
assert.Nil(t, ci)
|
||||||
|
|||||||
Reference in new issue
Block a user