Compare commits

..
Author SHA1 Message Date
Wade Simmons a9e53a4088 Apply suggestion from @wadey 2026-09-21 14:31:18 -04:00
Wade Simmons f24fb308a0 Update security report submission guidelines
Clarified submission process for security reports.
2026-09-21 09:44:32 -04:00
31 changed files with 121 additions and 2924 deletions

No files matched your search

-14
View File
@@ -263,20 +263,6 @@ try {
}
Write-Host "OK: WSL peer -> windows lighthouse over v6"
# The NlMtu check above proves the value was written, not that windows honors it. A payload this size only
# crosses the tunnel as fragments cut at NlMtu on the way out of the adapter. Left at the adapter default it
# reaches nebula whole, overflows the udp.MTU (9001) write buffer and is dropped, so the ping never answers.
# Anything smaller would ride out as one oversized datagram and survive on IP fragmentation of the underlay.
$BigPayload = 9000
foreach ($target in @(@{ Family = 'v4'; Ip = $Ip2 }, @{ Family = 'v6'; Ip = $Ip6_2 })) {
Wait-Until -TimeoutSec 30 -What "$($target.Family) ping with a $BigPayload byte payload from windows lighthouse to WSL peer ($($target.Ip))" -Predicate {
if ($peerProc.HasExited) { throw "peer exited (code $($peerProc.ExitCode)) before the large $($target.Family) ping succeeded" }
$null = & ping.exe -n 1 -w 1000 -l $BigPayload $target.Ip
$LASTEXITCODE -eq 0
}
Write-Host "OK: windows lighthouse -> WSL peer, $BigPayload byte $($target.Family) payload"
}
Write-Host ''
Write-Host 'All smoke checks passed.'
}
-3
View File
@@ -242,14 +242,11 @@ test-cov-html:
go test -coverprofile=coverage.out
go tool cover -html=coverage.out
# The package builds only compile. The final line links an android binary so a linker-only failure
# cannot pass CI.
build-test-mobile:
GOARCH=amd64 GOOS=ios go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
GOARCH=arm64 GOOS=ios go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
GOARCH=amd64 GOOS=android go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
GOARCH=arm64 GOOS=android go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
GOARCH=arm64 GOOS=android go build -o /dev/null ${NEBULA_CMD_PATH}
bench:
go test -bench=.
+3 -2
View File
@@ -8,5 +8,6 @@ If you believe you have found a security vulnerability with Nebula, please let
us know right away. We will investigate all reports and do our best to quickly
fix valid issues.
You can submit your report on [HackerOne](https://hackerone.com/slack) and our
security team will respond as soon as possible.
For critical reports, if you are interested in a bug bounty: You can submit your report on [HackerOne](https://hackerone.com/slack).
For other reports: You can [submit a report via GitHub](https://github.com/slackhq/nebula/security/advisories/new).
+1 -2
View File
@@ -203,8 +203,7 @@ func (c *Control) RebindUDPServer() {
}
// A failure here means we are likely still pinned to the interface we came up on, so the rest of this is
// unlikely to help. Say so instead of silently carrying on as if we rebound. Only the first writer is rebound;
// darwin's Rebind clears every listen routine's listener.
// unlikely to help. Say so instead of silently carrying on as if we rebound.
if err := c.f.outside.Rebind(); err != nil {
c.l.Error("Failed to rebind udp socket", "error", err)
}
-90
View File
@@ -1,90 +0,0 @@
package nebula
import (
"net/netip"
"sync"
"github.com/slackhq/nebula/udp"
)
// establishedRemotes tells the udp conns that implement udp.EstablishedPeerConn which addresses are the current
// direct remote of at least one established tunnel. A hostinfo holds a reference on its remote while it is in the
// main hostmap, and SetRemote moves the reference; a relayed tunnel has no direct remote and holds none.
type establishedRemotes struct {
mu sync.Mutex
conns []udp.EstablishedPeerConn
refs map[netip.AddrPort]int
}
// newEstablishedRemotes returns nil when no conn wants to know, which every method accepts.
func newEstablishedRemotes(conns []udp.Conn) *establishedRemotes {
var pc []udp.EstablishedPeerConn
for _, c := range conns {
if p, ok := c.(udp.EstablishedPeerConn); ok {
pc = append(pc, p)
}
}
if len(pc) == 0 {
return nil
}
return &establishedRemotes{conns: pc, refs: map[netip.AddrPort]int{}}
}
// add makes hostinfo hold a reference on its remote, as it joins the main hostmap. A hostinfo holds references in
// one establishedRemotes at a time, so an add while it is in another is ignored.
func (e *establishedRemotes) add(hostinfo *HostInfo) {
if e == nil {
return
}
e.mu.Lock()
defer e.mu.Unlock()
if !hostinfo.establishedIn.CompareAndSwap(nil, e) && hostinfo.establishedIn.Load() != e {
return
}
e.syncLocked(hostinfo)
}
// remove drops hostinfo's reference, as it leaves the main hostmap.
func (e *establishedRemotes) remove(hostinfo *HostInfo) {
if e == nil {
return
}
e.mu.Lock()
defer e.mu.Unlock()
if hostinfo.establishedIn.CompareAndSwap(e, nil) {
e.syncLocked(hostinfo)
}
}
// syncLocked moves hostinfo's reference to the remote it should hold now: its current remote while it is
// established, none otherwise. Reading both under mu makes the last call win however add, remove and SetRemote
// interleave. Only the establishedRemotes that hostinfo is in, or has just left, may call it, since
// hostinfo.establishedRemote is a reference in that one's refs.
func (e *establishedRemotes) syncLocked(hostinfo *HostInfo) {
var want netip.AddrPort
if hostinfo.establishedIn.Load() == e {
want = hostinfo.GetRemote()
}
held := hostinfo.establishedRemote
if want == held {
return
}
if held.IsValid() {
e.refs[held]--
if e.refs[held] == 0 {
delete(e.refs, held)
for _, c := range e.conns {
c.SetEstablishedPeer(held, false)
}
}
}
if want.IsValid() {
e.refs[want]++
if e.refs[want] == 1 {
for _, c := range e.conns {
c.SetEstablishedPeer(want, true)
}
}
}
hostinfo.establishedRemote = want
}
-173
View File
@@ -1,173 +0,0 @@
package nebula
import (
"net/netip"
"sync"
"testing"
"github.com/slackhq/nebula/test"
"github.com/slackhq/nebula/udp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// establishedPeerConn records which destinations the hostmap has told it are established peers, and fails the test
// on a call that doesn't change anything, which would mean a reference count went wrong.
type establishedPeerConn struct {
udp.NoopConn
t *testing.T
mu sync.Mutex
peers map[netip.AddrPort]bool
}
func (c *establishedPeerConn) SetEstablishedPeer(dst netip.AddrPort, established bool) {
c.mu.Lock()
defer c.mu.Unlock()
assert.NotEqual(c.t, established, c.peers[dst], "SetEstablishedPeer(%v, %v) repeated", dst, established)
if established {
c.peers[dst] = true
} else {
delete(c.peers, dst)
}
}
func (c *establishedPeerConn) established() []netip.AddrPort {
c.mu.Lock()
defer c.mu.Unlock()
var out []netip.AddrPort
for dst := range c.peers {
out = append(out, dst)
}
return out
}
// newEstablishedTestHostMap returns a hostmap whose conns are a recording conn and one that doesn't track peers.
func newEstablishedTestHostMap(t *testing.T) (*HostMap, *establishedPeerConn) {
hm := newHostMap(test.NewLogger())
hm.preferredRanges.Store(&[]netip.Prefix{netip.MustParsePrefix("192.168.0.0/16")})
c := &establishedPeerConn{t: t, peers: map[netip.AddrPort]bool{}}
hm.established = newEstablishedRemotes([]udp.Conn{c, udp.NoopConn{}})
require.NotNil(t, hm.established)
return hm, c
}
func newEstablishedTestHostInfo(vpnAddr netip.Addr, index uint32) *HostInfo {
return &HostInfo{
vpnAddrs: []netip.Addr{vpnAddr},
localIndexId: index,
remotes: NewRemoteList([]netip.Addr{vpnAddr}, nil),
}
}
func TestNewEstablishedRemotesWithoutTrackingConns(t *testing.T) {
assert.Nil(t, newEstablishedRemotes([]udp.Conn{udp.NoopConn{}}))
}
// A conn hears about a remote while at least one hostinfo in the main hostmap has it as its direct remote: from
// the add, through roaming and SetRemoteIfPreferred, until the last such hostinfo is deleted or retired by
// MaxHostInfosPerVpnIp. Pending and relayed hostinfos never count.
func TestHostMap_EstablishedRemotes(t *testing.T) {
hm, c := newEstablishedTestHostMap(t)
f := &Interface{}
a := netip.MustParseAddr("10.0.0.1")
r1 := netip.MustParseAddrPort("203.0.113.1:4242")
r2 := netip.MustParseAddrPort("203.0.113.2:4242")
r3 := netip.MustParseAddrPort("192.168.1.3:4242")
// A pending hostinfo, as a handshake sets its remote, isn't established.
h1 := newEstablishedTestHostInfo(a, 1)
h1.SetRemote(r1)
assert.Empty(t, c.established())
// Handshake completion adds it to the main hostmap.
hm.unlockedAddHostInfo(h1, f)
assert.ElementsMatch(t, []netip.AddrPort{r1}, c.established())
// A relayed tunnel has no direct remote.
relayed := newEstablishedTestHostInfo(netip.MustParseAddr("10.0.0.2"), 2)
hm.unlockedAddHostInfo(relayed, f)
assert.ElementsMatch(t, []netip.AddrPort{r1}, c.established())
// A rehandshake's new hostinfo shares the remote, which stays established until both are gone.
h3 := newEstablishedTestHostInfo(a, 3)
h3.SetRemote(r1)
hm.unlockedAddHostInfo(h3, f)
hm.DeleteHostInfo(h1)
assert.ElementsMatch(t, []netip.AddrPort{r1}, c.established())
// Roaming moves the reference.
h3.SetRemote(r2)
assert.ElementsMatch(t, []netip.AddrPort{r2}, c.established())
require.True(t, h3.SetRemoteIfPreferred(hm, ViaSender{UdpAddr: r3}))
assert.ElementsMatch(t, []netip.AddrPort{r3}, c.established())
// A relayed tunnel that hears from its peer directly roams onto a direct remote.
relayed.SetRemote(r1)
assert.ElementsMatch(t, []netip.AddrPort{r1, r3}, c.established())
hm.DeleteHostInfo(relayed)
// A deleted hostinfo lets go, and a SetRemote after that changes nothing.
hm.DeleteHostInfo(h3)
assert.Empty(t, c.established())
h3.SetRemote(r2)
assert.Empty(t, c.established())
hm.DeleteHostInfo(h3)
// Adding past MaxHostInfosPerVpnIp retires the oldest hostinfo and its remote.
var hs []*HostInfo
for i := range MaxHostInfosPerVpnIp + 1 {
h := newEstablishedTestHostInfo(a, uint32(10+i))
h.SetRemote(netip.AddrPortFrom(netip.MustParseAddr("198.51.100.1"), uint16(1000+i)))
hm.unlockedAddHostInfo(h, f)
hs = append(hs, h)
}
assert.Len(t, c.established(), MaxHostInfosPerVpnIp)
assert.NotContains(t, c.established(), hs[0].GetRemote())
}
// Roaming on the receive path races tunnel teardown on the connection manager; whatever the order, a deleted
// hostinfo holds no reference.
func TestHostMap_EstablishedRemotesRoamRacesDelete(t *testing.T) {
hm, c := newEstablishedTestHostMap(t)
f := &Interface{}
a := netip.MustParseAddr("10.0.0.1")
for i := range 200 {
h := newEstablishedTestHostInfo(a, uint32(i+1))
h.SetRemote(netip.MustParseAddrPort("203.0.113.1:4242"))
hm.Lock()
hm.unlockedAddHostInfo(h, f)
hm.Unlock()
var wg sync.WaitGroup
wg.Go(func() { h.SetRemote(netip.AddrPortFrom(netip.MustParseAddr("203.0.113.2"), uint16(i+1))) })
wg.Go(func() { hm.DeleteHostInfo(h) })
wg.Wait()
require.Empty(t, c.established(), "round %d", i)
}
}
// A hostinfo holds its reference in the first tracking hostmap it joins; another's add and delete of it change
// nothing, so neither hostmap's counts go wrong.
func TestHostMap_EstablishedRemotesSingleOwner(t *testing.T) {
hm1, c1 := newEstablishedTestHostMap(t)
hm2, c2 := newEstablishedTestHostMap(t)
f := &Interface{}
r := netip.MustParseAddrPort("203.0.113.1:4242")
h := newEstablishedTestHostInfo(netip.MustParseAddr("10.0.0.1"), 1)
h.SetRemote(r)
hm1.unlockedAddHostInfo(h, f)
hm2.unlockedAddHostInfo(h, f)
assert.ElementsMatch(t, []netip.AddrPort{r}, c1.established())
assert.Empty(t, c2.established())
hm2.DeleteHostInfo(h)
assert.Equal(t, map[netip.AddrPort]int{r: 1}, hm1.established.refs)
assert.Empty(t, hm2.established.refs)
assert.ElementsMatch(t, []netip.AddrPort{r}, c1.established())
hm1.DeleteHostInfo(h)
assert.Empty(t, hm1.established.refs)
assert.Empty(t, hm2.established.refs)
assert.Empty(t, c1.established())
assert.Empty(t, c2.established())
}
+1 -1
View File
@@ -5,7 +5,6 @@ go 1.26.0
require (
dario.cat/mergo v1.0.2
filippo.io/bigmod v0.1.0
github.com/DefinedNet/netlink v1.3.2-dn.1
github.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be
github.com/armon/go-radix v1.0.0
github.com/flynn/noise v1.1.0
@@ -21,6 +20,7 @@ require (
github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6
github.com/stretchr/testify v1.12.1
github.com/vishvananda/netlink v1.3.1
go.uber.org/goleak v1.3.0
go.yaml.in/yaml/v3 v3.0.5
golang.org/x/crypto v0.57.0
+4 -2
View File
@@ -3,8 +3,6 @@ dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
filippo.io/bigmod v0.1.0 h1:UNzDk7y9ADKST+axd9skUpBQeW7fG2KrTZyOE4uGQy8=
filippo.io/bigmod v0.1.0/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI=
github.com/DefinedNet/netlink v1.3.2-dn.1 h1:Md2PsUE1Xuy1Zxs/Bm6356n1kt5bq2HspXlPJ6pEspg=
github.com/DefinedNet/netlink v1.3.2-dn.1/go.mod h1:o4YSn8Jw7zoDcYXDmV77TRd4eS5sSLuE+vu2zAN67C8=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
@@ -140,6 +138,8 @@ github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81P
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/vishvananda/netlink v1.3.1 h1:3AEMt62VKqz90r0tmNhog0r/PpWKmrEShJU0wJW6bV0=
github.com/vishvananda/netlink v1.3.1/go.mod h1:ARtKouGSTGchR8aMwmkzC0qiNPrrWO5JS/XMVl45+b4=
github.com/vishvananda/netns v0.0.5 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
@@ -195,6 +195,8 @@ golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7w
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210603081109-ebe580a85c40/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+58 -16
View File
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"log/slog"
"net"
"net/netip"
"slices"
"sync"
@@ -17,6 +18,7 @@ import (
"github.com/slackhq/nebula/cert"
"github.com/slackhq/nebula/config"
"github.com/slackhq/nebula/header"
"github.com/slackhq/nebula/logging"
)
const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
@@ -69,8 +71,6 @@ type HostMap struct {
Hosts map[netip.Addr]*HostInfo
moreHosts map[netip.Addr][]*HostInfo
preferredRanges atomic.Pointer[[]netip.Prefix]
// established hears about each hostinfo that joins or leaves the hostmap; nil when no conn wants to know.
established *establishedRemotes
l *slog.Logger
}
@@ -278,11 +278,6 @@ type HostInfo struct {
// This value will be behind against actual tunnel utilization in the hot path.
// This should only be used by the ConnectionManagers ticker routine.
lastUsed time.Time
// establishedIn is set while the hostinfo is in a main hostmap whose conns track established remotes, and
// establishedRemote is the remote it holds a reference on there, guarded by establishedIn's mu.
establishedIn atomic.Pointer[establishedRemotes]
establishedRemote netip.AddrPort
}
type ViaSender struct {
@@ -523,7 +518,6 @@ func (hm *HostMap) unlockedDeleteHostInfo(hostinfo *HostInfo) bool {
if len(hm.Indexes) == 0 {
hm.Indexes = map[uint32]*HostInfo{}
}
hm.established.remove(hostinfo)
if hm.l.Enabled(context.Background(), slog.LevelDebug) {
hm.l.Debug("Hostmap hostInfo deleted",
@@ -670,7 +664,6 @@ func (hm *HostMap) unlockedAddHostInfo(hostinfo *HostInfo, f *Interface) {
hm.Indexes[hostinfo.localIndexId] = hostinfo
hm.RemoteIndexes[hostinfo.remoteIndexId] = hostinfo
hm.established.add(hostinfo)
hostinfo.markOut(f.rebindEpoch.Load())
if f.connectionManager != nil { // f.connectionManager is only nil in some unit tests
@@ -851,13 +844,6 @@ func (i *HostInfo) SetRemote(remote netip.AddrPort) {
if i.GetRemote() != remote {
i.remote.Store(&remote)
i.remotes.LearnRemote(i.vpnAddrs[0], remote)
if e := i.establishedIn.Load(); e != nil {
e.mu.Lock()
if i.establishedIn.Load() == e {
e.syncLocked(i)
}
e.mu.Unlock()
}
}
}
@@ -944,3 +930,59 @@ func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
return li
}
// Utility functions
func localAddrs(l *slog.Logger, allowList *LocalAllowList) []netip.Addr {
//FIXME: This function is pretty garbage
var finalAddrs []netip.Addr
ifaces, _ := net.Interfaces()
for _, i := range ifaces {
allow := allowList.AllowName(i.Name)
if l.Enabled(context.Background(), logging.LevelTrace) {
l.Log(context.Background(), logging.LevelTrace, "localAllowList.AllowName",
"interfaceName", i.Name,
"allow", allow,
)
}
if !allow {
continue
}
addrs, _ := i.Addrs()
for _, rawAddr := range addrs {
var addr netip.Addr
switch v := rawAddr.(type) {
case *net.IPNet:
//continue
addr, _ = netip.AddrFromSlice(v.IP)
case *net.IPAddr:
addr, _ = netip.AddrFromSlice(v.IP)
}
if !addr.IsValid() {
if l.Enabled(context.Background(), slog.LevelDebug) {
l.Debug("addr was invalid", "localAddr", rawAddr)
}
continue
}
addr = addr.Unmap()
if addr.IsLoopback() == false && addr.IsLinkLocalUnicast() == false {
isAllowed := allowList.Allow(addr)
if l.Enabled(context.Background(), logging.LevelTrace) {
l.Log(context.Background(), logging.LevelTrace, "localAllowList.Allow",
"localAddr", addr,
"allowed", isAllowed,
)
}
if !isAllowed {
continue
}
finalAddrs = append(finalAddrs, addr)
}
}
}
return finalAddrs
}
+13 -3
View File
@@ -45,7 +45,8 @@ func setTransportChecksum4(packet []byte) {
if ihl < ipv4.HeaderLen || end < ihl || end > len(packet) {
return
}
// do not attempt to set checksums for fragments
// The checksum covers the whole datagram, which a fragment (MF set or a
// non-zero offset) does not carry.
if binary.BigEndian.Uint16(packet[6:8])&0x3fff != 0 {
return
}
@@ -67,7 +68,10 @@ func setTransportChecksum6(packet []byte) {
return
}
// we must find the transport header in order to write a checksum
// The checksum covers the whole datagram, which a fragment does not carry.
// An unknown extension header hides where the transport header starts. A
// chain longer than the walk's budget ends it early, at an offset that was
// never checked against the packet.
proto, offset, _, anyFragment, err := IPv6FindUpperProtocol(packet[:end])
if err != nil || anyFragment || offset >= end {
return
@@ -105,7 +109,8 @@ func transportExtent(transport []byte, proto uint8) ([]byte, bool) {
// writeTransportChecksum stores the checksum of transport, taken over the
// pseudo-header sum csum, in the header's checksum field. A UDP checksum that
// computes to zero goes on the wire as 0xffff: zero means no checksum was
// computed (RFC 768), and over IPv6 the checksum is mandatory (RFC 8200 section 8.1).
// computed (RFC 768), and over IPv6 the checksum is mandatory (RFC 8200
// section 8.1).
func writeTransportChecksum(transport []byte, proto uint8, csum uint32) {
var at, minLen int
switch proto {
@@ -128,6 +133,11 @@ func writeTransportChecksum(transport []byte, proto uint8, csum uint32) {
binary.BigEndian.PutUint16(transport[at:], sum)
}
// fold reduces a pseudo-header sum to the 16 bit seed Checksum takes. Carrying
// the high half back into the low half is what keeps the reduction lossless, so
// the seed sums exactly as the wider value would; 0xffff is its fixed point.
// Every term of that sum comes from a 16 bit field, so it stays far below the
// width at which the accumulator would wrap.
func fold(csum uint32) uint16 {
for csum > 0xffff {
csum = (csum >> 16) + (csum & 0xffff)
+16 -13
View File
@@ -345,11 +345,14 @@ func ipv6CreateRejectTCPPacket(packet []byte, out []byte, offset int) []byte {
return out
}
// IPv6FindUpperProtocol walks the ipv6 extension header chain and returns the upper layer protocol, the offset it begins at, and whether the packet is a non-first fragment.
// Only the RFC 8200 and IANA extension headers below are walked.
// Everything else, including Mobility (135), HIP (139), Shim6 (140), experimental 253/254, and real upper layer protocols like SCTP or GRE, is terminal.
// For a non-first fragment the returned protocol is the fragmented protocol and offset points at the fragment header, there is no transport header to locate.
// Returns ErrIPv6CouldNotFindPayload if packet is smaller than an ipv6 header, or the chain is truncated, or if more than 8 extension headers are present.
// IPv6FindUpperProtocol walks the ipv6 extension header chain and returns the upper layer protocol, the
// offset it begins at, and whether the packet is a non-first fragment. Only the RFC 8200 and IANA extension
// headers below are walked. Everything else, including Mobility (135), HIP (139), Shim6 (140), experimental
// 253/254, and real upper layer protocols like SCTP or GRE, is terminal. Walking those as extension headers
// is a firewall bypass, so they fail closed. For a non-first fragment the returned protocol is the fragmented
// protocol and offset points at the fragment header, there is no transport header to locate. Returns
// ErrIPv6CouldNotFindPayload if packet is smaller than an ipv6 header or the chain is truncated before a
// terminal protocol is reached.
func IPv6FindUpperProtocol(packet []byte) (nextHeader uint8, offset int, isFragment bool, anyFragment bool, err error) {
const maxIPv6ExtHeaders = 8
if len(packet) < ipv6.HeaderLen {
@@ -362,14 +365,14 @@ func IPv6FindUpperProtocol(packet []byte) (nextHeader uint8, offset int, isFragm
switch nextHeader {
case 0, 43, 60: // Hop-by-Hop, Routing, Destination
if len(packet) < offset+2 {
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
return nextHeader, offset, isFragment, anyFragment, ErrIPv6CouldNotFindPayload
}
nextHeader = packet[offset]
offset += (int(packet[offset+1]) + 1) << 3
case 44: // Fragment
if len(packet) < offset+8 {
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
return nextHeader, offset, isFragment, anyFragment, ErrIPv6CouldNotFindPayload
}
anyFragment = true
// Non-first fragments carry no transport header, report the fragmented protocol and stop
@@ -381,21 +384,21 @@ func IPv6FindUpperProtocol(packet []byte) (nextHeader uint8, offset int, isFragm
case 51: // AH
if len(packet) < offset+2 {
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
return nextHeader, offset, isFragment, anyFragment, ErrIPv6CouldNotFindPayload
}
nextHeader = packet[offset]
offset += (int(packet[offset+1]) + 2) << 2
default:
// A prior extension header can declare a length that advances offset past the packet. The terminal
// protocol's header isn't actually here, so treat the chain as truncated rather than classifying it.
if offset > len(packet) {
// A prior extension header can declare a length that advances offset past the packet, reject this.
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
return nextHeader, offset, isFragment, anyFragment, ErrIPv6CouldNotFindPayload
}
return nextHeader, offset, isFragment, anyFragment, nil //success!
return nextHeader, offset, isFragment, anyFragment, nil
}
}
// Fail closed
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
return nextHeader, offset, isFragment, anyFragment, nil
}
func CreateICMPEchoResponse(packet, out []byte) []byte {
+5 -17
View File
@@ -529,17 +529,6 @@ func Test_IPv6FindUpperProtocol(t *testing.T) {
firstFragToUDP := []byte{17, 0, 0, 1, 0, 0, 0, 1} // frag offset 0, M=1, next = UDP
nonFirstFrag := []byte{17, 0, 0, 9, 0, 0, 0, 1} // frag offset non-zero, next = UDP
transport := []byte{0, 80, 1, 187, 0, 0, 0, 0} // stand-in bytes, IPv6FindUpperProtocol never reads ports
extToHbH := []byte{0, 0, 0, 0, 0, 0, 0, 0} // len 0 -> 8 bytes, next = Hop-by-Hop
// 8 walked headers spend the budget before the 9th slot's terminal is ever classified. This is the
// report 4040546 shape: without failing closed the walk hands back offset 104, and a caller reads ports
// from the attacker's bytes there.
var budgetChain []byte
for range 7 {
budgetChain = append(budgetChain, extToHbH...)
}
budgetChain = append(budgetChain, extToTCP...)
budgetChain = append(budgetChain, transport...)
tests := []struct {
name string
@@ -560,10 +549,9 @@ func Test_IPv6FindUpperProtocol(t *testing.T) {
{"first fragment walks to transport", 44, append(firstFragToUDP, transport...), 17, ipv6.HeaderLen + 8, false, true, nil},
{"non-first fragment stops", 44, append(nonFirstFrag, transport...), 17, ipv6.HeaderLen, true, true, nil},
{"unknown protocol is terminal", 132, transport, 132, ipv6.HeaderLen, false, false, nil}, // SCTP
{"truncated extension header", 0, nil, 0, 0, false, false, ErrIPv6CouldNotFindPayload},
{"truncated extension header", 0, nil, 0, ipv6.HeaderLen, false, false, ErrIPv6CouldNotFindPayload},
// Destination Options with a declared length (255+1)*8 = 2048 that runs past the 48 byte buffer, next = SCTP
{"extension length past buffer", 0, []byte{132, 255, 0, 0, 0, 0, 0, 0}, 0, 0, false, false, ErrIPv6CouldNotFindPayload},
{"budget exhausted fails closed", 0, budgetChain, 0, 0, false, false, ErrIPv6CouldNotFindPayload},
{"extension length past buffer", 60, []byte{132, 255, 0, 0, 0, 0, 0, 0}, 132, ipv6.HeaderLen + 2048, false, false, ErrIPv6CouldNotFindPayload},
}
for _, tt := range tests {
@@ -571,10 +559,10 @@ func Test_IPv6FindUpperProtocol(t *testing.T) {
packet := makeIPv6Packet(src, dst, tt.nextHeader, tt.payload)
proto, offset, isFragment, anyFragment, err := IPv6FindUpperProtocol(packet)
if tt.wantErr != nil {
require.ErrorIs(t, err, tt.wantErr)
} else {
require.NoError(t, err)
assert.ErrorIs(t, err, tt.wantErr)
return
}
require.NoError(t, err)
assert.Equal(t, tt.wantProto, proto)
assert.Equal(t, tt.wantOffset, offset)
assert.Equal(t, tt.wantFragment, isFragment)
+1 -28
View File
@@ -19,7 +19,6 @@ import (
"github.com/slackhq/nebula/config"
"github.com/slackhq/nebula/header"
"github.com/slackhq/nebula/logging"
"github.com/slackhq/nebula/nicfinder"
"github.com/slackhq/nebula/udp"
"github.com/slackhq/nebula/util"
)
@@ -43,10 +42,6 @@ type LightHouse struct {
// addresses rather than whatever this machine's NICs happen to be. Set it before Start.
localAddrsFn func(*LocalAllowList) []netip.Addr
// lastLocalAddrsErr is the previous localAddrsFn failure. Enumeration runs on every update, so an
// unchanged failure is demoted to Debug rather than warning every lighthouse.interval forever.
lastLocalAddrsErr atomic.Pointer[string]
// Local cache of answers from light houses
// map of vpn addr to answers
addrMap map[netip.Addr]*RemoteList
@@ -120,9 +115,7 @@ func NewLightHouseFromConfig(ctx context.Context, l *slog.Logger, c *config.C, c
l: l,
}
h.localAddrsFn = func(al *LocalAllowList) []netip.Addr {
addrs, err := nicfinder.Find(ctx, h.l, al)
h.logLocalAddrsErr(err)
return addrs
return localAddrs(h.l, al)
}
lighthouses := make([]netip.Addr, 0)
@@ -923,26 +916,6 @@ func (lh *LightHouse) TriggerUpdate() {
}
}
// logLocalAddrsErr reports a localAddrs failure at Warn the first time it is seen and at Debug while
// it persists unchanged, so a permanent failure does not warn on every update forever.
func (lh *LightHouse) logLocalAddrsErr(err error) {
if err == nil {
lh.lastLocalAddrsErr.Store(nil)
return
}
msg := err.Error()
prev := lh.lastLocalAddrsErr.Swap(&msg)
if prev != nil && *prev == msg {
if lh.l.Enabled(context.Background(), slog.LevelDebug) {
lh.l.Debug("Failed to collect local addresses to advertise", "error", err)
}
return
}
lh.l.Warn("Failed to collect local addresses to advertise", "error", err)
}
func (lh *LightHouse) SendUpdate() {
var v4 []*V4AddrPort
var v6 []*V6AddrPort
-31
View File
@@ -1,9 +1,7 @@
package nebula
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"net/netip"
"testing"
@@ -766,32 +764,3 @@ func TestLighthouse_DeletesWork(t *testing.T) {
out = lh.Query(testHost)
assert.Nil(t, out)
}
func TestLightHouse_logLocalAddrsErr(t *testing.T) {
out := &bytes.Buffer{}
lh := &LightHouse{l: test.NewLoggerWithOutput(out)}
// The first sighting of a failure warns.
lh.logLocalAddrsErr(errors.New("permission denied"))
assert.Contains(t, out.String(), "level=WARN")
assert.Contains(t, out.String(), "permission denied")
// Repeating unchanged does not warn again, which is what keeps a permanent failure from warning
// on every lighthouse.interval for the life of the process.
out.Reset()
lh.logLocalAddrsErr(errors.New("permission denied"))
assert.NotContains(t, out.String(), "level=WARN")
// A different failure is a new event and warns.
out.Reset()
lh.logLocalAddrsErr(errors.New("something else"))
assert.Contains(t, out.String(), "level=WARN")
assert.Contains(t, out.String(), "something else")
// Recovering resets, so the same failure returning later warns again.
out.Reset()
lh.logLocalAddrsErr(nil)
assert.Empty(t, out.String())
lh.logLocalAddrsErr(errors.New("something else"))
assert.Contains(t, out.String(), "level=WARN")
}
+2 -6
View File
@@ -32,12 +32,9 @@ const _ = noiseutil.RejectHeadroom - 4*maxRoutines
func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, deviceFactory overlay.DeviceFactory) (retcon *Control, reterr error) {
ctx, cancel := context.WithCancel(context.Background())
// The goroutines started below stop only when this context does, and only a caller holding the
// Control can arrange that. Cancel whenever we are not handing one back, which covers an error
// and a config test alike: a config test used to leave the lighthouse query worker, and a
// hostname resolver per dns named static host, running for the life of the process.
// Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
defer func() {
if retcon == nil {
if reterr != nil {
cancel()
}
}()
@@ -213,7 +210,6 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
}
hostMap := NewHostMapFromConfig(l, c)
hostMap.established = newEstablishedRemotes(udpConns)
punchy := NewPunchyFromConfig(l, c, udpConns[0])
connManager := newConnectionManagerFromConfig(l, c, hostMap, punchy)
lightHouse, err := NewLightHouseFromConfig(ctx, l, c, pki.getCertState(), udpConns[0], punchy)
-74
View File
@@ -1,21 +1,12 @@
package nebula
import (
"fmt"
"net/netip"
"os"
"path/filepath"
"testing"
"time"
"github.com/slackhq/nebula/cert"
cert_test "github.com/slackhq/nebula/cert_test"
"github.com/slackhq/nebula/config"
"github.com/slackhq/nebula/test"
"github.com/slackhq/nebula/util"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/goleak"
)
func TestParseCpuAffinity(t *testing.T) {
@@ -58,68 +49,3 @@ func TestParseCpuAffinity(t *testing.T) {
assert.Nil(t, parseCpuAffinity(newConfig([]any{1 << 20}), l, 1))
}
}
// TestMain_ConfigTestReleasesItsGoroutines pins the rule that Main only leaves goroutines running
// when it hands back a Control to stop them with.
//
// A config test gets no Control, so anything it started had nothing to stop it: the lighthouse
// query worker, and a hostname resolver per dns named static host, ran for the life of the
// process. That matters to every embedder that validates a config in process rather than by
// exec'ing, dnclient and the apple clients included, because they do it on each config load and
// the leak accumulates.
func TestMain_ConfigTestReleasesItsGoroutines(t *testing.T) {
defer goleak.VerifyNone(t, goleak.IgnoreCurrent())
l := test.NewLogger()
dir := t.TempDir()
before := time.Now().Add(-time.Hour)
after := time.Now().Add(time.Hour)
ca, _, caKey, caPEM := cert_test.NewTestCaCert(cert.Version2, cert.Curve_CURVE25519, before, after, nil, nil, nil)
networks := []netip.Prefix{netip.MustParsePrefix("10.0.0.1/24")}
_, _, keyPEM, certPEM := cert_test.NewTestCert(
cert.Version2, cert.Curve_CURVE25519, ca, caKey, "config-test", before, after, networks, nil, nil)
caPath := filepath.Join(dir, "ca.pem")
certPath := filepath.Join(dir, "cert.pem")
keyPath := filepath.Join(dir, "key.pem")
require.NoError(t, os.WriteFile(caPath, caPEM, 0o600))
require.NoError(t, os.WriteFile(certPath, certPEM, 0o600))
require.NoError(t, os.WriteFile(keyPath, keyPEM, 0o600))
// A static host by address, not by name: the query worker is the goroutine under test and a
// hostname would drag a real dns lookup into a unit test.
configBody := fmt.Sprintf(`
pki:
ca: %s
cert: %s
key: %s
static_host_map:
"10.0.0.2": ["192.0.2.1:4242"]
lighthouse:
hosts:
- "10.0.0.2"
listen:
host: 127.0.0.1
port: 0
tun:
disabled: true
firewall:
outbound:
- port: any
proto: any
host: any
inbound:
- port: any
proto: any
host: any
`, caPath, certPath, keyPath)
require.NoError(t, os.WriteFile(filepath.Join(dir, "config.yml"), []byte(configBody), 0o600))
c := config.NewC(l)
require.NoError(t, c.Load(dir))
ctrl, err := Main(c, true, "config-test", l, nil)
require.NoError(t, err)
require.Nil(t, ctrl, "a config test hands back nothing to stop, so it must stop itself")
}
-39
View File
@@ -1,39 +0,0 @@
//go:build !android
package nicfinder
import (
"context"
"errors"
"fmt"
"log/slog"
"net"
"net/netip"
)
func localAddrs(ctx context.Context, l *slog.Logger, filter Filter) ([]netip.Addr, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, fmt.Errorf("failed to enumerate local interfaces: %w", err)
}
var out []netip.Addr
var errs []error
for _, i := range ifaces {
if !allowName(ctx, l, filter, i.Name) {
continue
}
addrs, err := i.Addrs()
if err != nil {
errs = append(errs, fmt.Errorf("failed to get addresses for %s: %w", i.Name, err))
continue
}
for _, rawAddr := range addrs {
if addr, ok := allowedAddr(ctx, l, filter, rawAddr); ok {
out = append(out, addr)
}
}
}
return out, errors.Join(errs...)
}
-104
View File
@@ -1,104 +0,0 @@
//go:build android
package nicfinder
import (
"context"
"errors"
"fmt"
"log/slog"
"net/netip"
"os"
"github.com/DefinedNet/netlink"
"github.com/DefinedNet/netlink/nl"
"golang.org/x/sys/unix"
)
// Android denies bind() on netlink route sockets and RTM_GETLINK, so net.Interfaces fails with EACCES.
// Enumerate with an RTM_GETADDR dump on an unbound socket instead.
// localInterfaces returns every interface that has an address, with its addresses. It lists
// addresses over a netlink socket that is never bound and names each index with SIOCGIFNAME, the
// same operations Bionic's getifaddrs uses for app UIDs, which the sandbox permits.
func localAddrs(ctx context.Context, l *slog.Logger, filter Filter) ([]netip.Addr, error) {
var errs []error
addrs, err := netlinkAddrList()
if err != nil {
if !errors.Is(err, netlink.ErrDumpInterrupted) {
return nil, fmt.Errorf("failed to enumerate local interfaces: %w", err)
}
// The address table kept changing under the dump and netlink gave up retrying. What it
// returned is still worth advertising.
errs = append(errs, fmt.Errorf("local addresses may be incomplete: %w", err))
}
// Any socket will do for SIOCGIFNAME.
sfd, err := unix.Socket(unix.AF_INET, unix.SOCK_DGRAM|unix.SOCK_CLOEXEC, 0)
if err != nil {
return nil, os.NewSyscallError("socket", err)
}
defer unix.Close(sfd)
var out []netip.Addr
nameAllowed := make(map[int]bool) // by interface index, once named
for _, a := range addrs {
allow, named := nameAllowed[a.LinkIndex]
if (named && !allow) || a.IPNet == nil {
continue
}
addr, ok := allowedAddr(ctx, l, filter, a.IPNet)
if !ok {
continue
}
if !named {
name, err := interfaceNameByIndex(sfd, a.LinkIndex)
// ENODEV means the interface went away after the dump. Any other failure is reported
// and the interface skipped, so the rest are still returned.
if err != nil && !errors.Is(err, unix.ENODEV) {
errs = append(errs, fmt.Errorf("failed to resolve name of interface %d: %w", a.LinkIndex, err))
}
allow = err == nil && allowName(ctx, l, filter, name)
nameAllowed[a.LinkIndex] = allow
}
if allow {
out = append(out, addr)
}
}
return out, errors.Join(errs...)
}
// netlinkAddrList is netlink.AddrList over a socket that is never bound. The kernel autobinds it
// on the first send, which the sandbox permits.
func netlinkAddrList() ([]netlink.Addr, error) {
fd, err := unix.Socket(unix.AF_NETLINK, unix.SOCK_RAW|unix.SOCK_CLOEXEC, unix.NETLINK_ROUTE)
if err != nil {
return nil, os.NewSyscallError("socket", err)
}
s, err := nl.NewNetlinkSocketFromFd(fd)
if err != nil {
unix.Close(fd)
return nil, err
}
h := netlink.NewHandleFromSockets(
map[int]*nl.SocketHandle{unix.NETLINK_ROUTE: {Socket: s}},
netlink.HandleOptions{RetryInterrupted: true},
)
defer h.Close()
if err := h.SetSocketTimeout(netlink.GetSocketTimeout()); err != nil {
return nil, err
}
return h.AddrList(nil, netlink.FAMILY_ALL)
}
// interfaceNameByIndex resolves an interface index with SIOCGIFNAME.
func interfaceNameByIndex(fd int, index int) (string, error) {
var ifr unix.Ifreq
ifr.SetUint32(uint32(index)) // ifr_ifindex is in the ifr_ifru union
if err := unix.IoctlIfreq(fd, unix.SIOCGIFNAME, &ifr); err != nil {
return "", err
}
return ifr.Name(), nil
}
-59
View File
@@ -1,59 +0,0 @@
package nicfinder
import (
"context"
"log/slog"
"net"
"net/netip"
"github.com/slackhq/nebula/logging"
)
// Filter decides which interfaces, by name, and which of their addresses Find returns.
type Filter interface {
AllowName(string) bool
Allow(netip.Addr) bool
}
// Find returns the addresses of this host's network interfaces that allowList accepts, with
// loopback and link-local addresses left out. When only some interfaces could be read it returns
// their addresses alongside an error for the rest. allowList must not be nil; it is called as
// given, so a nil pointer of a type whose methods accept a nil receiver is fine.
func Find(ctx context.Context, l *slog.Logger, allowList Filter) ([]netip.Addr, error) {
return localAddrs(ctx, l, allowList)
}
// allowName asks filter about an interface name and traces the answer.
func allowName(ctx context.Context, l *slog.Logger, filter Filter, name string) bool {
allow := filter.AllowName(name)
if l.Enabled(ctx, logging.LevelTrace) {
l.Log(ctx, logging.LevelTrace, "localAllowList.AllowName", "interfaceName", name, "allow", allow)
}
return allow
}
// allowedAddr converts one address a platform reports and says whether to advertise it: it must
// be a *net.IPNet or *net.IPAddr carrying an IP, not be loopback or link-local, and be accepted by
// filter, whose answer is traced. IPv4 comes back unmapped.
func allowedAddr(ctx context.Context, l *slog.Logger, filter Filter, rawAddr net.Addr) (netip.Addr, bool) {
var ip net.IP
switch v := rawAddr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
addr, ok := netip.AddrFromSlice(ip)
if !ok {
return netip.Addr{}, false
}
addr = addr.Unmap()
if addr.IsLoopback() || addr.IsLinkLocalUnicast() {
return netip.Addr{}, false
}
isAllowed := filter.Allow(addr)
if l.Enabled(ctx, logging.LevelTrace) {
l.Log(ctx, logging.LevelTrace, "localAllowList.Allow", "localAddr", addr, "allowed", isAllowed)
}
return addr, isAllowed
}
-117
View File
@@ -1,117 +0,0 @@
package nicfinder
import (
"context"
"net"
"net/netip"
"regexp"
"testing"
"github.com/slackhq/nebula/test"
"github.com/stretchr/testify/assert"
)
type allowAll struct{}
func (allowAll) Allow(netip.Addr) bool { return true }
func (allowAll) AllowName(string) bool { return true }
type testAllowList struct {
bannedName *regexp.Regexp
bannedAddr netip.Addr
}
func (l *testAllowList) Allow(addr netip.Addr) bool {
return addr != l.bannedAddr
}
func (l *testAllowList) AllowName(n string) bool {
return !l.bannedName.MatchString(n)
}
func newTestAllowList(bannedName string) *testAllowList {
return &testAllowList{
bannedName: regexp.MustCompile(bannedName),
}
}
func TestAllowedAddr(t *testing.T) {
ctx, l := context.Background(), test.NewLogger()
allowed := func(filter Filter, addrs []net.Addr) []netip.Addr {
var out []netip.Addr
for _, rawAddr := range addrs {
if addr, ok := allowedAddr(ctx, l, filter, rawAddr); ok {
out = append(out, addr)
}
}
return out
}
addrs := []net.Addr{
&net.IPNet{IP: net.ParseIP("127.0.0.1"), Mask: net.CIDRMask(8, 32)},
&net.IPNet{IP: net.ParseIP("::1"), Mask: net.CIDRMask(128, 128)},
&net.IPNet{IP: net.ParseIP("10.0.0.5"), Mask: net.CIDRMask(24, 32)},
&net.IPNet{IP: net.ParseIP("169.254.10.10"), Mask: net.CIDRMask(16, 32)},
&net.IPNet{IP: net.ParseIP("fe80::1"), Mask: net.CIDRMask(64, 128)},
&net.IPAddr{IP: net.ParseIP("fd00::5")},
&net.IPNet{},
otherAddr{},
nil,
}
// Loopback, link local and anything without an IP are dropped, and IPv4 comes back unmapped
// even though net.ParseIP hands over a 16 byte slice.
assert.Equal(t, []netip.Addr{
netip.MustParseAddr("10.0.0.5"),
netip.MustParseAddr("fd00::5"),
}, allowed(allowAll{}, addrs))
// The filter sees the unmapped form and can drop a single address.
al := newTestAllowList("none")
al.bannedAddr = netip.MustParseAddr("10.0.0.5")
assert.Equal(t, []netip.Addr{netip.MustParseAddr("fd00::5")}, allowed(al, addrs))
}
// otherAddr is a net.Addr that is neither *net.IPNet nor *net.IPAddr. netlink.Addr is one such
// type: it satisfies net.Addr through an embedded *net.IPNet, and passing it directly once
// silently produced no addresses.
type otherAddr struct{}
func (otherAddr) Network() string { return "other" }
func (otherAddr) String() string { return "other" }
// hostFilter counts AllowName calls and can reject every name or every address.
type hostFilter struct {
rejectNames bool
rejectAddrs bool
asked map[string]int
}
func (f *hostFilter) Allow(netip.Addr) bool { return !f.rejectAddrs }
func (f *hostFilter) AllowName(name string) bool {
f.asked[name]++
return !f.rejectNames
}
// Runs this platform's localAddrs against the host and checks it honors the whole filter.
func TestLocalAddrsAppliesFilter(t *testing.T) {
ctx, l := context.Background(), test.NewLogger()
f := &hostFilter{asked: map[string]int{}}
all, err := localAddrs(ctx, l, f)
if len(f.asked) == 0 {
t.Skipf("no interfaces to enumerate here: %v", err)
}
for name, n := range f.asked {
assert.Equal(t, 1, n, "AllowName asked %d times for %s", n, name)
}
// Loopback and link-local never come back, whatever the filter says.
for _, addr := range all {
assert.False(t, addr.IsLoopback() || addr.IsLinkLocalUnicast(), "%s", addr)
}
none, _ := localAddrs(ctx, l, &hostFilter{rejectNames: true, asked: map[string]int{}})
assert.Empty(t, none, "addresses got past a filter that rejects every interface name")
none, _ = localAddrs(ctx, l, &hostFilter{rejectAddrs: true, asked: map[string]int{}})
assert.Empty(t, none, "addresses got past a filter that rejects every address")
}
+1 -1
View File
@@ -354,7 +354,7 @@ func parseV6(data []byte, incoming bool, fp *firewall.ParsedPacket) error {
// and cannot drift into misreading an unknown protocol (SCTP, GRE, etc.) as a forged transport.
proto, offset, isFragment, anyFragment, err := iputil.IPv6FindUpperProtocol(data)
if err != nil {
return err
return ErrIPv6PacketTooShort
}
fp.Protocol = proto
+7 -7
View File
@@ -117,7 +117,7 @@ func Test_newPacket_v6(t *testing.T) {
require.NoError(t, err)
err = newPacket(buffer.Bytes(), true, p)
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
// A v6 packet with a hop-by-hop extension
// ICMPv6 Payload (Echo Request)
@@ -151,12 +151,12 @@ func Test_newPacket_v6(t *testing.T) {
// A full IPv6 header and 1 byte in the first extension, but missing
// the length byte.
err = newPacket(buffer.Bytes()[:41], true, p)
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
// A full IPv6 header plus 1 full extension, but only 1 byte of the
// next layer, missing length byte
err = newPacket(buffer.Bytes()[:49], true, p)
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
err = nil
// A good ICMP packet
@@ -354,12 +354,12 @@ func Test_newPacket_v6(t *testing.T) {
// Ensure buffer bounds checking during processing, a truncated AH header can't reach the payload
err = newPacket(b[:41], true, p)
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
// Invalid AH header
b = buffer.Bytes()
err = newPacket(b, true, p)
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
}
func Test_newPacket_ipv6Fragment(t *testing.T) {
@@ -466,7 +466,7 @@ func Test_newPacket_ipv6Fragment(t *testing.T) {
// Too short of a fragment packet
err = newPacket(secondFrag[:len(secondFrag)-10], false, p)
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
}
func BenchmarkParseV6(b *testing.B) {
@@ -707,7 +707,7 @@ func Test_newPacket_v6ExtHeaderPastBuffer(t *testing.T) {
pkt[40] = byte(layers.IPProtocolSCTP) // Dest Options next header = SCTP
pkt[41] = 255 // declared length (255+1)*8 = 2048, past the 48 byte buffer
require.ErrorIs(t, newPacket(pkt, true, p), iputil.ErrIPv6CouldNotFindPayload)
require.ErrorIs(t, newPacket(pkt, true, p), ErrIPv6PacketTooShort)
}
// Test_newPacket_v6ExtHeaderConfusion is a regression test for parseV6 walking any unrecognized
+2 -60
View File
@@ -29,9 +29,6 @@ type tun struct {
Routes atomic.Pointer[[]Route]
routeTree atomic.Pointer[bart.Table[routing.Gateways]]
linkAddr *netroute.LinkAddr
// hostOwned means the fd arrived from the OS, which has already configured addressing, mtu
// and routes for it. NEPacketTunnelProvider on darwin does this.
hostOwned bool
l *slog.Logger
}
@@ -152,48 +149,8 @@ func (t *tun) deviceBytes() (o [16]byte) {
return
}
// newTunFromFd adopts a utun the host already created and configured, which is how a darwin
// network extension is handed its device. Everything about moving packets is shared with newTun,
// only the setup differs: the host owns addressing and routing here.
func newTunFromFd(c *config.C, l *slog.Logger, deviceFd int, vpnNetworks []netip.Prefix) (*tun, error) {
if err := unix.SetNonblock(deviceFd, true); err != nil {
// We own the fd from the moment it is handed to us
_ = unix.Close(deviceFd)
return nil, fmt.Errorf("failed to set the tun fd to non-blocking mode: %w", err)
}
file := os.NewFile(uintptr(deviceFd), "/dev/tun")
t := &tun{
f: file,
Device: utunNameFromFd(deviceFd),
vpnNetworks: vpnNetworks,
DefaultMTU: c.GetInt("tun.mtu", DefaultMTU),
hostOwned: true,
l: l,
}
if err := t.reload(c, true); err != nil {
_ = file.Close()
return nil, err
}
c.RegisterReloadCallback(func(c *config.C) {
if err := t.reload(c, false); err != nil {
util.LogWithContextIfNeeded("failed to reload tun device", err, t.l)
}
})
return t, nil
}
// utunNameFromFd asks the socket what interface it is, for logs. A blank name is not worth
// failing a tunnel over, so an error just leaves it empty.
func utunNameFromFd(fd int) string {
name, err := unix.GetsockoptString(fd, unix.AF_SYS_CONTROL, _UTUN_OPT_IFNAME)
if err != nil {
return ""
}
return name
func newTunFromFd(_ *config.C, _ *slog.Logger, _ int, _ []netip.Prefix) (*tun, error) {
return nil, fmt.Errorf("newTunFromFd not supported in Darwin")
}
func (t *tun) Close() error {
@@ -204,12 +161,6 @@ func (t *tun) Close() error {
}
func (t *tun) Activate() error {
// The host handed us a configured device. Its addresses, mtu and routes come from the network
// settings it applied, and a sandboxed extension cannot change them anyway.
if t.hostOwned {
return nil
}
devName := t.deviceBytes()
s, err := unix.Socket(
@@ -423,11 +374,6 @@ func getLinkAddr(name string) (*netroute.LinkAddr, error) {
}
func (t *tun) addRoutes(logErrors bool) error {
// The route tree is still ours, the system routing table is not
if t.hostOwned {
return nil
}
routes := *t.Routes.Load()
for _, r := range routes {
@@ -457,10 +403,6 @@ func (t *tun) addRoutes(logErrors bool) error {
}
func (t *tun) removeRoutes(routes []Route) error {
if t.hostOwned {
return nil
}
for _, r := range routes {
if !r.Install {
continue
+1 -1
View File
@@ -15,12 +15,12 @@ import (
"time"
"unsafe"
"github.com/DefinedNet/netlink"
"github.com/gaissmai/bart"
"github.com/slackhq/nebula/config"
"github.com/slackhq/nebula/overlay/tio"
"github.com/slackhq/nebula/routing"
"github.com/slackhq/nebula/util"
"github.com/vishvananda/netlink"
"golang.org/x/sys/unix"
)
-8
View File
@@ -48,14 +48,6 @@ type Conn interface {
Close() error
}
// EstablishedPeerConn is a Conn that treats the remotes of established tunnels differently from other
// destinations, as darwin's gives busy ones connected sockets.
type EstablishedPeerConn interface {
// SetEstablishedPeer reports whether dst is the current remote of at least one established tunnel. Calls for
// one dst must not race each other.
SetEstablishedPeer(dst netip.AddrPort, established bool)
}
type NoopConn struct{}
func (NoopConn) Rebind() error {
-115
View File
@@ -1,115 +0,0 @@
//go:build !e2e_testing
package udp
import (
"log/slog"
"net"
"net/netip"
"testing"
"time"
)
// benchConnSocks opens a wildcard listener with ListenOut running, with the connected socket knobs pinned to
// their defaults and then cfg applied, and a loopback peer that never reads, so its sends cost only the sender.
func benchConnSocks(b *testing.B, s Settings, cfg func(*connSockConfig)) (*StdConn, netip.AddrPort) {
b.Helper()
for k, v := range map[string]string{
"NEBULA_CONNSOCKS": "8",
"NEBULA_CONNSOCK_RUN": "64",
"NEBULA_CONNSOCK_WINDOW": "1s",
"NEBULA_CONNSOCK_IDLE": "30s",
"NEBULA_CONNSOCK_OPEN_EVERY": "1s",
} {
b.Setenv(k, v)
}
c, err := NewListener(slog.New(slog.DiscardHandler), s)
if err != nil {
b.Fatal(err)
}
b.Cleanup(func() { _ = c.Close() })
u := c.(*StdConn)
if cfg != nil {
cfg(&u.socks.cfg)
}
go func() { _ = u.ListenOut(func(netip.AddrPort, []byte) {}, func() {}) }()
for u.reader.Load() == nil {
time.Sleep(time.Millisecond)
}
pc, err := net.ListenPacket("udp4", "127.0.0.1:0")
if err != nil {
b.Fatal(err)
}
b.Cleanup(func() { _ = pc.Close() })
return u, pc.LocalAddr().(*net.UDPAddr).AddrPort()
}
// BenchmarkConnSockWriteTo measures one WriteTo of a full-size datagram down each path: the listener with
// connected sockets off, to a destination that is no tunnel's remote while another is, to an established peer
// that never gets busy, and on a connected socket.
func BenchmarkConnSockWriteTo(b *testing.B) {
pkt := make([]byte, 1400)
cases := []struct {
name string
cfg func(*connSockConfig)
setup func(b *testing.B, u *StdConn, dst netip.AddrPort)
}{
{name: "listener/off", cfg: func(c *connSockConfig) { c.max = 0 }},
{name: "listener/ineligible", setup: func(b *testing.B, u *StdConn, dst netip.AddrPort) {
u.SetEstablishedPeer(netip.AddrPortFrom(dst.Addr(), dst.Port()+1), true)
}},
{name: "listener/eligible-not-busy", cfg: func(c *connSockConfig) { c.run = 1 << 30 },
setup: func(b *testing.B, u *StdConn, dst netip.AddrPort) { u.SetEstablishedPeer(dst, true) }},
{name: "connected", setup: func(b *testing.B, u *StdConn, dst netip.AddrPort) {
u.SetEstablishedPeer(dst, true)
for range u.socks.cfg.run {
_ = u.WriteTo(pkt, dst)
}
if u.connSockFor(dst) == nil {
b.Fatal("no connected socket")
}
}},
}
for _, c := range cases {
b.Run(c.name, func(b *testing.B) {
u, dst := benchConnSocks(b, Settings{Listen: netip.MustParseAddrPort("0.0.0.0:0")}, c.cfg)
if c.setup != nil {
c.setup(b, u, dst)
}
b.ReportAllocs()
b.ResetTimer()
for range b.N {
_ = u.WriteTo(pkt, dst)
}
})
}
}
// BenchmarkConnSockDispatch measures what WriteTo adds before the listener's sendto, without the syscall: a v4
// listener refuses a v6 destination before sending, with connected sockets off or with another peer established.
func BenchmarkConnSockDispatch(b *testing.B) {
pkt := make([]byte, 1400)
dst := netip.MustParseAddrPort("[::1]:4242")
for _, c := range []struct {
name string
cfg func(*connSockConfig)
establish bool
}{
{name: "off", cfg: func(c *connSockConfig) { c.max = 0 }},
{name: "ineligible", establish: true},
} {
b.Run(c.name, func(b *testing.B) {
u, peer := benchConnSocks(b, Settings{Listen: netip.MustParseAddrPort("127.0.0.1:0"), Multi: true}, c.cfg)
if c.establish {
u.SetEstablishedPeer(peer, true)
}
b.ReportAllocs()
b.ResetTimer()
for range b.N {
if u.WriteTo(pkt, dst) == nil {
b.Fatal("sent a v6 datagram on a v4 listener")
}
}
})
}
}
-803
View File
@@ -1,803 +0,0 @@
//go:build !e2e_testing
package udp
import (
"context"
"errors"
"fmt"
"log/slog"
"maps"
"net"
"net/netip"
"os"
"slices"
"strconv"
"sync"
"sync/atomic"
"syscall"
"time"
"golang.org/x/sys/unix"
)
// A connected socket is a UDP socket connected to one busy peer, on the listener's port and bound to the source
// address the listener's route to that peer picks, so the peer sees the same address and port from either. A send
// on a connected socket skips the per-datagram address and MAC policy checks, and the EndpointSecurity send check
// that xprotectd can hold every unconnected sendto on, and it is the only UDP send that reports the interface
// queue's flow control, as ENOBUFS. A connected socket wins xnu's lookup for its peer's datagrams; it never sees
// anyone else's.
//
// A connected socket sets SO_REUSEPORT and binds a specific address beside a wildcard listener, which sets
// SO_REUSEPORT only for listen routines. xnu refuses a wildcard SO_REUSEPORT bind beside a holder without the
// option, and refuses another uid's bind to an address a socket holds specifically, so no other user can join the
// port while connected sockets open and close: uid nobody got EADDRINUSE on every bind against a root listener
// with connected sockets in the 09-25 probes. A connected socket is closed, never disconnected, because xnu widens
// a disconnected socket's local address to the wildcard.
//
// Only the current remote of an established tunnel may get one: Nebula names those with SetEstablishedPeer, so an
// unauthenticated sender can't earn a connected socket by drawing replies such as recv_error or handshake
// responses.
type connSock struct {
dst netip.AddrPort
peer *connSockPeer
conn *net.UDPConn
rc syscall.RawConn
// used is the monotonic time in nanoseconds of the connected socket's last send or receive.
used atomic.Int64
// stallAt is the monotonic time of the first ENOBUFS or EAGAIN since a send last went through, or 0, and
// dropping is set once that stall has dropped a datagram, so each stall logs its drops once.
stallAt atomic.Int64
dropping atomic.Bool
// parkMu serializes the writes that wait for a full send buffer, since the write deadline bounding each wait
// is the descriptor's, not the writer's.
parkMu sync.Mutex
// sys writes one datagram on the descriptor: writeFd, or a stand-in for the interface in tests.
sys func(fd int, b []byte) error
}
func writeFd(fd int, b []byte) error {
_, err := syscall.Write(fd, b)
return err
}
// errStallSpent is a write that found the connected socket's stall budget spent, so its datagram is dropped.
var errStallSpent = errors.New("connected socket stall budget spent")
// connSockWriter carries one write through RawConn.Write. They are pooled with fn bound once, since a closure
// passed through the RawConn interface escapes and would allocate on every send.
type connSockWriter struct {
s *connSock
b []byte
park bool
err error
fn func(fd uintptr) bool
}
var connSockWriters = sync.Pool{New: func() any {
w := &connSockWriter{}
w.fn = w.write
return w
}}
func (w *connSockWriter) write(fd uintptr) bool {
for {
w.err = w.s.sys(int(fd), w.b)
switch {
case w.err == syscall.EINTR:
case w.err == syscall.EAGAIN && w.park:
return false
default:
return true
}
}
}
// try writes b on s once and returns nil, the write's errno, os.ErrDeadlineExceeded, or net.ErrClosed. With park
// set, EAGAIN waits in the netpoller until the socket is writable or the write deadline passes; without it, EAGAIN
// is returned.
func (s *connSock) try(b []byte, park bool) error {
w := connSockWriters.Get().(*connSockWriter)
w.s, w.b, w.park = s, b, park
rerr := s.rc.Write(w.fn)
err := w.err
*w = connSockWriter{fn: w.fn}
connSockWriters.Put(w)
switch {
case rerr == nil:
return err
case errors.Is(rerr, os.ErrDeadlineExceeded):
return os.ErrDeadlineExceeded
default:
return net.ErrClosed
}
}
// connSockConfig holds the knobs. connSockConfigFromEnv reads all but backoff and enobufsMax from the environment,
// so one binary can be tuned without a rebuild.
type connSockConfig struct {
// max is how many connected sockets the listen routines may have open at once; 0 turns connected sockets off.
max int
// run is how many datagrams to one destination within one window earn it a connected socket. darwin's tun
// hands over one packet per read, so a peer's sends arrive one WriteTo or one-datagram batch at a time and
// busyness has to be counted across calls.
run int
window time.Duration
// idle closes a connected socket after it has neither sent nor received for this long.
idle time.Duration
// backoff keeps a destination whose connected socket failed on the listener for this long.
backoff time.Duration
// openEvery is how often the open bucket earns back an open once max are spent, which bounds connected socket
// churn however fast senders earn connected sockets and errors close them.
openEvery time.Duration
// enobufsMax is how long a connected socket's sends may wait out ENOBUFS without one going through before they
// drop instead, so a suspended interface costs one write per datagram rather than stalling the tun reader.
enobufsMax time.Duration
}
func connSockConfigFromEnv() connSockConfig {
c := connSockConfig{
max: 8,
run: 64,
window: time.Second,
idle: 30 * time.Second,
backoff: 30 * time.Second,
openEvery: time.Second,
enobufsMax: 10 * time.Millisecond,
}
if v, err := strconv.Atoi(os.Getenv("NEBULA_CONNSOCKS")); err == nil {
c.max = v
}
if v, err := strconv.Atoi(os.Getenv("NEBULA_CONNSOCK_RUN")); err == nil && v > 0 {
c.run = v
}
if v, err := time.ParseDuration(os.Getenv("NEBULA_CONNSOCK_WINDOW")); err == nil && v > 0 {
c.window = v
}
if v, err := time.ParseDuration(os.Getenv("NEBULA_CONNSOCK_IDLE")); err == nil && v > 0 {
c.idle = v
}
if v, err := time.ParseDuration(os.Getenv("NEBULA_CONNSOCK_OPEN_EVERY")); err == nil && v > 0 {
c.openEvery = v
}
return c
}
// connSockGroups holds the connSocks that the listen routines bound to one address share, so the limits, the
// connected sockets and Rebind cover every routine, and a peer has at most one connected socket.
var connSockGroups = struct {
sync.Mutex
m map[netip.AddrPort]*connSocks
}{m: map[netip.AddrPort]*connSocks{}}
// joinConnSocks returns the connSocks u shares with the other listen routines bound to la, and makes it for the
// first.
func joinConnSocks(u *StdConn, la netip.AddrPort, s Settings) *connSocks {
g := &connSockGroups
g.Lock()
defer g.Unlock()
if cs := g.m[la]; s.Multi && cs != nil {
cs.mu.Lock()
cs.members = append(cs.members, u)
cs.mu.Unlock()
return cs
}
cs := &connSocks{cfg: connSockConfigFromEnv(), key: la, members: []*StdConn{u}, clock: monoNow, sleep: time.Sleep}
if cs.cfg.max > 0 && !u.listenHost.IsUnspecified() && !s.Multi {
// A connected socket on a specific listen.host binds the listener's own address, which xnu allows only when
// both sockets set SO_REUSEPORT, and a listener with it lets another uid bind a dual-stack wildcard on the
// port.
cs.off.Store(true)
u.l.Debug("connected sockets: off for a specific listen.host", "addr", s.Listen)
}
if s.Multi {
g.m[la] = cs
}
return cs
}
type connSocks struct {
cfg connSockConfig
// key is the listeners' bound address, which connSockGroups files this under.
key netip.AddrPort
// off keeps connected sockets from opening, when the listener's address can't be shared with them.
off atomic.Bool
// table maps each destination that is the remote of an established tunnel, and that a connected socket could
// reach, to its peer; it is nil when there are none, so a send with nothing to consider costs one load. Every
// send reads it without a lock, and mu guards copying it. An open that holds mu and still finds its peer here
// can't outlive the tunnel.
table atomic.Pointer[map[netip.AddrPort]*connSockPeer]
// reserved counts the connected sockets that are open, opening or closing, against cfg.max; mu guards changing it.
reserved atomic.Int32
mu sync.Mutex
closed bool
// members are the listen routines' listeners that share these connected sockets.
members []*StdConn
// pending holds each destination whose connected socket is opening or closing, and not on its peer. xnu
// refuses to connect a 4-tuple that is still bound, so a destination in pending can't open another.
pending map[netip.AddrPort]struct{}
// rebinds counts Rebinds, so an open that copied the listener's interface before one is discarded.
rebinds uint64
// closers tracks the goroutines that close detached connected sockets.
closers sync.WaitGroup
// done stops the reaper; it is made when ListenOut starts the connected sockets.
done chan struct{}
// opens bounds connected socket opens to cfg.max at once and one per cfg.openEvery after.
opens gcra
// logs bounds connected socket log lines at info or warn; see connSockLogBurst.
logs gcra
// clock returns monotonic nanoseconds and sleep waits out ENOBUFS: monoNow and time.Sleep, or stand-ins in
// tests.
clock func() int64
sleep func(time.Duration)
// dialHook and closeHook, when set, run just before an open's dials and a close's Close, outside mu; tests
// use them to hold an open or close in flight.
dialHook, closeHook func(dst netip.AddrPort)
}
// connSockPeer is what connSocks keeps about an established tunnel's remote: its connected socket, how busy it is,
// and how long a failed connected socket keeps it on the listener.
type connSockPeer struct {
sock atomic.Pointer[connSock]
// windowMu guards start, the monotonic time the current window began, and n, the datagrams sent in it, so a
// window's reset and its counts can't interleave with another sender's.
windowMu sync.Mutex
start int64
n int
// retryAt is the monotonic time before which a peer whose connected socket failed stays on the listener;
// connSocks.mu guards it.
retryAt int64
}
// busy counts n more datagrams to p and reports whether it has now sent cfg.run within one window. A busy peer's
// count starts over, so a peer that can't get a connected socket retries at most once per cfg.run sends.
func (p *connSockPeer) busy(now int64, n int, cfg *connSockConfig) bool {
p.windowMu.Lock()
defer p.windowMu.Unlock()
if time.Duration(now-p.start) > cfg.window {
p.start, p.n = now, 0
}
p.n += n
if p.n < cfg.run {
return false
}
p.n = 0
return true
}
// connSockLogBurst and connSockLogEvery size the bucket that lets connected socket opens, closes and failures log
// at info or warn; past it they log at debug, so churn can't flood the log.
const (
connSockLogBurst = 32
connSockLogEvery = 10 * time.Second
)
var monoStart = time.Now()
func monoNow() int64 { return int64(time.Since(monoStart)) }
// gcra is a token bucket kept as the monotonic time it is next full (the generic cell rate algorithm), so it needs
// no refill tick.
type gcra struct{ tat int64 }
// take spends a token from a bucket of burst that earns one back per every, and reports whether there was one to
// spend.
func (g *gcra) take(now int64, burst int, every time.Duration) bool {
e := int64(every)
tat := max(g.tat, now)
if tat-now > int64(burst-1)*e {
return false
}
g.tat = tat + e
return true
}
// logLevelLocked returns level while the log bucket has a token, and debug once it is spent.
func (cs *connSocks) logLevelLocked(level slog.Level) slog.Level {
if cs.logs.take(cs.clock(), connSockLogBurst, connSockLogEvery) {
return level
}
return slog.LevelDebug
}
// startConnSocks starts the idle reaper.
func (u *StdConn) startConnSocks() {
cs := u.socks
cs.mu.Lock()
defer cs.mu.Unlock()
if cs.closed || cs.done != nil || cs.cfg.max <= 0 || cs.off.Load() {
return
}
cs.done = make(chan struct{})
go u.reapConnSocks(cs.done)
}
// stopConnSocks closes every connected socket and keeps new ones from opening, once any listen routine's listener
// closes, as they do together at shutdown. It returns once their descriptors are closed.
func (u *StdConn) stopConnSocks() {
cs := u.socks
cs.mu.Lock()
cs.members = slices.DeleteFunc(cs.members, func(m *StdConn) bool { return m == u })
if !cs.closed {
cs.closed = true
if cs.done != nil {
close(cs.done)
}
u.detachAllLocked("close")
}
cs.mu.Unlock()
connSockGroups.Lock()
if connSockGroups.m[cs.key] == cs {
delete(connSockGroups.m, cs.key)
}
connSockGroups.Unlock()
cs.closers.Wait()
}
// siblings returns the other listen routines' listeners.
func (cs *connSocks) siblings(u *StdConn) []*StdConn {
cs.mu.Lock()
defer cs.mu.Unlock()
return slices.DeleteFunc(slices.Clone(cs.members), func(m *StdConn) bool { return m == u })
}
// connSockFor returns dst's connected socket, or nil.
func (u *StdConn) connSockFor(dst netip.AddrPort) *connSock {
if p := u.socks.peer(dst); p != nil {
return p.sock.Load()
}
return nil
}
func (cs *connSocks) peer(dst netip.AddrPort) *connSockPeer {
if t := cs.table.Load(); t != nil {
return (*t)[dst]
}
return nil
}
// SetEstablishedPeer makes dst eligible for a connected socket while it is the remote of an established tunnel,
// and closes the one it has once it no longer is. Nebula calls it for every listen routine under the hostmap's
// write lock, so repeats are no-ops and it makes no syscalls: the descriptor is closed by another goroutine.
func (u *StdConn) SetEstablishedPeer(dst netip.AddrPort, established bool) {
cs := u.socks
if cs.cfg.max <= 0 || cs.off.Load() || !u.connSockable(dst) {
return
}
cs.mu.Lock()
defer cs.mu.Unlock()
t := cs.table.Load()
p := cs.peer(dst)
if cs.closed || (p != nil) == established {
return
}
next := map[netip.AddrPort]*connSockPeer{}
if t != nil {
next = maps.Clone(*t)
}
if established {
p = &connSockPeer{start: cs.clock()}
next[dst] = p
} else {
delete(next, dst)
if s := p.sock.Load(); s != nil {
u.detachLocked(s, "tunnel gone", false)
}
}
cs.storeTableLocked(next)
}
// storeTableLocked publishes t, or nil for an empty one.
func (cs *connSocks) storeTableLocked(t map[netip.AddrPort]*connSockPeer) {
if len(t) == 0 {
cs.table.Store(nil)
return
}
cs.table.Store(&t)
}
// connSockable reports whether a connected socket to dst could send what the listener would. A v4 listener can't
// reach a v6 destination at all, and a connected socket bound to a specific listen.host must share its family.
func (u *StdConn) connSockable(dst netip.AddrPort) bool {
if !dst.IsValid() || dst.Port() == 0 {
return false
}
if u.isV4 {
return dst.Addr().Is4()
}
return u.listenHost.IsUnspecified() || u.listenHost.Unmap().Is4() == dst.Addr().Unmap().Is4()
}
// connSockRun sends bufs, all to p's destination, on p's connected socket, opening one if they make p busy. It
// returns how many went out; when that is short of len(bufs), err is the failure of bufs[sent], or nil to leave
// bufs[sent:] to the listener.
func (u *StdConn) connSockRun(p *connSockPeer, dst netip.AddrPort, bufs [][]byte) (sent int, err error) {
s := p.sock.Load()
if s == nil {
if s = u.maybeOpenConnSock(p, dst, len(bufs)); s == nil {
return 0, nil
}
}
sent, errno, closed := u.connSockWrite(s, bufs)
switch {
case sent == len(bufs):
case connSockDead(errno):
u.closeConnSock(s, errno.Error(), true)
case !closed:
return sent, &net.OpError{Op: "write", Err: errno}
}
return sent, nil
}
// maybeOpenConnSock counts n datagrams to p, and opens a connected socket to it once it is busy and nothing rules
// one out.
func (u *StdConn) maybeOpenConnSock(p *connSockPeer, dst netip.AddrPort, n int) *connSock {
cs := u.socks
if n <= 0 || u.reader.Load() == nil || int(cs.reserved.Load()) >= cs.cfg.max || !p.busy(cs.clock(), n, &cs.cfg) {
return nil
}
cs.mu.Lock()
if cs.closed || cs.peer(dst) != p {
cs.mu.Unlock()
return nil
}
if s := p.sock.Load(); s != nil {
cs.mu.Unlock()
return s
}
now := cs.clock()
if _, ok := cs.pending[dst]; ok || int(cs.reserved.Load()) >= cs.cfg.max || now < p.retryAt ||
!cs.opens.take(now, cs.cfg.max, cs.cfg.openEvery) {
cs.mu.Unlock()
return nil
}
if cs.pending == nil {
cs.pending = map[netip.AddrPort]struct{}{}
}
cs.pending[dst] = struct{}{}
cs.reserved.Add(1)
rebinds := cs.rebinds
cs.mu.Unlock()
if cs.dialHook != nil {
cs.dialHook(dst)
}
s, err := u.dialConnSock(p, dst)
cs.mu.Lock()
if err != nil {
delete(cs.pending, dst)
cs.reserved.Add(-1)
p.retryAt = cs.clock() + int64(cs.cfg.backoff)
level := cs.logLevelLocked(slog.LevelWarn)
cs.mu.Unlock()
u.l.Log(context.Background(), level, "connected socket: open failed, staying on the listener", "udpAddr", dst, "error", err)
return nil
}
if cs.closed || cs.rebinds != rebinds || cs.peer(dst) != p {
// The tunnel went away, or a Rebind or shutdown ran, while the socket was opening; it stays in pending until
// it is closed.
cs.mu.Unlock()
u.finishClose(s)
u.l.Debug("connected socket: discarded, its tunnel or route changed while it opened", "udpAddr", dst)
return nil
}
delete(cs.pending, dst)
p.sock.Store(s)
go u.readConnSock(s)
level := cs.logLevelLocked(slog.LevelInfo)
cs.mu.Unlock()
u.l.Log(context.Background(), level, "connected socket: opened", "udpAddr", dst, "local", s.conn.LocalAddr(), "open", cs.reserved.Load())
return s
}
// dialConnSock opens a socket on the listener's port with SO_REUSEPORT, bound to the configured listen.host or,
// for a wildcard listener, to the source address the route to dst picks, and connected to dst. It carries the
// listener's IP_BOUND_IF, so both route the same way.
func (u *StdConn) dialConnSock(p *connSockPeer, dst netip.AddrPort) (*connSock, error) {
raddr := net.UDPAddrFromAddrPort(netip.AddrPortFrom(dst.Addr().Unmap(), dst.Port()))
network := "udp6"
if raddr.IP.To4() != nil {
network = "udp4"
}
ifindex, err := u.boundIf()
if err != nil {
return nil, err
}
local := &net.UDPAddr{IP: u.listenHost.AsSlice(), Zone: u.listenHost.Zone()}
if u.listenHost.IsUnspecified() {
// A connected socket gets the source address xnu would pick for an unconnected send to dst.
d := net.Dialer{Control: connSockControl(false, ifindex)}
probe, err := d.Dial(network, raddr.String())
if err != nil {
return nil, err
}
local = probe.LocalAddr().(*net.UDPAddr)
_ = probe.Close()
}
local.Port = int(u.port)
d := net.Dialer{LocalAddr: local, Control: connSockControl(true, ifindex)}
c, err := d.Dial(network, raddr.String())
if err != nil {
return nil, err
}
uc := c.(*net.UDPConn)
rc, err := uc.SyscallConn()
if err != nil {
_ = uc.Close()
return nil, err
}
s := &connSock{dst: dst, peer: p, conn: uc, rc: rc, sys: writeFd}
s.used.Store(u.socks.clock())
return s, nil
}
// connSockControl sets SO_REUSEPORT when reuse is set, and IP_BOUND_IF or IPV6_BOUND_IF when ifindex isn't 0,
// before the socket binds.
func connSockControl(reuse bool, ifindex int) func(network, address string, c syscall.RawConn) error {
return func(network, _ string, c syscall.RawConn) error {
var serr error
err := c.Control(func(fd uintptr) {
if reuse {
serr = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
}
if serr == nil && ifindex != 0 {
if network == "udp4" {
serr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IP, unix.IP_BOUND_IF, ifindex)
} else {
serr = unix.SetsockoptInt(int(fd), unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF, ifindex)
}
}
})
if err != nil {
return err
}
return serr
}
}
// boundIf returns the interface index the listener is scoped to, or 0. An error keeps the peer on the listener,
// since a connected socket opened without the listener's scope could route out an interface the listener can't.
func (u *StdConn) boundIf() (int, error) {
level, opt := unix.IPPROTO_IPV6, unix.IPV6_BOUND_IF
if u.isV4 {
level, opt = unix.IPPROTO_IP, unix.IP_BOUND_IF
}
v, err := unix.GetsockoptInt(int(u.sysFd), level, opt)
if err != nil {
return 0, fmt.Errorf("reading the listener's bound interface: %w", err)
}
return v, nil
}
// closeConnSock closes s if it is still open. With backoff set, the peer stays on the listener until the backoff
// runs out.
func (u *StdConn) closeConnSock(s *connSock, why string, backoff bool) {
u.socks.mu.Lock()
u.detachLocked(s, why, backoff)
u.socks.mu.Unlock()
}
// detachLocked takes s off its peer, if it is still there, and closes it on another goroutine, since callers such
// as SetEstablishedPeer hold locks that no socket syscall should run under. s.dst stays in pending until the close
// completes.
func (u *StdConn) detachLocked(s *connSock, why string, backoff bool) {
cs := u.socks
if !s.peer.sock.CompareAndSwap(s, nil) {
return
}
if backoff {
s.peer.retryAt = cs.clock() + int64(cs.cfg.backoff)
}
if cs.pending == nil {
cs.pending = map[netip.AddrPort]struct{}{}
}
cs.pending[s.dst] = struct{}{}
level := cs.logLevelLocked(slog.LevelInfo)
cs.closers.Add(1)
go func() {
defer cs.closers.Done()
open := u.finishClose(s)
u.l.Log(context.Background(), level, "connected socket: closed", "udpAddr", s.dst, "reason", why, "open", open)
}()
}
// finishClose closes s, whose destination is in pending, then lets the destination open again, and returns how
// many connected sockets are left. Closing waits only for a write already in a syscall: a write parked on a full
// buffer is woken, and one waiting out ENOBUFS holds no reference on the descriptor.
func (u *StdConn) finishClose(s *connSock) int32 {
cs := u.socks
if cs.closeHook != nil {
cs.closeHook(s.dst)
}
_ = s.conn.Close()
cs.mu.Lock()
defer cs.mu.Unlock()
delete(cs.pending, s.dst)
return cs.reserved.Add(-1)
}
// detachAllLocked detaches every connected socket, for a network change or shutdown.
func (u *StdConn) detachAllLocked(why string) {
if t := u.socks.table.Load(); t != nil {
for _, p := range *t {
if s := p.sock.Load(); s != nil {
u.detachLocked(s, why, false)
}
}
}
}
// closeConnSocks detaches every connected socket and discards the ones still opening, for a network change.
func (u *StdConn) closeConnSocks(why string) {
u.socks.mu.Lock()
u.socks.rebinds++
u.detachAllLocked(why)
u.socks.mu.Unlock()
}
func (u *StdConn) reapConnSocks(done <-chan struct{}) {
cs := u.socks
idle := cs.cfg.idle
tick := time.NewTicker(max(min(idle/4, 5*time.Second), time.Millisecond))
defer tick.Stop()
for {
select {
case <-done:
return
case <-tick.C:
}
t := cs.table.Load()
if t == nil {
continue
}
now := cs.clock()
for _, p := range *t {
if s := p.sock.Load(); s != nil && time.Duration(now-s.used.Load()) > idle {
u.closeConnSock(s, "idle", false)
}
}
}
}
// connSockDead reports whether a connected socket send or receive error means the connected path to the peer is
// gone, so its traffic belongs back on the listener. A connected UDP socket reports a peer's ICMP unreachable as
// ECONNREFUSED on its next call, which the unconnected listener never sees.
func connSockDead(errno syscall.Errno) bool {
switch errno {
case unix.ECONNREFUSED, unix.EHOSTUNREACH, unix.EHOSTDOWN, unix.ENETUNREACH, unix.ENETDOWN,
unix.EADDRNOTAVAIL, unix.EPIPE, unix.ENOTCONN, unix.EDESTADDRREQ:
return true
}
return false
}
// enobufsWait is how long a connected socket send sleeps when the interface queue is flow controlled. The kernel
// posts no wakeup when the advisory lifts, so this polls; 50us kept a gigabit link full without spinning a core in
// the 09-25 probes.
const enobufsWait = 50 * time.Microsecond
// connSockWrite writes bufs on s, one datagram per write. A full socket buffer parks the caller in the netpoller
// until the socket is writable, and a flow-controlled interface makes it wait out ENOBUFS, so a busy link slows
// the tun reader instead of dropping. Once the connected socket has waited cfg.enobufsMax without a send going
// through, either one drops the datagram instead, and a dropped datagram counts as sent, as the listener's
// unreported interface drops do; it never falls back to the listener, which would reorder it. closed reports that
// the connected socket was closed before bufs[sent] went out; any other error stops the run and is returned with
// how many went out.
func (u *StdConn) connSockWrite(s *connSock, bufs [][]byte) (sent int, errno syscall.Errno, closed bool) {
cs := u.socks
defer func() {
if sent > 0 {
s.used.Store(cs.clock())
}
}()
for sent < len(bufs) {
err := s.try(bufs[sent], false)
if err == syscall.EAGAIN || err == os.ErrDeadlineExceeded {
// os.ErrDeadlineExceeded here is another writer's parked deadline, passed but not yet cleared.
err = u.parkedWrite(s, bufs[sent])
}
switch err {
case nil:
sent++
if s.stallAt.Load() != 0 {
s.stallAt.Store(0)
s.dropping.Store(false)
}
continue
case errStallSpent:
u.dropStalled(s)
sent++
continue
}
errno, ok := err.(syscall.Errno)
if !ok {
return sent, 0, true
}
if errno != syscall.ENOBUFS {
return sent, errno, false
}
// The wait holds no reference on the descriptor, so a close doesn't wait for it.
if s.stalledFor(cs.clock()) < cs.cfg.enobufsMax {
cs.sleep(enobufsWait)
} else {
u.dropStalled(s)
sent++
}
}
return sent, 0, false
}
// parkedWrite writes b after EAGAIN, parked in the netpoller for what is left of s's stall budget, and returns
// errStallSpent once none is. golang/go#73919: a darwin UDP write parked on EAGAIN can wait forever for a
// writability event that never comes, so the wait always has a deadline.
func (u *StdConn) parkedWrite(s *connSock, b []byte) error {
cs := u.socks
s.parkMu.Lock()
defer s.parkMu.Unlock()
left := cs.cfg.enobufsMax - s.stalledFor(cs.clock())
if left <= 0 {
return errStallSpent
}
if err := s.conn.SetWriteDeadline(time.Now().Add(left)); err != nil {
return net.ErrClosed
}
err := s.try(b, true)
_ = s.conn.SetWriteDeadline(time.Time{})
if err == os.ErrDeadlineExceeded {
return errStallSpent
}
return err
}
// dropStalled logs the first datagram a stall drops.
func (u *StdConn) dropStalled(s *connSock) {
if !s.dropping.Swap(true) {
u.l.Debug("connected socket: sends stalled, dropping datagrams until one goes through", "udpAddr", s.dst)
}
}
// stalledFor records an ENOBUFS or EAGAIN on s at now and returns how long its sends have stalled: since the first
// ENOBUFS or EAGAIN after a send last went through. Every writer measures from that one time, so concurrent writers
// spend the budget no faster than one, and a send going through ends the stall for every writer, including one
// asleep in it.
func (s *connSock) stalledFor(now int64) time.Duration {
if s.stallAt.CompareAndSwap(0, now) {
return 0
}
at := s.stallAt.Load()
if at == 0 {
return 0
}
return time.Duration(now - at)
}
// readConnSock delivers a connected socket's datagrams through the listener's reader, serialized with ListenOut,
// until the connected socket is closed. Any receive error closes it: a connected socket reports its peer's
// unreachables here, and retrying an unexpected error could spin.
func (u *StdConn) readConnSock(s *connSock) {
rd := u.reader.Load()
buf := make([]byte, MTU)
for {
n, from, err := s.conn.ReadFromUDPAddrPort(buf)
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
why := err.Error()
var errno syscall.Errno
if errors.As(err, &errno) && connSockDead(errno) {
why = errno.Error()
} else {
u.l.Warn("connected socket: unexpected receive error", "udpAddr", s.dst, "error", err)
}
u.closeConnSock(s, why, true)
return
}
s.used.Store(u.socks.clock())
u.readMu.Lock()
rd.r(netip.AddrPortFrom(from.Addr().Unmap(), from.Port()), buf[:n:n])
rd.flush()
u.readMu.Unlock()
}
}
File diff suppressed because it is too large. Load diff
-6
View File
@@ -1,6 +0,0 @@
//go:build !race && !e2e_testing
package udp
// raceEnabled reports a -race build, whose sync.Pool drops a random share of what is put back.
const raceEnabled = false
-6
View File
@@ -1,6 +0,0 @@
//go:build race && !e2e_testing
package udp
// raceEnabled reports a -race build, whose sync.Pool drops a random share of what is put back.
const raceEnabled = true
+6 -103
View File
@@ -10,8 +10,6 @@ import (
"log/slog"
"net"
"net/netip"
"sync"
"sync/atomic"
"syscall"
"unsafe"
@@ -24,26 +22,9 @@ type StdConn struct {
isV4 bool
sysFd uintptr
l *slog.Logger
// listenHost and port are the configured address and the bound port, which a connected socket shares.
listenHost netip.Addr
port uint16
// rc reaches the listener's descriptor for another listen routine's Rebind.
rc syscall.RawConn
socks *connSocks
// reader is ListenOut's reader, which connected socket readers share; readMu serializes them, since an
// EncReader isn't safe for concurrent use.
reader atomic.Pointer[readerPair]
readMu sync.Mutex
}
type readerPair struct {
r EncReader
flush func()
}
var _ Conn = &StdConn{}
var _ EstablishedPeerConn = &StdConn{}
func NewListener(l *slog.Logger, s Settings) (Conn, error) {
lc := NewListenConfig(s.Multi)
@@ -53,13 +34,12 @@ func NewListener(l *slog.Logger, s Settings) (Conn, error) {
}
if uc, ok := pc.(*net.UDPConn); ok {
c := &StdConn{UDPConn: uc, l: l, listenHost: s.Listen.Addr()}
c := &StdConn{UDPConn: uc, l: l}
rc, err := uc.SyscallConn()
if err != nil {
return nil, fmt.Errorf("failed to open udp socket: %w", err)
}
c.rc = rc
err = rc.Control(func(fd uintptr) {
c.sysFd = fd
@@ -73,8 +53,6 @@ func NewListener(l *slog.Logger, s Settings) (Conn, error) {
return nil, err
}
c.isV4 = la.Addr().Is4()
c.port = la.Port()
c.socks = joinConnSocks(c, la, s)
return c, nil
}
@@ -111,19 +89,6 @@ func NewListenConfig(multi bool) net.ListenConfig {
func sendto(s int, buf []byte, flags int, to unsafe.Pointer, addrlen int32) (err error)
func (u *StdConn) WriteTo(b []byte, ap netip.AddrPort) error {
if t := u.socks.table.Load(); t != nil {
if p := (*t)[ap]; p != nil {
bufs := [1][]byte{b}
if sent, err := u.connSockRun(p, ap, bufs[:]); sent == 1 || err != nil {
return err
}
}
}
return u.writeTo(b, ap)
}
// writeTo sends b through the listener.
func (u *StdConn) writeTo(b []byte, ap netip.AddrPort) error {
var sa unsafe.Pointer
var addrLen int32
@@ -176,14 +141,12 @@ func (u *StdConn) writeTo(b []byte, ap netip.AddrPort) error {
func (u *StdConn) WriteBatch(bufs [][]byte, addrs []netip.AddrPort) (int, error) {
// An un-sendable destination costs its own packet, never the ones behind it in the batch.
// TODO: writeTo maps EWOULDBLOCK to an error, so a full listener send buffer
// silently drops those packets (linux blocks instead). Poll for
// writability on EAGAIN before giving up on them.
// TODO: WriteTo maps EWOULDBLOCK to an error, so a full send buffer
// silently drops the rest of a burst (linux blocks instead). Poll for
// writability on EAGAIN before giving up on the remainder.
written := 0
t := u.socks.table.Load()
if t == nil {
for i, b := range bufs {
if err := u.writeTo(b, addrs[i]); err == nil {
if err := u.WriteTo(b, addrs[i]); err == nil {
written++
} else {
u.l.Debug("failed to write packet in batch", "udpAddr", addrs[i], "error", err)
@@ -191,36 +154,6 @@ func (u *StdConn) WriteBatch(bufs [][]byte, addrs []netip.AddrPort) (int, error)
}
return written, nil
}
for off := 0; off < len(bufs); {
// A run of datagrams to one peer goes out together, on its connected socket if it has or earns one.
dst := addrs[off]
end := off + 1
for end < len(bufs) && addrs[end] == dst {
end++
}
if p := (*t)[dst]; p != nil {
for off < end {
sent, err := u.connSockRun(p, dst, bufs[off:end])
written += sent
off += sent
if err == nil {
break
}
u.l.Debug("failed to write packet in batch", "udpAddr", dst, "error", err)
off++
}
}
// The listener sends what no connected socket took.
for ; off < end; off++ {
if err := u.writeTo(bufs[off], dst); err == nil {
written++
} else {
u.l.Debug("failed to write packet in batch", "udpAddr", dst, "error", err)
}
}
}
return written, nil
}
func (u *StdConn) LocalAddr() (netip.AddrPort, error) {
a := u.UDPConn.LocalAddr()
@@ -249,8 +182,6 @@ func NewUDPStatsEmitter(udpConns []Conn) func() {
func (u *StdConn) ListenOut(r EncReader, flush func()) error {
buffer := make([]byte, MTU)
u.reader.Store(&readerPair{r: r, flush: flush})
u.startConnSocks()
for {
// Just read one packet at a time
@@ -263,29 +194,18 @@ func (u *StdConn) ListenOut(r EncReader, flush func()) error {
continue
}
u.readMu.Lock()
r(netip.AddrPortFrom(rua.Addr().Unmap(), rua.Port()), buffer[:n:n])
flush()
u.readMu.Unlock()
}
}
// Close closes the connected sockets of every listen routine, then the listener.
func (u *StdConn) Close() error {
u.stopConnSocks()
return u.UDPConn.Close()
}
func (u *StdConn) SupportsMultipleReaders() bool {
return false
}
// Rebind clears the interface the kernel scoped this socket to, so that sends are routed against the current
// routing table instead of the interface we happened to be on when the socket was created. Darwin pins sockets
// this way on its own, which is what strands us after the underlying network changes. Control.RebindUDPServer
// rebinds only the first writer, so this clears the other listen routines' listeners too. Connected sockets are
// closed after the listeners are cleared, and later ones copy the cleared scope and pick their source addresses
// afresh.
// this way on its own, which is what strands us after the underlying network changes.
func (u *StdConn) Rebind() error {
var err error
if u.isV4 {
@@ -293,23 +213,6 @@ func (u *StdConn) Rebind() error {
} else {
err = syscall.SetsockoptInt(int(u.sysFd), syscall.IPPROTO_IPV6, syscall.IPV6_BOUND_IF, 0)
}
for _, m := range u.socks.siblings(u) {
err = errors.Join(err, m.clearBoundIf())
}
u.closeConnSocks("rebind")
return err
}
// clearBoundIf clears the interface the listener is scoped to through its RawConn, which fails on a listener that
// closed concurrently instead of reaching whatever reused its descriptor number.
func (u *StdConn) clearBoundIf() error {
level, opt := syscall.IPPROTO_IPV6, syscall.IPV6_BOUND_IF
if u.isV4 {
level, opt = syscall.IPPROTO_IP, syscall.IP_BOUND_IF
}
var serr error
if err := u.rc.Control(func(fd uintptr) { serr = syscall.SetsockoptInt(int(fd), level, opt, 0) }); err != nil {
return err
}
return serr
}