mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 13:56:52 +01:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3bb5918e7c |
No files matched your search
@@ -7,7 +7,6 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/rcrowley/go-metrics"
|
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/overlay/overlaytest"
|
"github.com/slackhq/nebula/overlay/overlaytest"
|
||||||
@@ -22,8 +21,6 @@ func newTestLighthouse() *LightHouse {
|
|||||||
l: test.NewLogger(),
|
l: test.NewLogger(),
|
||||||
addrMap: map[netip.Addr]*RemoteList{},
|
addrMap: map[netip.Addr]*RemoteList{},
|
||||||
queryChan: make(chan netip.Addr, 10),
|
queryChan: make(chan netip.Addr, 10),
|
||||||
// Nothing drains queryChan here, so an 11th query is dropped.
|
|
||||||
queryDropped: metrics.NilCounter{},
|
|
||||||
}
|
}
|
||||||
lighthouses := []netip.Addr{}
|
lighthouses := []netip.Addr{}
|
||||||
staticList := map[netip.Addr]struct{}{}
|
staticList := map[netip.Addr]struct{}{}
|
||||||
|
|||||||
+2
-1
@@ -203,7 +203,8 @@ func (c *Control) RebindUDPServer() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// A failure here means we are likely still pinned to the interface we came up on, so the rest of this is
|
// A failure here means we are likely still pinned to the interface we came up on, so the rest of this is
|
||||||
// unlikely to help. Say so instead of silently carrying on as if we rebound.
|
// unlikely to help. Say so instead of silently carrying on as if we rebound. Only the first writer is rebound;
|
||||||
|
// darwin's Rebind clears every listen routine's listener.
|
||||||
if err := c.f.outside.Rebind(); err != nil {
|
if err := c.f.outside.Rebind(); err != nil {
|
||||||
c.l.Error("Failed to rebind udp socket", "error", err)
|
c.l.Error("Failed to rebind udp socket", "error", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package nebula
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula/udp"
|
||||||
|
)
|
||||||
|
|
||||||
|
// establishedRemotes tells the udp conns that implement udp.EstablishedPeerConn which addresses are the current
|
||||||
|
// direct remote of at least one established tunnel. A hostinfo holds a reference on its remote while it is in the
|
||||||
|
// main hostmap, and SetRemote moves the reference; a relayed tunnel has no direct remote and holds none.
|
||||||
|
type establishedRemotes struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
conns []udp.EstablishedPeerConn
|
||||||
|
refs map[netip.AddrPort]int
|
||||||
|
}
|
||||||
|
|
||||||
|
// newEstablishedRemotes returns nil when no conn wants to know, which every method accepts.
|
||||||
|
func newEstablishedRemotes(conns []udp.Conn) *establishedRemotes {
|
||||||
|
var pc []udp.EstablishedPeerConn
|
||||||
|
for _, c := range conns {
|
||||||
|
if p, ok := c.(udp.EstablishedPeerConn); ok {
|
||||||
|
pc = append(pc, p)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(pc) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &establishedRemotes{conns: pc, refs: map[netip.AddrPort]int{}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// add makes hostinfo hold a reference on its remote, as it joins the main hostmap. A hostinfo holds references in
|
||||||
|
// one establishedRemotes at a time, so an add while it is in another is ignored.
|
||||||
|
func (e *establishedRemotes) add(hostinfo *HostInfo) {
|
||||||
|
if e == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.mu.Lock()
|
||||||
|
defer e.mu.Unlock()
|
||||||
|
if !hostinfo.establishedIn.CompareAndSwap(nil, e) && hostinfo.establishedIn.Load() != e {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.syncLocked(hostinfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
// remove drops hostinfo's reference, as it leaves the main hostmap.
|
||||||
|
func (e *establishedRemotes) remove(hostinfo *HostInfo) {
|
||||||
|
if e == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
e.mu.Lock()
|
||||||
|
defer e.mu.Unlock()
|
||||||
|
if hostinfo.establishedIn.CompareAndSwap(e, nil) {
|
||||||
|
e.syncLocked(hostinfo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// syncLocked moves hostinfo's reference to the remote it should hold now: its current remote while it is
|
||||||
|
// established, none otherwise. Reading both under mu makes the last call win however add, remove and SetRemote
|
||||||
|
// interleave. Only the establishedRemotes that hostinfo is in, or has just left, may call it, since
|
||||||
|
// hostinfo.establishedRemote is a reference in that one's refs.
|
||||||
|
func (e *establishedRemotes) syncLocked(hostinfo *HostInfo) {
|
||||||
|
var want netip.AddrPort
|
||||||
|
if hostinfo.establishedIn.Load() == e {
|
||||||
|
want = hostinfo.GetRemote()
|
||||||
|
}
|
||||||
|
held := hostinfo.establishedRemote
|
||||||
|
if want == held {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if held.IsValid() {
|
||||||
|
e.refs[held]--
|
||||||
|
if e.refs[held] == 0 {
|
||||||
|
delete(e.refs, held)
|
||||||
|
for _, c := range e.conns {
|
||||||
|
c.SetEstablishedPeer(held, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if want.IsValid() {
|
||||||
|
e.refs[want]++
|
||||||
|
if e.refs[want] == 1 {
|
||||||
|
for _, c := range e.conns {
|
||||||
|
c.SetEstablishedPeer(want, true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
hostinfo.establishedRemote = want
|
||||||
|
}
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
package nebula
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula/test"
|
||||||
|
"github.com/slackhq/nebula/udp"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
// establishedPeerConn records which destinations the hostmap has told it are established peers, and fails the test
|
||||||
|
// on a call that doesn't change anything, which would mean a reference count went wrong.
|
||||||
|
type establishedPeerConn struct {
|
||||||
|
udp.NoopConn
|
||||||
|
t *testing.T
|
||||||
|
mu sync.Mutex
|
||||||
|
peers map[netip.AddrPort]bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *establishedPeerConn) SetEstablishedPeer(dst netip.AddrPort, established bool) {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
assert.NotEqual(c.t, established, c.peers[dst], "SetEstablishedPeer(%v, %v) repeated", dst, established)
|
||||||
|
if established {
|
||||||
|
c.peers[dst] = true
|
||||||
|
} else {
|
||||||
|
delete(c.peers, dst)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *establishedPeerConn) established() []netip.AddrPort {
|
||||||
|
c.mu.Lock()
|
||||||
|
defer c.mu.Unlock()
|
||||||
|
var out []netip.AddrPort
|
||||||
|
for dst := range c.peers {
|
||||||
|
out = append(out, dst)
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
// newEstablishedTestHostMap returns a hostmap whose conns are a recording conn and one that doesn't track peers.
|
||||||
|
func newEstablishedTestHostMap(t *testing.T) (*HostMap, *establishedPeerConn) {
|
||||||
|
hm := newHostMap(test.NewLogger())
|
||||||
|
hm.preferredRanges.Store(&[]netip.Prefix{netip.MustParsePrefix("192.168.0.0/16")})
|
||||||
|
c := &establishedPeerConn{t: t, peers: map[netip.AddrPort]bool{}}
|
||||||
|
hm.established = newEstablishedRemotes([]udp.Conn{c, udp.NoopConn{}})
|
||||||
|
require.NotNil(t, hm.established)
|
||||||
|
return hm, c
|
||||||
|
}
|
||||||
|
|
||||||
|
func newEstablishedTestHostInfo(vpnAddr netip.Addr, index uint32) *HostInfo {
|
||||||
|
return &HostInfo{
|
||||||
|
vpnAddrs: []netip.Addr{vpnAddr},
|
||||||
|
localIndexId: index,
|
||||||
|
remotes: NewRemoteList([]netip.Addr{vpnAddr}, nil),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestNewEstablishedRemotesWithoutTrackingConns(t *testing.T) {
|
||||||
|
assert.Nil(t, newEstablishedRemotes([]udp.Conn{udp.NoopConn{}}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// A conn hears about a remote while at least one hostinfo in the main hostmap has it as its direct remote: from
|
||||||
|
// the add, through roaming and SetRemoteIfPreferred, until the last such hostinfo is deleted or retired by
|
||||||
|
// MaxHostInfosPerVpnIp. Pending and relayed hostinfos never count.
|
||||||
|
func TestHostMap_EstablishedRemotes(t *testing.T) {
|
||||||
|
hm, c := newEstablishedTestHostMap(t)
|
||||||
|
f := &Interface{}
|
||||||
|
a := netip.MustParseAddr("10.0.0.1")
|
||||||
|
r1 := netip.MustParseAddrPort("203.0.113.1:4242")
|
||||||
|
r2 := netip.MustParseAddrPort("203.0.113.2:4242")
|
||||||
|
r3 := netip.MustParseAddrPort("192.168.1.3:4242")
|
||||||
|
|
||||||
|
// A pending hostinfo, as a handshake sets its remote, isn't established.
|
||||||
|
h1 := newEstablishedTestHostInfo(a, 1)
|
||||||
|
h1.SetRemote(r1)
|
||||||
|
assert.Empty(t, c.established())
|
||||||
|
|
||||||
|
// Handshake completion adds it to the main hostmap.
|
||||||
|
hm.unlockedAddHostInfo(h1, f)
|
||||||
|
assert.ElementsMatch(t, []netip.AddrPort{r1}, c.established())
|
||||||
|
|
||||||
|
// A relayed tunnel has no direct remote.
|
||||||
|
relayed := newEstablishedTestHostInfo(netip.MustParseAddr("10.0.0.2"), 2)
|
||||||
|
hm.unlockedAddHostInfo(relayed, f)
|
||||||
|
assert.ElementsMatch(t, []netip.AddrPort{r1}, c.established())
|
||||||
|
|
||||||
|
// A rehandshake's new hostinfo shares the remote, which stays established until both are gone.
|
||||||
|
h3 := newEstablishedTestHostInfo(a, 3)
|
||||||
|
h3.SetRemote(r1)
|
||||||
|
hm.unlockedAddHostInfo(h3, f)
|
||||||
|
hm.DeleteHostInfo(h1)
|
||||||
|
assert.ElementsMatch(t, []netip.AddrPort{r1}, c.established())
|
||||||
|
|
||||||
|
// Roaming moves the reference.
|
||||||
|
h3.SetRemote(r2)
|
||||||
|
assert.ElementsMatch(t, []netip.AddrPort{r2}, c.established())
|
||||||
|
require.True(t, h3.SetRemoteIfPreferred(hm, ViaSender{UdpAddr: r3}))
|
||||||
|
assert.ElementsMatch(t, []netip.AddrPort{r3}, c.established())
|
||||||
|
|
||||||
|
// A relayed tunnel that hears from its peer directly roams onto a direct remote.
|
||||||
|
relayed.SetRemote(r1)
|
||||||
|
assert.ElementsMatch(t, []netip.AddrPort{r1, r3}, c.established())
|
||||||
|
hm.DeleteHostInfo(relayed)
|
||||||
|
|
||||||
|
// A deleted hostinfo lets go, and a SetRemote after that changes nothing.
|
||||||
|
hm.DeleteHostInfo(h3)
|
||||||
|
assert.Empty(t, c.established())
|
||||||
|
h3.SetRemote(r2)
|
||||||
|
assert.Empty(t, c.established())
|
||||||
|
hm.DeleteHostInfo(h3)
|
||||||
|
|
||||||
|
// Adding past MaxHostInfosPerVpnIp retires the oldest hostinfo and its remote.
|
||||||
|
var hs []*HostInfo
|
||||||
|
for i := range MaxHostInfosPerVpnIp + 1 {
|
||||||
|
h := newEstablishedTestHostInfo(a, uint32(10+i))
|
||||||
|
h.SetRemote(netip.AddrPortFrom(netip.MustParseAddr("198.51.100.1"), uint16(1000+i)))
|
||||||
|
hm.unlockedAddHostInfo(h, f)
|
||||||
|
hs = append(hs, h)
|
||||||
|
}
|
||||||
|
assert.Len(t, c.established(), MaxHostInfosPerVpnIp)
|
||||||
|
assert.NotContains(t, c.established(), hs[0].GetRemote())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Roaming on the receive path races tunnel teardown on the connection manager; whatever the order, a deleted
|
||||||
|
// hostinfo holds no reference.
|
||||||
|
func TestHostMap_EstablishedRemotesRoamRacesDelete(t *testing.T) {
|
||||||
|
hm, c := newEstablishedTestHostMap(t)
|
||||||
|
f := &Interface{}
|
||||||
|
a := netip.MustParseAddr("10.0.0.1")
|
||||||
|
for i := range 200 {
|
||||||
|
h := newEstablishedTestHostInfo(a, uint32(i+1))
|
||||||
|
h.SetRemote(netip.MustParseAddrPort("203.0.113.1:4242"))
|
||||||
|
hm.Lock()
|
||||||
|
hm.unlockedAddHostInfo(h, f)
|
||||||
|
hm.Unlock()
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
wg.Go(func() { h.SetRemote(netip.AddrPortFrom(netip.MustParseAddr("203.0.113.2"), uint16(i+1))) })
|
||||||
|
wg.Go(func() { hm.DeleteHostInfo(h) })
|
||||||
|
wg.Wait()
|
||||||
|
require.Empty(t, c.established(), "round %d", i)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A hostinfo holds its reference in the first tracking hostmap it joins; another's add and delete of it change
|
||||||
|
// nothing, so neither hostmap's counts go wrong.
|
||||||
|
func TestHostMap_EstablishedRemotesSingleOwner(t *testing.T) {
|
||||||
|
hm1, c1 := newEstablishedTestHostMap(t)
|
||||||
|
hm2, c2 := newEstablishedTestHostMap(t)
|
||||||
|
f := &Interface{}
|
||||||
|
r := netip.MustParseAddrPort("203.0.113.1:4242")
|
||||||
|
h := newEstablishedTestHostInfo(netip.MustParseAddr("10.0.0.1"), 1)
|
||||||
|
h.SetRemote(r)
|
||||||
|
|
||||||
|
hm1.unlockedAddHostInfo(h, f)
|
||||||
|
hm2.unlockedAddHostInfo(h, f)
|
||||||
|
assert.ElementsMatch(t, []netip.AddrPort{r}, c1.established())
|
||||||
|
assert.Empty(t, c2.established())
|
||||||
|
|
||||||
|
hm2.DeleteHostInfo(h)
|
||||||
|
assert.Equal(t, map[netip.AddrPort]int{r: 1}, hm1.established.refs)
|
||||||
|
assert.Empty(t, hm2.established.refs)
|
||||||
|
assert.ElementsMatch(t, []netip.AddrPort{r}, c1.established())
|
||||||
|
|
||||||
|
hm1.DeleteHostInfo(h)
|
||||||
|
assert.Empty(t, hm1.established.refs)
|
||||||
|
assert.Empty(t, hm2.established.refs)
|
||||||
|
assert.Empty(t, c1.established())
|
||||||
|
assert.Empty(t, c2.established())
|
||||||
|
}
|
||||||
+2
-2
@@ -410,8 +410,8 @@ logging:
|
|||||||
#try_interval: 100ms
|
#try_interval: 100ms
|
||||||
#retries: 20
|
#retries: 20
|
||||||
|
|
||||||
# query_buffer is the size of the buffer channel for querying lighthouses, drops are recorded in the lighthouse.query.dropped metric.
|
# query_buffer is the size of the buffer channel for querying lighthouses
|
||||||
#query_buffer: 1024
|
#query_buffer: 64
|
||||||
|
|
||||||
# trigger_buffer is the size of the buffer channel for quickly sending handshakes
|
# trigger_buffer is the size of the buffer channel for quickly sending handshakes
|
||||||
# after receiving the response for lighthouse queries
|
# after receiving the response for lighthouse queries
|
||||||
|
|||||||
+111
-98
@@ -14,7 +14,6 @@ import (
|
|||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
"github.com/gaissmai/bart"
|
||||||
@@ -29,23 +28,16 @@ type FirewallInterface interface {
|
|||||||
AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, cidr, localCidr string, caName string, caSha string) error
|
AddRule(incoming bool, proto uint8, startPort int32, endPort int32, groups []string, host string, cidr, localCidr string, caName string, caSha string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
// conn is a conntrack entry. Only expires changes after it is stored, a rules version change
|
|
||||||
// stores a replacement entry instead.
|
|
||||||
type conn struct {
|
type conn struct {
|
||||||
expires atomic.Uint32 // conntrack clock second when this entry expires, see FirewallConntrack.now
|
Expires time.Time // Time when this conntrack entry will expire
|
||||||
|
|
||||||
// record why the original connection passed the firewall, so we can re-validate
|
// record why the original connection passed the firewall, so we can re-validate
|
||||||
// after ruleset changes
|
// after ruleset changes. Note, rulesVersion is a uint16 so that these two
|
||||||
|
// fields pack for free after the uint32 above
|
||||||
incoming bool
|
incoming bool
|
||||||
rulesVersion uint16
|
rulesVersion uint16
|
||||||
}
|
}
|
||||||
|
|
||||||
func newConn(expires uint32, incoming bool, rulesVersion uint16) *conn {
|
|
||||||
c := &conn{incoming: incoming, rulesVersion: rulesVersion}
|
|
||||||
c.expires.Store(expires)
|
|
||||||
return c
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: need conntrack max tracked connections handling
|
// TODO: need conntrack max tracked connections handling
|
||||||
type Firewall struct {
|
type Firewall struct {
|
||||||
Conntrack *FirewallConntrack
|
Conntrack *FirewallConntrack
|
||||||
@@ -87,69 +79,11 @@ type firewallMetrics struct {
|
|||||||
droppedNoRule metrics.Counter
|
droppedNoRule metrics.Counter
|
||||||
}
|
}
|
||||||
|
|
||||||
// FirewallConntrack is safe for concurrent use by every routine without a lock.
|
|
||||||
type FirewallConntrack struct {
|
type FirewallConntrack struct {
|
||||||
conns sync.Map // firewall.Packet -> *conn
|
sync.Mutex
|
||||||
count atomic.Int64 // entries in conns, which sync.Map can't tell us
|
|
||||||
now atomic.Uint32 // the conntrack clock: whole seconds since epoch, kept current by Run
|
|
||||||
epoch time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
func newFirewallConntrack() *FirewallConntrack {
|
Conns map[firewall.Packet]*conn
|
||||||
return &FirewallConntrack{epoch: time.Now()}
|
TimerWheel *TimerWheel[firewall.Packet]
|
||||||
}
|
|
||||||
|
|
||||||
// Run advances the conntrack clock every second and sweeps out expired entries every minute,
|
|
||||||
// until ctx is done. Reading a shared clock is much cheaper than asking the OS on every packet.
|
|
||||||
func (ct *FirewallConntrack) Run(ctx context.Context) {
|
|
||||||
t := time.NewTicker(time.Second)
|
|
||||||
defer t.Stop()
|
|
||||||
var nextSweep uint32
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-ctx.Done():
|
|
||||||
return
|
|
||||||
case <-t.C:
|
|
||||||
// Measured from epoch rather than counted, so a late tick can't slow the clock down
|
|
||||||
now := uint32(time.Since(ct.epoch) / time.Second)
|
|
||||||
ct.now.Store(now)
|
|
||||||
if now >= nextSweep {
|
|
||||||
ct.sweep(now)
|
|
||||||
nextSweep = now + 60
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// sweep deletes entries that expired at or before now.
|
|
||||||
func (ct *FirewallConntrack) sweep(now uint32) {
|
|
||||||
ct.conns.Range(func(k, v any) bool {
|
|
||||||
if v.(*conn).expires.Load() <= now {
|
|
||||||
ct.delete(k.(firewall.Packet), v.(*conn))
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ct *FirewallConntrack) store(fp firewall.Packet, c *conn) {
|
|
||||||
if _, replaced := ct.conns.Swap(fp, c); !replaced {
|
|
||||||
ct.count.Add(1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// delete removes fp's entry if it is still c, so a newer entry stored by another routine survives
|
|
||||||
func (ct *FirewallConntrack) delete(fp firewall.Packet, c *conn) {
|
|
||||||
if ct.conns.CompareAndDelete(fp, c) {
|
|
||||||
ct.count.Add(-1)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// clear deletes every entry
|
|
||||||
func (ct *FirewallConntrack) clear() {
|
|
||||||
ct.conns.Range(func(k, v any) bool {
|
|
||||||
ct.delete(k.(firewall.Packet), v.(*conn))
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// FirewallTable is the entry point for a rule, the evaluation order is:
|
// FirewallTable is the entry point for a rule, the evaluation order is:
|
||||||
@@ -198,10 +132,26 @@ type firewallLocalCIDR struct {
|
|||||||
LocalCIDR *bart.Lite
|
LocalCIDR *bart.Lite
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewFirewall creates a new Firewall object.
|
// NewFirewall creates a new Firewall object. A TimerWheel is created for you from the provided timeouts.
|
||||||
// The certificate provided should be the highest version loaded in memory.
|
// The certificate provided should be the highest version loaded in memory.
|
||||||
func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Duration, c cert.Certificate) *Firewall {
|
func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Duration, c cert.Certificate) *Firewall {
|
||||||
//TODO: error on 0 duration
|
//TODO: error on 0 duration
|
||||||
|
var tmin, tmax time.Duration
|
||||||
|
|
||||||
|
if tcpTimeout < UDPTimeout {
|
||||||
|
tmin = tcpTimeout
|
||||||
|
tmax = UDPTimeout
|
||||||
|
} else {
|
||||||
|
tmin = UDPTimeout
|
||||||
|
tmax = tcpTimeout
|
||||||
|
}
|
||||||
|
|
||||||
|
if defaultTimeout < tmin {
|
||||||
|
tmin = defaultTimeout
|
||||||
|
} else if defaultTimeout > tmax {
|
||||||
|
tmax = defaultTimeout
|
||||||
|
}
|
||||||
|
|
||||||
routableNetworks := new(bart.Lite)
|
routableNetworks := new(bart.Lite)
|
||||||
var assignedNetworks []netip.Prefix
|
var assignedNetworks []netip.Prefix
|
||||||
for _, network := range c.Networks() {
|
for _, network := range c.Networks() {
|
||||||
@@ -216,7 +166,10 @@ func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Dur
|
|||||||
}
|
}
|
||||||
|
|
||||||
return &Firewall{
|
return &Firewall{
|
||||||
Conntrack: newFirewallConntrack(),
|
Conntrack: &FirewallConntrack{
|
||||||
|
Conns: make(map[firewall.Packet]*conn),
|
||||||
|
TimerWheel: NewTimerWheel[firewall.Packet](tmin, tmax),
|
||||||
|
},
|
||||||
InRules: newFirewallTable(),
|
InRules: newFirewallTable(),
|
||||||
OutRules: newFirewallTable(),
|
OutRules: newFirewallTable(),
|
||||||
TCPTimeout: tcpTimeout,
|
TCPTimeout: tcpTimeout,
|
||||||
@@ -470,7 +423,7 @@ var ErrNoMatchingRule = errors.New("no matching rule in firewall table")
|
|||||||
|
|
||||||
// Drop returns an error if the packet should be dropped, explaining why. It
|
// Drop returns an error if the packet should be dropped, explaining why. It
|
||||||
// returns nil if the packet should not be dropped.
|
// returns nil if the packet should not be dropped.
|
||||||
func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *cert.CAPool) error {
|
func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) error {
|
||||||
// Make sure remote address matches nebula certificate, and determine how to treat it
|
// Make sure remote address matches nebula certificate, and determine how to treat it
|
||||||
if h.networks == nil {
|
if h.networks == nil {
|
||||||
// Simple case: Certificate has one address and no unsafe networks
|
// Simple case: Certificate has one address and no unsafe networks
|
||||||
@@ -505,7 +458,7 @@ func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Check if we spoke to this tuple, if we did then allow this packet
|
// Check if we spoke to this tuple, if we did then allow this packet
|
||||||
if f.inConns(fp, h, caPool) {
|
if f.inConns(fp, h, caPool, localCache) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -541,19 +494,36 @@ func (f *Firewall) Destroy() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (f *Firewall) EmitStats() {
|
func (f *Firewall) EmitStats() {
|
||||||
metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(f.Conntrack.count.Load())
|
conntrack := f.Conntrack
|
||||||
|
conntrack.Lock()
|
||||||
|
conntrackCount := len(conntrack.Conns)
|
||||||
|
conntrack.Unlock()
|
||||||
|
metrics.GetOrRegisterGauge("firewall.conntrack.count", nil).Update(int64(conntrackCount))
|
||||||
metrics.GetOrRegisterGauge("firewall.rules.version", nil).Update(int64(f.rulesVersion))
|
metrics.GetOrRegisterGauge("firewall.rules.version", nil).Update(int64(f.rulesVersion))
|
||||||
metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
|
metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool) bool {
|
func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) bool {
|
||||||
|
if localCache != nil {
|
||||||
|
if _, ok := localCache[fp]; ok {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
conntrack := f.Conntrack
|
conntrack := f.Conntrack
|
||||||
v, ok := conntrack.conns.Load(fp)
|
conntrack.Lock()
|
||||||
|
|
||||||
|
// Purge every time we test
|
||||||
|
ep, has := conntrack.TimerWheel.Purge()
|
||||||
|
if has {
|
||||||
|
f.evict(ep)
|
||||||
|
}
|
||||||
|
|
||||||
|
c, ok := conntrack.Conns[fp]
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
|
conntrack.Unlock()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
c := v.(*conn)
|
|
||||||
expires := conntrack.now.Load() + f.timeout(fp.Protocol)
|
|
||||||
|
|
||||||
if c.rulesVersion != f.rulesVersion {
|
if c.rulesVersion != f.rulesVersion {
|
||||||
// This conntrack entry was for an older rule set, validate
|
// This conntrack entry was for an older rule set, validate
|
||||||
@@ -573,7 +543,8 @@ func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool)
|
|||||||
"oldRulesVersion", c.rulesVersion,
|
"oldRulesVersion", c.rulesVersion,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
conntrack.delete(fp, c)
|
delete(conntrack.Conns, fp)
|
||||||
|
conntrack.Unlock()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -586,35 +557,77 @@ func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool)
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
conntrack.store(fp, newConn(expires, c.incoming, f.rulesVersion))
|
c.rulesVersion = f.rulesVersion
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Most packets land in the same second as the one before, skip writing an unchanged expiry
|
switch fp.Protocol {
|
||||||
if c.expires.Load() != expires {
|
case iputil.IPProtocolTCP:
|
||||||
c.expires.Store(expires)
|
c.Expires = time.Now().Add(f.TCPTimeout)
|
||||||
|
case iputil.IPProtocolUDP:
|
||||||
|
c.Expires = time.Now().Add(f.UDPTimeout)
|
||||||
|
default:
|
||||||
|
c.Expires = time.Now().Add(f.DefaultTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
conntrack.Unlock()
|
||||||
|
|
||||||
|
if localCache != nil {
|
||||||
|
localCache[fp] = struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Firewall) addConn(fp firewall.Packet, incoming bool) {
|
func (f *Firewall) addConn(fp firewall.Packet, incoming bool) {
|
||||||
|
var timeout time.Duration
|
||||||
|
c := &conn{}
|
||||||
|
|
||||||
|
switch fp.Protocol {
|
||||||
|
case iputil.IPProtocolTCP:
|
||||||
|
timeout = f.TCPTimeout
|
||||||
|
case iputil.IPProtocolUDP:
|
||||||
|
timeout = f.UDPTimeout
|
||||||
|
default:
|
||||||
|
timeout = f.DefaultTimeout
|
||||||
|
}
|
||||||
|
|
||||||
|
conntrack := f.Conntrack
|
||||||
|
conntrack.Lock()
|
||||||
|
if _, ok := conntrack.Conns[fp]; !ok {
|
||||||
|
conntrack.TimerWheel.Advance(time.Now())
|
||||||
|
conntrack.TimerWheel.Add(fp, timeout)
|
||||||
|
}
|
||||||
|
|
||||||
// Record which rulesVersion allowed this connection, so we can retest after
|
// Record which rulesVersion allowed this connection, so we can retest after
|
||||||
// firewall reload
|
// firewall reload
|
||||||
conntrack := f.Conntrack
|
c.incoming = incoming
|
||||||
conntrack.store(fp, newConn(conntrack.now.Load()+f.timeout(fp.Protocol), incoming, f.rulesVersion))
|
c.rulesVersion = f.rulesVersion
|
||||||
|
c.Expires = time.Now().Add(timeout)
|
||||||
|
conntrack.Conns[fp] = c
|
||||||
|
conntrack.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// timeout returns how many seconds a conntrack entry for proto lives past its last packet
|
// Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
|
||||||
func (f *Firewall) timeout(proto uint8) uint32 {
|
// Caller must own the connMutex lock!
|
||||||
switch proto {
|
func (f *Firewall) evict(p firewall.Packet) {
|
||||||
case iputil.IPProtocolTCP:
|
// Are we still tracking this conn?
|
||||||
return uint32(f.TCPTimeout / time.Second)
|
conntrack := f.Conntrack
|
||||||
case iputil.IPProtocolUDP:
|
t, ok := conntrack.Conns[p]
|
||||||
return uint32(f.UDPTimeout / time.Second)
|
if !ok {
|
||||||
default:
|
return
|
||||||
return uint32(f.DefaultTimeout / time.Second)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
newT := t.Expires.Sub(time.Now())
|
||||||
|
|
||||||
|
// Timeout is in the future, re-add the timer
|
||||||
|
if newT > 0 {
|
||||||
|
conntrack.TimerWheel.Advance(time.Now())
|
||||||
|
conntrack.TimerWheel.Add(p, newT)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// This conn is done
|
||||||
|
delete(conntrack.Conns, p)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
|
func (ft *FirewallTable) match(p firewall.Packet, incoming bool, c *cert.CachedCertificate, caPool *cert.CAPool) bool {
|
||||||
|
|||||||
@@ -0,0 +1,69 @@
|
|||||||
|
package firewall
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"log/slog"
|
||||||
|
"sync/atomic"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula/logging"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ConntrackCache is used as a local routine cache to know if a given flow
|
||||||
|
// has been seen in the conntrack table.
|
||||||
|
type ConntrackCache map[Packet]struct{}
|
||||||
|
|
||||||
|
type ConntrackCacheTicker struct {
|
||||||
|
cacheV uint64
|
||||||
|
cacheTick atomic.Uint64
|
||||||
|
|
||||||
|
l *slog.Logger
|
||||||
|
cache ConntrackCache
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewConntrackCacheTicker(ctx context.Context, l *slog.Logger, d time.Duration) *ConntrackCacheTicker {
|
||||||
|
if d == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
c := &ConntrackCacheTicker{
|
||||||
|
l: l,
|
||||||
|
cache: ConntrackCache{},
|
||||||
|
}
|
||||||
|
|
||||||
|
go c.tick(ctx, d)
|
||||||
|
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *ConntrackCacheTicker) tick(ctx context.Context, d time.Duration) {
|
||||||
|
t := time.NewTicker(d)
|
||||||
|
defer t.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
case <-t.C:
|
||||||
|
c.cacheTick.Add(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get checks if the cache ticker has moved to the next version before returning
|
||||||
|
// the map. If it has moved, we reset the map.
|
||||||
|
func (c *ConntrackCacheTicker) Get() ConntrackCache {
|
||||||
|
if c == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if tick := c.cacheTick.Load(); tick != c.cacheV {
|
||||||
|
c.cacheV = tick
|
||||||
|
if ll := len(c.cache); ll > 0 {
|
||||||
|
if c.l.Enabled(context.Background(), logging.LevelTrace) {
|
||||||
|
c.l.Log(context.Background(), logging.LevelTrace, "resetting conntrack cache", "len", ll)
|
||||||
|
}
|
||||||
|
c.cache = make(ConntrackCache, ll)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return c.cache
|
||||||
|
}
|
||||||
@@ -0,0 +1,70 @@
|
|||||||
|
package firewall
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"log/slog"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula/logging"
|
||||||
|
"github.com/slackhq/nebula/test"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
)
|
||||||
|
|
||||||
|
// The tests below pin the log format produced by ConntrackCacheTicker.Get
|
||||||
|
// so changes cannot silently break what operators are grepping for. The
|
||||||
|
// ticker's internal state (cache + cacheTick) is poked directly to avoid
|
||||||
|
// racing a goroutine-driven tick in tests.
|
||||||
|
|
||||||
|
func newFixedTicker(t *testing.T, l *slog.Logger, cacheLen int) *ConntrackCacheTicker {
|
||||||
|
t.Helper()
|
||||||
|
c := &ConntrackCacheTicker{
|
||||||
|
l: l,
|
||||||
|
cache: make(ConntrackCache, cacheLen),
|
||||||
|
}
|
||||||
|
for i := range cacheLen {
|
||||||
|
c.cache[Packet{LocalPort: uint16(i) + 1}] = struct{}{}
|
||||||
|
}
|
||||||
|
c.cacheTick.Store(1) // cacheV starts at 0, so Get() takes the reset path
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConntrackCacheTicker_Get_TextFormat(t *testing.T) {
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
l := test.NewLoggerWithOutputAndLevel(buf, logging.LevelTrace)
|
||||||
|
|
||||||
|
c := newFixedTicker(t, l, 3)
|
||||||
|
c.Get()
|
||||||
|
|
||||||
|
assert.Equal(t, "level=DEBUG-4 msg=\"resetting conntrack cache\" len=3\n", buf.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConntrackCacheTicker_Get_JSONFormat(t *testing.T) {
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
l := test.NewJSONLoggerWithOutput(buf, logging.LevelTrace)
|
||||||
|
|
||||||
|
c := newFixedTicker(t, l, 2)
|
||||||
|
c.Get()
|
||||||
|
|
||||||
|
assert.JSONEq(t, `{"level":"DEBUG-4","msg":"resetting conntrack cache","len":2}`, strings.TrimSpace(buf.String()))
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConntrackCacheTicker_Get_QuietBelowTrace(t *testing.T) {
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
l := test.NewLoggerWithOutputAndLevel(buf, slog.LevelDebug)
|
||||||
|
|
||||||
|
c := newFixedTicker(t, l, 5)
|
||||||
|
c.Get()
|
||||||
|
|
||||||
|
assert.Empty(t, buf.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConntrackCacheTicker_Get_QuietWhenCacheEmpty(t *testing.T) {
|
||||||
|
buf := &bytes.Buffer{}
|
||||||
|
l := test.NewLoggerWithOutputAndLevel(buf, logging.LevelTrace)
|
||||||
|
|
||||||
|
c := newFixedTicker(t, l, 0)
|
||||||
|
c.Get()
|
||||||
|
|
||||||
|
assert.Empty(t, buf.String())
|
||||||
|
}
|
||||||
@@ -26,10 +26,6 @@ type Packet struct {
|
|||||||
RemotePort uint16
|
RemotePort uint16
|
||||||
Protocol uint8
|
Protocol uint8
|
||||||
Fragment bool
|
Fragment bool
|
||||||
|
|
||||||
// pad fills what would otherwise be compiler padding. A Packet with no padding hashes as one
|
|
||||||
// block of memory, which makes it a much faster map key. Always zero.
|
|
||||||
pad [2]byte
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fp *Packet) Copy() *Packet {
|
func (fp *Packet) Copy() *Packet {
|
||||||
|
|||||||
+100
-126
@@ -2,7 +2,6 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
|
||||||
"errors"
|
"errors"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"math"
|
"math"
|
||||||
@@ -24,12 +23,39 @@ func TestNewFirewall(t *testing.T) {
|
|||||||
l := test.NewLogger()
|
l := test.NewLogger()
|
||||||
c := &dummyCert{}
|
c := &dummyCert{}
|
||||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c)
|
||||||
assert.NotNil(t, fw.Conntrack)
|
conntrack := fw.Conntrack
|
||||||
|
assert.NotNil(t, conntrack)
|
||||||
|
assert.NotNil(t, conntrack.Conns)
|
||||||
|
assert.NotNil(t, conntrack.TimerWheel)
|
||||||
assert.NotNil(t, fw.InRules)
|
assert.NotNil(t, fw.InRules)
|
||||||
assert.NotNil(t, fw.OutRules)
|
assert.NotNil(t, fw.OutRules)
|
||||||
assert.Equal(t, time.Second, fw.TCPTimeout)
|
assert.Equal(t, time.Second, fw.TCPTimeout)
|
||||||
assert.Equal(t, time.Minute, fw.UDPTimeout)
|
assert.Equal(t, time.Minute, fw.UDPTimeout)
|
||||||
assert.Equal(t, time.Hour, fw.DefaultTimeout)
|
assert.Equal(t, time.Hour, fw.DefaultTimeout)
|
||||||
|
|
||||||
|
assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
|
||||||
|
assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
|
||||||
|
assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
|
||||||
|
|
||||||
|
fw = NewFirewall(l, time.Second, time.Hour, time.Minute, c)
|
||||||
|
assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
|
||||||
|
assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
|
||||||
|
|
||||||
|
fw = NewFirewall(l, time.Hour, time.Second, time.Minute, c)
|
||||||
|
assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
|
||||||
|
assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
|
||||||
|
|
||||||
|
fw = NewFirewall(l, time.Hour, time.Minute, time.Second, c)
|
||||||
|
assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
|
||||||
|
assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
|
||||||
|
|
||||||
|
fw = NewFirewall(l, time.Minute, time.Hour, time.Second, c)
|
||||||
|
assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
|
||||||
|
assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
|
||||||
|
|
||||||
|
fw = NewFirewall(l, time.Minute, time.Second, time.Hour, c)
|
||||||
|
assert.Equal(t, time.Hour, conntrack.TimerWheel.wheelDuration)
|
||||||
|
assert.Equal(t, 3602, conntrack.TimerWheel.wheelLen)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirewall_AddRule(t *testing.T) {
|
func TestFirewall_AddRule(t *testing.T) {
|
||||||
@@ -186,44 +212,44 @@ func TestFirewall_Drop(t *testing.T) {
|
|||||||
cp := cert.NewCAPool()
|
cp := cert.NewCAPool()
|
||||||
|
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp))
|
assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp, nil))
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
require.NoError(t, fw.Drop(p, true, &h, cp))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
// Allow outbound because conntrack
|
// Allow outbound because conntrack
|
||||||
require.NoError(t, fw.Drop(p, false, &h, cp))
|
require.NoError(t, fw.Drop(p, false, &h, cp, nil))
|
||||||
|
|
||||||
// test remote mismatch
|
// test remote mismatch
|
||||||
oldRemote := p.RemoteAddr
|
oldRemote := p.RemoteAddr
|
||||||
p.RemoteAddr = netip.MustParseAddr("1.2.3.10")
|
p.RemoteAddr = netip.MustParseAddr("1.2.3.10")
|
||||||
assert.Equal(t, fw.Drop(p, false, &h, cp), ErrInvalidRemoteIP)
|
assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrInvalidRemoteIP)
|
||||||
p.RemoteAddr = oldRemote
|
p.RemoteAddr = oldRemote
|
||||||
|
|
||||||
// ensure signer doesn't get in the way of group checks
|
// ensure signer doesn't get in the way of group checks
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum"))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum"))
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum-bad"))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum-bad"))
|
||||||
assert.Equal(t, fw.Drop(p, true, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
|
||||||
|
|
||||||
// test caSha doesn't drop on match
|
// test caSha doesn't drop on match
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum-bad"))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum-bad"))
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum"))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum"))
|
||||||
require.NoError(t, fw.Drop(p, true, &h, cp))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
|
|
||||||
// ensure ca name doesn't get in the way of group checks
|
// ensure ca name doesn't get in the way of group checks
|
||||||
cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
|
cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good", ""))
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good-bad", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good-bad", ""))
|
||||||
assert.Equal(t, fw.Drop(p, true, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
|
||||||
|
|
||||||
// test caName doesn't drop on match
|
// test caName doesn't drop on match
|
||||||
cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
|
cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good-bad", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good-bad", ""))
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good", ""))
|
||||||
require.NoError(t, fw.Drop(p, true, &h, cp))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirewall_DropV6(t *testing.T) {
|
func TestFirewall_DropV6(t *testing.T) {
|
||||||
@@ -264,44 +290,44 @@ func TestFirewall_DropV6(t *testing.T) {
|
|||||||
cp := cert.NewCAPool()
|
cp := cert.NewCAPool()
|
||||||
|
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp))
|
assert.Equal(t, ErrNoMatchingRule, fw.Drop(p, false, &h, cp, nil))
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
require.NoError(t, fw.Drop(p, true, &h, cp))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
// Allow outbound because conntrack
|
// Allow outbound because conntrack
|
||||||
require.NoError(t, fw.Drop(p, false, &h, cp))
|
require.NoError(t, fw.Drop(p, false, &h, cp, nil))
|
||||||
|
|
||||||
// test remote mismatch
|
// test remote mismatch
|
||||||
oldRemote := p.RemoteAddr
|
oldRemote := p.RemoteAddr
|
||||||
p.RemoteAddr = netip.MustParseAddr("fd12::56")
|
p.RemoteAddr = netip.MustParseAddr("fd12::56")
|
||||||
assert.Equal(t, fw.Drop(p, false, &h, cp), ErrInvalidRemoteIP)
|
assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrInvalidRemoteIP)
|
||||||
p.RemoteAddr = oldRemote
|
p.RemoteAddr = oldRemote
|
||||||
|
|
||||||
// ensure signer doesn't get in the way of group checks
|
// ensure signer doesn't get in the way of group checks
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum"))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum"))
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum-bad"))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum-bad"))
|
||||||
assert.Equal(t, fw.Drop(p, true, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
|
||||||
|
|
||||||
// test caSha doesn't drop on match
|
// test caSha doesn't drop on match
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum-bad"))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "", "signer-shasum-bad"))
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum"))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "", "signer-shasum"))
|
||||||
require.NoError(t, fw.Drop(p, true, &h, cp))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
|
|
||||||
// ensure ca name doesn't get in the way of group checks
|
// ensure ca name doesn't get in the way of group checks
|
||||||
cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
|
cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good", ""))
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good-bad", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good-bad", ""))
|
||||||
assert.Equal(t, fw.Drop(p, true, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(p, true, &h, cp, nil), ErrNoMatchingRule)
|
||||||
|
|
||||||
// test caName doesn't drop on match
|
// test caName doesn't drop on match
|
||||||
cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
|
cp.CAs["signer-shasum"] = &cert.CachedCertificate{Certificate: &dummyCert{name: "ca-good"}}
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, &c)
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good-bad", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"nope"}, "", "", "", "ca-good-bad", ""))
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"default-group"}, "", "", "", "ca-good", ""))
|
||||||
require.NoError(t, fw.Drop(p, true, &h, cp))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkFirewallTable_match(b *testing.B) {
|
func BenchmarkFirewallTable_match(b *testing.B) {
|
||||||
@@ -508,10 +534,10 @@ func TestFirewall_Drop2(t *testing.T) {
|
|||||||
cp := cert.NewCAPool()
|
cp := cert.NewCAPool()
|
||||||
|
|
||||||
// h1/c1 lacks the proper groups
|
// h1/c1 lacks the proper groups
|
||||||
require.ErrorIs(t, fw.Drop(p, true, &h1, cp), ErrNoMatchingRule)
|
require.ErrorIs(t, fw.Drop(p, true, &h1, cp, nil), ErrNoMatchingRule)
|
||||||
// c has the proper groups
|
// c has the proper groups
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
require.NoError(t, fw.Drop(p, true, &h, cp))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirewall_Drop3(t *testing.T) {
|
func TestFirewall_Drop3(t *testing.T) {
|
||||||
@@ -588,18 +614,18 @@ func TestFirewall_Drop3(t *testing.T) {
|
|||||||
cp := cert.NewCAPool()
|
cp := cert.NewCAPool()
|
||||||
|
|
||||||
// c1 should pass because host match
|
// c1 should pass because host match
|
||||||
require.NoError(t, fw.Drop(p, true, &h1, cp))
|
require.NoError(t, fw.Drop(p, true, &h1, cp, nil))
|
||||||
// c2 should pass because ca sha match
|
// c2 should pass because ca sha match
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
require.NoError(t, fw.Drop(p, true, &h2, cp))
|
require.NoError(t, fw.Drop(p, true, &h2, cp, nil))
|
||||||
// c3 should fail because no match
|
// c3 should fail because no match
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
assert.Equal(t, fw.Drop(p, true, &h3, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(p, true, &h3, cp, nil), ErrNoMatchingRule)
|
||||||
|
|
||||||
// Test a remote address match
|
// Test a remote address match
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "1.2.3.4/24", "", "", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "1.2.3.4/24", "", "", ""))
|
||||||
require.NoError(t, fw.Drop(p, true, &h1, cp))
|
require.NoError(t, fw.Drop(p, true, &h1, cp, nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirewall_Drop3V6(t *testing.T) {
|
func TestFirewall_Drop3V6(t *testing.T) {
|
||||||
@@ -636,7 +662,7 @@ func TestFirewall_Drop3V6(t *testing.T) {
|
|||||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
||||||
cp := cert.NewCAPool()
|
cp := cert.NewCAPool()
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "fd12::34/120", "", "", ""))
|
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 1, 1, []string{}, "", "fd12::34/120", "", "", ""))
|
||||||
require.NoError(t, fw.Drop(p, true, &h, cp))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirewall_DropConntrackReload(t *testing.T) {
|
func TestFirewall_DropConntrackReload(t *testing.T) {
|
||||||
@@ -677,12 +703,12 @@ func TestFirewall_DropConntrackReload(t *testing.T) {
|
|||||||
cp := cert.NewCAPool()
|
cp := cert.NewCAPool()
|
||||||
|
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, fw.Drop(p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
require.NoError(t, fw.Drop(p, true, &h, cp))
|
require.NoError(t, fw.Drop(p, true, &h, cp, nil))
|
||||||
// Allow outbound because conntrack
|
// Allow outbound because conntrack
|
||||||
require.NoError(t, fw.Drop(p, false, &h, cp))
|
require.NoError(t, fw.Drop(p, false, &h, cp, nil))
|
||||||
|
|
||||||
oldFw := fw
|
oldFw := fw
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
||||||
@@ -691,7 +717,7 @@ func TestFirewall_DropConntrackReload(t *testing.T) {
|
|||||||
fw.rulesVersion = oldFw.rulesVersion + 1
|
fw.rulesVersion = oldFw.rulesVersion + 1
|
||||||
|
|
||||||
// Allow outbound because conntrack and new rules allow port 10
|
// Allow outbound because conntrack and new rules allow port 10
|
||||||
require.NoError(t, fw.Drop(p, false, &h, cp))
|
require.NoError(t, fw.Drop(p, false, &h, cp, nil))
|
||||||
|
|
||||||
oldFw = fw
|
oldFw = fw
|
||||||
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
fw = NewFirewall(l, time.Second, time.Minute, time.Hour, c.Certificate)
|
||||||
@@ -700,7 +726,7 @@ func TestFirewall_DropConntrackReload(t *testing.T) {
|
|||||||
fw.rulesVersion = oldFw.rulesVersion + 1
|
fw.rulesVersion = oldFw.rulesVersion + 1
|
||||||
|
|
||||||
// Drop outbound because conntrack doesn't match new ruleset
|
// Drop outbound because conntrack doesn't match new ruleset
|
||||||
assert.Equal(t, fw.Drop(p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
||||||
@@ -745,12 +771,12 @@ func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
|||||||
p.LocalPort = 0
|
p.LocalPort = 0
|
||||||
p.RemotePort = 0
|
p.RemotePort = 0
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
require.NoError(t, fw.Drop(*p, true, &h, cp))
|
require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
|
||||||
//now also allow outbound
|
//now also allow outbound
|
||||||
require.NoError(t, fw.Drop(*p, false, &h, cp))
|
require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("nonzero ports", func(t *testing.T) {
|
t.Run("nonzero ports", func(t *testing.T) {
|
||||||
@@ -758,12 +784,12 @@ func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
|||||||
p.LocalPort = 0xabcd
|
p.LocalPort = 0xabcd
|
||||||
p.RemotePort = 0x1234
|
p.RemotePort = 0x1234
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
require.NoError(t, fw.Drop(*p, true, &h, cp))
|
require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
|
||||||
//now also allow outbound
|
//now also allow outbound
|
||||||
require.NoError(t, fw.Drop(*p, false, &h, cp))
|
require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -775,12 +801,12 @@ func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
|||||||
p.LocalPort = 0
|
p.LocalPort = 0
|
||||||
p.RemotePort = 0
|
p.RemotePort = 0
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
assert.Equal(t, fw.Drop(*p, true, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, true, &h, cp, nil), ErrNoMatchingRule)
|
||||||
//now also allow outbound
|
//now also allow outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("nonzero ports, still blocked", func(t *testing.T) {
|
t.Run("nonzero ports, still blocked", func(t *testing.T) {
|
||||||
@@ -788,12 +814,12 @@ func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
|||||||
p.LocalPort = 0xabcd
|
p.LocalPort = 0xabcd
|
||||||
p.RemotePort = 0x1234
|
p.RemotePort = 0x1234
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
assert.Equal(t, fw.Drop(*p, true, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, true, &h, cp, nil), ErrNoMatchingRule)
|
||||||
//now also allow outbound
|
//now also allow outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("nonzero, matching ports, still blocked", func(t *testing.T) {
|
t.Run("nonzero, matching ports, still blocked", func(t *testing.T) {
|
||||||
@@ -801,12 +827,12 @@ func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
|||||||
p.LocalPort = 80
|
p.LocalPort = 80
|
||||||
p.RemotePort = 80
|
p.RemotePort = 80
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
assert.Equal(t, fw.Drop(*p, true, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, true, &h, cp, nil), ErrNoMatchingRule)
|
||||||
//now also allow outbound
|
//now also allow outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
t.Run("Any proto, any port", func(t *testing.T) {
|
t.Run("Any proto, any port", func(t *testing.T) {
|
||||||
@@ -818,12 +844,12 @@ func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
|||||||
p.LocalPort = 0
|
p.LocalPort = 0
|
||||||
p.RemotePort = 0
|
p.RemotePort = 0
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
require.NoError(t, fw.Drop(*p, true, &h, cp))
|
require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
|
||||||
//now also allow outbound
|
//now also allow outbound
|
||||||
require.NoError(t, fw.Drop(*p, false, &h, cp))
|
require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
|
||||||
})
|
})
|
||||||
|
|
||||||
t.Run("nonzero ports, allowed", func(t *testing.T) {
|
t.Run("nonzero ports, allowed", func(t *testing.T) {
|
||||||
@@ -832,15 +858,15 @@ func TestFirewall_ICMPPortBehavior(t *testing.T) {
|
|||||||
p.LocalPort = 0xabcd
|
p.LocalPort = 0xabcd
|
||||||
p.RemotePort = 0x1234
|
p.RemotePort = 0x1234
|
||||||
// Drop outbound
|
// Drop outbound
|
||||||
assert.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
assert.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
// Allow inbound
|
// Allow inbound
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
require.NoError(t, fw.Drop(*p, true, &h, cp))
|
require.NoError(t, fw.Drop(*p, true, &h, cp, nil))
|
||||||
//now also allow outbound
|
//now also allow outbound
|
||||||
require.NoError(t, fw.Drop(*p, false, &h, cp))
|
require.NoError(t, fw.Drop(*p, false, &h, cp, nil))
|
||||||
//different ID is blocked
|
//different ID is blocked
|
||||||
p.RemotePort++
|
p.RemotePort++
|
||||||
require.Equal(t, fw.Drop(*p, false, &h, cp), ErrNoMatchingRule)
|
require.Equal(t, fw.Drop(*p, false, &h, cp, nil), ErrNoMatchingRule)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -888,7 +914,7 @@ func TestFirewall_DropIPSpoofing(t *testing.T) {
|
|||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
Fragment: false,
|
Fragment: false,
|
||||||
}
|
}
|
||||||
assert.Equal(t, fw.Drop(p, true, &h1, cp), ErrInvalidRemoteIP)
|
assert.Equal(t, fw.Drop(p, true, &h1, cp, nil), ErrInvalidRemoteIP)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirewall_ConntrackSourceSpoofingAcrossPeers(t *testing.T) {
|
func TestFirewall_ConntrackSourceSpoofingAcrossPeers(t *testing.T) {
|
||||||
@@ -939,84 +965,20 @@ func TestFirewall_ConntrackSourceSpoofingAcrossPeers(t *testing.T) {
|
|||||||
Protocol: iputil.IPProtocolUDP,
|
Protocol: iputil.IPProtocolUDP,
|
||||||
}
|
}
|
||||||
|
|
||||||
require.NoError(t, fw.Drop(flow, true, &victimHI, cp),
|
require.NoError(t, fw.Drop(flow, true, &victimHI, cp, nil),
|
||||||
"victim's own traffic from its own overlay IP must be allowed")
|
"victim's own traffic from its own overlay IP must be allowed")
|
||||||
|
|
||||||
unseen := flow
|
unseen := flow
|
||||||
unseen.RemotePort = 55001
|
unseen.RemotePort = 55001
|
||||||
assert.Equal(t, ErrInvalidRemoteIP, fw.Drop(unseen, true, &attackerHI, cp),
|
assert.Equal(t, ErrInvalidRemoteIP, fw.Drop(unseen, true, &attackerHI, cp, nil),
|
||||||
"sanity: attacker forging victim's source IP must be rejected when no conntrack entry exists")
|
"sanity: attacker forging victim's source IP must be rejected when no conntrack entry exists")
|
||||||
|
|
||||||
got := fw.Drop(flow, true, &attackerHI, cp)
|
got := fw.Drop(flow, true, &attackerHI, cp, nil)
|
||||||
t.Logf("attacker replaying victim's 4-tuple: Drop returned %v (nil == packet ALLOWED == spoof succeeded)", got)
|
t.Logf("attacker replaying victim's 4-tuple: Drop returned %v (nil == packet ALLOWED == spoof succeeded)", got)
|
||||||
assert.Equal(t, ErrInvalidRemoteIP, got,
|
assert.Equal(t, ErrInvalidRemoteIP, got,
|
||||||
"SECURITY: attacker spoofed victim's overlay source IP (192.0.2.2) by reusing an existing conntrack 4-tuple; Drop returned %v instead of rejecting", got)
|
"SECURITY: attacker spoofed victim's overlay source IP (192.0.2.2) by reusing an existing conntrack 4-tuple; Drop returned %v instead of rejecting", got)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestFirewallConntrack_sweep(t *testing.T) {
|
|
||||||
ct := newFirewallConntrack()
|
|
||||||
live := firewall.Packet{LocalPort: 1}
|
|
||||||
dead := firewall.Packet{LocalPort: 2}
|
|
||||||
ct.store(live, newConn(11, true, 0))
|
|
||||||
ct.store(dead, newConn(10, true, 0))
|
|
||||||
assert.Equal(t, int64(2), ct.count.Load())
|
|
||||||
|
|
||||||
ct.sweep(10)
|
|
||||||
_, ok := ct.conns.Load(live)
|
|
||||||
assert.True(t, ok)
|
|
||||||
_, ok = ct.conns.Load(dead)
|
|
||||||
assert.False(t, ok)
|
|
||||||
assert.Equal(t, int64(1), ct.count.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFirewallConntrack_storeAndDeleteCount(t *testing.T) {
|
|
||||||
ct := newFirewallConntrack()
|
|
||||||
fp := firewall.Packet{LocalPort: 1}
|
|
||||||
first := newConn(10, true, 0)
|
|
||||||
ct.store(fp, first)
|
|
||||||
|
|
||||||
// Replacing an entry doesn't add to the count
|
|
||||||
second := newConn(20, true, 1)
|
|
||||||
ct.store(fp, second)
|
|
||||||
assert.Equal(t, int64(1), ct.count.Load())
|
|
||||||
|
|
||||||
// Deleting a stale entry is a no-op, the newer one stays
|
|
||||||
ct.delete(fp, first)
|
|
||||||
v, ok := ct.conns.Load(fp)
|
|
||||||
assert.True(t, ok)
|
|
||||||
assert.Same(t, second, v)
|
|
||||||
assert.Equal(t, int64(1), ct.count.Load())
|
|
||||||
|
|
||||||
ct.delete(fp, second)
|
|
||||||
_, ok = ct.conns.Load(fp)
|
|
||||||
assert.False(t, ok)
|
|
||||||
assert.Equal(t, int64(0), ct.count.Load())
|
|
||||||
|
|
||||||
ct.store(fp, first)
|
|
||||||
ct.store(firewall.Packet{LocalPort: 2}, newConn(10, true, 0))
|
|
||||||
ct.clear()
|
|
||||||
assert.Equal(t, int64(0), ct.count.Load())
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFirewallConntrack_Run(t *testing.T) {
|
|
||||||
ct := newFirewallConntrack()
|
|
||||||
ct.epoch = time.Now().Add(-time.Hour)
|
|
||||||
ct.store(firewall.Packet{LocalPort: 1}, newConn(10, true, 0))
|
|
||||||
|
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
|
||||||
done := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
ct.Run(ctx)
|
|
||||||
close(done)
|
|
||||||
}()
|
|
||||||
|
|
||||||
// The first tick sets the clock to an hour in and sweeps the long expired entry
|
|
||||||
require.Eventually(t, func() bool { return ct.count.Load() == 0 }, 5*time.Second, 10*time.Millisecond)
|
|
||||||
assert.GreaterOrEqual(t, ct.now.Load(), uint32(3600))
|
|
||||||
cancel()
|
|
||||||
<-done
|
|
||||||
}
|
|
||||||
|
|
||||||
// BenchmarkFirewallDropConntrackHit measures Drop on an already-established flow
|
// BenchmarkFirewallDropConntrackHit measures Drop on an already-established flow
|
||||||
// (a conntrack hit). This is the fast path that the source-IP<->cert binding
|
// (a conntrack hit). This is the fast path that the source-IP<->cert binding
|
||||||
// reordering adds work to, so it quantifies the cost of moving the address checks
|
// reordering adds work to, so it quantifies the cost of moving the address checks
|
||||||
@@ -1025,6 +987,8 @@ func TestFirewallConntrack_Run(t *testing.T) {
|
|||||||
// so the remote-address check is a single netip.Addr compare.
|
// so the remote-address check is a single netip.Addr compare.
|
||||||
// - complex: peer cert has unsafe networks (h.networks populated), so the
|
// - complex: peer cert has unsafe networks (h.networks populated), so the
|
||||||
// remote-address check is a BART lookup.
|
// remote-address check is a BART lookup.
|
||||||
|
// - noCache/localCache: whether a per-batch ConntrackCache is supplied, which in
|
||||||
|
// the original code let the fast path skip straight past the address checks.
|
||||||
func BenchmarkFirewallDropConntrackHit(b *testing.B) {
|
func BenchmarkFirewallDropConntrackHit(b *testing.B) {
|
||||||
l := test.NewLoggerWithOutput(&bytes.Buffer{})
|
l := test.NewLoggerWithOutput(&bytes.Buffer{})
|
||||||
|
|
||||||
@@ -1074,9 +1038,12 @@ func BenchmarkFirewallDropConntrackHit(b *testing.B) {
|
|||||||
cases := []struct {
|
cases := []struct {
|
||||||
name string
|
name string
|
||||||
host *HostInfo
|
host *HostInfo
|
||||||
|
useCache bool
|
||||||
}{
|
}{
|
||||||
{"simple", simpleHost},
|
{"simple/noCache", simpleHost, false},
|
||||||
{"complex", complexHost},
|
{"simple/localCache", simpleHost, true},
|
||||||
|
{"complex/noCache", complexHost, false},
|
||||||
|
{"complex/localCache", complexHost, true},
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tc := range cases {
|
for _, tc := range cases {
|
||||||
@@ -1085,12 +1052,17 @@ func BenchmarkFirewallDropConntrackHit(b *testing.B) {
|
|||||||
require.NoError(b, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
require.NoError(b, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
||||||
|
|
||||||
// Establish the conntrack entry so every benchmarked Drop is a hit.
|
// Establish the conntrack entry so every benchmarked Drop is a hit.
|
||||||
require.NoError(b, fw.Drop(flow, true, tc.host, cp))
|
require.NoError(b, fw.Drop(flow, true, tc.host, cp, nil))
|
||||||
|
|
||||||
|
var cache firewall.ConntrackCache
|
||||||
|
if tc.useCache {
|
||||||
|
cache = firewall.ConntrackCache{}
|
||||||
|
}
|
||||||
|
|
||||||
b.ReportAllocs()
|
b.ReportAllocs()
|
||||||
b.ResetTimer()
|
b.ResetTimer()
|
||||||
for i := 0; i < b.N; i++ {
|
for i := 0; i < b.N; i++ {
|
||||||
if err := fw.Drop(flow, true, tc.host, cp); err != nil {
|
if err := fw.Drop(flow, true, tc.host, cp, cache); err != nil {
|
||||||
b.Fatal(err)
|
b.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1578,7 +1550,7 @@ func (c *testcase) Test(t *testing.T, fw *Firewall) {
|
|||||||
t.Helper()
|
t.Helper()
|
||||||
cp := cert.NewCAPool()
|
cp := cert.NewCAPool()
|
||||||
resetConntrack(fw)
|
resetConntrack(fw)
|
||||||
err := fw.Drop(c.p, true, c.h, cp)
|
err := fw.Drop(c.p, true, c.h, cp, nil)
|
||||||
if c.err == nil {
|
if c.err == nil {
|
||||||
require.NoError(t, err, "failed to not drop remote address %s", c.p.RemoteAddr)
|
require.NoError(t, err, "failed to not drop remote address %s", c.p.RemoteAddr)
|
||||||
} else {
|
} else {
|
||||||
@@ -1769,5 +1741,7 @@ func (mf *mockFirewall) AddRule(incoming bool, proto uint8, startPort int32, end
|
|||||||
}
|
}
|
||||||
|
|
||||||
func resetConntrack(fw *Firewall) {
|
func resetConntrack(fw *Firewall) {
|
||||||
fw.Conntrack.clear()
|
fw.Conntrack.Lock()
|
||||||
|
fw.Conntrack.Conns = map[firewall.Packet]*conn{}
|
||||||
|
fw.Conntrack.Unlock()
|
||||||
}
|
}
|
||||||
+16
@@ -69,6 +69,8 @@ type HostMap struct {
|
|||||||
Hosts map[netip.Addr]*HostInfo
|
Hosts map[netip.Addr]*HostInfo
|
||||||
moreHosts map[netip.Addr][]*HostInfo
|
moreHosts map[netip.Addr][]*HostInfo
|
||||||
preferredRanges atomic.Pointer[[]netip.Prefix]
|
preferredRanges atomic.Pointer[[]netip.Prefix]
|
||||||
|
// established hears about each hostinfo that joins or leaves the hostmap; nil when no conn wants to know.
|
||||||
|
established *establishedRemotes
|
||||||
l *slog.Logger
|
l *slog.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -276,6 +278,11 @@ type HostInfo struct {
|
|||||||
// This value will be behind against actual tunnel utilization in the hot path.
|
// This value will be behind against actual tunnel utilization in the hot path.
|
||||||
// This should only be used by the ConnectionManagers ticker routine.
|
// This should only be used by the ConnectionManagers ticker routine.
|
||||||
lastUsed time.Time
|
lastUsed time.Time
|
||||||
|
|
||||||
|
// establishedIn is set while the hostinfo is in a main hostmap whose conns track established remotes, and
|
||||||
|
// establishedRemote is the remote it holds a reference on there, guarded by establishedIn's mu.
|
||||||
|
establishedIn atomic.Pointer[establishedRemotes]
|
||||||
|
establishedRemote netip.AddrPort
|
||||||
}
|
}
|
||||||
|
|
||||||
type ViaSender struct {
|
type ViaSender struct {
|
||||||
@@ -516,6 +523,7 @@ func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
|
|||||||
if len(hm.Indexes) == 0 {
|
if len(hm.Indexes) == 0 {
|
||||||
hm.Indexes = map[uint32]*HostInfo{}
|
hm.Indexes = map[uint32]*HostInfo{}
|
||||||
}
|
}
|
||||||
|
hm.established.remove(hostinfo)
|
||||||
|
|
||||||
if hm.l.Enabled(context.Background(), slog.LevelDebug) {
|
if hm.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
hm.l.Debug("Hostmap hostInfo deleted",
|
hm.l.Debug("Hostmap hostInfo deleted",
|
||||||
@@ -662,6 +670,7 @@ func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
|
|||||||
|
|
||||||
hm.Indexes[hostinfo.localIndexId] = hostinfo
|
hm.Indexes[hostinfo.localIndexId] = hostinfo
|
||||||
hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
|
hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
|
||||||
|
hm.established.add(hostinfo)
|
||||||
|
|
||||||
hostinfo.markOut(f.rebindEpoch.Load())
|
hostinfo.markOut(f.rebindEpoch.Load())
|
||||||
if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
|
if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
|
||||||
@@ -842,6 +851,13 @@ func (i *HostInfo) SetRemote(remote netip.AddrPort) {
|
|||||||
if i.GetRemote() != remote {
|
if i.GetRemote() != remote {
|
||||||
i.remote.Store(&remote)
|
i.remote.Store(&remote)
|
||||||
i.remotes.LearnRemote(i.vpnAddrs[0], remote)
|
i.remotes.LearnRemote(i.vpnAddrs[0], remote)
|
||||||
|
if e := i.establishedIn.Load(); e != nil {
|
||||||
|
e.mu.Lock()
|
||||||
|
if i.establishedIn.Load() == e {
|
||||||
|
e.syncLocked(i)
|
||||||
|
}
|
||||||
|
e.mu.Unlock()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,7 +16,7 @@ import (
|
|||||||
"github.com/slackhq/nebula/routing"
|
"github.com/slackhq/nebula/routing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, nb []byte, sendBatch *batch.SendBatch, rejectBuf []byte, q int) {
|
func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, nb []byte, sendBatch *batch.SendBatch, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
|
||||||
// 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. Every consumer below
|
||||||
// (parse, self-forward, handshake cache, sendInsideMessage) reads it
|
// (parse, self-forward, handshake cache, sendInsideMessage) reads it
|
||||||
@@ -109,7 +109,7 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool())
|
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
|
||||||
if dropReason == nil {
|
if dropReason == nil {
|
||||||
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
|
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
|
||||||
} else {
|
} else {
|
||||||
@@ -380,7 +380,7 @@ func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubTyp
|
|||||||
}
|
}
|
||||||
|
|
||||||
// check if packet is in outbound fw rules
|
// check if packet is in outbound fw rules
|
||||||
dropReason := f.firewall.Drop(fp.Packet, false, hostinfo, f.pki.GetCAPool())
|
dropReason := f.firewall.Drop(fp.Packet, false, hostinfo, f.pki.GetCAPool(), nil)
|
||||||
if dropReason != nil {
|
if dropReason != nil {
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
f.l.Debug("dropping cached packet",
|
f.l.Debug("dropping cached packet",
|
||||||
|
|||||||
+1
-1
@@ -50,7 +50,7 @@ func newSelfForwardInterface(myAddrs ...netip.Addr) (*Interface, *capturingTun)
|
|||||||
}
|
}
|
||||||
|
|
||||||
func consumeInside(f *Interface, packet []byte) {
|
func consumeInside(f *Interface, packet []byte) {
|
||||||
f.consumeInsidePacket(tio.Packet{Bytes: packet}, &firewall.ParsedPacket{}, make([]byte, 12), nil, make([]byte, mtu), 0)
|
f.consumeInsidePacket(tio.Packet{Bytes: packet}, &firewall.ParsedPacket{}, make([]byte, 12), nil, make([]byte, mtu), 0, nil)
|
||||||
}
|
}
|
||||||
|
|
||||||
// l4Proto describes one upper-layer header for these tests: its IP next-header
|
// l4Proto describes one upper-layer header for these tests: its IP next-header
|
||||||
|
|||||||
+16
-17
@@ -52,6 +52,8 @@ type InterfaceConfig struct {
|
|||||||
reQueryEvery uint32
|
reQueryEvery uint32
|
||||||
reQueryWait time.Duration
|
reQueryWait time.Duration
|
||||||
|
|
||||||
|
ConntrackCacheTimeout time.Duration
|
||||||
|
|
||||||
// CpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
|
// CpuAffinity, when non-empty, names the CPUs each TUN reader goroutine
|
||||||
// should pin to. Queue i pins to CpuAffinity[i % len(CpuAffinity)] —
|
// should pin to. Queue i pins to CpuAffinity[i % len(CpuAffinity)] —
|
||||||
// shorter lists than `routines` cycle. Empty list keeps the default
|
// shorter lists than `routines` cycle. Empty list keeps the default
|
||||||
@@ -109,6 +111,8 @@ type Interface struct {
|
|||||||
rebindEpoch atomic.Uint32
|
rebindEpoch atomic.Uint32
|
||||||
version string
|
version string
|
||||||
|
|
||||||
|
conntrackCacheTimeout time.Duration
|
||||||
|
|
||||||
ctx context.Context
|
ctx context.Context
|
||||||
writers []udp.Conn
|
writers []udp.Conn
|
||||||
queues []tio.Queue
|
queues []tio.Queue
|
||||||
@@ -223,6 +227,7 @@ func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
|
|||||||
myBroadcastAddrsTable: cs.myVpnBroadcastAddrsTable,
|
myBroadcastAddrsTable: cs.myVpnBroadcastAddrsTable,
|
||||||
relayManager: c.relayManager,
|
relayManager: c.relayManager,
|
||||||
connectionManager: c.connectionManager,
|
connectionManager: c.connectionManager,
|
||||||
|
conntrackCacheTimeout: c.ConntrackCacheTimeout,
|
||||||
cpuAffinity: c.CpuAffinity,
|
cpuAffinity: c.CpuAffinity,
|
||||||
pinThreads: c.PinThreads,
|
pinThreads: c.PinThreads,
|
||||||
|
|
||||||
@@ -356,19 +361,8 @@ type rxContext struct {
|
|||||||
h *header.H
|
h *header.H
|
||||||
fwPacket *firewall.ParsedPacket
|
fwPacket *firewall.ParsedPacket
|
||||||
hostmapCache map[uint32]*HostInfo
|
hostmapCache map[uint32]*HostInfo
|
||||||
|
|
||||||
// lastAllowed is the last flow the inbound firewall let in during this batch. UDP GRO hands us segments
|
|
||||||
// in runs from the same flow, so the rest of a run can skip the firewall. Cleared by endBatch.
|
|
||||||
lastAllowed firewall.Packet
|
|
||||||
lastAllowedHost *HostInfo
|
|
||||||
lhh *LightHouseHandler
|
lhh *LightHouseHandler
|
||||||
}
|
ctCache *firewall.ConntrackCacheTicker
|
||||||
|
|
||||||
// endBatch forgets what was learned during a batch, so nothing outlives a hostmap or firewall change by more than one batch
|
|
||||||
func (rxc *rxContext) endBatch() {
|
|
||||||
clear(rxc.hostmapCache)
|
|
||||||
rxc.lastAllowed = firewall.Packet{}
|
|
||||||
rxc.lastAllowedHost = nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func newRxContext(f *Interface, q int) *rxContext {
|
func newRxContext(f *Interface, q int) *rxContext {
|
||||||
@@ -380,6 +374,7 @@ func newRxContext(f *Interface, q int) *rxContext {
|
|||||||
fwPacket: &firewall.ParsedPacket{},
|
fwPacket: &firewall.ParsedPacket{},
|
||||||
hostmapCache: map[uint32]*HostInfo{},
|
hostmapCache: map[uint32]*HostInfo{},
|
||||||
lhh: f.lightHouse.NewRequestHandler(),
|
lhh: f.lightHouse.NewRequestHandler(),
|
||||||
|
ctCache: firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -401,7 +396,7 @@ func (f *Interface) listenOut(i int) {
|
|||||||
if err := f.batchers[i].Flush(); err != nil {
|
if err := f.batchers[i].Flush(); err != nil {
|
||||||
f.l.Error("Failed to flush tun coalescer", "error", err)
|
f.l.Error("Failed to flush tun coalescer", "error", err)
|
||||||
}
|
}
|
||||||
rxc.endBatch()
|
clear(rxc.hostmapCache)
|
||||||
}
|
}
|
||||||
|
|
||||||
err := li.ListenOut(listener, flusher)
|
err := li.ListenOut(listener, flusher)
|
||||||
@@ -449,6 +444,8 @@ func (f *Interface) listenIn(queue tio.Queue, i int) {
|
|||||||
fwPacket := &firewall.ParsedPacket{}
|
fwPacket := &firewall.ParsedPacket{}
|
||||||
nb := make([]byte, 12, 12)
|
nb := make([]byte, 12, 12)
|
||||||
|
|
||||||
|
conntrackCache := firewall.NewConntrackCacheTicker(f.ctx, f.l, f.conntrackCacheTimeout)
|
||||||
|
|
||||||
for {
|
for {
|
||||||
pkts, err := queue.Read()
|
pkts, err := queue.Read()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -461,7 +458,7 @@ func (f *Interface) listenIn(queue tio.Queue, i int) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, pkt := range pkts {
|
for _, pkt := range pkts {
|
||||||
f.consumeInsidePacket(pkt, fwPacket, nb, sb, rejectBuf, i)
|
f.consumeInsidePacket(pkt, fwPacket, nb, sb, rejectBuf, i, conntrackCache.Get())
|
||||||
// Flush incrementally once a full sendmmsg batch has
|
// Flush incrementally once a full sendmmsg batch has
|
||||||
// accumulated so the first packets of a deep read drain
|
// accumulated so the first packets of a deep read drain
|
||||||
// hit the wire while the rest are still being encrypted.
|
// hit the wire while the rest are still being encrypted.
|
||||||
@@ -534,8 +531,9 @@ func (f *Interface) reloadFirewall(c *config.C) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
oldFw := f.firewall
|
oldFw := f.firewall
|
||||||
// Conntrack lives as long as the interface, keep using the running one
|
conntrack := oldFw.Conntrack
|
||||||
fw.Conntrack = oldFw.Conntrack
|
conntrack.Lock()
|
||||||
|
defer conntrack.Unlock()
|
||||||
|
|
||||||
fw.rulesVersion = oldFw.rulesVersion + 1
|
fw.rulesVersion = oldFw.rulesVersion + 1
|
||||||
// If rulesVersion is back to zero, we have wrapped all the way around. Be
|
// If rulesVersion is back to zero, we have wrapped all the way around. Be
|
||||||
@@ -546,7 +544,8 @@ func (f *Interface) reloadFirewall(c *config.C) {
|
|||||||
"oldFirewallHashes", oldFw.GetRuleHashes(),
|
"oldFirewallHashes", oldFw.GetRuleHashes(),
|
||||||
"rulesVersion", fw.rulesVersion,
|
"rulesVersion", fw.rulesVersion,
|
||||||
)
|
)
|
||||||
fw.Conntrack.clear()
|
} else {
|
||||||
|
fw.Conntrack = conntrack
|
||||||
}
|
}
|
||||||
|
|
||||||
f.firewall = fw
|
f.firewall = fw
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import (
|
|||||||
|
|
||||||
"github.com/rcrowley/go-metrics"
|
"github.com/rcrowley/go-metrics"
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
|
"github.com/slackhq/nebula/firewall"
|
||||||
"github.com/slackhq/nebula/overlay/overlaytest"
|
"github.com/slackhq/nebula/overlay/overlaytest"
|
||||||
"github.com/slackhq/nebula/test"
|
"github.com/slackhq/nebula/test"
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
@@ -42,7 +43,7 @@ func Test_emitStats_primesGauges(t *testing.T) {
|
|||||||
hostMap: hostMap,
|
hostMap: hostMap,
|
||||||
inside: &overlaytest.NoopTun{},
|
inside: &overlaytest.NoopTun{},
|
||||||
outside: &udp.NoopConn{},
|
outside: &udp.NoopConn{},
|
||||||
firewall: &Firewall{Conntrack: newFirewallConntrack()},
|
firewall: &Firewall{Conntrack: &FirewallConntrack{Conns: map[firewall.Packet]*conn{}}},
|
||||||
lightHouse: lh,
|
lightHouse: lh,
|
||||||
pki: &PKI{},
|
pki: &PKI{},
|
||||||
handshakeManager: NewHandshakeManager(l, hostMap, lh, &udp.NoopConn{}, defaultHandshakeConfig),
|
handshakeManager: NewHandshakeManager(l, hostMap, lh, &udp.NoopConn{}, defaultHandshakeConfig),
|
||||||
|
|||||||
+3
-12
@@ -15,7 +15,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
"github.com/gaissmai/bart"
|
||||||
"github.com/rcrowley/go-metrics"
|
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
@@ -82,8 +81,6 @@ type LightHouse struct {
|
|||||||
|
|
||||||
updateTrigger chan struct{}
|
updateTrigger chan struct{}
|
||||||
queryChan chan netip.Addr
|
queryChan chan netip.Addr
|
||||||
// queryDropped counts queries QueryServer dropped because queryChan was full.
|
|
||||||
queryDropped metrics.Counter
|
|
||||||
|
|
||||||
calculatedRemotes atomic.Pointer[bart.Table[[]*calculatedRemote]] // Maps VpnAddr to []*calculatedRemote
|
calculatedRemotes atomic.Pointer[bart.Table[[]*calculatedRemote]] // Maps VpnAddr to []*calculatedRemote
|
||||||
|
|
||||||
@@ -119,8 +116,7 @@ func NewLightHouseFromConfig(ctx context.Context, l *slog.Logger, c *config.C, c
|
|||||||
nebulaPort: nebulaPort,
|
nebulaPort: nebulaPort,
|
||||||
punchy: p,
|
punchy: p,
|
||||||
updateTrigger: make(chan struct{}, 1),
|
updateTrigger: make(chan struct{}, 1),
|
||||||
queryChan: make(chan netip.Addr, c.GetUint32("handshakes.query_buffer", 1024)),
|
queryChan: make(chan netip.Addr, c.GetUint32("handshakes.query_buffer", 64)),
|
||||||
queryDropped: metrics.GetOrRegisterCounter("lighthouse.query.dropped", nil),
|
|
||||||
l: l,
|
l: l,
|
||||||
}
|
}
|
||||||
h.localAddrsFn = func(al *LocalAllowList) []netip.Addr {
|
h.localAddrsFn = func(al *LocalAllowList) []netip.Addr {
|
||||||
@@ -516,19 +512,14 @@ func (lh *LightHouse) Query(vpnAddr netip.Addr) *RemoteList {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// QueryServer is asynchronous and non-blocking, no reply should be expected.
|
// QueryServer is asynchronous so no reply should be expected
|
||||||
// If the query channel is full, the query is dropped.
|
|
||||||
func (lh *LightHouse) QueryServer(vpnAddr netip.Addr) {
|
func (lh *LightHouse) QueryServer(vpnAddr netip.Addr) {
|
||||||
// Don't put lighthouse addrs in the query channel because we can't query lighthouses about lighthouses
|
// Don't put lighthouse addrs in the query channel because we can't query lighthouses about lighthouses
|
||||||
if lh.amLighthouse || lh.IsLighthouseAddr(vpnAddr) {
|
if lh.amLighthouse || lh.IsLighthouseAddr(vpnAddr) {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
select {
|
lh.queryChan <- vpnAddr
|
||||||
case lh.queryChan <- vpnAddr:
|
|
||||||
default:
|
|
||||||
lh.queryDropped.Inc(1)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (lh *LightHouse) QueryCache(vpnAddrs []netip.Addr) *RemoteList {
|
func (lh *LightHouse) QueryCache(vpnAddrs []netip.Addr) *RemoteList {
|
||||||
|
|||||||
@@ -6,9 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"sync"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
"github.com/gaissmai/bart"
|
||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
@@ -797,55 +795,3 @@ func TestLightHouse_logLocalAddrsErr(t *testing.T) {
|
|||||||
lh.logLocalAddrsErr(errors.New("something else"))
|
lh.logLocalAddrsErr(errors.New("something else"))
|
||||||
assert.Contains(t, out.String(), "level=WARN")
|
assert.Contains(t, out.String(), "level=WARN")
|
||||||
}
|
}
|
||||||
|
|
||||||
// heldEncWriter holds the query worker in its first GetHostInfo until release closes.
|
|
||||||
type heldEncWriter struct {
|
|
||||||
mockEncWriter
|
|
||||||
once sync.Once
|
|
||||||
held chan struct{}
|
|
||||||
release chan struct{}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *heldEncWriter) GetHostInfo(netip.Addr) *HostInfo {
|
|
||||||
w.once.Do(func() { close(w.held) })
|
|
||||||
<-w.release
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// QueryServer never waits on the query worker, since the packet readers call it and nothing drains the channel at
|
|
||||||
// shutdown; a query that finds the channel full is dropped and counted. The worker is held on its first query so the
|
|
||||||
// channel fills.
|
|
||||||
func TestLighthouse_QueryServerDoesNotBlock(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
cs := testCertState(netip.MustParsePrefix("10.128.0.1/16"))
|
|
||||||
lh1 := "10.128.0.2"
|
|
||||||
c := config.NewC(l)
|
|
||||||
c.Settings["lighthouse"] = map[string]any{"hosts": []any{lh1}}
|
|
||||||
c.Settings["static_host_map"] = map[string]any{lh1: []any{"1.1.1.1:4242"}}
|
|
||||||
c.Settings["handshakes"] = map[string]any{"query_buffer": 1}
|
|
||||||
lh, err := NewLightHouseFromConfig(t.Context(), l, c, cs, nil, nil)
|
|
||||||
require.NoError(t, err)
|
|
||||||
w := &heldEncWriter{held: make(chan struct{}), release: make(chan struct{})}
|
|
||||||
lh.ifce = w
|
|
||||||
t.Cleanup(func() { close(w.release) })
|
|
||||||
|
|
||||||
lh.QueryServer(netip.MustParseAddr("10.128.0.10"))
|
|
||||||
select {
|
|
||||||
case <-w.held:
|
|
||||||
case <-time.After(5 * time.Second):
|
|
||||||
t.Fatal("the query worker never took the first query")
|
|
||||||
}
|
|
||||||
dropped := lh.queryDropped.Count()
|
|
||||||
done := make(chan struct{})
|
|
||||||
go func() {
|
|
||||||
lh.QueryServer(netip.MustParseAddr("10.128.0.11"))
|
|
||||||
lh.QueryServer(netip.MustParseAddr("10.128.0.12"))
|
|
||||||
close(done)
|
|
||||||
}()
|
|
||||||
select {
|
|
||||||
case <-done:
|
|
||||||
case <-time.After(5 * time.Second):
|
|
||||||
t.Fatal("QueryServer blocked on a full query channel")
|
|
||||||
}
|
|
||||||
assert.EqualValues(t, 1, lh.queryDropped.Count()-dropped)
|
|
||||||
}
|
|
||||||
@@ -113,6 +113,18 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
|||||||
l.Info("Using multiple routines", "routines", routines)
|
l.Info("Using multiple routines", "routines", routines)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EXPERIMENTAL
|
||||||
|
// Intentionally not documented yet while we do more testing and determine
|
||||||
|
// a good default value.
|
||||||
|
conntrackCacheTimeout := c.GetDuration("firewall.conntrack.routine_cache_timeout", 0)
|
||||||
|
if routines > 1 && !c.IsSet("firewall.conntrack.routine_cache_timeout") {
|
||||||
|
// Use a different default if we are running with multiple routines
|
||||||
|
conntrackCacheTimeout = 1 * time.Second
|
||||||
|
}
|
||||||
|
if conntrackCacheTimeout > 0 {
|
||||||
|
l.Info("Using routine-local conntrack cache", "duration", conntrackCacheTimeout)
|
||||||
|
}
|
||||||
|
|
||||||
var tun overlay.Device
|
var tun overlay.Device
|
||||||
if !configTest {
|
if !configTest {
|
||||||
c.CatchHUP(ctx)
|
c.CatchHUP(ctx)
|
||||||
@@ -201,6 +213,7 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
|||||||
}
|
}
|
||||||
|
|
||||||
hostMap := NewHostMapFromConfig(l, c)
|
hostMap := NewHostMapFromConfig(l, c)
|
||||||
|
hostMap.established = newEstablishedRemotes(udpConns)
|
||||||
punchy := NewPunchyFromConfig(l, c, udpConns[0])
|
punchy := NewPunchyFromConfig(l, c, udpConns[0])
|
||||||
connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
|
connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
|
||||||
lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
|
lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
|
||||||
@@ -281,6 +294,7 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
|||||||
version: buildVersion,
|
version: buildVersion,
|
||||||
relayManager: NewRelayManager(ctx, l, hostMap, c),
|
relayManager: NewRelayManager(ctx, l, hostMap, c),
|
||||||
punchy: punchy,
|
punchy: punchy,
|
||||||
|
ConntrackCacheTimeout: conntrackCacheTimeout,
|
||||||
CpuAffinity: cpuAffinity,
|
CpuAffinity: cpuAffinity,
|
||||||
PinThreads: pinThreads,
|
PinThreads: pinThreads,
|
||||||
l: l,
|
l: l,
|
||||||
@@ -303,7 +317,6 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
|||||||
|
|
||||||
handshakeManager.f = ifce
|
handshakeManager.f = ifce
|
||||||
go handshakeManager.Run(ctx)
|
go handshakeManager.Run(ctx)
|
||||||
go ifce.firewall.Conntrack.Run(ctx)
|
|
||||||
|
|
||||||
punchy.Start(ctx, ifce, hostMap, lightHouse)
|
punchy.Start(ctx, ifce, hostMap, lightHouse)
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-18
@@ -477,7 +477,7 @@ func (f *Interface) handleOutsideMessagePacket(hostinfo *HostInfo, messageCounte
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
dropReason := f.allowInbound(hostinfo, rxc)
|
dropReason := f.firewall.Drop(rxc.fwPacket.Packet, true, hostinfo, f.pki.GetCAPool(), rxc.ctCache.Get())
|
||||||
if dropReason != nil {
|
if dropReason != nil {
|
||||||
f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, rxc.nb, rxc.scratch, rxc.q)
|
f.rejectOutside(out, hostinfo.ConnectionState, hostinfo, rxc.nb, rxc.scratch, rxc.q)
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
@@ -492,23 +492,6 @@ func (f *Interface) handleOutsideMessagePacket(hostinfo *HostInfo, messageCounte
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// allowInbound runs the inbound firewall check on rxc.fwPacket. It skips the check when the packet belongs to
|
|
||||||
// the same flow from the same host as the last one allowed in this batch.
|
|
||||||
func (f *Interface) allowInbound(hostinfo *HostInfo, rxc *rxContext) error {
|
|
||||||
fp := rxc.fwPacket.Packet
|
|
||||||
if hostinfo == rxc.lastAllowedHost && fp == rxc.lastAllowed {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := f.firewall.Drop(fp, true, hostinfo, f.pki.GetCAPool()); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
rxc.lastAllowed = fp
|
|
||||||
rxc.lastAllowedHost = hostinfo
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32) {
|
func (f *Interface) maybeSendRecvError(endpoint netip.AddrPort, index uint32) {
|
||||||
if f.sendRecvErrorConfig.ShouldRecvError(endpoint) {
|
if f.sendRecvErrorConfig.ShouldRecvError(endpoint) {
|
||||||
f.sendRecvError(endpoint, index)
|
f.sendRecvError(endpoint, index)
|
||||||
|
|||||||
@@ -6,16 +6,12 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
|
||||||
"github.com/google/gopacket"
|
"github.com/google/gopacket"
|
||||||
"github.com/google/gopacket/layers"
|
"github.com/google/gopacket/layers"
|
||||||
"github.com/slackhq/nebula/cert"
|
|
||||||
"github.com/slackhq/nebula/iputil"
|
"github.com/slackhq/nebula/iputil"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/firewall"
|
"github.com/slackhq/nebula/firewall"
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
"golang.org/x/net/ipv4"
|
"golang.org/x/net/ipv4"
|
||||||
@@ -845,49 +841,3 @@ func Test_newPacket_parsedFields(t *testing.T) {
|
|||||||
assert.True(t, p.Fragment)
|
assert.True(t, p.Fragment)
|
||||||
assert.True(t, p.FragAny)
|
assert.True(t, p.FragAny)
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestInterface_allowInbound(t *testing.T) {
|
|
||||||
l := test.NewLoggerWithOutput(&bytes.Buffer{})
|
|
||||||
myNetworks := new(bart.Lite)
|
|
||||||
myNetworks.Insert(netip.MustParsePrefix("192.0.2.1/24"))
|
|
||||||
me := &dummyCert{name: "me", networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")}}
|
|
||||||
peer := &cert.CachedCertificate{Certificate: &dummyCert{name: "peer", networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24")}}}
|
|
||||||
h := &HostInfo{ConnectionState: &ConnectionState{peerCert: peer}, vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.2")}}
|
|
||||||
h.buildNetworks(myNetworks, peer.Certificate)
|
|
||||||
|
|
||||||
allowAll := NewFirewall(l, time.Minute, time.Minute, time.Minute, me)
|
|
||||||
require.NoError(t, allowAll.AddRule(true, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
|
||||||
allowNone := NewFirewall(l, time.Minute, time.Minute, time.Minute, me)
|
|
||||||
|
|
||||||
f := &Interface{firewall: allowAll, pki: &PKI{}, l: l}
|
|
||||||
rxc := &rxContext{fwPacket: &firewall.ParsedPacket{}, hostmapCache: map[uint32]*HostInfo{}}
|
|
||||||
flow := firewall.Packet{
|
|
||||||
LocalAddr: netip.MustParseAddr("192.0.2.1"),
|
|
||||||
RemoteAddr: netip.MustParseAddr("192.0.2.2"),
|
|
||||||
LocalPort: 443,
|
|
||||||
RemotePort: 55000,
|
|
||||||
Protocol: iputil.IPProtocolUDP,
|
|
||||||
}
|
|
||||||
rxc.fwPacket.Packet = flow
|
|
||||||
require.NoError(t, f.allowInbound(h, rxc))
|
|
||||||
|
|
||||||
// With a firewall that allows nothing, the rest of the flow's run in this batch still passes
|
|
||||||
f.firewall = allowNone
|
|
||||||
require.NoError(t, f.allowInbound(h, rxc))
|
|
||||||
|
|
||||||
// A different flow is checked
|
|
||||||
other := flow
|
|
||||||
other.RemotePort++
|
|
||||||
rxc.fwPacket.Packet = other
|
|
||||||
require.ErrorIs(t, f.allowInbound(h, rxc), ErrNoMatchingRule)
|
|
||||||
|
|
||||||
// So is the same flow from a different host
|
|
||||||
rxc.fwPacket.Packet = flow
|
|
||||||
h2 := &HostInfo{ConnectionState: h.ConnectionState, vpnAddrs: h.vpnAddrs}
|
|
||||||
h2.buildNetworks(myNetworks, peer.Certificate)
|
|
||||||
require.ErrorIs(t, f.allowInbound(h2, rxc), ErrNoMatchingRule)
|
|
||||||
|
|
||||||
// And the same flow in the next batch
|
|
||||||
rxc.endBatch()
|
|
||||||
require.ErrorIs(t, f.allowInbound(h, rxc), ErrNoMatchingRule)
|
|
||||||
}
|
|
||||||
@@ -48,6 +48,14 @@ type Conn interface {
|
|||||||
Close() error
|
Close() error
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// EstablishedPeerConn is a Conn that treats the remotes of established tunnels differently from other
|
||||||
|
// destinations, as darwin's gives busy ones connected sockets.
|
||||||
|
type EstablishedPeerConn interface {
|
||||||
|
// SetEstablishedPeer reports whether dst is the current remote of at least one established tunnel. Calls for
|
||||||
|
// one dst must not race each other.
|
||||||
|
SetEstablishedPeer(dst netip.AddrPort, established bool)
|
||||||
|
}
|
||||||
|
|
||||||
type NoopConn struct{}
|
type NoopConn struct{}
|
||||||
|
|
||||||
func (NoopConn) Rebind() error {
|
func (NoopConn) Rebind() error {
|
||||||
|
|||||||
@@ -0,0 +1,115 @@
|
|||||||
|
//go:build !e2e_testing
|
||||||
|
|
||||||
|
package udp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log/slog"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// benchConnSocks opens a wildcard listener with ListenOut running, with the connected socket knobs pinned to
|
||||||
|
// their defaults and then cfg applied, and a loopback peer that never reads, so its sends cost only the sender.
|
||||||
|
func benchConnSocks(b *testing.B, s Settings, cfg func(*connSockConfig)) (*StdConn, netip.AddrPort) {
|
||||||
|
b.Helper()
|
||||||
|
for k, v := range map[string]string{
|
||||||
|
"NEBULA_CONNSOCKS": "8",
|
||||||
|
"NEBULA_CONNSOCK_RUN": "64",
|
||||||
|
"NEBULA_CONNSOCK_WINDOW": "1s",
|
||||||
|
"NEBULA_CONNSOCK_IDLE": "30s",
|
||||||
|
"NEBULA_CONNSOCK_OPEN_EVERY": "1s",
|
||||||
|
} {
|
||||||
|
b.Setenv(k, v)
|
||||||
|
}
|
||||||
|
c, err := NewListener(slog.New(slog.DiscardHandler), s)
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
b.Cleanup(func() { _ = c.Close() })
|
||||||
|
u := c.(*StdConn)
|
||||||
|
if cfg != nil {
|
||||||
|
cfg(&u.socks.cfg)
|
||||||
|
}
|
||||||
|
go func() { _ = u.ListenOut(func(netip.AddrPort, []byte) {}, func() {}) }()
|
||||||
|
for u.reader.Load() == nil {
|
||||||
|
time.Sleep(time.Millisecond)
|
||||||
|
}
|
||||||
|
pc, err := net.ListenPacket("udp4", "127.0.0.1:0")
|
||||||
|
if err != nil {
|
||||||
|
b.Fatal(err)
|
||||||
|
}
|
||||||
|
b.Cleanup(func() { _ = pc.Close() })
|
||||||
|
return u, pc.LocalAddr().(*net.UDPAddr).AddrPort()
|
||||||
|
}
|
||||||
|
|
||||||
|
// BenchmarkConnSockWriteTo measures one WriteTo of a full-size datagram down each path: the listener with
|
||||||
|
// connected sockets off, to a destination that is no tunnel's remote while another is, to an established peer
|
||||||
|
// that never gets busy, and on a connected socket.
|
||||||
|
func BenchmarkConnSockWriteTo(b *testing.B) {
|
||||||
|
pkt := make([]byte, 1400)
|
||||||
|
cases := []struct {
|
||||||
|
name string
|
||||||
|
cfg func(*connSockConfig)
|
||||||
|
setup func(b *testing.B, u *StdConn, dst netip.AddrPort)
|
||||||
|
}{
|
||||||
|
{name: "listener/off", cfg: func(c *connSockConfig) { c.max = 0 }},
|
||||||
|
{name: "listener/ineligible", setup: func(b *testing.B, u *StdConn, dst netip.AddrPort) {
|
||||||
|
u.SetEstablishedPeer(netip.AddrPortFrom(dst.Addr(), dst.Port()+1), true)
|
||||||
|
}},
|
||||||
|
{name: "listener/eligible-not-busy", cfg: func(c *connSockConfig) { c.run = 1 << 30 },
|
||||||
|
setup: func(b *testing.B, u *StdConn, dst netip.AddrPort) { u.SetEstablishedPeer(dst, true) }},
|
||||||
|
{name: "connected", setup: func(b *testing.B, u *StdConn, dst netip.AddrPort) {
|
||||||
|
u.SetEstablishedPeer(dst, true)
|
||||||
|
for range u.socks.cfg.run {
|
||||||
|
_ = u.WriteTo(pkt, dst)
|
||||||
|
}
|
||||||
|
if u.connSockFor(dst) == nil {
|
||||||
|
b.Fatal("no connected socket")
|
||||||
|
}
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
for _, c := range cases {
|
||||||
|
b.Run(c.name, func(b *testing.B) {
|
||||||
|
u, dst := benchConnSocks(b, Settings{Listen: netip.MustParseAddrPort("0.0.0.0:0")}, c.cfg)
|
||||||
|
if c.setup != nil {
|
||||||
|
c.setup(b, u, dst)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.ResetTimer()
|
||||||
|
for range b.N {
|
||||||
|
_ = u.WriteTo(pkt, dst)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BenchmarkConnSockDispatch measures what WriteTo adds before the listener's sendto, without the syscall: a v4
|
||||||
|
// listener refuses a v6 destination before sending, with connected sockets off or with another peer established.
|
||||||
|
func BenchmarkConnSockDispatch(b *testing.B) {
|
||||||
|
pkt := make([]byte, 1400)
|
||||||
|
dst := netip.MustParseAddrPort("[::1]:4242")
|
||||||
|
for _, c := range []struct {
|
||||||
|
name string
|
||||||
|
cfg func(*connSockConfig)
|
||||||
|
establish bool
|
||||||
|
}{
|
||||||
|
{name: "off", cfg: func(c *connSockConfig) { c.max = 0 }},
|
||||||
|
{name: "ineligible", establish: true},
|
||||||
|
} {
|
||||||
|
b.Run(c.name, func(b *testing.B) {
|
||||||
|
u, peer := benchConnSocks(b, Settings{Listen: netip.MustParseAddrPort("127.0.0.1:0"), Multi: true}, c.cfg)
|
||||||
|
if c.establish {
|
||||||
|
u.SetEstablishedPeer(peer, true)
|
||||||
|
}
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.ResetTimer()
|
||||||
|
for range b.N {
|
||||||
|
if u.WriteTo(pkt, dst) == nil {
|
||||||
|
b.Fatal("sent a v6 datagram on a v4 listener")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,803 @@
|
|||||||
|
//go:build !e2e_testing
|
||||||
|
|
||||||
|
package udp
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"log/slog"
|
||||||
|
"maps"
|
||||||
|
"net"
|
||||||
|
"net/netip"
|
||||||
|
"os"
|
||||||
|
"slices"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
// A connected socket is a UDP socket connected to one busy peer, on the listener's port and bound to the source
|
||||||
|
// address the listener's route to that peer picks, so the peer sees the same address and port from either. A send
|
||||||
|
// on a connected socket skips the per-datagram address and MAC policy checks, and the EndpointSecurity send check
|
||||||
|
// that xprotectd can hold every unconnected sendto on, and it is the only UDP send that reports the interface
|
||||||
|
// queue's flow control, as ENOBUFS. A connected socket wins xnu's lookup for its peer's datagrams; it never sees
|
||||||
|
// anyone else's.
|
||||||
|
//
|
||||||
|
// A connected socket sets SO_REUSEPORT and binds a specific address beside a wildcard listener, which sets
|
||||||
|
// SO_REUSEPORT only for listen routines. xnu refuses a wildcard SO_REUSEPORT bind beside a holder without the
|
||||||
|
// option, and refuses another uid's bind to an address a socket holds specifically, so no other user can join the
|
||||||
|
// port while connected sockets open and close: uid nobody got EADDRINUSE on every bind against a root listener
|
||||||
|
// with connected sockets in the 09-25 probes. A connected socket is closed, never disconnected, because xnu widens
|
||||||
|
// a disconnected socket's local address to the wildcard.
|
||||||
|
//
|
||||||
|
// Only the current remote of an established tunnel may get one: Nebula names those with SetEstablishedPeer, so an
|
||||||
|
// unauthenticated sender can't earn a connected socket by drawing replies such as recv_error or handshake
|
||||||
|
// responses.
|
||||||
|
type connSock struct {
|
||||||
|
dst netip.AddrPort
|
||||||
|
peer *connSockPeer
|
||||||
|
conn *net.UDPConn
|
||||||
|
rc syscall.RawConn
|
||||||
|
// used is the monotonic time in nanoseconds of the connected socket's last send or receive.
|
||||||
|
used atomic.Int64
|
||||||
|
// stallAt is the monotonic time of the first ENOBUFS or EAGAIN since a send last went through, or 0, and
|
||||||
|
// dropping is set once that stall has dropped a datagram, so each stall logs its drops once.
|
||||||
|
stallAt atomic.Int64
|
||||||
|
dropping atomic.Bool
|
||||||
|
// parkMu serializes the writes that wait for a full send buffer, since the write deadline bounding each wait
|
||||||
|
// is the descriptor's, not the writer's.
|
||||||
|
parkMu sync.Mutex
|
||||||
|
// sys writes one datagram on the descriptor: writeFd, or a stand-in for the interface in tests.
|
||||||
|
sys func(fd int, b []byte) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeFd(fd int, b []byte) error {
|
||||||
|
_, err := syscall.Write(fd, b)
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// errStallSpent is a write that found the connected socket's stall budget spent, so its datagram is dropped.
|
||||||
|
var errStallSpent = errors.New("connected socket stall budget spent")
|
||||||
|
|
||||||
|
// connSockWriter carries one write through RawConn.Write. They are pooled with fn bound once, since a closure
|
||||||
|
// passed through the RawConn interface escapes and would allocate on every send.
|
||||||
|
type connSockWriter struct {
|
||||||
|
s *connSock
|
||||||
|
b []byte
|
||||||
|
park bool
|
||||||
|
err error
|
||||||
|
fn func(fd uintptr) bool
|
||||||
|
}
|
||||||
|
|
||||||
|
var connSockWriters = sync.Pool{New: func() any {
|
||||||
|
w := &connSockWriter{}
|
||||||
|
w.fn = w.write
|
||||||
|
return w
|
||||||
|
}}
|
||||||
|
|
||||||
|
func (w *connSockWriter) write(fd uintptr) bool {
|
||||||
|
for {
|
||||||
|
w.err = w.s.sys(int(fd), w.b)
|
||||||
|
switch {
|
||||||
|
case w.err == syscall.EINTR:
|
||||||
|
case w.err == syscall.EAGAIN && w.park:
|
||||||
|
return false
|
||||||
|
default:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// try writes b on s once and returns nil, the write's errno, os.ErrDeadlineExceeded, or net.ErrClosed. With park
|
||||||
|
// set, EAGAIN waits in the netpoller until the socket is writable or the write deadline passes; without it, EAGAIN
|
||||||
|
// is returned.
|
||||||
|
func (s *connSock) try(b []byte, park bool) error {
|
||||||
|
w := connSockWriters.Get().(*connSockWriter)
|
||||||
|
w.s, w.b, w.park = s, b, park
|
||||||
|
rerr := s.rc.Write(w.fn)
|
||||||
|
err := w.err
|
||||||
|
*w = connSockWriter{fn: w.fn}
|
||||||
|
connSockWriters.Put(w)
|
||||||
|
switch {
|
||||||
|
case rerr == nil:
|
||||||
|
return err
|
||||||
|
case errors.Is(rerr, os.ErrDeadlineExceeded):
|
||||||
|
return os.ErrDeadlineExceeded
|
||||||
|
default:
|
||||||
|
return net.ErrClosed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// connSockConfig holds the knobs. connSockConfigFromEnv reads all but backoff and enobufsMax from the environment,
|
||||||
|
// so one binary can be tuned without a rebuild.
|
||||||
|
type connSockConfig struct {
|
||||||
|
// max is how many connected sockets the listen routines may have open at once; 0 turns connected sockets off.
|
||||||
|
max int
|
||||||
|
// run is how many datagrams to one destination within one window earn it a connected socket. darwin's tun
|
||||||
|
// hands over one packet per read, so a peer's sends arrive one WriteTo or one-datagram batch at a time and
|
||||||
|
// busyness has to be counted across calls.
|
||||||
|
run int
|
||||||
|
window time.Duration
|
||||||
|
// idle closes a connected socket after it has neither sent nor received for this long.
|
||||||
|
idle time.Duration
|
||||||
|
// backoff keeps a destination whose connected socket failed on the listener for this long.
|
||||||
|
backoff time.Duration
|
||||||
|
// openEvery is how often the open bucket earns back an open once max are spent, which bounds connected socket
|
||||||
|
// churn however fast senders earn connected sockets and errors close them.
|
||||||
|
openEvery time.Duration
|
||||||
|
// enobufsMax is how long a connected socket's sends may wait out ENOBUFS without one going through before they
|
||||||
|
// drop instead, so a suspended interface costs one write per datagram rather than stalling the tun reader.
|
||||||
|
enobufsMax time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func connSockConfigFromEnv() connSockConfig {
|
||||||
|
c := connSockConfig{
|
||||||
|
max: 8,
|
||||||
|
run: 64,
|
||||||
|
window: time.Second,
|
||||||
|
idle: 30 * time.Second,
|
||||||
|
backoff: 30 * time.Second,
|
||||||
|
openEvery: time.Second,
|
||||||
|
enobufsMax: 10 * time.Millisecond,
|
||||||
|
}
|
||||||
|
if v, err := strconv.Atoi(os.Getenv("NEBULA_CONNSOCKS")); err == nil {
|
||||||
|
c.max = v
|
||||||
|
}
|
||||||
|
if v, err := strconv.Atoi(os.Getenv("NEBULA_CONNSOCK_RUN")); err == nil && v > 0 {
|
||||||
|
c.run = v
|
||||||
|
}
|
||||||
|
if v, err := time.ParseDuration(os.Getenv("NEBULA_CONNSOCK_WINDOW")); err == nil && v > 0 {
|
||||||
|
c.window = v
|
||||||
|
}
|
||||||
|
if v, err := time.ParseDuration(os.Getenv("NEBULA_CONNSOCK_IDLE")); err == nil && v > 0 {
|
||||||
|
c.idle = v
|
||||||
|
}
|
||||||
|
if v, err := time.ParseDuration(os.Getenv("NEBULA_CONNSOCK_OPEN_EVERY")); err == nil && v > 0 {
|
||||||
|
c.openEvery = v
|
||||||
|
}
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
// connSockGroups holds the connSocks that the listen routines bound to one address share, so the limits, the
|
||||||
|
// connected sockets and Rebind cover every routine, and a peer has at most one connected socket.
|
||||||
|
var connSockGroups = struct {
|
||||||
|
sync.Mutex
|
||||||
|
m map[netip.AddrPort]*connSocks
|
||||||
|
}{m: map[netip.AddrPort]*connSocks{}}
|
||||||
|
|
||||||
|
// joinConnSocks returns the connSocks u shares with the other listen routines bound to la, and makes it for the
|
||||||
|
// first.
|
||||||
|
func joinConnSocks(u *StdConn, la netip.AddrPort, s Settings) *connSocks {
|
||||||
|
g := &connSockGroups
|
||||||
|
g.Lock()
|
||||||
|
defer g.Unlock()
|
||||||
|
if cs := g.m[la]; s.Multi && cs != nil {
|
||||||
|
cs.mu.Lock()
|
||||||
|
cs.members = append(cs.members, u)
|
||||||
|
cs.mu.Unlock()
|
||||||
|
return cs
|
||||||
|
}
|
||||||
|
cs := &connSocks{cfg: connSockConfigFromEnv(), key: la, members: []*StdConn{u}, clock: monoNow, sleep: time.Sleep}
|
||||||
|
if cs.cfg.max > 0 && !u.listenHost.IsUnspecified() && !s.Multi {
|
||||||
|
// A connected socket on a specific listen.host binds the listener's own address, which xnu allows only when
|
||||||
|
// both sockets set SO_REUSEPORT, and a listener with it lets another uid bind a dual-stack wildcard on the
|
||||||
|
// port.
|
||||||
|
cs.off.Store(true)
|
||||||
|
u.l.Debug("connected sockets: off for a specific listen.host", "addr", s.Listen)
|
||||||
|
}
|
||||||
|
if s.Multi {
|
||||||
|
g.m[la] = cs
|
||||||
|
}
|
||||||
|
return cs
|
||||||
|
}
|
||||||
|
|
||||||
|
type connSocks struct {
|
||||||
|
cfg connSockConfig
|
||||||
|
// key is the listeners' bound address, which connSockGroups files this under.
|
||||||
|
key netip.AddrPort
|
||||||
|
// off keeps connected sockets from opening, when the listener's address can't be shared with them.
|
||||||
|
off atomic.Bool
|
||||||
|
// table maps each destination that is the remote of an established tunnel, and that a connected socket could
|
||||||
|
// reach, to its peer; it is nil when there are none, so a send with nothing to consider costs one load. Every
|
||||||
|
// send reads it without a lock, and mu guards copying it. An open that holds mu and still finds its peer here
|
||||||
|
// can't outlive the tunnel.
|
||||||
|
table atomic.Pointer[map[netip.AddrPort]*connSockPeer]
|
||||||
|
// reserved counts the connected sockets that are open, opening or closing, against cfg.max; mu guards changing it.
|
||||||
|
reserved atomic.Int32
|
||||||
|
mu sync.Mutex
|
||||||
|
closed bool
|
||||||
|
// members are the listen routines' listeners that share these connected sockets.
|
||||||
|
members []*StdConn
|
||||||
|
// pending holds each destination whose connected socket is opening or closing, and not on its peer. xnu
|
||||||
|
// refuses to connect a 4-tuple that is still bound, so a destination in pending can't open another.
|
||||||
|
pending map[netip.AddrPort]struct{}
|
||||||
|
// rebinds counts Rebinds, so an open that copied the listener's interface before one is discarded.
|
||||||
|
rebinds uint64
|
||||||
|
// closers tracks the goroutines that close detached connected sockets.
|
||||||
|
closers sync.WaitGroup
|
||||||
|
// done stops the reaper; it is made when ListenOut starts the connected sockets.
|
||||||
|
done chan struct{}
|
||||||
|
// opens bounds connected socket opens to cfg.max at once and one per cfg.openEvery after.
|
||||||
|
opens gcra
|
||||||
|
// logs bounds connected socket log lines at info or warn; see connSockLogBurst.
|
||||||
|
logs gcra
|
||||||
|
// clock returns monotonic nanoseconds and sleep waits out ENOBUFS: monoNow and time.Sleep, or stand-ins in
|
||||||
|
// tests.
|
||||||
|
clock func() int64
|
||||||
|
sleep func(time.Duration)
|
||||||
|
// dialHook and closeHook, when set, run just before an open's dials and a close's Close, outside mu; tests
|
||||||
|
// use them to hold an open or close in flight.
|
||||||
|
dialHook, closeHook func(dst netip.AddrPort)
|
||||||
|
}
|
||||||
|
|
||||||
|
// connSockPeer is what connSocks keeps about an established tunnel's remote: its connected socket, how busy it is,
|
||||||
|
// and how long a failed connected socket keeps it on the listener.
|
||||||
|
type connSockPeer struct {
|
||||||
|
sock atomic.Pointer[connSock]
|
||||||
|
// windowMu guards start, the monotonic time the current window began, and n, the datagrams sent in it, so a
|
||||||
|
// window's reset and its counts can't interleave with another sender's.
|
||||||
|
windowMu sync.Mutex
|
||||||
|
start int64
|
||||||
|
n int
|
||||||
|
// retryAt is the monotonic time before which a peer whose connected socket failed stays on the listener;
|
||||||
|
// connSocks.mu guards it.
|
||||||
|
retryAt int64
|
||||||
|
}
|
||||||
|
|
||||||
|
// busy counts n more datagrams to p and reports whether it has now sent cfg.run within one window. A busy peer's
|
||||||
|
// count starts over, so a peer that can't get a connected socket retries at most once per cfg.run sends.
|
||||||
|
func (p *connSockPeer) busy(now int64, n int, cfg *connSockConfig) bool {
|
||||||
|
p.windowMu.Lock()
|
||||||
|
defer p.windowMu.Unlock()
|
||||||
|
if time.Duration(now-p.start) > cfg.window {
|
||||||
|
p.start, p.n = now, 0
|
||||||
|
}
|
||||||
|
p.n += n
|
||||||
|
if p.n < cfg.run {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
p.n = 0
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// connSockLogBurst and connSockLogEvery size the bucket that lets connected socket opens, closes and failures log
|
||||||
|
// at info or warn; past it they log at debug, so churn can't flood the log.
|
||||||
|
const (
|
||||||
|
connSockLogBurst = 32
|
||||||
|
connSockLogEvery = 10 * time.Second
|
||||||
|
)
|
||||||
|
|
||||||
|
var monoStart = time.Now()
|
||||||
|
|
||||||
|
func monoNow() int64 { return int64(time.Since(monoStart)) }
|
||||||
|
|
||||||
|
// gcra is a token bucket kept as the monotonic time it is next full (the generic cell rate algorithm), so it needs
|
||||||
|
// no refill tick.
|
||||||
|
type gcra struct{ tat int64 }
|
||||||
|
|
||||||
|
// take spends a token from a bucket of burst that earns one back per every, and reports whether there was one to
|
||||||
|
// spend.
|
||||||
|
func (g *gcra) take(now int64, burst int, every time.Duration) bool {
|
||||||
|
e := int64(every)
|
||||||
|
tat := max(g.tat, now)
|
||||||
|
if tat-now > int64(burst-1)*e {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
g.tat = tat + e
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// logLevelLocked returns level while the log bucket has a token, and debug once it is spent.
|
||||||
|
func (cs *connSocks) logLevelLocked(level slog.Level) slog.Level {
|
||||||
|
if cs.logs.take(cs.clock(), connSockLogBurst, connSockLogEvery) {
|
||||||
|
return level
|
||||||
|
}
|
||||||
|
return slog.LevelDebug
|
||||||
|
}
|
||||||
|
|
||||||
|
// startConnSocks starts the idle reaper.
|
||||||
|
func (u *StdConn) startConnSocks() {
|
||||||
|
cs := u.socks
|
||||||
|
cs.mu.Lock()
|
||||||
|
defer cs.mu.Unlock()
|
||||||
|
if cs.closed || cs.done != nil || cs.cfg.max <= 0 || cs.off.Load() {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cs.done = make(chan struct{})
|
||||||
|
go u.reapConnSocks(cs.done)
|
||||||
|
}
|
||||||
|
|
||||||
|
// stopConnSocks closes every connected socket and keeps new ones from opening, once any listen routine's listener
|
||||||
|
// closes, as they do together at shutdown. It returns once their descriptors are closed.
|
||||||
|
func (u *StdConn) stopConnSocks() {
|
||||||
|
cs := u.socks
|
||||||
|
cs.mu.Lock()
|
||||||
|
cs.members = slices.DeleteFunc(cs.members, func(m *StdConn) bool { return m == u })
|
||||||
|
if !cs.closed {
|
||||||
|
cs.closed = true
|
||||||
|
if cs.done != nil {
|
||||||
|
close(cs.done)
|
||||||
|
}
|
||||||
|
u.detachAllLocked("close")
|
||||||
|
}
|
||||||
|
cs.mu.Unlock()
|
||||||
|
connSockGroups.Lock()
|
||||||
|
if connSockGroups.m[cs.key] == cs {
|
||||||
|
delete(connSockGroups.m, cs.key)
|
||||||
|
}
|
||||||
|
connSockGroups.Unlock()
|
||||||
|
cs.closers.Wait()
|
||||||
|
}
|
||||||
|
|
||||||
|
// siblings returns the other listen routines' listeners.
|
||||||
|
func (cs *connSocks) siblings(u *StdConn) []*StdConn {
|
||||||
|
cs.mu.Lock()
|
||||||
|
defer cs.mu.Unlock()
|
||||||
|
return slices.DeleteFunc(slices.Clone(cs.members), func(m *StdConn) bool { return m == u })
|
||||||
|
}
|
||||||
|
|
||||||
|
// connSockFor returns dst's connected socket, or nil.
|
||||||
|
func (u *StdConn) connSockFor(dst netip.AddrPort) *connSock {
|
||||||
|
if p := u.socks.peer(dst); p != nil {
|
||||||
|
return p.sock.Load()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cs *connSocks) peer(dst netip.AddrPort) *connSockPeer {
|
||||||
|
if t := cs.table.Load(); t != nil {
|
||||||
|
return (*t)[dst]
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetEstablishedPeer makes dst eligible for a connected socket while it is the remote of an established tunnel,
|
||||||
|
// and closes the one it has once it no longer is. Nebula calls it for every listen routine under the hostmap's
|
||||||
|
// write lock, so repeats are no-ops and it makes no syscalls: the descriptor is closed by another goroutine.
|
||||||
|
func (u *StdConn) SetEstablishedPeer(dst netip.AddrPort, established bool) {
|
||||||
|
cs := u.socks
|
||||||
|
if cs.cfg.max <= 0 || cs.off.Load() || !u.connSockable(dst) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cs.mu.Lock()
|
||||||
|
defer cs.mu.Unlock()
|
||||||
|
t := cs.table.Load()
|
||||||
|
p := cs.peer(dst)
|
||||||
|
if cs.closed || (p != nil) == established {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
next := map[netip.AddrPort]*connSockPeer{}
|
||||||
|
if t != nil {
|
||||||
|
next = maps.Clone(*t)
|
||||||
|
}
|
||||||
|
if established {
|
||||||
|
p = &connSockPeer{start: cs.clock()}
|
||||||
|
next[dst] = p
|
||||||
|
} else {
|
||||||
|
delete(next, dst)
|
||||||
|
if s := p.sock.Load(); s != nil {
|
||||||
|
u.detachLocked(s, "tunnel gone", false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cs.storeTableLocked(next)
|
||||||
|
}
|
||||||
|
|
||||||
|
// storeTableLocked publishes t, or nil for an empty one.
|
||||||
|
func (cs *connSocks) storeTableLocked(t map[netip.AddrPort]*connSockPeer) {
|
||||||
|
if len(t) == 0 {
|
||||||
|
cs.table.Store(nil)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
cs.table.Store(&t)
|
||||||
|
}
|
||||||
|
|
||||||
|
// connSockable reports whether a connected socket to dst could send what the listener would. A v4 listener can't
|
||||||
|
// reach a v6 destination at all, and a connected socket bound to a specific listen.host must share its family.
|
||||||
|
func (u *StdConn) connSockable(dst netip.AddrPort) bool {
|
||||||
|
if !dst.IsValid() || dst.Port() == 0 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if u.isV4 {
|
||||||
|
return dst.Addr().Is4()
|
||||||
|
}
|
||||||
|
return u.listenHost.IsUnspecified() || u.listenHost.Unmap().Is4() == dst.Addr().Unmap().Is4()
|
||||||
|
}
|
||||||
|
|
||||||
|
// connSockRun sends bufs, all to p's destination, on p's connected socket, opening one if they make p busy. It
|
||||||
|
// returns how many went out; when that is short of len(bufs), err is the failure of bufs[sent], or nil to leave
|
||||||
|
// bufs[sent:] to the listener.
|
||||||
|
func (u *StdConn) connSockRun(p *connSockPeer, dst netip.AddrPort, bufs [][]byte) (sent int, err error) {
|
||||||
|
s := p.sock.Load()
|
||||||
|
if s == nil {
|
||||||
|
if s = u.maybeOpenConnSock(p, dst, len(bufs)); s == nil {
|
||||||
|
return 0, nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sent, errno, closed := u.connSockWrite(s, bufs)
|
||||||
|
switch {
|
||||||
|
case sent == len(bufs):
|
||||||
|
case connSockDead(errno):
|
||||||
|
u.closeConnSock(s, errno.Error(), true)
|
||||||
|
case !closed:
|
||||||
|
return sent, &net.OpError{Op: "write", Err: errno}
|
||||||
|
}
|
||||||
|
return sent, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// maybeOpenConnSock counts n datagrams to p, and opens a connected socket to it once it is busy and nothing rules
|
||||||
|
// one out.
|
||||||
|
func (u *StdConn) maybeOpenConnSock(p *connSockPeer, dst netip.AddrPort, n int) *connSock {
|
||||||
|
cs := u.socks
|
||||||
|
if n <= 0 || u.reader.Load() == nil || int(cs.reserved.Load()) >= cs.cfg.max || !p.busy(cs.clock(), n, &cs.cfg) {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
cs.mu.Lock()
|
||||||
|
if cs.closed || cs.peer(dst) != p {
|
||||||
|
cs.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if s := p.sock.Load(); s != nil {
|
||||||
|
cs.mu.Unlock()
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
now := cs.clock()
|
||||||
|
if _, ok := cs.pending[dst]; ok || int(cs.reserved.Load()) >= cs.cfg.max || now < p.retryAt ||
|
||||||
|
!cs.opens.take(now, cs.cfg.max, cs.cfg.openEvery) {
|
||||||
|
cs.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if cs.pending == nil {
|
||||||
|
cs.pending = map[netip.AddrPort]struct{}{}
|
||||||
|
}
|
||||||
|
cs.pending[dst] = struct{}{}
|
||||||
|
cs.reserved.Add(1)
|
||||||
|
rebinds := cs.rebinds
|
||||||
|
cs.mu.Unlock()
|
||||||
|
|
||||||
|
if cs.dialHook != nil {
|
||||||
|
cs.dialHook(dst)
|
||||||
|
}
|
||||||
|
s, err := u.dialConnSock(p, dst)
|
||||||
|
|
||||||
|
cs.mu.Lock()
|
||||||
|
if err != nil {
|
||||||
|
delete(cs.pending, dst)
|
||||||
|
cs.reserved.Add(-1)
|
||||||
|
p.retryAt = cs.clock() + int64(cs.cfg.backoff)
|
||||||
|
level := cs.logLevelLocked(slog.LevelWarn)
|
||||||
|
cs.mu.Unlock()
|
||||||
|
u.l.Log(context.Background(), level, "connected socket: open failed, staying on the listener", "udpAddr", dst, "error", err)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if cs.closed || cs.rebinds != rebinds || cs.peer(dst) != p {
|
||||||
|
// The tunnel went away, or a Rebind or shutdown ran, while the socket was opening; it stays in pending until
|
||||||
|
// it is closed.
|
||||||
|
cs.mu.Unlock()
|
||||||
|
u.finishClose(s)
|
||||||
|
u.l.Debug("connected socket: discarded, its tunnel or route changed while it opened", "udpAddr", dst)
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
delete(cs.pending, dst)
|
||||||
|
p.sock.Store(s)
|
||||||
|
go u.readConnSock(s)
|
||||||
|
level := cs.logLevelLocked(slog.LevelInfo)
|
||||||
|
cs.mu.Unlock()
|
||||||
|
u.l.Log(context.Background(), level, "connected socket: opened", "udpAddr", dst, "local", s.conn.LocalAddr(), "open", cs.reserved.Load())
|
||||||
|
return s
|
||||||
|
}
|
||||||
|
|
||||||
|
// dialConnSock opens a socket on the listener's port with SO_REUSEPORT, bound to the configured listen.host or,
|
||||||
|
// for a wildcard listener, to the source address the route to dst picks, and connected to dst. It carries the
|
||||||
|
// listener's IP_BOUND_IF, so both route the same way.
|
||||||
|
func (u *StdConn) dialConnSock(p *connSockPeer, dst netip.AddrPort) (*connSock, error) {
|
||||||
|
raddr := net.UDPAddrFromAddrPort(netip.AddrPortFrom(dst.Addr().Unmap(), dst.Port()))
|
||||||
|
network := "udp6"
|
||||||
|
if raddr.IP.To4() != nil {
|
||||||
|
network = "udp4"
|
||||||
|
}
|
||||||
|
ifindex, err := u.boundIf()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
local := &net.UDPAddr{IP: u.listenHost.AsSlice(), Zone: u.listenHost.Zone()}
|
||||||
|
if u.listenHost.IsUnspecified() {
|
||||||
|
// A connected socket gets the source address xnu would pick for an unconnected send to dst.
|
||||||
|
d := net.Dialer{Control: connSockControl(false, ifindex)}
|
||||||
|
probe, err := d.Dial(network, raddr.String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
local = probe.LocalAddr().(*net.UDPAddr)
|
||||||
|
_ = probe.Close()
|
||||||
|
}
|
||||||
|
local.Port = int(u.port)
|
||||||
|
d := net.Dialer{LocalAddr: local, Control: connSockControl(true, ifindex)}
|
||||||
|
c, err := d.Dial(network, raddr.String())
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
uc := c.(*net.UDPConn)
|
||||||
|
rc, err := uc.SyscallConn()
|
||||||
|
if err != nil {
|
||||||
|
_ = uc.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
s := &connSock{dst: dst, peer: p, conn: uc, rc: rc, sys: writeFd}
|
||||||
|
s.used.Store(u.socks.clock())
|
||||||
|
return s, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// connSockControl sets SO_REUSEPORT when reuse is set, and IP_BOUND_IF or IPV6_BOUND_IF when ifindex isn't 0,
|
||||||
|
// before the socket binds.
|
||||||
|
func connSockControl(reuse bool, ifindex int) func(network, address string, c syscall.RawConn) error {
|
||||||
|
return func(network, _ string, c syscall.RawConn) error {
|
||||||
|
var serr error
|
||||||
|
err := c.Control(func(fd uintptr) {
|
||||||
|
if reuse {
|
||||||
|
serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
|
||||||
|
}
|
||||||
|
if serr == nil && ifindex != 0 {
|
||||||
|
if network == "udp4" {
|
||||||
|
serr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, ifindex)
|
||||||
|
} else {
|
||||||
|
serr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, ifindex)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return serr
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// boundIf returns the interface index the listener is scoped to, or 0. An error keeps the peer on the listener,
|
||||||
|
// since a connected socket opened without the listener's scope could route out an interface the listener can't.
|
||||||
|
func (u *StdConn) boundIf() (int, error) {
|
||||||
|
level, opt := unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF
|
||||||
|
if u.isV4 {
|
||||||
|
level, opt = unix.IPPROTO_IP, unix.IP_BOUND_IF
|
||||||
|
}
|
||||||
|
v, err := unix.GetsockoptInt(int(u.sysFd), level, opt)
|
||||||
|
if err != nil {
|
||||||
|
return 0, fmt.Errorf("reading the listener's bound interface: %w", err)
|
||||||
|
}
|
||||||
|
return v, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// closeConnSock closes s if it is still open. With backoff set, the peer stays on the listener until the backoff
|
||||||
|
// runs out.
|
||||||
|
func (u *StdConn) closeConnSock(s *connSock, why string, backoff bool) {
|
||||||
|
u.socks.mu.Lock()
|
||||||
|
u.detachLocked(s, why, backoff)
|
||||||
|
u.socks.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
// detachLocked takes s off its peer, if it is still there, and closes it on another goroutine, since callers such
|
||||||
|
// as SetEstablishedPeer hold locks that no socket syscall should run under. s.dst stays in pending until the close
|
||||||
|
// completes.
|
||||||
|
func (u *StdConn) detachLocked(s *connSock, why string, backoff bool) {
|
||||||
|
cs := u.socks
|
||||||
|
if !s.peer.sock.CompareAndSwap(s, nil) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if backoff {
|
||||||
|
s.peer.retryAt = cs.clock() + int64(cs.cfg.backoff)
|
||||||
|
}
|
||||||
|
if cs.pending == nil {
|
||||||
|
cs.pending = map[netip.AddrPort]struct{}{}
|
||||||
|
}
|
||||||
|
cs.pending[s.dst] = struct{}{}
|
||||||
|
level := cs.logLevelLocked(slog.LevelInfo)
|
||||||
|
cs.closers.Add(1)
|
||||||
|
go func() {
|
||||||
|
defer cs.closers.Done()
|
||||||
|
open := u.finishClose(s)
|
||||||
|
u.l.Log(context.Background(), level, "connected socket: closed", "udpAddr", s.dst, "reason", why, "open", open)
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// finishClose closes s, whose destination is in pending, then lets the destination open again, and returns how
|
||||||
|
// many connected sockets are left. Closing waits only for a write already in a syscall: a write parked on a full
|
||||||
|
// buffer is woken, and one waiting out ENOBUFS holds no reference on the descriptor.
|
||||||
|
func (u *StdConn) finishClose(s *connSock) int32 {
|
||||||
|
cs := u.socks
|
||||||
|
if cs.closeHook != nil {
|
||||||
|
cs.closeHook(s.dst)
|
||||||
|
}
|
||||||
|
_ = s.conn.Close()
|
||||||
|
cs.mu.Lock()
|
||||||
|
defer cs.mu.Unlock()
|
||||||
|
delete(cs.pending, s.dst)
|
||||||
|
return cs.reserved.Add(-1)
|
||||||
|
}
|
||||||
|
|
||||||
|
// detachAllLocked detaches every connected socket, for a network change or shutdown.
|
||||||
|
func (u *StdConn) detachAllLocked(why string) {
|
||||||
|
if t := u.socks.table.Load(); t != nil {
|
||||||
|
for _, p := range *t {
|
||||||
|
if s := p.sock.Load(); s != nil {
|
||||||
|
u.detachLocked(s, why, false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// closeConnSocks detaches every connected socket and discards the ones still opening, for a network change.
|
||||||
|
func (u *StdConn) closeConnSocks(why string) {
|
||||||
|
u.socks.mu.Lock()
|
||||||
|
u.socks.rebinds++
|
||||||
|
u.detachAllLocked(why)
|
||||||
|
u.socks.mu.Unlock()
|
||||||
|
}
|
||||||
|
|
||||||
|
func (u *StdConn) reapConnSocks(done <-chan struct{}) {
|
||||||
|
cs := u.socks
|
||||||
|
idle := cs.cfg.idle
|
||||||
|
tick := time.NewTicker(max(min(idle/4, 5*time.Second), time.Millisecond))
|
||||||
|
defer tick.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-done:
|
||||||
|
return
|
||||||
|
case <-tick.C:
|
||||||
|
}
|
||||||
|
t := cs.table.Load()
|
||||||
|
if t == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
now := cs.clock()
|
||||||
|
for _, p := range *t {
|
||||||
|
if s := p.sock.Load(); s != nil && time.Duration(now-s.used.Load()) > idle {
|
||||||
|
u.closeConnSock(s, "idle", false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// connSockDead reports whether a connected socket send or receive error means the connected path to the peer is
|
||||||
|
// gone, so its traffic belongs back on the listener. A connected UDP socket reports a peer's ICMP unreachable as
|
||||||
|
// ECONNREFUSED on its next call, which the unconnected listener never sees.
|
||||||
|
func connSockDead(errno syscall.Errno) bool {
|
||||||
|
switch errno {
|
||||||
|
case unix.ECONNREFUSED, unix.EHOSTUNREACH, unix.EHOSTDOWN, unix.ENETUNREACH, unix.ENETDOWN,
|
||||||
|
unix.EADDRNOTAVAIL, unix.EPIPE, unix.ENOTCONN, unix.EDESTADDRREQ:
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
// enobufsWait is how long a connected socket send sleeps when the interface queue is flow controlled. The kernel
|
||||||
|
// posts no wakeup when the advisory lifts, so this polls; 50us kept a gigabit link full without spinning a core in
|
||||||
|
// the 09-25 probes.
|
||||||
|
const enobufsWait = 50 * time.Microsecond
|
||||||
|
|
||||||
|
// connSockWrite writes bufs on s, one datagram per write. A full socket buffer parks the caller in the netpoller
|
||||||
|
// until the socket is writable, and a flow-controlled interface makes it wait out ENOBUFS, so a busy link slows
|
||||||
|
// the tun reader instead of dropping. Once the connected socket has waited cfg.enobufsMax without a send going
|
||||||
|
// through, either one drops the datagram instead, and a dropped datagram counts as sent, as the listener's
|
||||||
|
// unreported interface drops do; it never falls back to the listener, which would reorder it. closed reports that
|
||||||
|
// the connected socket was closed before bufs[sent] went out; any other error stops the run and is returned with
|
||||||
|
// how many went out.
|
||||||
|
func (u *StdConn) connSockWrite(s *connSock, bufs [][]byte) (sent int, errno syscall.Errno, closed bool) {
|
||||||
|
cs := u.socks
|
||||||
|
defer func() {
|
||||||
|
if sent > 0 {
|
||||||
|
s.used.Store(cs.clock())
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
for sent < len(bufs) {
|
||||||
|
err := s.try(bufs[sent], false)
|
||||||
|
if err == syscall.EAGAIN || err == os.ErrDeadlineExceeded {
|
||||||
|
// os.ErrDeadlineExceeded here is another writer's parked deadline, passed but not yet cleared.
|
||||||
|
err = u.parkedWrite(s, bufs[sent])
|
||||||
|
}
|
||||||
|
switch err {
|
||||||
|
case nil:
|
||||||
|
sent++
|
||||||
|
if s.stallAt.Load() != 0 {
|
||||||
|
s.stallAt.Store(0)
|
||||||
|
s.dropping.Store(false)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
case errStallSpent:
|
||||||
|
u.dropStalled(s)
|
||||||
|
sent++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
errno, ok := err.(syscall.Errno)
|
||||||
|
if !ok {
|
||||||
|
return sent, 0, true
|
||||||
|
}
|
||||||
|
if errno != syscall.ENOBUFS {
|
||||||
|
return sent, errno, false
|
||||||
|
}
|
||||||
|
// The wait holds no reference on the descriptor, so a close doesn't wait for it.
|
||||||
|
if s.stalledFor(cs.clock()) < cs.cfg.enobufsMax {
|
||||||
|
cs.sleep(enobufsWait)
|
||||||
|
} else {
|
||||||
|
u.dropStalled(s)
|
||||||
|
sent++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sent, 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// parkedWrite writes b after EAGAIN, parked in the netpoller for what is left of s's stall budget, and returns
|
||||||
|
// errStallSpent once none is. golang/go#73919: a darwin UDP write parked on EAGAIN can wait forever for a
|
||||||
|
// writability event that never comes, so the wait always has a deadline.
|
||||||
|
func (u *StdConn) parkedWrite(s *connSock, b []byte) error {
|
||||||
|
cs := u.socks
|
||||||
|
s.parkMu.Lock()
|
||||||
|
defer s.parkMu.Unlock()
|
||||||
|
left := cs.cfg.enobufsMax - s.stalledFor(cs.clock())
|
||||||
|
if left <= 0 {
|
||||||
|
return errStallSpent
|
||||||
|
}
|
||||||
|
if err := s.conn.SetWriteDeadline(time.Now().Add(left)); err != nil {
|
||||||
|
return net.ErrClosed
|
||||||
|
}
|
||||||
|
err := s.try(b, true)
|
||||||
|
_ = s.conn.SetWriteDeadline(time.Time{})
|
||||||
|
if err == os.ErrDeadlineExceeded {
|
||||||
|
return errStallSpent
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
// dropStalled logs the first datagram a stall drops.
|
||||||
|
func (u *StdConn) dropStalled(s *connSock) {
|
||||||
|
if !s.dropping.Swap(true) {
|
||||||
|
u.l.Debug("connected socket: sends stalled, dropping datagrams until one goes through", "udpAddr", s.dst)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// stalledFor records an ENOBUFS or EAGAIN on s at now and returns how long its sends have stalled: since the first
|
||||||
|
// ENOBUFS or EAGAIN after a send last went through. Every writer measures from that one time, so concurrent writers
|
||||||
|
// spend the budget no faster than one, and a send going through ends the stall for every writer, including one
|
||||||
|
// asleep in it.
|
||||||
|
func (s *connSock) stalledFor(now int64) time.Duration {
|
||||||
|
if s.stallAt.CompareAndSwap(0, now) {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
at := s.stallAt.Load()
|
||||||
|
if at == 0 {
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
return time.Duration(now - at)
|
||||||
|
}
|
||||||
|
|
||||||
|
// readConnSock delivers a connected socket's datagrams through the listener's reader, serialized with ListenOut,
|
||||||
|
// until the connected socket is closed. Any receive error closes it: a connected socket reports its peer's
|
||||||
|
// unreachables here, and retrying an unexpected error could spin.
|
||||||
|
func (u *StdConn) readConnSock(s *connSock) {
|
||||||
|
rd := u.reader.Load()
|
||||||
|
buf := make([]byte, MTU)
|
||||||
|
for {
|
||||||
|
n, from, err := s.conn.ReadFromUDPAddrPort(buf)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, net.ErrClosed) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
why := err.Error()
|
||||||
|
var errno syscall.Errno
|
||||||
|
if errors.As(err, &errno) && connSockDead(errno) {
|
||||||
|
why = errno.Error()
|
||||||
|
} else {
|
||||||
|
u.l.Warn("connected socket: unexpected receive error", "udpAddr", s.dst, "error", err)
|
||||||
|
}
|
||||||
|
u.closeConnSock(s, why, true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
s.used.Store(u.socks.clock())
|
||||||
|
u.readMu.Lock()
|
||||||
|
rd.r(netip.AddrPortFrom(from.Addr().Unmap(), from.Port()), buf[:n:n])
|
||||||
|
rd.flush()
|
||||||
|
u.readMu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,6 @@
|
|||||||
|
//go:build !race && !e2e_testing
|
||||||
|
|
||||||
|
package udp
|
||||||
|
|
||||||
|
// raceEnabled reports a -race build, whose sync.Pool drops a random share of what is put back.
|
||||||
|
const raceEnabled = false
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
//go:build race && !e2e_testing
|
||||||
|
|
||||||
|
package udp
|
||||||
|
|
||||||
|
// raceEnabled reports a -race build, whose sync.Pool drops a random share of what is put back.
|
||||||
|
const raceEnabled = true
|
||||||
+104
-7
@@ -10,6 +10,8 @@ import (
|
|||||||
"log/slog"
|
"log/slog"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
|
"sync"
|
||||||
|
"sync/atomic"
|
||||||
"syscall"
|
"syscall"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
@@ -22,9 +24,26 @@ type StdConn struct {
|
|||||||
isV4 bool
|
isV4 bool
|
||||||
sysFd uintptr
|
sysFd uintptr
|
||||||
l *slog.Logger
|
l *slog.Logger
|
||||||
|
|
||||||
|
// listenHost and port are the configured address and the bound port, which a connected socket shares.
|
||||||
|
listenHost netip.Addr
|
||||||
|
port uint16
|
||||||
|
// rc reaches the listener's descriptor for another listen routine's Rebind.
|
||||||
|
rc syscall.RawConn
|
||||||
|
socks *connSocks
|
||||||
|
// reader is ListenOut's reader, which connected socket readers share; readMu serializes them, since an
|
||||||
|
// EncReader isn't safe for concurrent use.
|
||||||
|
reader atomic.Pointer[readerPair]
|
||||||
|
readMu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
type readerPair struct {
|
||||||
|
r EncReader
|
||||||
|
flush func()
|
||||||
}
|
}
|
||||||
|
|
||||||
var _ Conn = &StdConn{}
|
var _ Conn = &StdConn{}
|
||||||
|
var _ EstablishedPeerConn = &StdConn{}
|
||||||
|
|
||||||
func NewListener(l *slog.Logger, s Settings) (Conn, error) {
|
func NewListener(l *slog.Logger, s Settings) (Conn, error) {
|
||||||
lc := NewListenConfig(s.Multi)
|
lc := NewListenConfig(s.Multi)
|
||||||
@@ -34,12 +53,13 @@ func NewListener(l *slog.Logger, s Settings) (Conn, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if uc, ok := pc.(*net.UDPConn); ok {
|
if uc, ok := pc.(*net.UDPConn); ok {
|
||||||
c := &StdConn{UDPConn: uc, l: l}
|
c := &StdConn{UDPConn: uc, l: l, listenHost: s.Listen.Addr()}
|
||||||
|
|
||||||
rc, err := uc.SyscallConn()
|
rc, err := uc.SyscallConn()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("failed to open udp socket: %w", err)
|
return nil, fmt.Errorf("failed to open udp socket: %w", err)
|
||||||
}
|
}
|
||||||
|
c.rc = rc
|
||||||
|
|
||||||
err = rc.Control(func(fd uintptr) {
|
err = rc.Control(func(fd uintptr) {
|
||||||
c.sysFd = fd
|
c.sysFd = fd
|
||||||
@@ -53,6 +73,8 @@ func NewListener(l *slog.Logger, s Settings) (Conn, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
c.isV4 = la.Addr().Is4()
|
c.isV4 = la.Addr().Is4()
|
||||||
|
c.port = la.Port()
|
||||||
|
c.socks = joinConnSocks(c, la, s)
|
||||||
|
|
||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
@@ -89,6 +111,19 @@ func NewListenConfig(multi bool) net.ListenConfig {
|
|||||||
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen int32) (err error)
|
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen int32) (err error)
|
||||||
|
|
||||||
func (u *StdConn) WriteTo(b []byte, ap netip.AddrPort) error {
|
func (u *StdConn) WriteTo(b []byte, ap netip.AddrPort) error {
|
||||||
|
if t := u.socks.table.Load(); t != nil {
|
||||||
|
if p := (*t)[ap]; p != nil {
|
||||||
|
bufs := [1][]byte{b}
|
||||||
|
if sent, err := u.connSockRun(p, ap, bufs[:]); sent == 1 || err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return u.writeTo(b, ap)
|
||||||
|
}
|
||||||
|
|
||||||
|
// writeTo sends b through the listener.
|
||||||
|
func (u *StdConn) writeTo(b []byte, ap netip.AddrPort) error {
|
||||||
var sa unsafe.Pointer
|
var sa unsafe.Pointer
|
||||||
var addrLen int32
|
var addrLen int32
|
||||||
|
|
||||||
@@ -141,18 +176,50 @@ func (u *StdConn) WriteTo(b []byte, ap netip.AddrPort) error {
|
|||||||
|
|
||||||
func (u *StdConn) WriteBatch(bufs [][]byte, addrs []netip.AddrPort) (int, error) {
|
func (u *StdConn) WriteBatch(bufs [][]byte, addrs []netip.AddrPort) (int, error) {
|
||||||
// An un-sendable destination costs its own packet, never the ones behind it in the batch.
|
// An un-sendable destination costs its own packet, never the ones behind it in the batch.
|
||||||
// TODO: WriteTo maps EWOULDBLOCK to an error, so a full send buffer
|
// TODO: writeTo maps EWOULDBLOCK to an error, so a full listener send buffer
|
||||||
// silently drops the rest of a burst (linux blocks instead). Poll for
|
// silently drops those packets (linux blocks instead). Poll for
|
||||||
// writability on EAGAIN before giving up on the remainder.
|
// writability on EAGAIN before giving up on them.
|
||||||
written := 0
|
written := 0
|
||||||
|
t := u.socks.table.Load()
|
||||||
|
if t == nil {
|
||||||
for i, b := range bufs {
|
for i, b := range bufs {
|
||||||
if err := u.WriteTo(b, addrs[i]); err == nil {
|
if err := u.writeTo(b, addrs[i]); err == nil {
|
||||||
written++
|
written++
|
||||||
} else {
|
} else {
|
||||||
u.l.Debug("failed to write packet in batch", "udpAddr", addrs[i], "error", err)
|
u.l.Debug("failed to write packet in batch", "udpAddr", addrs[i], "error", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return written, nil
|
return written, nil
|
||||||
|
}
|
||||||
|
for off := 0; off < len(bufs); {
|
||||||
|
// A run of datagrams to one peer goes out together, on its connected socket if it has or earns one.
|
||||||
|
dst := addrs[off]
|
||||||
|
end := off + 1
|
||||||
|
for end < len(bufs) && addrs[end] == dst {
|
||||||
|
end++
|
||||||
|
}
|
||||||
|
if p := (*t)[dst]; p != nil {
|
||||||
|
for off < end {
|
||||||
|
sent, err := u.connSockRun(p, dst, bufs[off:end])
|
||||||
|
written += sent
|
||||||
|
off += sent
|
||||||
|
if err == nil {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
u.l.Debug("failed to write packet in batch", "udpAddr", dst, "error", err)
|
||||||
|
off++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// The listener sends what no connected socket took.
|
||||||
|
for ; off < end; off++ {
|
||||||
|
if err := u.writeTo(bufs[off], dst); err == nil {
|
||||||
|
written++
|
||||||
|
} else {
|
||||||
|
u.l.Debug("failed to write packet in batch", "udpAddr", dst, "error", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return written, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *StdConn) LocalAddr() (netip.AddrPort, error) {
|
func (u *StdConn) LocalAddr() (netip.AddrPort, error) {
|
||||||
@@ -182,6 +249,8 @@ func NewUDPStatsEmitter(udpConns []Conn) func() {
|
|||||||
|
|
||||||
func (u *StdConn) ListenOut(r EncReader, flush func()) error {
|
func (u *StdConn) ListenOut(r EncReader, flush func()) error {
|
||||||
buffer := make([]byte, MTU)
|
buffer := make([]byte, MTU)
|
||||||
|
u.reader.Store(&readerPair{r: r, flush: flush})
|
||||||
|
u.startConnSocks()
|
||||||
|
|
||||||
for {
|
for {
|
||||||
// Just read one packet at a time
|
// Just read one packet at a time
|
||||||
@@ -194,18 +263,29 @@ func (u *StdConn) ListenOut(r EncReader, flush func()) error {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
|
u.readMu.Lock()
|
||||||
r(netip.AddrPortFrom(rua.Addr().Unmap(), rua.Port()), buffer[:n:n])
|
r(netip.AddrPortFrom(rua.Addr().Unmap(), rua.Port()), buffer[:n:n])
|
||||||
flush()
|
flush()
|
||||||
|
u.readMu.Unlock()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Close closes the connected sockets of every listen routine, then the listener.
|
||||||
|
func (u *StdConn) Close() error {
|
||||||
|
u.stopConnSocks()
|
||||||
|
return u.UDPConn.Close()
|
||||||
|
}
|
||||||
|
|
||||||
func (u *StdConn) SupportsMultipleReaders() bool {
|
func (u *StdConn) SupportsMultipleReaders() bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
// Rebind clears the interface the kernel scoped this socket to, so that sends are routed against the current
|
// Rebind clears the interface the kernel scoped this socket to, so that sends are routed against the current
|
||||||
// routing table instead of the interface we happened to be on when the socket was created. Darwin pins sockets
|
// routing table instead of the interface we happened to be on when the socket was created. Darwin pins sockets
|
||||||
// this way on its own, which is what strands us after the underlying network changes.
|
// this way on its own, which is what strands us after the underlying network changes. Control.RebindUDPServer
|
||||||
|
// rebinds only the first writer, so this clears the other listen routines' listeners too. Connected sockets are
|
||||||
|
// closed after the listeners are cleared, and later ones copy the cleared scope and pick their source addresses
|
||||||
|
// afresh.
|
||||||
func (u *StdConn) Rebind() error {
|
func (u *StdConn) Rebind() error {
|
||||||
var err error
|
var err error
|
||||||
if u.isV4 {
|
if u.isV4 {
|
||||||
@@ -213,6 +293,23 @@ func (u *StdConn) Rebind() error {
|
|||||||
} else {
|
} else {
|
||||||
err = syscall.SetsockoptInt(int(u.sysFd), syscall.IPPROTO_IPV6, syscall.IPV6_BOUND_IF, 0)
|
err = syscall.SetsockoptInt(int(u.sysFd), syscall.IPPROTO_IPV6, syscall.IPV6_BOUND_IF, 0)
|
||||||
}
|
}
|
||||||
|
for _, m := range u.socks.siblings(u) {
|
||||||
|
err = errors.Join(err, m.clearBoundIf())
|
||||||
|
}
|
||||||
|
u.closeConnSocks("rebind")
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// clearBoundIf clears the interface the listener is scoped to through its RawConn, which fails on a listener that
|
||||||
|
// closed concurrently instead of reaching whatever reused its descriptor number.
|
||||||
|
func (u *StdConn) clearBoundIf() error {
|
||||||
|
level, opt := syscall.IPPROTO_IPV6, syscall.IPV6_BOUND_IF
|
||||||
|
if u.isV4 {
|
||||||
|
level, opt = syscall.IPPROTO_IP, syscall.IP_BOUND_IF
|
||||||
|
}
|
||||||
|
var serr error
|
||||||
|
if err := u.rc.Control(func(fd uintptr) { serr = syscall.SetsockoptInt(int(fd), level, opt, 0) }); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return serr
|
||||||
|
}
|
||||||
Reference in new issue
Block a user