mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 15:26:52 +01:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6826c04103 | ||
|
|
5bf666dd90 | ||
|
|
49207da077 |
No files matched your search
@@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
|
||||||
|
- The SSH debug server's `start-cpu-profile`, `stop-cpu-profile`, `save-heap-profile`, `save-mutex-profile`, and
|
||||||
|
`mutex-profile-fraction` commands, and `sshd.sandbox_dir`, which is now ignored if set.
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
- `create-tunnel -address <ip:port>` panicked on a nil RemoteList and, over the ssh debug server, took nebula
|
- `create-tunnel -address <ip:port>` panicked on a nil RemoteList and, over the ssh debug server, took nebula
|
||||||
|
|||||||
+1
-7
@@ -8,6 +8,7 @@ pki:
|
|||||||
cert: /etc/nebula/host.crt
|
cert: /etc/nebula/host.crt
|
||||||
key: /etc/nebula/host.key
|
key: /etc/nebula/host.key
|
||||||
# blocklist is a list of certificate fingerprints that we will refuse to talk to
|
# blocklist is a list of certificate fingerprints that we will refuse to talk to
|
||||||
|
# Entries are the hex fingerprints shown by `nebula-cert print`, an invalid entry fails startup and reload.
|
||||||
#blocklist:
|
#blocklist:
|
||||||
# - c99d4e650533b92061b09918e838a5a0a6aaee21eed1d12fd937682865936c72
|
# - c99d4e650533b92061b09918e838a5a0a6aaee21eed1d12fd937682865936c72
|
||||||
# disconnect_invalid is a toggle to force a client to be disconnected if the certificate is expired or invalid.
|
# disconnect_invalid is a toggle to force a client to be disconnected if the certificate is expired or invalid.
|
||||||
@@ -232,13 +233,6 @@ punchy:
|
|||||||
# Trusted SSH CA public keys. These are the public keys of the CAs that are allowed to sign SSH keys for access.
|
# Trusted SSH CA public keys. These are the public keys of the CAs that are allowed to sign SSH keys for access.
|
||||||
#trusted_cas:
|
#trusted_cas:
|
||||||
#- "ssh public key string"
|
#- "ssh public key string"
|
||||||
# sandbox_dir restricts file paths for profiling commands (start-cpu-profile, save-heap-profile,
|
|
||||||
# save-mutex-profile) to the specified directory. Relative paths will be resolved within this directory,
|
|
||||||
# and absolute paths outside of it will be rejected. Default is $TMP/nebula-debug.
|
|
||||||
# The directory is NOT automatically created.
|
|
||||||
# Overriding this to "" is the same as "/" and will allow overwriting any path on the host.
|
|
||||||
# Not reloadable.
|
|
||||||
#sandbox_dir: /var/tmp/nebula-debug
|
|
||||||
|
|
||||||
# EXPERIMENTAL: relay support for networks that can't establish direct connections.
|
# EXPERIMENTAL: relay support for networks that can't establish direct connections.
|
||||||
relay:
|
relay:
|
||||||
|
|||||||
+34
-101
@@ -32,21 +32,16 @@ type conn struct {
|
|||||||
Expires time.Time // Time when this conntrack entry will expire
|
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 or when the peer handshakes again, which may present a
|
// after ruleset changes. Note, rulesVersion is a uint16 so that these two
|
||||||
// cert with different groups. These pack into the word after Expires.
|
// fields pack for free after the uint32 above
|
||||||
incoming bool
|
incoming bool
|
||||||
rulesVersion uint16
|
rulesVersion uint16
|
||||||
localIndex uint32
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// TODO: need conntrack max tracked connections handling
|
// TODO: need conntrack max tracked connections handling
|
||||||
type Firewall struct {
|
type Firewall struct {
|
||||||
Conntrack *FirewallConntrack
|
Conntrack *FirewallConntrack
|
||||||
|
|
||||||
// siblings finds the other gateways we route an unsafe network through, so a reply that comes back through a
|
|
||||||
// different gateway than the flow went out through can be matched to it. Nil turns that off.
|
|
||||||
siblings gatewaySiblings
|
|
||||||
|
|
||||||
InRules *FirewallTable
|
InRules *FirewallTable
|
||||||
OutRules *FirewallTable
|
OutRules *FirewallTable
|
||||||
|
|
||||||
@@ -87,8 +82,8 @@ type firewallMetrics struct {
|
|||||||
type FirewallConntrack struct {
|
type FirewallConntrack struct {
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
|
|
||||||
Conns map[firewall.ConntrackKey]*conn
|
Conns map[firewall.Packet]*conn
|
||||||
TimerWheel *TimerWheel[firewall.ConntrackKey]
|
TimerWheel *TimerWheel[firewall.Packet]
|
||||||
}
|
}
|
||||||
|
|
||||||
// FirewallTable is the entry point for a rule, the evaluation order is:
|
// FirewallTable is the entry point for a rule, the evaluation order is:
|
||||||
@@ -172,8 +167,8 @@ func NewFirewall(l *slog.Logger, tcpTimeout, UDPTimeout, defaultTimeout time.Dur
|
|||||||
|
|
||||||
return &Firewall{
|
return &Firewall{
|
||||||
Conntrack: &FirewallConntrack{
|
Conntrack: &FirewallConntrack{
|
||||||
Conns: make(map[firewall.ConntrackKey]*conn),
|
Conns: make(map[firewall.Packet]*conn),
|
||||||
TimerWheel: NewTimerWheel[firewall.ConntrackKey](tmin, tmax),
|
TimerWheel: NewTimerWheel[firewall.Packet](tmin, tmax),
|
||||||
},
|
},
|
||||||
InRules: newFirewallTable(),
|
InRules: newFirewallTable(),
|
||||||
OutRules: newFirewallTable(),
|
OutRules: newFirewallTable(),
|
||||||
@@ -430,7 +425,6 @@ var ErrNoMatchingRule = errors.New("no matching rule in firewall table")
|
|||||||
// 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, localCache firewall.ConntrackCache) 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
|
||||||
unsafe := false
|
|
||||||
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
|
||||||
if h.vpnAddrs[0] != fp.RemoteAddr {
|
if h.vpnAddrs[0] != fp.RemoteAddr {
|
||||||
@@ -450,7 +444,7 @@ func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *
|
|||||||
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
||||||
return ErrPeerRejected // reject for now, one day this may have different FW rules
|
return ErrPeerRejected // reject for now, one day this may have different FW rules
|
||||||
case NetworkTypeUnsafe:
|
case NetworkTypeUnsafe:
|
||||||
unsafe = true // nothing else special, one day this may have different FW rules
|
break // nothing special, one day this may have different FW rules
|
||||||
default:
|
default:
|
||||||
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
f.metrics(incoming).droppedRemoteAddr.Inc(1)
|
||||||
return ErrUnknownNetworkType //should never happen
|
return ErrUnknownNetworkType //should never happen
|
||||||
@@ -463,11 +457,8 @@ func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *
|
|||||||
return ErrInvalidLocalIP
|
return ErrInvalidLocalIP
|
||||||
}
|
}
|
||||||
|
|
||||||
// The first vpn address identifies the peer, as it does elsewhere. A host's v1 and v2 certs must agree on it
|
|
||||||
key := firewall.ConntrackKey{Packet: fp, Peer: h.vpnAddrs[0]}
|
|
||||||
|
|
||||||
// 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(key, h, caPool, localCache) {
|
if f.inConns(fp, h, caPool, localCache) {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -478,15 +469,12 @@ func (f *Firewall) Drop(fp firewall.Packet, incoming bool, h *HostInfo, caPool *
|
|||||||
|
|
||||||
// We now know which firewall table to check against
|
// We now know which firewall table to check against
|
||||||
if !table.match(fp, incoming, h.ConnectionState.peerCert, caPool) {
|
if !table.match(fp, incoming, h.ConnectionState.peerCert, caPool) {
|
||||||
if unsafe && f.inheritConn(key, incoming, h, caPool) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
f.metrics(incoming).droppedNoRule.Inc(1)
|
f.metrics(incoming).droppedNoRule.Inc(1)
|
||||||
return ErrNoMatchingRule
|
return ErrNoMatchingRule
|
||||||
}
|
}
|
||||||
|
|
||||||
// We always want to conntrack since it is a faster operation
|
// We always want to conntrack since it is a faster operation
|
||||||
f.addConn(key, incoming, h)
|
f.addConn(fp, incoming)
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
@@ -515,9 +503,9 @@ func (f *Firewall) EmitStats() {
|
|||||||
metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
|
metrics.GetOrRegisterGauge("firewall.rules.hash", nil).Update(int64(f.GetRuleHashFNV()))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Firewall) inConns(key firewall.ConntrackKey, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) bool {
|
func (f *Firewall) inConns(fp firewall.Packet, h *HostInfo, caPool *cert.CAPool, localCache firewall.ConntrackCache) bool {
|
||||||
if localCache != nil {
|
if localCache != nil {
|
||||||
if _, ok := localCache[key]; ok {
|
if _, ok := localCache[fp]; ok {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -530,52 +518,49 @@ func (f *Firewall) inConns(key firewall.ConntrackKey, h *HostInfo, caPool *cert.
|
|||||||
f.evict(ep)
|
f.evict(ep)
|
||||||
}
|
}
|
||||||
|
|
||||||
c, ok := conntrack.Conns[key]
|
c, ok := conntrack.Conns[fp]
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
conntrack.Unlock()
|
conntrack.Unlock()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.rulesVersion != f.rulesVersion || c.localIndex != h.localIndexId {
|
if c.rulesVersion != f.rulesVersion {
|
||||||
// This conntrack entry was allowed by an older rule set or for an earlier tunnel to the peer, validate
|
// This conntrack entry was for an older rule set, validate
|
||||||
// it still passes with the current rule set and the peer's current certificate
|
// it still passes with the current rule set
|
||||||
table := f.OutRules
|
table := f.OutRules
|
||||||
if c.incoming {
|
if c.incoming {
|
||||||
table = f.InRules
|
table = f.InRules
|
||||||
}
|
}
|
||||||
|
|
||||||
// We now know which firewall table to check against
|
// We now know which firewall table to check against
|
||||||
if !table.match(key.Packet, c.incoming, h.ConnectionState.peerCert, caPool) {
|
if !table.match(fp, c.incoming, h.ConnectionState.peerCert, caPool) {
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
h.logger(f.l).Debug("dropping old conntrack entry, does not match current ruleset and certificate",
|
h.logger(f.l).Debug("dropping old conntrack entry, does not match new ruleset",
|
||||||
"fwPacket", key.Packet,
|
"fwPacket", fp,
|
||||||
"incoming", c.incoming,
|
"incoming", c.incoming,
|
||||||
"rulesVersion", f.rulesVersion,
|
"rulesVersion", f.rulesVersion,
|
||||||
"oldRulesVersion", c.rulesVersion,
|
"oldRulesVersion", c.rulesVersion,
|
||||||
"oldLocalIndex", c.localIndex,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
delete(conntrack.Conns, key)
|
delete(conntrack.Conns, fp)
|
||||||
conntrack.Unlock()
|
conntrack.Unlock()
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
h.logger(f.l).Debug("keeping old conntrack entry, does match current ruleset and certificate",
|
h.logger(f.l).Debug("keeping old conntrack entry, does match new ruleset",
|
||||||
"fwPacket", key.Packet,
|
"fwPacket", fp,
|
||||||
"incoming", c.incoming,
|
"incoming", c.incoming,
|
||||||
"rulesVersion", f.rulesVersion,
|
"rulesVersion", f.rulesVersion,
|
||||||
"oldRulesVersion", c.rulesVersion,
|
"oldRulesVersion", c.rulesVersion,
|
||||||
"oldLocalIndex", c.localIndex,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
c.rulesVersion = f.rulesVersion
|
c.rulesVersion = f.rulesVersion
|
||||||
c.localIndex = h.localIndexId
|
|
||||||
}
|
}
|
||||||
|
|
||||||
switch key.Protocol {
|
switch fp.Protocol {
|
||||||
case iputil.IPProtocolTCP:
|
case iputil.IPProtocolTCP:
|
||||||
c.Expires = time.Now().Add(f.TCPTimeout)
|
c.Expires = time.Now().Add(f.TCPTimeout)
|
||||||
case iputil.IPProtocolUDP:
|
case iputil.IPProtocolUDP:
|
||||||
@@ -587,17 +572,17 @@ func (f *Firewall) inConns(key firewall.ConntrackKey, h *HostInfo, caPool *cert.
|
|||||||
conntrack.Unlock()
|
conntrack.Unlock()
|
||||||
|
|
||||||
if localCache != nil {
|
if localCache != nil {
|
||||||
localCache[key] = struct{}{}
|
localCache[fp] = struct{}{}
|
||||||
}
|
}
|
||||||
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Firewall) addConn(key firewall.ConntrackKey, incoming bool, h *HostInfo) {
|
func (f *Firewall) addConn(fp firewall.Packet, incoming bool) {
|
||||||
var timeout time.Duration
|
var timeout time.Duration
|
||||||
c := &conn{}
|
c := &conn{}
|
||||||
|
|
||||||
switch key.Protocol {
|
switch fp.Protocol {
|
||||||
case iputil.IPProtocolTCP:
|
case iputil.IPProtocolTCP:
|
||||||
timeout = f.TCPTimeout
|
timeout = f.TCPTimeout
|
||||||
case iputil.IPProtocolUDP:
|
case iputil.IPProtocolUDP:
|
||||||
@@ -608,78 +593,26 @@ func (f *Firewall) addConn(key firewall.ConntrackKey, incoming bool, h *HostInfo
|
|||||||
|
|
||||||
conntrack := f.Conntrack
|
conntrack := f.Conntrack
|
||||||
conntrack.Lock()
|
conntrack.Lock()
|
||||||
if _, ok := conntrack.Conns[key]; !ok {
|
if _, ok := conntrack.Conns[fp]; !ok {
|
||||||
conntrack.TimerWheel.Advance(time.Now())
|
conntrack.TimerWheel.Advance(time.Now())
|
||||||
conntrack.TimerWheel.Add(key, timeout)
|
conntrack.TimerWheel.Add(fp, timeout)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Record which rulesVersion and tunnel allowed this connection, so we can retest after
|
// Record which rulesVersion allowed this connection, so we can retest after
|
||||||
// firewall reload or when the peer handshakes again
|
// firewall reload
|
||||||
c.incoming = incoming
|
c.incoming = incoming
|
||||||
c.rulesVersion = f.rulesVersion
|
c.rulesVersion = f.rulesVersion
|
||||||
c.localIndex = h.localIndexId
|
|
||||||
c.Expires = time.Now().Add(timeout)
|
c.Expires = time.Now().Add(timeout)
|
||||||
conntrack.Conns[key] = c
|
conntrack.Conns[fp] = c
|
||||||
conntrack.Unlock()
|
conntrack.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
// gatewaySiblings finds the other gateways we route an unsafe network through
|
|
||||||
type gatewaySiblings interface {
|
|
||||||
// siblingPeers appends to buf the conntrack peer of every other gateway we route remote through, if h is one of
|
|
||||||
// those gateways
|
|
||||||
siblingPeers(remote netip.Addr, h *HostInfo, buf []netip.Addr) []netip.Addr
|
|
||||||
}
|
|
||||||
|
|
||||||
// inheritConn lets h carry a flow that another of our gateways for the same unsafe network already carries. We
|
|
||||||
// spread the flows we open across the gateways, but the hosts behind them answer through whichever gateway their own
|
|
||||||
// routing picks, so a reply can come back through a different gateway than the flow went out through. The flow is
|
|
||||||
// checked against the rules that allowed it in the first place with h's certificate, the same check an entry gets
|
|
||||||
// when its peer reconnects. Peers that aren't one of our gateways for the network never inherit a flow.
|
|
||||||
func (f *Firewall) inheritConn(key firewall.ConntrackKey, incoming bool, h *HostInfo, caPool *cert.CAPool) bool {
|
|
||||||
if f.siblings == nil {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
var buf [4]netip.Addr
|
|
||||||
now := time.Now()
|
|
||||||
for _, peer := range f.siblings.siblingPeers(key.RemoteAddr, h, buf[:0]) {
|
|
||||||
sk := key
|
|
||||||
sk.Peer = peer
|
|
||||||
conntrack := f.Conntrack
|
|
||||||
conntrack.Lock()
|
|
||||||
c, ok := conntrack.Conns[sk]
|
|
||||||
live := ok && c.Expires.After(now)
|
|
||||||
var allowedIncoming bool
|
|
||||||
if live {
|
|
||||||
allowedIncoming = c.incoming
|
|
||||||
}
|
|
||||||
conntrack.Unlock()
|
|
||||||
|
|
||||||
// The rules for this packet's own direction already said no, only a flow allowed the other way can help
|
|
||||||
if !live || allowedIncoming == incoming {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
table := f.OutRules
|
|
||||||
if allowedIncoming {
|
|
||||||
table = f.InRules
|
|
||||||
}
|
|
||||||
if !table.match(key.Packet, allowedIncoming, h.ConnectionState.peerCert, caPool) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
f.addConn(key, allowedIncoming, h)
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
// Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
|
// Evict checks if a conntrack entry has expired, if so it is removed, if not it is re-added to the wheel
|
||||||
// Caller must own the connMutex lock!
|
// Caller must own the connMutex lock!
|
||||||
func (f *Firewall) evict(key firewall.ConntrackKey) {
|
func (f *Firewall) evict(p firewall.Packet) {
|
||||||
// Are we still tracking this conn?
|
// Are we still tracking this conn?
|
||||||
conntrack := f.Conntrack
|
conntrack := f.Conntrack
|
||||||
t, ok := conntrack.Conns[key]
|
t, ok := conntrack.Conns[p]
|
||||||
if !ok {
|
if !ok {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -689,12 +622,12 @@ func (f *Firewall) evict(key firewall.ConntrackKey) {
|
|||||||
// Timeout is in the future, re-add the timer
|
// Timeout is in the future, re-add the timer
|
||||||
if newT > 0 {
|
if newT > 0 {
|
||||||
conntrack.TimerWheel.Advance(time.Now())
|
conntrack.TimerWheel.Advance(time.Now())
|
||||||
conntrack.TimerWheel.Add(key, newT)
|
conntrack.TimerWheel.Add(p, newT)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// This conn is done
|
// This conn is done
|
||||||
delete(conntrack.Conns, key)
|
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 {
|
||||||
|
|||||||
+1
-9
@@ -3,23 +3,15 @@ package firewall
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/netip"
|
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/logging"
|
"github.com/slackhq/nebula/logging"
|
||||||
)
|
)
|
||||||
|
|
||||||
// ConntrackKey identifies a tracked flow by its packet and the peer it was allowed for, so peers that route
|
|
||||||
// the same unsafe network never share a conntrack entry.
|
|
||||||
type ConntrackKey struct {
|
|
||||||
Peer netip.Addr
|
|
||||||
Packet
|
|
||||||
}
|
|
||||||
|
|
||||||
// ConntrackCache is used as a local routine cache to know if a given flow
|
// ConntrackCache is used as a local routine cache to know if a given flow
|
||||||
// has been seen in the conntrack table.
|
// has been seen in the conntrack table.
|
||||||
type ConntrackCache map[ConntrackKey]struct{}
|
type ConntrackCache map[Packet]struct{}
|
||||||
|
|
||||||
type ConntrackCacheTicker struct {
|
type ConntrackCacheTicker struct {
|
||||||
cacheV uint64
|
cacheV uint64
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ func newFixedTicker(t *testing.T, l *slog.Logger, cacheLen int) *ConntrackCacheT
|
|||||||
cache: make(ConntrackCache, cacheLen),
|
cache: make(ConntrackCache, cacheLen),
|
||||||
}
|
}
|
||||||
for i := range cacheLen {
|
for i := range cacheLen {
|
||||||
c.cache[ConntrackKey{Packet: Packet{LocalPort: uint16(i) + 1}}] = struct{}{}
|
c.cache[Packet{LocalPort: uint16(i) + 1}] = struct{}{}
|
||||||
}
|
}
|
||||||
c.cacheTick.Store(1) // cacheV starts at 0, so Get() takes the reset path
|
c.cacheTick.Store(1) // cacheV starts at 0, so Get() takes the reset path
|
||||||
return c
|
return c
|
||||||
|
|||||||
@@ -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 trailing padding so maps hash and compare a ConntrackKey as one
|
|
||||||
// block of memory instead of field by field. It must always be zero.
|
|
||||||
pad [2]byte
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (fp *Packet) Copy() *Packet {
|
func (fp *Packet) Copy() *Packet {
|
||||||
|
|||||||
+1
-248
@@ -3,7 +3,6 @@ package nebula
|
|||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"math"
|
"math"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
@@ -980,252 +979,6 @@ func TestFirewall_ConntrackSourceSpoofingAcrossPeers(t *testing.T) {
|
|||||||
"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 TestFirewall_ConntrackUnsafeNetworkPeers(t *testing.T) {
|
|
||||||
l := test.NewLoggerWithOutput(&bytes.Buffer{})
|
|
||||||
|
|
||||||
myVpnNetworksTable := new(bart.Lite)
|
|
||||||
myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.1/24"))
|
|
||||||
|
|
||||||
owner := &dummyCert{
|
|
||||||
name: "owner",
|
|
||||||
networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Two routers for the same unsafe network, only one of them is trusted inbound
|
|
||||||
router := func(name string, addr string, groups ...string) *HostInfo {
|
|
||||||
inverted := map[string]struct{}{}
|
|
||||||
for _, g := range groups {
|
|
||||||
inverted[g] = struct{}{}
|
|
||||||
}
|
|
||||||
c := &cert.CachedCertificate{
|
|
||||||
Certificate: &dummyCert{
|
|
||||||
name: name,
|
|
||||||
groups: groups,
|
|
||||||
networks: []netip.Prefix{netip.MustParsePrefix(addr + "/24")},
|
|
||||||
unsafeNetworks: []netip.Prefix{netip.MustParsePrefix("198.51.100.0/24")},
|
|
||||||
},
|
|
||||||
InvertedGroups: inverted,
|
|
||||||
}
|
|
||||||
h := &HostInfo{
|
|
||||||
ConnectionState: &ConnectionState{peerCert: c},
|
|
||||||
vpnAddrs: []netip.Addr{netip.MustParseAddr(addr)},
|
|
||||||
}
|
|
||||||
h.buildNetworks(myVpnNetworksTable, c.Certificate)
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
trusted := router("trusted", "192.0.2.2", "trusted")
|
|
||||||
other := router("other", "192.0.2.3")
|
|
||||||
|
|
||||||
cp := cert.NewCAPool()
|
|
||||||
flow := firewall.Packet{
|
|
||||||
LocalAddr: netip.MustParseAddr("192.0.2.1"),
|
|
||||||
RemoteAddr: netip.MustParseAddr("198.51.100.5"),
|
|
||||||
LocalPort: 443,
|
|
||||||
RemotePort: 55000,
|
|
||||||
Protocol: iputil.IPProtocolTCP,
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, useCache := range []bool{false, true} {
|
|
||||||
var cache firewall.ConntrackCache
|
|
||||||
if useCache {
|
|
||||||
cache = firewall.ConntrackCache{}
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run(fmt.Sprintf("inbound flow allowed for one peer/cache=%v", useCache), func(t *testing.T) {
|
|
||||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, owner)
|
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"trusted"}, "", "", "", "", ""))
|
|
||||||
clear(cache)
|
|
||||||
|
|
||||||
require.NoError(t, fw.Drop(flow, true, trusted, cp, cache))
|
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(flow, true, other, cp, cache))
|
|
||||||
require.NoError(t, fw.Drop(flow, true, trusted, cp, cache))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run(fmt.Sprintf("reply to a flow opened via one peer/cache=%v", useCache), func(t *testing.T) {
|
|
||||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, owner)
|
|
||||||
require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
|
||||||
clear(cache)
|
|
||||||
|
|
||||||
require.NoError(t, fw.Drop(flow, false, trusted, cp, cache))
|
|
||||||
require.NoError(t, fw.Drop(flow, true, trusted, cp, cache))
|
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(flow, true, other, cp, cache))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// fakeSiblings maps each gateway to the conntrack peers of the gateways it shares a route with
|
|
||||||
type fakeSiblings map[*HostInfo][]netip.Addr
|
|
||||||
|
|
||||||
func (s fakeSiblings) siblingPeers(_ netip.Addr, h *HostInfo, buf []netip.Addr) []netip.Addr {
|
|
||||||
return append(buf, s[h]...)
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFirewall_ConntrackGatewaySiblings(t *testing.T) {
|
|
||||||
l := test.NewLoggerWithOutput(&bytes.Buffer{})
|
|
||||||
|
|
||||||
myVpnNetworksTable := new(bart.Lite)
|
|
||||||
myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.1/24"))
|
|
||||||
|
|
||||||
owner := &dummyCert{
|
|
||||||
name: "owner",
|
|
||||||
networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Routers for the same unsafe network. a and b are both our gateways for it, c only claims it in its cert
|
|
||||||
router := func(name string, addr string, groups ...string) *HostInfo {
|
|
||||||
inverted := map[string]struct{}{}
|
|
||||||
for _, g := range groups {
|
|
||||||
inverted[g] = struct{}{}
|
|
||||||
}
|
|
||||||
c := &cert.CachedCertificate{
|
|
||||||
Certificate: &dummyCert{
|
|
||||||
name: name,
|
|
||||||
groups: groups,
|
|
||||||
networks: []netip.Prefix{netip.MustParsePrefix(addr + "/24")},
|
|
||||||
unsafeNetworks: []netip.Prefix{netip.MustParsePrefix("198.51.100.0/24")},
|
|
||||||
},
|
|
||||||
InvertedGroups: inverted,
|
|
||||||
}
|
|
||||||
h := &HostInfo{
|
|
||||||
ConnectionState: &ConnectionState{peerCert: c},
|
|
||||||
vpnAddrs: []netip.Addr{netip.MustParseAddr(addr)},
|
|
||||||
}
|
|
||||||
h.buildNetworks(myVpnNetworksTable, c.Certificate)
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
a := router("a", "192.0.2.2", "trusted")
|
|
||||||
b := router("b", "192.0.2.3", "trusted")
|
|
||||||
c := router("c", "192.0.2.4", "trusted")
|
|
||||||
siblings := fakeSiblings{a: {b.vpnAddrs[0]}, b: {a.vpnAddrs[0]}}
|
|
||||||
|
|
||||||
cp := cert.NewCAPool()
|
|
||||||
flow := firewall.Packet{
|
|
||||||
LocalAddr: netip.MustParseAddr("192.0.2.1"),
|
|
||||||
RemoteAddr: netip.MustParseAddr("198.51.100.5"),
|
|
||||||
LocalPort: 55000,
|
|
||||||
RemotePort: 443,
|
|
||||||
Protocol: iputil.IPProtocolTCP,
|
|
||||||
}
|
|
||||||
|
|
||||||
// We open flows through our gateways, nothing is allowed in on its own
|
|
||||||
newFirewall := func(outGroup string) *Firewall {
|
|
||||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, owner)
|
|
||||||
require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{outGroup}, "", "", "", "", ""))
|
|
||||||
fw.siblings = siblings
|
|
||||||
return fw
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("reply through the other gateway", func(t *testing.T) {
|
|
||||||
fw := newFirewall("trusted")
|
|
||||||
require.NoError(t, fw.Drop(flow, false, b, cp, nil))
|
|
||||||
require.NoError(t, fw.Drop(flow, true, a, cp, nil))
|
|
||||||
|
|
||||||
// a has its own entry now, and keeps the flow when b's is gone
|
|
||||||
delete(fw.Conntrack.Conns, firewall.ConntrackKey{Packet: flow, Peer: b.vpnAddrs[0]})
|
|
||||||
require.NoError(t, fw.Drop(flow, true, a, cp, nil))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("not our gateway", func(t *testing.T) {
|
|
||||||
fw := newFirewall("trusted")
|
|
||||||
require.NoError(t, fw.Drop(flow, false, b, cp, nil))
|
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(flow, true, c, cp, nil))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("off without siblings", func(t *testing.T) {
|
|
||||||
fw := newFirewall("trusted")
|
|
||||||
fw.siblings = nil
|
|
||||||
require.NoError(t, fw.Drop(flow, false, b, cp, nil))
|
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(flow, true, a, cp, nil))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("expired sibling entry", func(t *testing.T) {
|
|
||||||
fw := newFirewall("trusted")
|
|
||||||
require.NoError(t, fw.Drop(flow, false, b, cp, nil))
|
|
||||||
fw.Conntrack.Conns[firewall.ConntrackKey{Packet: flow, Peer: b.vpnAddrs[0]}].Expires = time.Now().Add(-time.Second)
|
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(flow, true, a, cp, nil))
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("the original rules must allow the new gateway", func(t *testing.T) {
|
|
||||||
fw := newFirewall("b-only")
|
|
||||||
b.ConnectionState.peerCert.InvertedGroups["b-only"] = struct{}{}
|
|
||||||
defer delete(b.ConnectionState.peerCert.InvertedGroups, "b-only")
|
|
||||||
|
|
||||||
require.NoError(t, fw.Drop(flow, false, b, cp, nil))
|
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(flow, true, a, cp, nil))
|
|
||||||
})
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestFirewall_ConntrackPeerRehandshake(t *testing.T) {
|
|
||||||
l := test.NewLoggerWithOutput(&bytes.Buffer{})
|
|
||||||
|
|
||||||
myVpnNetworksTable := new(bart.Lite)
|
|
||||||
myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.1/24"))
|
|
||||||
|
|
||||||
owner := &dummyCert{
|
|
||||||
name: "owner",
|
|
||||||
networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.1/24")},
|
|
||||||
}
|
|
||||||
|
|
||||||
// Each call is a new tunnel to the same peer, presenting a cert with the given groups
|
|
||||||
tunnel := func(localIndex uint32, groups ...string) *HostInfo {
|
|
||||||
inverted := map[string]struct{}{}
|
|
||||||
for _, g := range groups {
|
|
||||||
inverted[g] = struct{}{}
|
|
||||||
}
|
|
||||||
c := &cert.CachedCertificate{
|
|
||||||
Certificate: &dummyCert{
|
|
||||||
name: "peer",
|
|
||||||
groups: groups,
|
|
||||||
networks: []netip.Prefix{netip.MustParsePrefix("192.0.2.2/24"), netip.MustParsePrefix("2001:db8::2/64")},
|
|
||||||
},
|
|
||||||
InvertedGroups: inverted,
|
|
||||||
}
|
|
||||||
h := &HostInfo{
|
|
||||||
ConnectionState: &ConnectionState{peerCert: c},
|
|
||||||
vpnAddrs: []netip.Addr{netip.MustParseAddr("192.0.2.2"), netip.MustParseAddr("2001:db8::2")},
|
|
||||||
localIndexId: localIndex,
|
|
||||||
}
|
|
||||||
h.buildNetworks(myVpnNetworksTable, c.Certificate)
|
|
||||||
return h
|
|
||||||
}
|
|
||||||
|
|
||||||
cp := cert.NewCAPool()
|
|
||||||
flow := firewall.Packet{
|
|
||||||
LocalAddr: netip.MustParseAddr("192.0.2.1"),
|
|
||||||
RemoteAddr: netip.MustParseAddr("192.0.2.2"),
|
|
||||||
LocalPort: 443,
|
|
||||||
RemotePort: 55000,
|
|
||||||
Protocol: iputil.IPProtocolTCP,
|
|
||||||
}
|
|
||||||
key := firewall.ConntrackKey{Packet: flow, Peer: netip.MustParseAddr("192.0.2.2")}
|
|
||||||
|
|
||||||
t.Run("inbound flow follows the peer's groups", func(t *testing.T) {
|
|
||||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, owner)
|
|
||||||
require.NoError(t, fw.AddRule(true, firewall.ProtoAny, 0, 0, []string{"trusted"}, "", "", "", "", ""))
|
|
||||||
|
|
||||||
require.NoError(t, fw.Drop(flow, true, tunnel(1, "trusted"), cp, nil))
|
|
||||||
|
|
||||||
// Same groups on a new tunnel keeps the entry and moves it to the new tunnel
|
|
||||||
require.NoError(t, fw.Drop(flow, true, tunnel(2, "trusted"), cp, nil))
|
|
||||||
require.Contains(t, fw.Conntrack.Conns, key)
|
|
||||||
assert.Equal(t, uint32(2), fw.Conntrack.Conns[key].localIndex)
|
|
||||||
|
|
||||||
// Losing the group on a new tunnel removes the entry
|
|
||||||
assert.Equal(t, ErrNoMatchingRule, fw.Drop(flow, true, tunnel(3), cp, nil))
|
|
||||||
assert.NotContains(t, fw.Conntrack.Conns, key)
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("reply to a flow we opened survives a new tunnel", func(t *testing.T) {
|
|
||||||
fw := NewFirewall(l, time.Second, time.Minute, time.Hour, owner)
|
|
||||||
require.NoError(t, fw.AddRule(false, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
|
||||||
|
|
||||||
require.NoError(t, fw.Drop(flow, false, tunnel(1, "trusted"), cp, nil))
|
|
||||||
require.NoError(t, fw.Drop(flow, true, tunnel(2), cp, nil))
|
|
||||||
assert.Equal(t, uint32(2), fw.Conntrack.Conns[key].localIndex)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// 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
|
||||||
@@ -1989,6 +1742,6 @@ func (mf *mockFirewall) AddRule(incoming bool, proto uint8, startPort int32, end
|
|||||||
|
|
||||||
func resetConntrack(fw *Firewall) {
|
func resetConntrack(fw *Firewall) {
|
||||||
fw.Conntrack.Lock()
|
fw.Conntrack.Lock()
|
||||||
fw.Conntrack.Conns = map[firewall.ConntrackKey]*conn{}
|
fw.Conntrack.Conns = map[firewall.Packet]*conn{}
|
||||||
fw.Conntrack.Unlock()
|
fw.Conntrack.Unlock()
|
||||||
}
|
}
|
||||||
@@ -18,12 +18,20 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, nb []byte, sendBatch *batch.SendBatch, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
|
func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, nb []byte, sendBatch *batch.SendBatch, rejectBuf []byte, q int, localCache firewall.ConntrackCache) {
|
||||||
|
if hostinfo := f.filterInsidePacket(pkt, fwPacket, rejectBuf, q, localCache); hostinfo != nil {
|
||||||
|
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// filterInsidePacket parses and filters pkt, handling local traffic, destination lookup, pending handshakes and
|
||||||
|
// the outbound firewall. It returns the hostinfo to send pkt to, or nil when pkt was dropped, rejected, forwarded
|
||||||
|
// to self or cached for a pending handshake.
|
||||||
|
func (f *Interface) filterInsidePacket(pkt tio.Packet, fwPacket *firewall.ParsedPacket, rejectBuf []byte, q int, localCache firewall.ConntrackCache) *HostInfo {
|
||||||
// borrowed: pkt.Bytes is owned by the originating tio.Queue and is
|
// borrowed: pkt.Bytes is owned by the originating tio.Queue and is
|
||||||
// only valid until the next Read on that queue. Every consumer below
|
// only valid until the next Read on that queue. Filtering and sending
|
||||||
// (parse, self-forward, handshake cache, sendInsideMessage) reads it
|
// must finish before then. Self-forwarding writes synchronously and the
|
||||||
// synchronously; do not retain pkt outside this call. If a future
|
// handshake cache copies each segment. To retain the packet beyond the
|
||||||
// caller needs to keep the packet, use pkt.Clone() to detach it from
|
// next Read, use pkt.Clone() to detach it from the borrow.
|
||||||
// the borrow.
|
|
||||||
//
|
//
|
||||||
// pkt.Bytes is either one IP datagram (GSO zero) or a TSO/USO
|
// pkt.Bytes is either one IP datagram (GSO zero) or a TSO/USO
|
||||||
// superpacket. In both cases the L3+L4 headers at the start describe
|
// superpacket. In both cases the L3+L4 headers at the start describe
|
||||||
@@ -38,13 +46,13 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
"error", err,
|
"error", err,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ignore local broadcast packets
|
// Ignore local broadcast packets
|
||||||
if f.dropLocalBroadcast {
|
if f.dropLocalBroadcast {
|
||||||
if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
|
if f.myBroadcastAddrsTable.Contains(fwPacket.RemoteAddr) {
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,12 +79,12 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
}
|
}
|
||||||
// Otherwise, drop. On linux, we should never see these packets - Linux
|
// Otherwise, drop. On linux, we should never see these packets - Linux
|
||||||
// routes packets from the nebula addr to the nebula addr through the loopback device.
|
// routes packets from the nebula addr to the nebula addr through the loopback device.
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ignore multicast packets
|
// Ignore multicast packets
|
||||||
if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
|
if f.dropMulticast && fwPacket.RemoteAddr.IsMulticast() {
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
hostinfo, ready := f.getOrHandshakeConsiderRouting(&fwPacket.Packet, func(hh *HandshakeHostInfo) {
|
hostinfo, ready := f.getOrHandshakeConsiderRouting(&fwPacket.Packet, func(hh *HandshakeHostInfo) {
|
||||||
@@ -103,17 +111,18 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
"fwPacket", fwPacket,
|
"fwPacket", fwPacket,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
if !ready {
|
if !ready {
|
||||||
return
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
|
dropReason := f.firewall.Drop(fwPacket.Packet, false, hostinfo, f.pki.GetCAPool(), localCache)
|
||||||
if dropReason == nil {
|
if dropReason == nil {
|
||||||
f.sendInsideMessage(hostinfo, pkt, nb, sendBatch)
|
return hostinfo
|
||||||
} else {
|
}
|
||||||
|
|
||||||
f.rejectInside(packet, rejectBuf, q)
|
f.rejectInside(packet, rejectBuf, q)
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
hostinfo.logger(f.l).Debug("dropping outbound packet",
|
hostinfo.logger(f.l).Debug("dropping outbound packet",
|
||||||
@@ -121,7 +130,7 @@ func (f *Interface) consumeInsidePacket(pkt tio.Packet, fwPacket *firewall.Parse
|
|||||||
"reason", dropReason,
|
"reason", dropReason,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, seg, scratch, nb []byte) []byte {
|
func (f *Interface) sendInsideEncrypt(hostinfo *HostInfo, ci *ConnectionState, seg, scratch, nb []byte) []byte {
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
package nebula
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/netip"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/gaissmai/bart"
|
||||||
|
"github.com/slackhq/nebula/cert"
|
||||||
|
"github.com/slackhq/nebula/firewall"
|
||||||
|
"github.com/slackhq/nebula/header"
|
||||||
|
"github.com/slackhq/nebula/overlay/batch"
|
||||||
|
"github.com/slackhq/nebula/overlay/overlaytest"
|
||||||
|
"github.com/slackhq/nebula/overlay/tio"
|
||||||
|
"github.com/slackhq/nebula/udp"
|
||||||
|
"github.com/stretchr/testify/assert"
|
||||||
|
"github.com/stretchr/testify/require"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newInsideFilterTestInterface(t *testing.T, allow bool) (*Interface, *HostInfo, *capturingTun) {
|
||||||
|
t.Helper()
|
||||||
|
local := netip.MustParseAddr("192.0.2.1")
|
||||||
|
remote := netip.MustParseAddr("192.0.2.2")
|
||||||
|
f, tun := newSelfForwardInterface(local)
|
||||||
|
f.inside = overlaytest.NoopTun{}
|
||||||
|
f.myVpnNetworksTable = &bart.Lite{}
|
||||||
|
f.myVpnNetworksTable.Insert(netip.MustParsePrefix("192.0.2.0/24"))
|
||||||
|
f.myBroadcastAddrsTable.Insert(netip.MustParsePrefix("192.0.2.255/32"))
|
||||||
|
f.dropLocalBroadcast, f.dropMulticast = true, true
|
||||||
|
localCert := &dummyCert{version: cert.Version1, networks: []netip.Prefix{netip.PrefixFrom(local, 24)}}
|
||||||
|
peerCert := &dummyCert{version: cert.Version1, networks: []netip.Prefix{netip.PrefixFrom(remote, 24)}}
|
||||||
|
f.firewall = NewFirewall(f.l, time.Minute, time.Minute, time.Minute, localCert)
|
||||||
|
if allow {
|
||||||
|
require.NoError(t, f.firewall.AddRule(false, firewall.ProtoAny, 0, 0, []string{"any"}, "", "", "", "", ""))
|
||||||
|
}
|
||||||
|
f.pki = &PKI{}
|
||||||
|
f.pki.caPool.Store(cert.NewCAPool())
|
||||||
|
f.hostMap = newHostMap(f.l)
|
||||||
|
f.lightHouse = newTestLighthouse()
|
||||||
|
f.lightHouse.amLighthouse = true // Keep destination lookup from probing other remotes.
|
||||||
|
f.handshakeManager = NewHandshakeManager(f.l, f.hostMap, f.lightHouse, udp.NoopConn{}, defaultHandshakeConfig)
|
||||||
|
f.handshakeManager.f = f
|
||||||
|
f.connectionManager = &connectionManager{intf: f}
|
||||||
|
h := &HostInfo{
|
||||||
|
vpnAddrs: []netip.Addr{remote},
|
||||||
|
ConnectionState: &ConnectionState{
|
||||||
|
peerCert: &cert.CachedCertificate{Certificate: peerCert},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
f.hostMap.Hosts[remote] = h
|
||||||
|
return f, h, tun
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterInsidePacket(t *testing.T) {
|
||||||
|
local := netip.MustParseAddr("192.0.2.1")
|
||||||
|
remote := netip.MustParseAddr("192.0.2.2")
|
||||||
|
for _, tt := range []struct {
|
||||||
|
name string
|
||||||
|
packet []byte
|
||||||
|
allow bool
|
||||||
|
reject bool
|
||||||
|
ready bool
|
||||||
|
writes int
|
||||||
|
}{
|
||||||
|
{name: "allowed", packet: buildIPv4(local, remote, tcpSyn), allow: true, ready: true},
|
||||||
|
{name: "malformed", packet: []byte{0x45}, allow: true},
|
||||||
|
{name: "broadcast", packet: buildIPv4(local, netip.MustParseAddr("192.0.2.255"), udpDatagram), allow: true},
|
||||||
|
{name: "multicast", packet: buildIPv4(local, netip.MustParseAddr("224.0.0.1"), udpDatagram), allow: true},
|
||||||
|
{name: "firewall drop", packet: buildIPv4(local, remote, tcpSyn)},
|
||||||
|
{name: "firewall reject", packet: buildIPv4(local, remote, tcpSyn), reject: true, writes: 1},
|
||||||
|
{name: "unroutable drop", packet: buildIPv4(local, netip.MustParseAddr("198.51.100.1"), tcpSyn), allow: true},
|
||||||
|
{name: "unroutable reject", packet: buildIPv4(local, netip.MustParseAddr("198.51.100.1"), tcpSyn), allow: true, reject: true, writes: 1},
|
||||||
|
} {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
f, h, tun := newInsideFilterTestInterface(t, tt.allow)
|
||||||
|
f.firewall.OutboundSendReject = tt.reject
|
||||||
|
fp := &firewall.ParsedPacket{}
|
||||||
|
got := f.filterInsidePacket(tio.Packet{Bytes: tt.packet}, fp, make([]byte, mtu), 0, nil)
|
||||||
|
if tt.ready {
|
||||||
|
require.Same(t, h, got)
|
||||||
|
assert.Equal(t, local, fp.LocalAddr)
|
||||||
|
assert.Equal(t, remote, fp.RemoteAddr)
|
||||||
|
} else {
|
||||||
|
require.Nil(t, got)
|
||||||
|
}
|
||||||
|
assert.Zero(t, h.ConnectionState.messageCounter.Load(), "filtering must not allocate encryption counters")
|
||||||
|
assert.False(t, h.sentSinceCheck(), "filtering must not mark outbound traffic")
|
||||||
|
require.Len(t, tun.writes, tt.writes)
|
||||||
|
if tt.writes > 0 {
|
||||||
|
require.GreaterOrEqual(t, len(tun.writes[0]), 40)
|
||||||
|
assert.Equal(t, tt.packet[16:20], tun.writes[0][12:16])
|
||||||
|
assert.Equal(t, tt.packet[12:16], tun.writes[0][16:20])
|
||||||
|
assert.NotZero(t, tun.writes[0][33]&0x04, "reject must carry a TCP reset")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterInsidePacketSelf(t *testing.T) {
|
||||||
|
local := netip.MustParseAddr("192.0.2.1")
|
||||||
|
f, _, tun := newInsideFilterTestInterface(t, true)
|
||||||
|
pkt := buildIPv4(local, local, tcpSyn)
|
||||||
|
require.Nil(t, f.filterInsidePacket(tio.Packet{Bytes: pkt}, &firewall.ParsedPacket{}, nil, 0, nil))
|
||||||
|
if immediatelyForwardToSelf {
|
||||||
|
require.Len(t, tun.writes, 1)
|
||||||
|
assert.Equal(t, pkt, tun.writes[0])
|
||||||
|
} else {
|
||||||
|
assert.Empty(t, tun.writes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFilterInsidePacketPendingHandshake(t *testing.T) {
|
||||||
|
f, h, tun := newInsideFilterTestInterface(t, true)
|
||||||
|
remote := h.vpnAddrs[0]
|
||||||
|
delete(f.hostMap.Hosts, remote)
|
||||||
|
hh := &HandshakeHostInfo{hostinfo: h}
|
||||||
|
f.handshakeManager.vpnIps[remote] = hh
|
||||||
|
pkt := buildIPv4(netip.MustParseAddr("192.0.2.1"), remote, udpDatagram)
|
||||||
|
want := append([]byte(nil), pkt...)
|
||||||
|
require.Nil(t, f.filterInsidePacket(tio.Packet{Bytes: pkt}, &firewall.ParsedPacket{}, nil, 0, nil))
|
||||||
|
require.Len(t, hh.packetStore, 1)
|
||||||
|
clear(pkt)
|
||||||
|
assert.Equal(t, want, hh.packetStore[0].packet, "the handshake cache must own its packet")
|
||||||
|
assert.Equal(t, header.Message, hh.packetStore[0].messageType)
|
||||||
|
assert.Empty(t, tun.writes)
|
||||||
|
assert.Zero(t, h.ConnectionState.messageCounter.Load())
|
||||||
|
}
|
||||||
|
|
||||||
|
type insideFilterConn struct {
|
||||||
|
udp.NoopConn
|
||||||
|
packets [][]byte
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *insideFilterConn) WriteBatch(bufs [][]byte, _ []netip.AddrPort) (int, error) {
|
||||||
|
for _, b := range bufs {
|
||||||
|
c.packets = append(c.packets, append([]byte(nil), b...))
|
||||||
|
}
|
||||||
|
return len(bufs), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConsumeInsidePacketFilterAndSend(t *testing.T) {
|
||||||
|
for _, allow := range []bool{false, true} {
|
||||||
|
t.Run(map[bool]string{false: "denied", true: "allowed"}[allow], func(t *testing.T) {
|
||||||
|
f, h, _ := newInsideFilterTestInterface(t, allow)
|
||||||
|
initR, respR := runTestHandshake(t)
|
||||||
|
ci, err := newConnectionStateFromResult(initR)
|
||||||
|
require.NoError(t, err)
|
||||||
|
rci, err := newConnectionStateFromResult(respR)
|
||||||
|
require.NoError(t, err)
|
||||||
|
ci.peerCert = h.ConnectionState.peerCert
|
||||||
|
h.ConnectionState = ci
|
||||||
|
h.remoteIndexId = 100
|
||||||
|
remote := netip.MustParseAddrPort("198.51.100.2:4242")
|
||||||
|
h.remote.Store(&remote)
|
||||||
|
conn := &insideFilterConn{}
|
||||||
|
sb := batch.NewSendBatch(conn, 1, mtu)
|
||||||
|
pkt := buildIPv4(netip.MustParseAddr("192.0.2.1"), h.vpnAddrs[0], udpDatagram)
|
||||||
|
before := ci.messageCounter.Load()
|
||||||
|
f.consumeInsidePacket(tio.Packet{Bytes: pkt}, &firewall.ParsedPacket{}, make([]byte, 12), sb, nil, 0, nil)
|
||||||
|
_, err = sb.Flush()
|
||||||
|
require.NoError(t, err)
|
||||||
|
if !allow {
|
||||||
|
assert.Empty(t, conn.packets)
|
||||||
|
assert.Equal(t, before, ci.messageCounter.Load())
|
||||||
|
assert.False(t, h.sentSinceCheck())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
require.Len(t, conn.packets, 1)
|
||||||
|
assert.True(t, h.sentSinceCheck())
|
||||||
|
hdr := &header.H{}
|
||||||
|
require.NoError(t, hdr.Parse(conn.packets[0]))
|
||||||
|
assert.Equal(t, header.Message, hdr.Type)
|
||||||
|
assert.Equal(t, h.remoteIndexId, hdr.RemoteIndex)
|
||||||
|
assert.Equal(t, before+1, hdr.MessageCounter)
|
||||||
|
plain, err := rci.Decrypt(f.l, hdr.MessageCounter, conn.packets[0], make([]byte, 12))
|
||||||
|
require.NoError(t, err)
|
||||||
|
assert.Equal(t, pkt, plain)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -25,7 +25,6 @@ import (
|
|||||||
"github.com/slackhq/nebula/overlay/batch"
|
"github.com/slackhq/nebula/overlay/batch"
|
||||||
"github.com/slackhq/nebula/overlay/tio"
|
"github.com/slackhq/nebula/overlay/tio"
|
||||||
"github.com/slackhq/nebula/ratelimit"
|
"github.com/slackhq/nebula/ratelimit"
|
||||||
"github.com/slackhq/nebula/routing"
|
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -269,9 +268,6 @@ func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
|
|||||||
ifce.reQueryWait.Store(int64(c.reQueryWait))
|
ifce.reQueryWait.Store(int64(c.reQueryWait))
|
||||||
|
|
||||||
ifce.connectionManager.intf = ifce
|
ifce.connectionManager.intf = ifce
|
||||||
if ifce.firewall != nil {
|
|
||||||
ifce.firewall.siblings = ifce
|
|
||||||
}
|
|
||||||
|
|
||||||
// Held until Close so waiting on the interface blocks until the resources are actually released
|
// Held until Close so waiting on the interface blocks until the resources are actually released
|
||||||
ifce.wg.Add(1)
|
ifce.wg.Add(1)
|
||||||
@@ -558,7 +554,6 @@ func (f *Interface) reloadFirewall(c *config.C, r *config.Reload) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
oldFw := f.firewall
|
oldFw := f.firewall
|
||||||
fw.siblings = f
|
|
||||||
conntrack := oldFw.Conntrack
|
conntrack := oldFw.Conntrack
|
||||||
conntrack.Lock()
|
conntrack.Lock()
|
||||||
defer conntrack.Unlock()
|
defer conntrack.Unlock()
|
||||||
@@ -716,24 +711,3 @@ func (f *Interface) Close() error {
|
|||||||
f.wg.Done()
|
f.wg.Done()
|
||||||
return errors.Join(errs...)
|
return errors.Join(errs...)
|
||||||
}
|
}
|
||||||
|
|
||||||
// siblingPeers implements gatewaySiblings from the routes and tunnels we have now. Routes name a gateway by any of its
|
|
||||||
// vpn addresses, conntrack keys a peer by its first one, so each gateway is resolved through its tunnel. A gateway
|
|
||||||
// we have no tunnel to can't be carrying a live flow.
|
|
||||||
func (f *Interface) siblingPeers(remote netip.Addr, h *HostInfo, buf []netip.Addr) []netip.Addr {
|
|
||||||
gateways := f.inside.RoutesFor(remote)
|
|
||||||
isGateway := func(g routing.Gateway) bool { return slices.Contains(h.vpnAddrs, g.Addr()) }
|
|
||||||
if len(gateways) < 2 || !slices.ContainsFunc(gateways, isGateway) {
|
|
||||||
return buf
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, g := range gateways {
|
|
||||||
if isGateway(g) {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if s := f.hostMap.QueryVpnAddr(g.Addr()); s != nil && s != h {
|
|
||||||
buf = append(buf, s.vpnAddrs[0])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return buf
|
|
||||||
}
|
|
||||||
@@ -39,7 +39,7 @@ func Test_statsEmitter_setsGauges(t *testing.T) {
|
|||||||
hostMap: hostMap,
|
hostMap: hostMap,
|
||||||
inside: &overlaytest.NoopTun{},
|
inside: &overlaytest.NoopTun{},
|
||||||
outside: &udp.NoopConn{},
|
outside: &udp.NoopConn{},
|
||||||
firewall: &Firewall{Conntrack: &FirewallConntrack{Conns: map[firewall.ConntrackKey]*conn{}}},
|
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),
|
||||||
|
|||||||
@@ -4,11 +4,8 @@ import (
|
|||||||
"net/netip"
|
"net/netip"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/gaissmai/bart"
|
|
||||||
"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/routing"
|
|
||||||
"github.com/slackhq/nebula/test"
|
"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"
|
||||||
@@ -143,42 +140,3 @@ func TestReloadFirewall_BadRulesFailTheReload(t *testing.T) {
|
|||||||
assert.True(t, res.Failed)
|
assert.True(t, res.Failed)
|
||||||
assert.Same(t, fw, f.firewall)
|
assert.Same(t, fw, f.firewall)
|
||||||
}
|
}
|
||||||
|
|
||||||
// routesTun is a NoopTun with a route table
|
|
||||||
type routesTun struct {
|
|
||||||
overlaytest.NoopTun
|
|
||||||
routes *bart.Table[routing.Gateways]
|
|
||||||
}
|
|
||||||
|
|
||||||
func (t routesTun) RoutesFor(ip netip.Addr) routing.Gateways {
|
|
||||||
r, _ := t.routes.Lookup(ip)
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestInterface_SiblingPeers(t *testing.T) {
|
|
||||||
addr := netip.MustParseAddr
|
|
||||||
routes := new(bart.Table[routing.Gateways])
|
|
||||||
// a and b carry 198.51.100.0/24, the route names b by its v6 address
|
|
||||||
routes.Insert(netip.MustParsePrefix("198.51.100.0/24"), routing.Gateways{
|
|
||||||
routing.NewGateway(addr("192.0.2.2"), 1),
|
|
||||||
routing.NewGateway(addr("fd00::3"), 1),
|
|
||||||
routing.NewGateway(addr("192.0.2.5"), 1), // no tunnel to this one
|
|
||||||
})
|
|
||||||
routes.Insert(netip.MustParsePrefix("203.0.113.0/24"), routing.Gateways{routing.NewGateway(addr("192.0.2.2"), 1)})
|
|
||||||
|
|
||||||
hm := newHostMap(test.NewLogger())
|
|
||||||
a := &HostInfo{vpnAddrs: []netip.Addr{addr("192.0.2.2"), addr("fd00::2")}, localIndexId: 1}
|
|
||||||
b := &HostInfo{vpnAddrs: []netip.Addr{addr("192.0.2.3"), addr("fd00::3")}, localIndexId: 2}
|
|
||||||
c := &HostInfo{vpnAddrs: []netip.Addr{addr("192.0.2.4")}, localIndexId: 3}
|
|
||||||
for _, h := range []*HostInfo{a, b, c} {
|
|
||||||
hm.unlockedAddHostInfo(h, &Interface{})
|
|
||||||
}
|
|
||||||
f := &Interface{inside: routesTun{routes: routes}, hostMap: hm}
|
|
||||||
|
|
||||||
// Siblings come back as their first vpn address, the one conntrack keys on, whichever address the route names
|
|
||||||
assert.Equal(t, []netip.Addr{addr("192.0.2.3")}, f.siblingPeers(addr("198.51.100.5"), a, nil))
|
|
||||||
assert.Equal(t, []netip.Addr{addr("192.0.2.2")}, f.siblingPeers(addr("198.51.100.5"), b, nil))
|
|
||||||
assert.Empty(t, f.siblingPeers(addr("198.51.100.5"), c, nil), "not one of our gateways for the network")
|
|
||||||
assert.Empty(t, f.siblingPeers(addr("203.0.113.5"), a, nil), "a single gateway route has no siblings")
|
|
||||||
assert.Empty(t, f.siblingPeers(addr("192.0.2.3"), a, nil), "no route")
|
|
||||||
}
|
|
||||||
@@ -2,7 +2,9 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto/fips140"
|
"crypto/fips140"
|
||||||
|
"crypto/sha256"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
|
"encoding/hex"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -233,12 +235,14 @@ func (p *PKI) reloadCerts(c *config.C, initial bool) *util.ContextualError {
|
|||||||
|
|
||||||
func (p *PKI) reloadCAPool(c *config.C) *util.ContextualError {
|
func (p *PKI) reloadCAPool(c *config.C) *util.ContextualError {
|
||||||
caPool, err := loadCAPoolFromConfig(p.l, c)
|
caPool, err := loadCAPoolFromConfig(p.l, c)
|
||||||
|
if caPool != nil {
|
||||||
|
p.caPool.Store(caPool)
|
||||||
|
p.l.Debug("Trusted CA fingerprints", "fingerprints", caPool.GetFingerprints())
|
||||||
|
}
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return util.NewContextualError("Failed to load ca from config", nil, err)
|
return util.NewContextualError("Failed to load ca from config", nil, err)
|
||||||
}
|
}
|
||||||
|
|
||||||
p.caPool.Store(caPool)
|
|
||||||
p.l.Debug("Trusted CA fingerprints", "fingerprints", caPool.GetFingerprints())
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -613,11 +617,22 @@ func loadCAPoolFromConfig(l *slog.Logger, c *config.C) (*cert.CAPool, error) {
|
|||||||
|
|
||||||
bl := c.GetStringSlice("pki.blocklist", []string{})
|
bl := c.GetStringSlice("pki.blocklist", []string{})
|
||||||
if len(bl) > 0 {
|
if len(bl) > 0 {
|
||||||
for _, fp := range bl {
|
var bad []string
|
||||||
|
for i, raw := range bl {
|
||||||
|
// Fingerprints are compared as lowercase hex strings, a malformed entry would silently block nothing
|
||||||
|
fp := strings.ToLower(strings.TrimSpace(raw))
|
||||||
|
if b, err := hex.DecodeString(fp); err != nil || len(b) != sha256.Size {
|
||||||
|
bad = append(bad, fmt.Sprintf("entry %d %q", i+1, raw))
|
||||||
|
continue
|
||||||
|
}
|
||||||
caPool.BlocklistFingerprint(fp)
|
caPool.BlocklistFingerprint(fp)
|
||||||
}
|
}
|
||||||
|
|
||||||
l.Info("Blocklisted certificates", "fingerprintCount", len(bl))
|
l.Info("Blocklisted certificates", "fingerprintCount", len(bl)-len(bad))
|
||||||
|
if len(bad) > 0 {
|
||||||
|
// The valid entries are still returned so a failed reload blocks them, startup refuses the error
|
||||||
|
return caPool, fmt.Errorf("pki.blocklist entries are not hex certificate fingerprints: %s", strings.Join(bad, ", "))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return caPool, nil
|
return caPool, nil
|
||||||
|
|||||||
+43
@@ -217,3 +217,46 @@ func TestPKIReloadChachapolyInFIPSOnlyFails(t *testing.T) {
|
|||||||
assert.True(t, res.Failed)
|
assert.True(t, res.Failed)
|
||||||
assert.False(t, res.RestartRequired)
|
assert.False(t, res.RestartRequired)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLoadCAPoolBlocklist(t *testing.T) {
|
||||||
|
ca, _, caKey, caPEM := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, time.Time{}, time.Time{}, nil, nil, nil)
|
||||||
|
crt, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey, "host", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.1.0.2/24")}, nil, nil)
|
||||||
|
fp, err := crt.Fingerprint()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
load := func(entry string) (*cert.CAPool, error) {
|
||||||
|
c := config.NewC(test.NewLogger())
|
||||||
|
require.NoError(t, c.LoadString(fmt.Sprintf("pki:\n ca: %q\n blocklist:\n - %q\n", caPEM, entry)))
|
||||||
|
return loadCAPoolFromConfig(test.NewLogger(), c)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, entry := range []string{fp, strings.ToUpper(fp), " " + fp + "\t"} {
|
||||||
|
pool, err := load(entry)
|
||||||
|
require.NoError(t, err, entry)
|
||||||
|
assert.True(t, pool.IsBlocklisted(fp), entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, entry := range []string{fp[1:], fp + "00", "sha256:" + fp, "zz" + fp[2:], ""} {
|
||||||
|
_, err := load(entry)
|
||||||
|
require.Error(t, err, entry)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A bad entry on reload fails it, the valid entries are still blocked
|
||||||
|
_, _, keyPEM, certPEM := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey, "me", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.1.0.1/24")}, nil, nil)
|
||||||
|
pkiConfig := func(entry string) string {
|
||||||
|
return fmt.Sprintf("pki:\n ca: %q\n cert: %q\n key: %q\n blocklist:\n - %q\n", caPEM, certPEM, keyPEM, entry)
|
||||||
|
}
|
||||||
|
c := config.NewC(test.NewLogger())
|
||||||
|
require.NoError(t, c.LoadString(pkiConfig(fp)))
|
||||||
|
p, err := NewPKIFromConfig(test.NewLogger(), c)
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
other, _, _, _ := cert_test.NewTestCert(cert.Version2, cert.Curve_CURVE25519, ca, caKey, "other", time.Time{}, time.Time{}, []netip.Prefix{netip.MustParsePrefix("10.1.0.3/24")}, nil, nil)
|
||||||
|
otherFp, err := other.Fingerprint()
|
||||||
|
require.NoError(t, err)
|
||||||
|
|
||||||
|
res := c.ReloadConfigString(pkiConfig(fp) + fmt.Sprintf(" - %q\n - %q\n", otherFp, fp[1:]))
|
||||||
|
assert.True(t, res.Failed)
|
||||||
|
assert.True(t, p.GetCAPool().IsBlocklisted(fp))
|
||||||
|
assert.True(t, p.GetCAPool().IsBlocklisted(otherFp))
|
||||||
|
}
|
||||||
@@ -11,12 +11,8 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
|
||||||
"runtime"
|
|
||||||
"runtime/pprof"
|
|
||||||
"slices"
|
"slices"
|
||||||
"sort"
|
"sort"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
@@ -60,8 +56,6 @@ type sshDeviceInfoFlags struct {
|
|||||||
|
|
||||||
func wireSSHReload(l *slog.Logger, ssh *sshd.SSHServer, c *config.C) {
|
func wireSSHReload(l *slog.Logger, ssh *sshd.SSHServer, c *config.C) {
|
||||||
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
c.RegisterReloadCallback(func(c *config.C, r *config.Reload) {
|
||||||
// sshd.sandbox_dir is read once, when the commands are attached
|
|
||||||
r.RestartRequiredIfChanged("sshd.sandbox_dir")
|
|
||||||
if c.GetBool("sshd.enabled", false) {
|
if c.GetBool("sshd.enabled", false) {
|
||||||
// Restarting the server drops every open session, the one that asked for this reload included. Only restart
|
// Restarting the server drops every open session, the one that asked for this reload included. Only restart
|
||||||
// when it isn't running or its config changed. The host key file can change under the same config, new
|
// when it isn't running or its config changed. The host key file can change under the same config, new
|
||||||
@@ -93,8 +87,7 @@ func wireSSHReload(l *slog.Logger, ssh *sshd.SSHServer, c *config.C) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// sshdServerKeys are what configSSH reads. sshd.sandbox_dir isn't one, it's read once at startup and restarting the
|
// sshdServerKeys are what configSSH reads
|
||||||
// server doesn't apply it
|
|
||||||
var sshdServerKeys = []string{"sshd.enabled", "sshd.listen", "sshd.host_key", "sshd.trusted_cas", "sshd.authorized_users"}
|
var sshdServerKeys = []string{"sshd.enabled", "sshd.listen", "sshd.host_key", "sshd.trusted_cas", "sshd.authorized_users"}
|
||||||
|
|
||||||
// loadSSHHostKey returns sshd.host_key, read from its file when it names one.
|
// loadSSHHostKey returns sshd.host_key, read from its file when it names one.
|
||||||
@@ -236,12 +229,6 @@ func configSSH(l *slog.Logger, ssh *sshd.SSHServer, c *config.C, r *config.Reloa
|
|||||||
}
|
}
|
||||||
|
|
||||||
func attachCommands(l *slog.Logger, c *config.C, ssh *sshd.SSHServer, f *Interface) {
|
func attachCommands(l *slog.Logger, c *config.C, ssh *sshd.SSHServer, f *Interface) {
|
||||||
// sandboxDir defaults to a dir in temp. The intention is that end user will
|
|
||||||
// create this dir as needed. Overriding this config value to "" allows
|
|
||||||
// writing to anywhere in the system.
|
|
||||||
defaultDir := filepath.Join(os.TempDir(), "nebula-debug")
|
|
||||||
sandboxDir := c.GetString("sshd.sandbox_dir", defaultDir)
|
|
||||||
|
|
||||||
ssh.RegisterCommand(&sshd.Command{
|
ssh.RegisterCommand(&sshd.Command{
|
||||||
Name: "list-hostmap",
|
Name: "list-hostmap",
|
||||||
ShortDescription: "List all known previously connected hosts",
|
ShortDescription: "List all known previously connected hosts",
|
||||||
@@ -297,45 +284,6 @@ func attachCommands(l *slog.Logger, c *config.C, ssh *sshd.SSHServer, f *Interfa
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
|
|
||||||
ssh.RegisterCommand(&sshd.Command{
|
|
||||||
Name: "start-cpu-profile",
|
|
||||||
ShortDescription: "Starts a cpu profile and write output to the provided file, ex: `cpu-profile.pb.gz`",
|
|
||||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
|
||||||
return sshStartCpuProfile(sandboxDir, fs, a, w)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
ssh.RegisterCommand(&sshd.Command{
|
|
||||||
Name: "stop-cpu-profile",
|
|
||||||
ShortDescription: "Stops a cpu profile and writes output to the previously provided file",
|
|
||||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
|
||||||
pprof.StopCPUProfile()
|
|
||||||
return w.WriteLine("If a CPU profile was running it is now stopped")
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
ssh.RegisterCommand(&sshd.Command{
|
|
||||||
Name: "save-heap-profile",
|
|
||||||
ShortDescription: "Saves a heap profile to the provided path, ex: `heap-profile.pb.gz`",
|
|
||||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
|
||||||
return sshGetHeapProfile(sandboxDir, fs, a, w)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
ssh.RegisterCommand(&sshd.Command{
|
|
||||||
Name: "mutex-profile-fraction",
|
|
||||||
ShortDescription: "Gets or sets runtime.SetMutexProfileFraction",
|
|
||||||
Callback: sshMutexProfileFraction,
|
|
||||||
})
|
|
||||||
|
|
||||||
ssh.RegisterCommand(&sshd.Command{
|
|
||||||
Name: "save-mutex-profile",
|
|
||||||
ShortDescription: "Saves a mutex profile to the provided path, ex: `mutex-profile.pb.gz`",
|
|
||||||
Callback: func(fs any, a []string, w sshd.StringWriter) error {
|
|
||||||
return sshGetMutexProfile(sandboxDir, fs, a, w)
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
ssh.RegisterCommand(&sshd.Command{
|
ssh.RegisterCommand(&sshd.Command{
|
||||||
Name: "log-level",
|
Name: "log-level",
|
||||||
ShortDescription: "Gets or sets the current log level",
|
ShortDescription: "Gets or sets the current log level",
|
||||||
@@ -566,58 +514,6 @@ func sshListLighthouseMap(lightHouse *LightHouse, a any, w sshd.StringWriter) er
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// sshSanitizeFilePath validates that the given file path is within the sandbox directory.
|
|
||||||
// If sandboxDir is empty, the path is returned as-is for backwards compatibility.
|
|
||||||
func sshSanitizeFilePath(sandboxDir, filePath string) (string, error) {
|
|
||||||
if sandboxDir == "" {
|
|
||||||
return filePath, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// Clean and resolve the path relative to the sandbox directory
|
|
||||||
if !filepath.IsAbs(filePath) {
|
|
||||||
filePath = filepath.Join(sandboxDir, filePath)
|
|
||||||
}
|
|
||||||
cleaned := filepath.Clean(filePath)
|
|
||||||
|
|
||||||
// Ensure the resolved path is within the sandbox directory
|
|
||||||
cleanedSandbox := filepath.Clean(sandboxDir)
|
|
||||||
if cleaned == cleanedSandbox {
|
|
||||||
return "", fmt.Errorf("path %q resolves to the sandbox directory itself %q", filePath, sandboxDir)
|
|
||||||
}
|
|
||||||
if !strings.HasPrefix(cleaned, cleanedSandbox+string(filepath.Separator)) {
|
|
||||||
return "", fmt.Errorf("path %q is outside the sandbox directory %q", filePath, sandboxDir)
|
|
||||||
}
|
|
||||||
|
|
||||||
return cleaned, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func sshStartCpuProfile(sandboxDir string, fs any, a []string, w sshd.StringWriter) error {
|
|
||||||
if len(a) == 0 {
|
|
||||||
err := w.WriteLine("No path to write profile provided")
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
filePath, err := sshSanitizeFilePath(sandboxDir, a[0])
|
|
||||||
if err != nil {
|
|
||||||
return w.WriteLine(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := os.Create(filePath)
|
|
||||||
if err != nil {
|
|
||||||
err = w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = pprof.StartCPUProfile(file)
|
|
||||||
if err != nil {
|
|
||||||
err = w.WriteLine(fmt.Sprintf("Unable to start cpu profile: %s", err))
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = w.WriteLine(fmt.Sprintf("Started cpu profile, issue stop-cpu-profile to write the output to %s", a))
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func sshVersion(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
func sshVersion(ifce *Interface, fs any, a []string, w sshd.StringWriter) error {
|
||||||
return w.WriteLine(fmt.Sprintf("%s", ifce.version))
|
return w.WriteLine(fmt.Sprintf("%s", ifce.version))
|
||||||
}
|
}
|
||||||
@@ -770,76 +666,6 @@ func sshChangeRemote(ifce *Interface, fs any, a []string, w sshd.StringWriter) e
|
|||||||
return w.WriteLine("Changed")
|
return w.WriteLine("Changed")
|
||||||
}
|
}
|
||||||
|
|
||||||
func sshGetHeapProfile(sandboxDir string, fs any, a []string, w sshd.StringWriter) error {
|
|
||||||
if len(a) == 0 {
|
|
||||||
return w.WriteLine("No path to write profile provided")
|
|
||||||
}
|
|
||||||
|
|
||||||
filePath, err := sshSanitizeFilePath(sandboxDir, a[0])
|
|
||||||
if err != nil {
|
|
||||||
return w.WriteLine(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := os.Create(filePath)
|
|
||||||
if err != nil {
|
|
||||||
err = w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = pprof.WriteHeapProfile(file)
|
|
||||||
if err != nil {
|
|
||||||
err = w.WriteLine(fmt.Sprintf("Unable to write profile: %s", err))
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
err = w.WriteLine(fmt.Sprintf("Mem profile created at %s", a))
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
func sshMutexProfileFraction(fs any, a []string, w sshd.StringWriter) error {
|
|
||||||
if len(a) == 0 {
|
|
||||||
rate := runtime.SetMutexProfileFraction(-1)
|
|
||||||
return w.WriteLine(fmt.Sprintf("Current value: %d", rate))
|
|
||||||
}
|
|
||||||
|
|
||||||
newRate, err := strconv.Atoi(a[0])
|
|
||||||
if err != nil {
|
|
||||||
return w.WriteLine(fmt.Sprintf("Invalid argument: %s", a[0]))
|
|
||||||
}
|
|
||||||
|
|
||||||
oldRate := runtime.SetMutexProfileFraction(newRate)
|
|
||||||
return w.WriteLine(fmt.Sprintf("New value: %d. Old value: %d", newRate, oldRate))
|
|
||||||
}
|
|
||||||
|
|
||||||
func sshGetMutexProfile(sandboxDir string, fs any, a []string, w sshd.StringWriter) error {
|
|
||||||
if len(a) == 0 {
|
|
||||||
return w.WriteLine("No path to write profile provided")
|
|
||||||
}
|
|
||||||
|
|
||||||
filePath, err := sshSanitizeFilePath(sandboxDir, a[0])
|
|
||||||
if err != nil {
|
|
||||||
return w.WriteLine(err.Error())
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := os.Create(filePath)
|
|
||||||
if err != nil {
|
|
||||||
return w.WriteLine(fmt.Sprintf("Unable to create profile file: %s", err))
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
mutexProfile := pprof.Lookup("mutex")
|
|
||||||
if mutexProfile == nil {
|
|
||||||
return w.WriteLine("Unable to get pprof.Lookup(\"mutex\")")
|
|
||||||
}
|
|
||||||
|
|
||||||
err = mutexProfile.WriteTo(file, 0)
|
|
||||||
if err != nil {
|
|
||||||
return w.WriteLine(fmt.Sprintf("Unable to write profile: %s", err))
|
|
||||||
}
|
|
||||||
|
|
||||||
return w.WriteLine(fmt.Sprintf("Mutex profile created at %s", a))
|
|
||||||
}
|
|
||||||
|
|
||||||
func sshLogLevel(l *slog.Logger, fs any, a []string, w sshd.StringWriter) error {
|
func sshLogLevel(l *slog.Logger, fs any, a []string, w sshd.StringWriter) error {
|
||||||
ctrl, ok := l.Handler().(interface {
|
ctrl, ok := l.Handler().(interface {
|
||||||
GetLevel() slog.Level
|
GetLevel() slog.Level
|
||||||
|
|||||||
@@ -165,18 +165,6 @@ func TestSSHDReload_ChangedConfigRestarts(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// sandbox_dir is only read at startup, restarting sshd for it would drop every session and still not apply it
|
|
||||||
func TestSSHDReload_SandboxDirKeepsSessions(t *testing.T) {
|
|
||||||
h := newSSHDReloadHarness(t)
|
|
||||||
client, _ := h.connect(t)
|
|
||||||
|
|
||||||
h.extra = " sandbox_dir: " + t.TempDir() + "\n"
|
|
||||||
res := h.c.ReloadConfigString(h.config())
|
|
||||||
require.NoError(t, res.Err)
|
|
||||||
assert.Equal(t, []string{"sshd.sandbox_dir"}, res.RestartKeys)
|
|
||||||
assert.False(t, dropped(client, 500*time.Millisecond), "sshd was restarted")
|
|
||||||
}
|
|
||||||
|
|
||||||
// The config can stay the same while the host key file it names changes. New connections get the new key, open
|
// The config can stay the same while the host key file it names changes. New connections get the new key, open
|
||||||
// sessions are left alone
|
// sessions are left alone
|
||||||
func TestSSHDReload_ChangedHostKeyFile(t *testing.T) {
|
func TestSSHDReload_ChangedHostKeyFile(t *testing.T) {
|
||||||
|
|||||||
Reference in new issue
Block a user