mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 16:26:52 +01:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c914ea30ed |
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
-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,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)
|
||||||
@@ -281,6 +293,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 +316,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)
|
|
||||||
}
|
|
||||||
+67
-1
@@ -607,6 +607,72 @@ func (t *tun) Read(to []byte) (int, error) {
|
|||||||
return n - 4, nil
|
return n - 4, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// tunReadBatch is the most packets one tunQueue.Read returns.
|
||||||
|
const tunReadBatch = 64
|
||||||
|
|
||||||
|
// tunReadArena is tunQueue's receive buffer. Draining stops once less than defaultBatchBufSize of it
|
||||||
|
// is left, so every readv has room for the largest packet utun can return at any device MTU.
|
||||||
|
const tunReadArena = 4 * defaultBatchBufSize
|
||||||
|
|
||||||
|
// tunQueue is the darwin tun's Queue. Read drains every packet already queued on the utun, up to
|
||||||
|
// tunReadBatch, so the caller encrypts and sends them as one batch rather than one per wakeup.
|
||||||
|
type tunQueue struct {
|
||||||
|
t *tun
|
||||||
|
buf []byte
|
||||||
|
pkts [tunReadBatch]tio.Packet
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read waits for the utun to become readable, then reads packets until it would block. An error after
|
||||||
|
// at least one packet is dropped in favor of returning those packets; a persistent one recurs on the
|
||||||
|
// next Read.
|
||||||
|
func (q *tunQueue) Read() ([]tio.Packet, error) {
|
||||||
|
rc, err := q.t.f.SyscallConn()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
var head [4]byte
|
||||||
|
n, off := 0, 0
|
||||||
|
var callErr error
|
||||||
|
err = rc.Read(func(fd uintptr) bool {
|
||||||
|
for n < tunReadBatch && len(q.buf)-off >= defaultBatchBufSize {
|
||||||
|
iovecs := [2]unix.Iovec{
|
||||||
|
{Base: &head[0], Len: 4},
|
||||||
|
{Base: &q.buf[off], Len: uint64(len(q.buf) - off)},
|
||||||
|
}
|
||||||
|
l, e := tunReadv(int(fd), iovecs[:])
|
||||||
|
if e != nil {
|
||||||
|
if errno, ok := e.(syscall.Errno); ok && errno.Temporary() {
|
||||||
|
// Park on the poller only while there is nothing to hand back.
|
||||||
|
return n > 0
|
||||||
|
}
|
||||||
|
callErr = e
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if l < 4 {
|
||||||
|
// A datagram too short to carry the AF prefix, or end of file; stop rather than spin on it.
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
end := off + l - 4
|
||||||
|
q.pkts[n] = tio.Packet{Bytes: q.buf[off:end:end]}
|
||||||
|
n++
|
||||||
|
off = end
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
})
|
||||||
|
if n > 0 {
|
||||||
|
return q.pkts[:n], nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return nil, callErr
|
||||||
|
}
|
||||||
|
|
||||||
|
func (q *tunQueue) Write(p []byte) (int, error) { return q.t.Write(p) }
|
||||||
|
|
||||||
|
func (q *tunQueue) Close() error { return q.t.Close() }
|
||||||
|
|
||||||
// Write pushes one IP packet onto the utun device. Safe for concurrent use:
|
// Write pushes one IP packet onto the utun device. Safe for concurrent use:
|
||||||
// the AF prefix and iovecs are per-call stack state, and the fd write itself
|
// the AF prefix and iovecs are per-call stack state, and the fd write itself
|
||||||
// serializes on the runtime's fd mutex (see the Queue contract in tio.go).
|
// serializes on the runtime's fd mutex (see the Queue contract in tio.go).
|
||||||
@@ -666,5 +732,5 @@ func (t *tun) Name() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) Queues(int) ([]tio.Queue, error) {
|
func (t *tun) Queues(int) ([]tio.Queue, error) {
|
||||||
return []tio.Queue{tio.NewSingleQueue(t, defaultBatchBufSize)}, nil
|
return []tio.Queue{&tunQueue{t: t, buf: make([]byte, tunReadArena)}}, nil
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
//go:build !ios && !e2e_testing
|
||||||
|
|
||||||
|
package overlay
|
||||||
|
|
||||||
|
import (
|
||||||
|
"os"
|
||||||
|
"syscall"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/slackhq/nebula/test"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
)
|
||||||
|
|
||||||
|
// newSocketpairTun returns a tun on one end of a connected AF_UNIX datagram socketpair, which keeps
|
||||||
|
// datagram boundaries the way a utun control socket does, and the other end's fd.
|
||||||
|
// sndbuf is the tun end's send buffer, which caps the largest datagram it accepts.
|
||||||
|
func newSocketpairTun(t *testing.T, sndbuf int) (*tun, int) {
|
||||||
|
t.Helper()
|
||||||
|
fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_DGRAM, 0)
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_SNDBUF, sndbuf))
|
||||||
|
require.NoError(t, unix.SetsockoptInt(fds[1], unix.SOL_SOCKET, unix.SO_RCVBUF, 1<<20))
|
||||||
|
// A dropped datagram fails the read-back instead of hanging it.
|
||||||
|
require.NoError(t, unix.SetsockoptTimeval(fds[1], unix.SOL_SOCKET, unix.SO_RCVTIMEO, &unix.Timeval{Sec: 2}))
|
||||||
|
require.NoError(t, unix.SetNonblock(fds[0], true))
|
||||||
|
f := os.NewFile(uintptr(fds[0]), "socketpair")
|
||||||
|
t.Cleanup(func() {
|
||||||
|
_ = f.Close()
|
||||||
|
_ = unix.Close(fds[1])
|
||||||
|
})
|
||||||
|
return &tun{f: f, l: test.NewLogger()}, fds[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
// testTunPkt returns packet i of size bytes, alternating IPv4 and IPv6, and the same packet as a utun
|
||||||
|
// datagram, behind its AF prefix.
|
||||||
|
func testTunPkt(i, size int) (pkt, wire []byte) {
|
||||||
|
pkt = make([]byte, size)
|
||||||
|
pkt[0] = 0x45
|
||||||
|
af := byte(syscall.AF_INET)
|
||||||
|
if i%2 == 1 {
|
||||||
|
pkt[0] = 0x60
|
||||||
|
af = syscall.AF_INET6
|
||||||
|
}
|
||||||
|
pkt[1] = byte(i)
|
||||||
|
pkt[2] = byte(i >> 8)
|
||||||
|
return pkt, append([]byte{0, 0, 0, af}, pkt...)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTunQueueReadDrains pins that Read hands back every queued packet, AF prefix stripped and in
|
||||||
|
// order, capped at tunReadBatch per call, and doesn't wait for more once the queue is empty.
|
||||||
|
func TestTunQueueReadDrains(t *testing.T) {
|
||||||
|
tn, w := newSocketpairTun(t, 1<<20)
|
||||||
|
// An AF_UNIX datagram send is bounded by the receiver's buffer, here the tun's end.
|
||||||
|
rc, err := tn.f.SyscallConn()
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.NoError(t, rc.Control(func(fd uintptr) {
|
||||||
|
require.NoError(t, unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RCVBUF, 1<<20))
|
||||||
|
}))
|
||||||
|
q := &tunQueue{t: tn, buf: make([]byte, tunReadArena)}
|
||||||
|
total := tunReadBatch + 3
|
||||||
|
var want [][]byte
|
||||||
|
for i := range total {
|
||||||
|
pkt, wire := testTunPkt(i, 60+i)
|
||||||
|
_, err := unix.Write(w, wire)
|
||||||
|
require.NoError(t, err)
|
||||||
|
want = append(want, pkt)
|
||||||
|
}
|
||||||
|
|
||||||
|
var got [][]byte
|
||||||
|
for _, size := range []int{tunReadBatch, 3} {
|
||||||
|
pkts, err := q.Read()
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Len(t, pkts, size)
|
||||||
|
for _, p := range pkts {
|
||||||
|
got = append(got, p.Clone().Bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert.Equal(t, want, got)
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestTunQueueReadClipsPackets pins that each returned packet's capacity ends at its own bytes, so
|
||||||
|
// appending to one can't overwrite the next.
|
||||||
|
func TestTunQueueReadClipsPackets(t *testing.T) {
|
||||||
|
tn, w := newSocketpairTun(t, 1<<20)
|
||||||
|
q := &tunQueue{t: tn, buf: make([]byte, tunReadArena)}
|
||||||
|
for i := range 2 {
|
||||||
|
_, wire := testTunPkt(i, 100)
|
||||||
|
_, err := unix.Write(w, wire)
|
||||||
|
require.NoError(t, err)
|
||||||
|
}
|
||||||
|
pkts, err := q.Read()
|
||||||
|
require.NoError(t, err)
|
||||||
|
require.Len(t, pkts, 2)
|
||||||
|
assert.Equal(t, len(pkts[0].Bytes), cap(pkts[0].Bytes))
|
||||||
|
}
|
||||||
Reference in new issue
Block a user