mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 16:16:52 +01:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9e53a4088 | ||
|
|
f24fb308a0 |
No files matched your search
@@ -263,20 +263,6 @@ try {
|
|||||||
}
|
}
|
||||||
Write-Host "OK: WSL peer -> windows lighthouse over v6"
|
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 ''
|
||||||
Write-Host 'All smoke checks passed.'
|
Write-Host 'All smoke checks passed.'
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -242,14 +242,11 @@ test-cov-html:
|
|||||||
go test -coverprofile=coverage.out
|
go test -coverprofile=coverage.out
|
||||||
go tool cover -html=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:
|
build-test-mobile:
|
||||||
GOARCH=amd64 GOOS=ios go build $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
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=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=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 $(shell go list ./... | grep -v '/cmd/\|/examples/')
|
||||||
GOARCH=arm64 GOOS=android go build -o /dev/null ${NEBULA_CMD_PATH}
|
|
||||||
|
|
||||||
bench:
|
bench:
|
||||||
go test -bench=.
|
go test -bench=.
|
||||||
|
|||||||
+3
-2
@@ -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
|
us know right away. We will investigate all reports and do our best to quickly
|
||||||
fix valid issues.
|
fix valid issues.
|
||||||
|
|
||||||
You can submit your report on [HackerOne](https://hackerone.com/slack) and our
|
For critical reports, if you are interested in a bug bounty: You can submit your report on [HackerOne](https://hackerone.com/slack).
|
||||||
security team will respond as soon as possible.
|
|
||||||
|
For other reports: You can [submit a report via GitHub](https://github.com/slackhq/nebula/security/advisories/new).
|
||||||
@@ -5,7 +5,6 @@ go 1.26.0
|
|||||||
require (
|
require (
|
||||||
dario.cat/mergo v1.0.2
|
dario.cat/mergo v1.0.2
|
||||||
filippo.io/bigmod v0.1.0
|
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/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be
|
||||||
github.com/armon/go-radix v1.0.0
|
github.com/armon/go-radix v1.0.0
|
||||||
github.com/flynn/noise v1.1.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/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e
|
||||||
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6
|
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6
|
||||||
github.com/stretchr/testify v1.12.1
|
github.com/stretchr/testify v1.12.1
|
||||||
|
github.com/vishvananda/netlink v1.3.1
|
||||||
go.uber.org/goleak v1.3.0
|
go.uber.org/goleak v1.3.0
|
||||||
go.yaml.in/yaml/v3 v3.0.5
|
go.yaml.in/yaml/v3 v3.0.5
|
||||||
golang.org/x/crypto v0.57.0
|
golang.org/x/crypto v0.57.0
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ dario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=
|
|||||||
dario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=
|
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 h1:UNzDk7y9ADKST+axd9skUpBQeW7fG2KrTZyOE4uGQy8=
|
||||||
filippo.io/bigmod v0.1.0/go.mod h1:OjOXDNlClLblvXdwgFFOQFJEocLhhtai8vGLy0JCZlI=
|
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-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
|
||||||
github.com/alecthomas/template v0.0.0-20190718012654-fb15b899a751/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=
|
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.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||||
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
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 h1:DfiHV+j8bA32MFM7bfEunvT8IAqQ/NzSJHtcmW5zdEY=
|
||||||
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
github.com/vishvananda/netns v0.0.5/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
|
||||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
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-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-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.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 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||||
|
|||||||
+58
@@ -6,6 +6,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"slices"
|
"slices"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -17,6 +18,7 @@ import (
|
|||||||
"github.com/slackhq/nebula/cert"
|
"github.com/slackhq/nebula/cert"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
|
"github.com/slackhq/nebula/logging"
|
||||||
)
|
)
|
||||||
|
|
||||||
const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
|
const defaultPromoteEvery = 1000 // Count of packets sent before we try moving a tunnel to a preferred underlay ip address
|
||||||
@@ -928,3 +930,59 @@ func (i *HostInfo) logger(l *slog.Logger) *slog.Logger {
|
|||||||
|
|
||||||
return li
|
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
@@ -45,7 +45,8 @@ func setTransportChecksum4(packet []byte) {
|
|||||||
if ihl < ipv4.HeaderLen || end < ihl || end > len(packet) {
|
if ihl < ipv4.HeaderLen || end < ihl || end > len(packet) {
|
||||||
return
|
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 {
|
if binary.BigEndian.Uint16(packet[6:8])&0x3fff != 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -67,7 +68,10 @@ func setTransportChecksum6(packet []byte) {
|
|||||||
return
|
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])
|
proto, offset, _, anyFragment, err := IPv6FindUpperProtocol(packet[:end])
|
||||||
if err != nil || anyFragment || offset >= end {
|
if err != nil || anyFragment || offset >= end {
|
||||||
return
|
return
|
||||||
@@ -105,7 +109,8 @@ func transportExtent(transport []byte, proto uint8) ([]byte, bool) {
|
|||||||
// writeTransportChecksum stores the checksum of transport, taken over the
|
// writeTransportChecksum stores the checksum of transport, taken over the
|
||||||
// pseudo-header sum csum, in the header's checksum field. A UDP checksum that
|
// 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
|
// 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) {
|
func writeTransportChecksum(transport []byte, proto uint8, csum uint32) {
|
||||||
var at, minLen int
|
var at, minLen int
|
||||||
switch proto {
|
switch proto {
|
||||||
@@ -128,6 +133,11 @@ func writeTransportChecksum(transport []byte, proto uint8, csum uint32) {
|
|||||||
binary.BigEndian.PutUint16(transport[at:], sum)
|
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 {
|
func fold(csum uint32) uint16 {
|
||||||
for csum > 0xffff {
|
for csum > 0xffff {
|
||||||
csum = (csum >> 16) + (csum & 0xffff)
|
csum = (csum >> 16) + (csum & 0xffff)
|
||||||
|
|||||||
+16
-13
@@ -345,11 +345,14 @@ func ipv6CreateRejectTCPPacket(packet []byte, out []byte, offset int) []byte {
|
|||||||
return out
|
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.
|
// IPv6FindUpperProtocol walks the ipv6 extension header chain and returns the upper layer protocol, the
|
||||||
// Only the RFC 8200 and IANA extension headers below are walked.
|
// offset it begins at, and whether the packet is a non-first fragment. Only the RFC 8200 and IANA extension
|
||||||
// Everything else, including Mobility (135), HIP (139), Shim6 (140), experimental 253/254, and real upper layer protocols like SCTP or GRE, is terminal.
|
// headers below are walked. Everything else, including Mobility (135), HIP (139), Shim6 (140), experimental
|
||||||
// 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.
|
// 253/254, and real upper layer protocols like SCTP or GRE, is terminal. Walking those as extension headers
|
||||||
// Returns ErrIPv6CouldNotFindPayload if packet is smaller than an ipv6 header, or the chain is truncated, or if more than 8 extension headers are present.
|
// 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) {
|
func IPv6FindUpperProtocol(packet []byte) (nextHeader uint8, offset int, isFragment bool, anyFragment bool, err error) {
|
||||||
const maxIPv6ExtHeaders = 8
|
const maxIPv6ExtHeaders = 8
|
||||||
if len(packet) < ipv6.HeaderLen {
|
if len(packet) < ipv6.HeaderLen {
|
||||||
@@ -362,14 +365,14 @@ func IPv6FindUpperProtocol(packet []byte) (nextHeader uint8, offset int, isFragm
|
|||||||
switch nextHeader {
|
switch nextHeader {
|
||||||
case 0, 43, 60: // Hop-by-Hop, Routing, Destination
|
case 0, 43, 60: // Hop-by-Hop, Routing, Destination
|
||||||
if len(packet) < offset+2 {
|
if len(packet) < offset+2 {
|
||||||
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
return nextHeader, offset, isFragment, anyFragment, ErrIPv6CouldNotFindPayload
|
||||||
}
|
}
|
||||||
nextHeader = packet[offset]
|
nextHeader = packet[offset]
|
||||||
offset += (int(packet[offset+1]) + 1) << 3
|
offset += (int(packet[offset+1]) + 1) << 3
|
||||||
|
|
||||||
case 44: // Fragment
|
case 44: // Fragment
|
||||||
if len(packet) < offset+8 {
|
if len(packet) < offset+8 {
|
||||||
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
return nextHeader, offset, isFragment, anyFragment, ErrIPv6CouldNotFindPayload
|
||||||
}
|
}
|
||||||
anyFragment = true
|
anyFragment = true
|
||||||
// Non-first fragments carry no transport header, report the fragmented protocol and stop
|
// 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
|
case 51: // AH
|
||||||
if len(packet) < offset+2 {
|
if len(packet) < offset+2 {
|
||||||
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
return nextHeader, offset, isFragment, anyFragment, ErrIPv6CouldNotFindPayload
|
||||||
}
|
}
|
||||||
nextHeader = packet[offset]
|
nextHeader = packet[offset]
|
||||||
offset += (int(packet[offset+1]) + 2) << 2
|
offset += (int(packet[offset+1]) + 2) << 2
|
||||||
|
|
||||||
default:
|
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) {
|
if offset > len(packet) {
|
||||||
// A prior extension header can declare a length that advances offset past the packet, reject this.
|
return nextHeader, offset, isFragment, anyFragment, ErrIPv6CouldNotFindPayload
|
||||||
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
|
||||||
}
|
}
|
||||||
return nextHeader, offset, isFragment, anyFragment, nil //success!
|
return nextHeader, offset, isFragment, anyFragment, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Fail closed
|
return nextHeader, offset, isFragment, anyFragment, nil
|
||||||
return 0, 0, false, false, ErrIPv6CouldNotFindPayload
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateICMPEchoResponse(packet, out []byte) []byte {
|
func CreateICMPEchoResponse(packet, out []byte) []byte {
|
||||||
|
|||||||
+5
-17
@@ -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
|
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
|
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
|
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 {
|
tests := []struct {
|
||||||
name string
|
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},
|
{"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},
|
{"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
|
{"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
|
// 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},
|
{"extension length past buffer", 60, []byte{132, 255, 0, 0, 0, 0, 0, 0}, 132, ipv6.HeaderLen + 2048, false, false, ErrIPv6CouldNotFindPayload},
|
||||||
{"budget exhausted fails closed", 0, budgetChain, 0, 0, false, false, ErrIPv6CouldNotFindPayload},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for _, tt := range tests {
|
for _, tt := range tests {
|
||||||
@@ -571,10 +559,10 @@ func Test_IPv6FindUpperProtocol(t *testing.T) {
|
|||||||
packet := makeIPv6Packet(src, dst, tt.nextHeader, tt.payload)
|
packet := makeIPv6Packet(src, dst, tt.nextHeader, tt.payload)
|
||||||
proto, offset, isFragment, anyFragment, err := IPv6FindUpperProtocol(packet)
|
proto, offset, isFragment, anyFragment, err := IPv6FindUpperProtocol(packet)
|
||||||
if tt.wantErr != nil {
|
if tt.wantErr != nil {
|
||||||
require.ErrorIs(t, err, tt.wantErr)
|
assert.ErrorIs(t, err, tt.wantErr)
|
||||||
} else {
|
return
|
||||||
require.NoError(t, err)
|
|
||||||
}
|
}
|
||||||
|
require.NoError(t, err)
|
||||||
assert.Equal(t, tt.wantProto, proto)
|
assert.Equal(t, tt.wantProto, proto)
|
||||||
assert.Equal(t, tt.wantOffset, offset)
|
assert.Equal(t, tt.wantOffset, offset)
|
||||||
assert.Equal(t, tt.wantFragment, isFragment)
|
assert.Equal(t, tt.wantFragment, isFragment)
|
||||||
|
|||||||
+1
-28
@@ -19,7 +19,6 @@ import (
|
|||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/logging"
|
"github.com/slackhq/nebula/logging"
|
||||||
"github.com/slackhq/nebula/nicfinder"
|
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
"github.com/slackhq/nebula/util"
|
"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.
|
// addresses rather than whatever this machine's NICs happen to be. Set it before Start.
|
||||||
localAddrsFn func(*LocalAllowList) []netip.Addr
|
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
|
// Local cache of answers from light houses
|
||||||
// map of vpn addr to answers
|
// map of vpn addr to answers
|
||||||
addrMap map[netip.Addr]*RemoteList
|
addrMap map[netip.Addr]*RemoteList
|
||||||
@@ -120,9 +115,7 @@ func NewLightHouseFromConfig(ctx context.Context, l *slog.Logger, c *config.C, c
|
|||||||
l: l,
|
l: l,
|
||||||
}
|
}
|
||||||
h.localAddrsFn = func(al *LocalAllowList) []netip.Addr {
|
h.localAddrsFn = func(al *LocalAllowList) []netip.Addr {
|
||||||
addrs, err := nicfinder.Find(ctx, h.l, al)
|
return localAddrs(h.l, al)
|
||||||
h.logLocalAddrsErr(err)
|
|
||||||
return addrs
|
|
||||||
}
|
}
|
||||||
|
|
||||||
lighthouses := make([]netip.Addr, 0)
|
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() {
|
func (lh *LightHouse) SendUpdate() {
|
||||||
var v4 []*V4AddrPort
|
var v4 []*V4AddrPort
|
||||||
var v6 []*V6AddrPort
|
var v6 []*V6AddrPort
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
package nebula
|
package nebula
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -766,32 +764,3 @@ func TestLighthouse_DeletesWork(t *testing.T) {
|
|||||||
out = lh.Query(testHost)
|
out = lh.Query(testHost)
|
||||||
assert.Nil(t, out)
|
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")
|
|
||||||
}
|
|
||||||
@@ -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) {
|
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())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
// The goroutines started below stop only when this context does, and only a caller holding the
|
// Automatically cancel the context if Main returns an error, to signal all created goroutines to quit.
|
||||||
// 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.
|
|
||||||
defer func() {
|
defer func() {
|
||||||
if retcon == nil {
|
if reterr != nil {
|
||||||
cancel()
|
cancel()
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|||||||
@@ -1,21 +1,12 @@
|
|||||||
package nebula
|
package nebula
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"net/netip"
|
|
||||||
"os"
|
|
||||||
"path/filepath"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/cert"
|
|
||||||
cert_test "github.com/slackhq/nebula/cert_test"
|
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/test"
|
"github.com/slackhq/nebula/test"
|
||||||
"github.com/slackhq/nebula/util"
|
"github.com/slackhq/nebula/util"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"go.uber.org/goleak"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestParseCpuAffinity(t *testing.T) {
|
func TestParseCpuAffinity(t *testing.T) {
|
||||||
@@ -58,68 +49,3 @@ func TestParseCpuAffinity(t *testing.T) {
|
|||||||
assert.Nil(t, parseCpuAffinity(newConfig([]any{1 << 20}), l, 1))
|
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")
|
|
||||||
}
|
|
||||||
@@ -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...)
|
|
||||||
}
|
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
@@ -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
@@ -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.
|
// and cannot drift into misreading an unknown protocol (SCTP, GRE, etc.) as a forged transport.
|
||||||
proto, offset, isFragment, anyFragment, err := iputil.IPv6FindUpperProtocol(data)
|
proto, offset, isFragment, anyFragment, err := iputil.IPv6FindUpperProtocol(data)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return ErrIPv6PacketTooShort
|
||||||
}
|
}
|
||||||
|
|
||||||
fp.Protocol = proto
|
fp.Protocol = proto
|
||||||
|
|||||||
+7
-7
@@ -117,7 +117,7 @@ func Test_newPacket_v6(t *testing.T) {
|
|||||||
require.NoError(t, err)
|
require.NoError(t, err)
|
||||||
|
|
||||||
err = newPacket(buffer.Bytes(), true, p)
|
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
|
// A v6 packet with a hop-by-hop extension
|
||||||
// ICMPv6 Payload (Echo Request)
|
// 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
|
// A full IPv6 header and 1 byte in the first extension, but missing
|
||||||
// the length byte.
|
// the length byte.
|
||||||
err = newPacket(buffer.Bytes()[:41], true, p)
|
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
|
// A full IPv6 header plus 1 full extension, but only 1 byte of the
|
||||||
// next layer, missing length byte
|
// next layer, missing length byte
|
||||||
err = newPacket(buffer.Bytes()[:49], true, p)
|
err = newPacket(buffer.Bytes()[:49], true, p)
|
||||||
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
|
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
|
||||||
err = nil
|
err = nil
|
||||||
|
|
||||||
// A good ICMP packet
|
// 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
|
// Ensure buffer bounds checking during processing, a truncated AH header can't reach the payload
|
||||||
err = newPacket(b[:41], true, p)
|
err = newPacket(b[:41], true, p)
|
||||||
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
|
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
|
||||||
|
|
||||||
// Invalid AH header
|
// Invalid AH header
|
||||||
b = buffer.Bytes()
|
b = buffer.Bytes()
|
||||||
err = newPacket(b, true, p)
|
err = newPacket(b, true, p)
|
||||||
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
|
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_newPacket_ipv6Fragment(t *testing.T) {
|
func Test_newPacket_ipv6Fragment(t *testing.T) {
|
||||||
@@ -466,7 +466,7 @@ func Test_newPacket_ipv6Fragment(t *testing.T) {
|
|||||||
|
|
||||||
// Too short of a fragment packet
|
// Too short of a fragment packet
|
||||||
err = newPacket(secondFrag[:len(secondFrag)-10], false, p)
|
err = newPacket(secondFrag[:len(secondFrag)-10], false, p)
|
||||||
require.ErrorIs(t, err, iputil.ErrIPv6CouldNotFindPayload)
|
require.ErrorIs(t, err, ErrIPv6PacketTooShort)
|
||||||
}
|
}
|
||||||
|
|
||||||
func BenchmarkParseV6(b *testing.B) {
|
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[40] = byte(layers.IPProtocolSCTP) // Dest Options next header = SCTP
|
||||||
pkt[41] = 255 // declared length (255+1)*8 = 2048, past the 48 byte buffer
|
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
|
// Test_newPacket_v6ExtHeaderConfusion is a regression test for parseV6 walking any unrecognized
|
||||||
|
|||||||
+3
-127
@@ -29,9 +29,6 @@ type tun struct {
|
|||||||
Routes atomic.Pointer[[]Route]
|
Routes atomic.Pointer[[]Route]
|
||||||
routeTree atomic.Pointer[bart.Table[routing.Gateways]]
|
routeTree atomic.Pointer[bart.Table[routing.Gateways]]
|
||||||
linkAddr *netroute.LinkAddr
|
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
|
l *slog.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -152,48 +149,8 @@ func (t *tun) deviceBytes() (o [16]byte) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// newTunFromFd adopts a utun the host already created and configured, which is how a darwin
|
func newTunFromFd(_ *config.C, _ *slog.Logger, _ int, _ []netip.Prefix) (*tun, error) {
|
||||||
// network extension is handed its device. Everything about moving packets is shared with newTun,
|
return nil, fmt.Errorf("newTunFromFd not supported in Darwin")
|
||||||
// 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 (t *tun) Close() error {
|
func (t *tun) Close() error {
|
||||||
@@ -204,12 +161,6 @@ func (t *tun) Close() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) Activate() 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()
|
devName := t.deviceBytes()
|
||||||
|
|
||||||
s, err := unix.Socket(
|
s, err := unix.Socket(
|
||||||
@@ -423,11 +374,6 @@ func getLinkAddr(name string) (*netroute.LinkAddr, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) addRoutes(logErrors bool) 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()
|
routes := *t.Routes.Load()
|
||||||
|
|
||||||
for _, r := range routes {
|
for _, r := range routes {
|
||||||
@@ -457,10 +403,6 @@ func (t *tun) addRoutes(logErrors bool) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) removeRoutes(routes []Route) error {
|
func (t *tun) removeRoutes(routes []Route) error {
|
||||||
if t.hostOwned {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, r := range routes {
|
for _, r := range routes {
|
||||||
if !r.Install {
|
if !r.Install {
|
||||||
continue
|
continue
|
||||||
@@ -607,72 +549,6 @@ func (t *tun) Read(to []byte) (int, error) {
|
|||||||
return n - 4, nil
|
return n - 4, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// tunReadBatch is the most packets one tunQueue.Read returns.
|
|
||||||
const tunReadBatch = 64
|
|
||||||
|
|
||||||
// tunReadArena is tunQueue's receive buffer. Draining stops once less than defaultBatchBufSize of it
|
|
||||||
// is left, so every readv has room for the largest packet utun can return at any device MTU.
|
|
||||||
const tunReadArena = 4 * defaultBatchBufSize
|
|
||||||
|
|
||||||
// tunQueue is the darwin tun's Queue. Read drains every packet already queued on the utun, up to
|
|
||||||
// tunReadBatch, so the caller encrypts and sends them as one batch rather than one per wakeup.
|
|
||||||
type tunQueue struct {
|
|
||||||
t *tun
|
|
||||||
buf []byte
|
|
||||||
pkts [tunReadBatch]tio.Packet
|
|
||||||
}
|
|
||||||
|
|
||||||
// Read waits for the utun to become readable, then reads packets until it would block. An error after
|
|
||||||
// at least one packet is dropped in favor of returning those packets; a persistent one recurs on the
|
|
||||||
// next Read.
|
|
||||||
func (q *tunQueue) Read() ([]tio.Packet, error) {
|
|
||||||
rc, err := q.t.f.SyscallConn()
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
var head [4]byte
|
|
||||||
n, off := 0, 0
|
|
||||||
var callErr error
|
|
||||||
err = rc.Read(func(fd uintptr) bool {
|
|
||||||
for n < tunReadBatch && len(q.buf)-off >= defaultBatchBufSize {
|
|
||||||
iovecs := [2]unix.Iovec{
|
|
||||||
{Base: &head[0], Len: 4},
|
|
||||||
{Base: &q.buf[off], Len: uint64(len(q.buf) - off)},
|
|
||||||
}
|
|
||||||
l, e := tunReadv(int(fd), iovecs[:])
|
|
||||||
if e != nil {
|
|
||||||
if errno, ok := e.(syscall.Errno); ok && errno.Temporary() {
|
|
||||||
// Park on the poller only while there is nothing to hand back.
|
|
||||||
return n > 0
|
|
||||||
}
|
|
||||||
callErr = e
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
if l < 4 {
|
|
||||||
// A datagram too short to carry the AF prefix, or end of file; stop rather than spin on it.
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
end := off + l - 4
|
|
||||||
q.pkts[n] = tio.Packet{Bytes: q.buf[off:end:end]}
|
|
||||||
n++
|
|
||||||
off = end
|
|
||||||
}
|
|
||||||
return true
|
|
||||||
})
|
|
||||||
if n > 0 {
|
|
||||||
return q.pkts[:n], nil
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return nil, callErr
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *tunQueue) Write(p []byte) (int, error) { return q.t.Write(p) }
|
|
||||||
|
|
||||||
func (q *tunQueue) Close() error { return q.t.Close() }
|
|
||||||
|
|
||||||
// Write pushes one IP packet onto the utun device. Safe for concurrent use:
|
// Write pushes one IP packet onto the utun device. Safe for concurrent use:
|
||||||
// the AF prefix and iovecs are per-call stack state, and the fd write itself
|
// the AF prefix and iovecs are per-call stack state, and the fd write itself
|
||||||
// serializes on the runtime's fd mutex (see the Queue contract in tio.go).
|
// serializes on the runtime's fd mutex (see the Queue contract in tio.go).
|
||||||
@@ -732,5 +608,5 @@ func (t *tun) Name() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) Queues(int) ([]tio.Queue, error) {
|
func (t *tun) Queues(int) ([]tio.Queue, error) {
|
||||||
return []tio.Queue{&tunQueue{t: t, buf: make([]byte, tunReadArena)}}, nil
|
return []tio.Queue{tio.NewSingleQueue(t, defaultBatchBufSize)}, nil
|
||||||
}
|
}
|
||||||
@@ -1,97 +0,0 @@
|
|||||||
//go:build !ios && !e2e_testing
|
|
||||||
|
|
||||||
package overlay
|
|
||||||
|
|
||||||
import (
|
|
||||||
"os"
|
|
||||||
"syscall"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
)
|
|
||||||
|
|
||||||
// newSocketpairTun returns a tun on one end of a connected AF_UNIX datagram socketpair, which keeps
|
|
||||||
// datagram boundaries the way a utun control socket does, and the other end's fd.
|
|
||||||
// sndbuf is the tun end's send buffer, which caps the largest datagram it accepts.
|
|
||||||
func newSocketpairTun(t *testing.T, sndbuf int) (*tun, int) {
|
|
||||||
t.Helper()
|
|
||||||
fds, err := unix.Socketpair(unix.AF_UNIX, unix.SOCK_DGRAM, 0)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NoError(t, unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_SNDBUF, sndbuf))
|
|
||||||
require.NoError(t, unix.SetsockoptInt(fds[1], unix.SOL_SOCKET, unix.SO_RCVBUF, 1<<20))
|
|
||||||
// A dropped datagram fails the read-back instead of hanging it.
|
|
||||||
require.NoError(t, unix.SetsockoptTimeval(fds[1], unix.SOL_SOCKET, unix.SO_RCVTIMEO, &unix.Timeval{Sec: 2}))
|
|
||||||
require.NoError(t, unix.SetNonblock(fds[0], true))
|
|
||||||
f := os.NewFile(uintptr(fds[0]), "socketpair")
|
|
||||||
t.Cleanup(func() {
|
|
||||||
_ = f.Close()
|
|
||||||
_ = unix.Close(fds[1])
|
|
||||||
})
|
|
||||||
return &tun{f: f, l: test.NewLogger()}, fds[1]
|
|
||||||
}
|
|
||||||
|
|
||||||
// testTunPkt returns packet i of size bytes, alternating IPv4 and IPv6, and the same packet as a utun
|
|
||||||
// datagram, behind its AF prefix.
|
|
||||||
func testTunPkt(i, size int) (pkt, wire []byte) {
|
|
||||||
pkt = make([]byte, size)
|
|
||||||
pkt[0] = 0x45
|
|
||||||
af := byte(syscall.AF_INET)
|
|
||||||
if i%2 == 1 {
|
|
||||||
pkt[0] = 0x60
|
|
||||||
af = syscall.AF_INET6
|
|
||||||
}
|
|
||||||
pkt[1] = byte(i)
|
|
||||||
pkt[2] = byte(i >> 8)
|
|
||||||
return pkt, append([]byte{0, 0, 0, af}, pkt...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestTunQueueReadDrains pins that Read hands back every queued packet, AF prefix stripped and in
|
|
||||||
// order, capped at tunReadBatch per call, and doesn't wait for more once the queue is empty.
|
|
||||||
func TestTunQueueReadDrains(t *testing.T) {
|
|
||||||
tn, w := newSocketpairTun(t, 1<<20)
|
|
||||||
// An AF_UNIX datagram send is bounded by the receiver's buffer, here the tun's end.
|
|
||||||
rc, err := tn.f.SyscallConn()
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NoError(t, rc.Control(func(fd uintptr) {
|
|
||||||
require.NoError(t, unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_RCVBUF, 1<<20))
|
|
||||||
}))
|
|
||||||
q := &tunQueue{t: tn, buf: make([]byte, tunReadArena)}
|
|
||||||
total := tunReadBatch + 3
|
|
||||||
var want [][]byte
|
|
||||||
for i := range total {
|
|
||||||
pkt, wire := testTunPkt(i, 60+i)
|
|
||||||
_, err := unix.Write(w, wire)
|
|
||||||
require.NoError(t, err)
|
|
||||||
want = append(want, pkt)
|
|
||||||
}
|
|
||||||
|
|
||||||
var got [][]byte
|
|
||||||
for _, size := range []int{tunReadBatch, 3} {
|
|
||||||
pkts, err := q.Read()
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, pkts, size)
|
|
||||||
for _, p := range pkts {
|
|
||||||
got = append(got, p.Clone().Bytes)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert.Equal(t, want, got)
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestTunQueueReadClipsPackets pins that each returned packet's capacity ends at its own bytes, so
|
|
||||||
// appending to one can't overwrite the next.
|
|
||||||
func TestTunQueueReadClipsPackets(t *testing.T) {
|
|
||||||
tn, w := newSocketpairTun(t, 1<<20)
|
|
||||||
q := &tunQueue{t: tn, buf: make([]byte, tunReadArena)}
|
|
||||||
for i := range 2 {
|
|
||||||
_, wire := testTunPkt(i, 100)
|
|
||||||
_, err := unix.Write(w, wire)
|
|
||||||
require.NoError(t, err)
|
|
||||||
}
|
|
||||||
pkts, err := q.Read()
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, pkts, 2)
|
|
||||||
assert.Equal(t, len(pkts[0].Bytes), cap(pkts[0].Bytes))
|
|
||||||
}
|
|
||||||
@@ -15,12 +15,12 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
"unsafe"
|
"unsafe"
|
||||||
|
|
||||||
"github.com/DefinedNet/netlink"
|
|
||||||
"github.com/gaissmai/bart"
|
"github.com/gaissmai/bart"
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/overlay/tio"
|
"github.com/slackhq/nebula/overlay/tio"
|
||||||
"github.com/slackhq/nebula/routing"
|
"github.com/slackhq/nebula/routing"
|
||||||
"github.com/slackhq/nebula/util"
|
"github.com/slackhq/nebula/util"
|
||||||
|
"github.com/vishvananda/netlink"
|
||||||
"golang.org/x/sys/unix"
|
"golang.org/x/sys/unix"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user