mirror of
https://github.com/slackhq/nebula.git
synced 2026-11-16 17:16:52 +01:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aa880d85b6 | ||
|
|
553e874122 | ||
|
|
f62c54a4f2 |
No files matched your search
@@ -13,6 +13,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
down with it. A hostinfo returned by StartHandshake had no RemoteList until the handshake loop's first
|
down with it. A hostinfo returned by StartHandshake had no RemoteList until the handshake loop's first
|
||||||
pass attached one, and `create-tunnel -address` set the remote before that. The list is now attached when
|
pass attached one, and `create-tunnel -address` set the remote before that. The list is now attached when
|
||||||
the handshake starts, so a pending hostinfo never exists without one.
|
the handshake starts, so a pending hostinfo never exists without one.
|
||||||
|
- A firewall rule with `group: []`, `groups:` with no value, or a `groups` entry that isn't a string, such as
|
||||||
|
`groups: [1, 2]`, no longer crashes Nebula on startup or reload. A null `group` or `groups` means none was
|
||||||
|
provided. An unquoted int or bool group, such as `group: 7`, is still read as a string but logs a warning to
|
||||||
|
quote it, since YAML has already turned a value like `007` into `7`. A float, a date, an empty array, a null
|
||||||
|
entry, a nested array, or a map is rejected with an error.
|
||||||
|
|
||||||
## [1.11.1] - 2026-08-21
|
## [1.11.1] - 2026-08-21
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ package nebula
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strconv"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -13,7 +11,6 @@ import (
|
|||||||
ct "github.com/slackhq/nebula/cert_test"
|
ct "github.com/slackhq/nebula/cert_test"
|
||||||
"github.com/slackhq/nebula/handshake"
|
"github.com/slackhq/nebula/handshake"
|
||||||
"github.com/slackhq/nebula/header"
|
"github.com/slackhq/nebula/header"
|
||||||
"github.com/slackhq/nebula/overlay"
|
|
||||||
"github.com/slackhq/nebula/test"
|
"github.com/slackhq/nebula/test"
|
||||||
"github.com/slackhq/nebula/udp"
|
"github.com/slackhq/nebula/udp"
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
@@ -150,122 +147,6 @@ func TestSendNoMetricsCloseTunnelKeepsRebindEpoch(t *testing.T) {
|
|||||||
assert.True(t, hostinfo.markOut(1), "a CloseTunnel send must not consume the rebind epoch")
|
assert.True(t, hostinfo.markOut(1), "a CloseTunnel send must not consume the rebind epoch")
|
||||||
}
|
}
|
||||||
|
|
||||||
// capturingConn is a udp.Conn that records every WriteTo.
|
|
||||||
type capturingConn struct {
|
|
||||||
udp.NoopConn
|
|
||||||
writes [][]byte
|
|
||||||
addrs []netip.AddrPort
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *capturingConn) WriteTo(b []byte, addr netip.AddrPort) error {
|
|
||||||
c.writes = append(c.writes, append([]byte(nil), b...))
|
|
||||||
c.addrs = append(c.addrs, addr)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestSendNoMetricsViaRelay sends through a relay from the mtu sized buffer the cached packet flush uses. Payloads up
|
|
||||||
// to overlay.MaxMTU go out intact, anything bigger is dropped rather than outgrowing the buffer, which once panicked.
|
|
||||||
func TestSendNoMetricsViaRelay(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
n int
|
|
||||||
sent bool
|
|
||||||
}{
|
|
||||||
{0, true},
|
|
||||||
{1300, true},
|
|
||||||
{overlay.MaxMTU, true},
|
|
||||||
{overlay.MaxMTU + 1, false}, // too big for the relay's tag
|
|
||||||
{mtu - 47, false}, // too big for the inner tag, this panicked
|
|
||||||
{9000, false}, // a full packet at tun.mtu 9000
|
|
||||||
}
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(strconv.Itoa(tt.n), func(t *testing.T) {
|
|
||||||
// One tunnel to the target, carried end to end, and one to the relay that wraps it
|
|
||||||
targetInit, targetResp := runTestHandshake(t)
|
|
||||||
relayInit, relayResp := runTestHandshake(t)
|
|
||||||
ci, err := newConnectionStateFromResult(targetInit)
|
|
||||||
require.NoError(t, err)
|
|
||||||
relayCI, err := newConnectionStateFromResult(relayInit)
|
|
||||||
require.NoError(t, err)
|
|
||||||
|
|
||||||
targetAddr := netip.MustParseAddr("10.0.0.2")
|
|
||||||
relayAddr := netip.MustParseAddr("10.0.0.3")
|
|
||||||
relayRemote := netip.MustParseAddrPort("192.0.2.1:4242")
|
|
||||||
|
|
||||||
relay := &Relay{Type: TerminalType, State: Established, LocalIndex: 5, RemoteIndex: 6, PeerAddr: targetAddr}
|
|
||||||
relayHI := &HostInfo{
|
|
||||||
vpnAddrs: []netip.Addr{relayAddr},
|
|
||||||
ConnectionState: relayCI,
|
|
||||||
relayState: RelayState{
|
|
||||||
relayForByAddr: map[netip.Addr]*Relay{targetAddr: relay},
|
|
||||||
relayForByIdx: map[uint32]*Relay{relay.LocalIndex: relay},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
relayHI.remote.Store(&relayRemote)
|
|
||||||
|
|
||||||
// No remote of its own, so the send has to go via the relay
|
|
||||||
hostinfo := &HostInfo{
|
|
||||||
vpnAddrs: []netip.Addr{targetAddr},
|
|
||||||
ConnectionState: ci,
|
|
||||||
remoteIndexId: 7,
|
|
||||||
relayState: RelayState{
|
|
||||||
relays: []netip.Addr{relayAddr},
|
|
||||||
relayForByAddr: map[netip.Addr]*Relay{},
|
|
||||||
relayForByIdx: map[uint32]*Relay{},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
l := test.NewLogger()
|
|
||||||
hm := newHostMap(l)
|
|
||||||
hm.Hosts[relayAddr] = relayHI
|
|
||||||
conn := &capturingConn{}
|
|
||||||
f := &Interface{
|
|
||||||
l: l,
|
|
||||||
hostMap: hm,
|
|
||||||
messageMetrics: &MessageMetrics{txExhausted: metrics.NewCounter()},
|
|
||||||
writers: []udp.Conn{conn},
|
|
||||||
}
|
|
||||||
f.connectionManager = &connectionManager{intf: f, relayUsed: map[uint32]struct{}{}, relayUsedLock: &sync.RWMutex{}}
|
|
||||||
|
|
||||||
payload := make([]byte, tt.n)
|
|
||||||
for i := range payload {
|
|
||||||
payload[i] = byte(i)
|
|
||||||
}
|
|
||||||
counter := ci.messageCounter.Load()
|
|
||||||
f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, payload, make([]byte, 12), make([]byte, mtu), 0)
|
|
||||||
|
|
||||||
if !tt.sent {
|
|
||||||
assert.Empty(t, conn.writes)
|
|
||||||
assert.Equal(t, counter, ci.messageCounter.Load(), "a dropped packet must not spend a counter")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
require.Len(t, conn.writes, 1)
|
|
||||||
assert.Equal(t, relayRemote, conn.addrs[0])
|
|
||||||
pkt := conn.writes[0]
|
|
||||||
|
|
||||||
// The relay authenticates the whole packet under its own header
|
|
||||||
outer := &header.H{}
|
|
||||||
require.NoError(t, outer.Parse(pkt))
|
|
||||||
assert.Equal(t, header.MessageRelay, outer.Subtype)
|
|
||||||
assert.Equal(t, relay.RemoteIndex, outer.RemoteIndex)
|
|
||||||
relayPeer, err := newConnectionStateFromResult(relayResp)
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.NoError(t, relayPeer.VerifyRelay(l, outer.MessageCounter, pkt, make([]byte, 12)))
|
|
||||||
|
|
||||||
// Inside it, the target decrypts the end to end packet back to the payload
|
|
||||||
inner := pkt[header.Len : len(pkt)-relayPeer.dKey.Overhead()]
|
|
||||||
h := &header.H{}
|
|
||||||
require.NoError(t, h.Parse(inner))
|
|
||||||
assert.Equal(t, header.Message, h.Type)
|
|
||||||
assert.Equal(t, hostinfo.remoteIndexId, h.RemoteIndex)
|
|
||||||
targetPeer, err := newConnectionStateFromResult(targetResp)
|
|
||||||
require.NoError(t, err)
|
|
||||||
got, err := targetPeer.Decrypt(l, h.MessageCounter, inner, make([]byte, 12))
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, payload, got)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNewConnectionStateFromResult(t *testing.T) {
|
func TestNewConnectionStateFromResult(t *testing.T) {
|
||||||
initR, respR := runTestHandshake(t)
|
initR, respR := runTestHandshake(t)
|
||||||
|
|
||||||
|
|||||||
@@ -1,68 +0,0 @@
|
|||||||
# vpnemu
|
|
||||||
|
|
||||||
Reproduces, on macOS and without Tailscale, the way a VPN with an exit node takes nebula's vpn network route
|
|
||||||
away from its utun (#1931).
|
|
||||||
|
|
||||||
A macOS network extension never touches the routing table. Its routes are published in configd's dynamic store
|
|
||||||
under `State:/Network/Service/<id>/IPv4` and `/IPv6`, and configd's IPMonitor installs them. vpnemu creates a
|
|
||||||
utun and publishes those keys itself, so configd does exactly what it would do for the real app. It publishes
|
|
||||||
the routes Tailscale would with an exit node: every interface prefix that isn't a single IP, the rule in
|
|
||||||
Tailscale's `ipnlocal.internalAndExternalInterfacesFrom`.
|
|
||||||
|
|
||||||
| mode | Tailscale setting | published as | where nebula's prefix goes |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| `claim` | exit node, no LAN access | `AdditionalRoutes` | into vpnemu's utun |
|
|
||||||
| `exclude` | exit node, LAN access | `ExcludedRoutes`, service overrides primary | out the next interface (en0) |
|
|
||||||
|
|
||||||
configd answers `EEXIST` with a delete and an add, so whatever held the prefix loses it. When the service is
|
|
||||||
withdrawn, configd deletes its routes by prefix alone, whoever holds them by then.
|
|
||||||
|
|
||||||
## Build
|
|
||||||
|
|
||||||
It is its own module, so `purego` stays out of nebula's `go.mod`. purego reaches CoreFoundation and
|
|
||||||
SystemConfiguration without cgo, so it cross compiles and runs on a mac with no developer tools.
|
|
||||||
|
|
||||||
```sh
|
|
||||||
cd e2e/darwin/vpnemu
|
|
||||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -o vpnemu .
|
|
||||||
# a cross compiled binary copied to a mac may need: codesign -s - -f vpnemu
|
|
||||||
```
|
|
||||||
|
|
||||||
## Run
|
|
||||||
|
|
||||||
```sh
|
|
||||||
sudo ./vpnemu -mode claim -keep en0 # runs until ctrl-c, then withdraws and closes its utun
|
|
||||||
sudo ./vpnemu -clear # withdraw a service a crashed run left behind
|
|
||||||
```
|
|
||||||
|
|
||||||
`-keep` names interfaces whose prefixes are never published. Keep the one your ssh session arrives on, or
|
|
||||||
`claim` takes your LAN into a utun nobody reads. `exclude` makes vpnemu primary, so anything off a kept
|
|
||||||
interface's subnet, internet included, goes into its utun and is dropped while it runs.
|
|
||||||
|
|
||||||
`-follow` (default on) republishes when interface prefixes change, as Tailscale does on link changes. With
|
|
||||||
`-follow=false` a route stays published after its interface is gone, which stages the route configd leaves
|
|
||||||
behind for a nebula that restarts before the VPN has caught up.
|
|
||||||
|
|
||||||
## A/B a nebula build
|
|
||||||
|
|
||||||
`repro.sh` starts nebula, then runs vpnemu, and reports egress and ping per peer before, during and after:
|
|
||||||
|
|
||||||
```sh
|
|
||||||
sudo ./repro.sh -n ./nebula -c config.yml -p 192.168.212.1 -p fd19:31::1 -m claim -k en0
|
|
||||||
```
|
|
||||||
|
|
||||||
Before #1931 (utun holds `/24` and `/64`):
|
|
||||||
|
|
||||||
```
|
|
||||||
during 192.168.212.1 egress=utun2 ping=FAIL
|
|
||||||
after 192.168.212.1 egress=en0 ping=FAIL
|
|
||||||
```
|
|
||||||
|
|
||||||
With #1931 (utun holds `/32` and `/128`, network routes added explicitly) every phase stays on nebula's utun.
|
|
||||||
|
|
||||||
### Leftover route
|
|
||||||
|
|
||||||
Run an old nebula, start `vpnemu -follow=false`, then restart onto a new nebula while vpnemu is still up. The
|
|
||||||
new nebula finds the vpn network routed to vpnemu's utun, replaces it and starts. Stop vpnemu and configd deletes
|
|
||||||
the prefix, taking nebula's route with it until nebula restarts. With real Tailscale this needs nebula to restart
|
|
||||||
before Tailscale notices the old utun is gone, a one time window when upgrading from a nebula without #1931.
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
module github.com/slackhq/nebula/e2e/darwin/vpnemu
|
|
||||||
|
|
||||||
go 1.26.0
|
|
||||||
|
|
||||||
require (
|
|
||||||
github.com/ebitengine/purego v0.9.1
|
|
||||||
golang.org/x/sys v0.48.0
|
|
||||||
)
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
github.com/ebitengine/purego v0.9.1 h1:a/k2f2HQU3Pi399RPW1MOaZyhKJL9w/xFpKAg4q1s0A=
|
|
||||||
github.com/ebitengine/purego v0.9.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
|
|
||||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
|
||||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
|
||||||
@@ -1,292 +0,0 @@
|
|||||||
//go:build darwin
|
|
||||||
|
|
||||||
// vpnemu stands in for a macOS VPN app with an exit node in use, so route hijacks like the one
|
|
||||||
// Tailscale causes can be reproduced without Tailscale.
|
|
||||||
//
|
|
||||||
// A network extension does not touch the routing table itself. It hands its routes to
|
|
||||||
// nesessionmanager, which publishes them in configd's dynamic store under
|
|
||||||
// State:/Network/Service/<id>/IPv4 and /IPv6, and configd's IPMonitor installs them. vpnemu
|
|
||||||
// creates a utun and publishes the same keys directly, so configd does exactly what it would do
|
|
||||||
// for the real thing.
|
|
||||||
//
|
|
||||||
// Which routes it publishes follows Tailscale's rule for exit nodes
|
|
||||||
// (ipnlocal.internalAndExternalInterfacesFrom): every interface address prefix that is not a
|
|
||||||
// single IP counts as an attached LAN. With LAN access off those prefixes are claimed into the
|
|
||||||
// tunnel (-mode claim, published as AdditionalRoutes). With LAN access on they are excluded and
|
|
||||||
// leave through the next interface (-mode exclude, published as ExcludedRoutes on a service that
|
|
||||||
// overrides the primary).
|
|
||||||
//
|
|
||||||
// It runs until interrupted, then withdraws the service and closes its utun. Needs root.
|
|
||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"flag"
|
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
"net"
|
|
||||||
"net/netip"
|
|
||||||
"os"
|
|
||||||
"os/exec"
|
|
||||||
"os/signal"
|
|
||||||
"slices"
|
|
||||||
"strings"
|
|
||||||
"syscall"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/ebitengine/purego"
|
|
||||||
"golang.org/x/sys/unix"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
serviceID = "VPNEMU"
|
|
||||||
// Tailscale's own addresses, single IPs, so the rule skips them like Tailscale skips its own
|
|
||||||
addr4 = "100.100.0.1"
|
|
||||||
addr6 = "fd7a:115c:a1e0::1"
|
|
||||||
|
|
||||||
utunControlName = "com.apple.net.utun_control"
|
|
||||||
utunOptIfname = 2
|
|
||||||
cfStringUTF8 = 0x08000100
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
cfStringCreateWithCString func(alloc uintptr, s *byte, enc uint32) uintptr
|
|
||||||
cfDataCreate func(alloc uintptr, b *byte, n int) uintptr
|
|
||||||
cfPropertyListCreateWithData func(alloc, data uintptr, opts uint, format *int, err *uintptr) uintptr
|
|
||||||
cfRelease func(ref uintptr)
|
|
||||||
scDynamicStoreCreate func(alloc, name, callout, ctx uintptr) uintptr
|
|
||||||
scDynamicStoreSetValue func(store, key, value uintptr) bool
|
|
||||||
scDynamicStoreRemoveValue func(store, key uintptr) bool
|
|
||||||
scError func() int32
|
|
||||||
)
|
|
||||||
|
|
||||||
// loadFrameworks binds the few CoreFoundation and SystemConfiguration calls we need. purego does
|
|
||||||
// it without cgo, so this cross compiles and runs on a mac with no developer tools. JXA can read
|
|
||||||
// the dynamic store but its writes fail, and scutil cannot build the arrays of dictionaries the
|
|
||||||
// route keys hold.
|
|
||||||
func loadFrameworks() {
|
|
||||||
cf, err := purego.Dlopen("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
sc, err := purego.Dlopen("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration", purego.RTLD_NOW|purego.RTLD_GLOBAL)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
purego.RegisterLibFunc(&cfStringCreateWithCString, cf, "CFStringCreateWithCString")
|
|
||||||
purego.RegisterLibFunc(&cfDataCreate, cf, "CFDataCreate")
|
|
||||||
purego.RegisterLibFunc(&cfPropertyListCreateWithData, cf, "CFPropertyListCreateWithData")
|
|
||||||
purego.RegisterLibFunc(&cfRelease, cf, "CFRelease")
|
|
||||||
purego.RegisterLibFunc(&scDynamicStoreCreate, sc, "SCDynamicStoreCreate")
|
|
||||||
purego.RegisterLibFunc(&scDynamicStoreSetValue, sc, "SCDynamicStoreSetValue")
|
|
||||||
purego.RegisterLibFunc(&scDynamicStoreRemoveValue, sc, "SCDynamicStoreRemoveValue")
|
|
||||||
purego.RegisterLibFunc(&scError, sc, "SCError")
|
|
||||||
}
|
|
||||||
|
|
||||||
func cfString(s string) uintptr {
|
|
||||||
b := append([]byte(s), 0)
|
|
||||||
return cfStringCreateWithCString(0, &b[0], cfStringUTF8)
|
|
||||||
}
|
|
||||||
|
|
||||||
// cfPlist builds a property list from its xml form, the least code way to make nested CF values
|
|
||||||
func cfPlist(xml string) uintptr {
|
|
||||||
b := []byte(xml)
|
|
||||||
d := cfDataCreate(0, &b[0], len(b))
|
|
||||||
defer cfRelease(d)
|
|
||||||
var errRef uintptr
|
|
||||||
p := cfPropertyListCreateWithData(0, d, 0, nil, &errRef)
|
|
||||||
if p == 0 {
|
|
||||||
log.Fatalf("invalid property list:\n%s", xml)
|
|
||||||
}
|
|
||||||
return p
|
|
||||||
}
|
|
||||||
|
|
||||||
type store struct {
|
|
||||||
ref uintptr
|
|
||||||
k4, k6 uintptr
|
|
||||||
}
|
|
||||||
|
|
||||||
func openStore() *store {
|
|
||||||
return &store{
|
|
||||||
ref: scDynamicStoreCreate(0, cfString("vpnemu"), 0, 0),
|
|
||||||
k4: cfString("State:/Network/Service/" + serviceID + "/IPv4"),
|
|
||||||
k6: cfString("State:/Network/Service/" + serviceID + "/IPv6"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *store) set(key uintptr, xml string) {
|
|
||||||
v := cfPlist(xml)
|
|
||||||
defer cfRelease(v)
|
|
||||||
if !scDynamicStoreSetValue(s.ref, key, v) {
|
|
||||||
log.Fatalf("SCDynamicStoreSetValue failed: SCError %d", scError())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *store) withdraw() {
|
|
||||||
scDynamicStoreRemoveValue(s.ref, s.k4)
|
|
||||||
scDynamicStoreRemoveValue(s.ref, s.k6)
|
|
||||||
}
|
|
||||||
|
|
||||||
// createUtun opens a utun the kernel numbers for us and gives it Tailscale-like single addresses.
|
|
||||||
// The interface lives as long as the returned fd.
|
|
||||||
func createUtun() (int, string) {
|
|
||||||
fd, err := unix.Socket(unix.AF_SYSTEM, unix.SOCK_DGRAM, unix.AF_SYS_CONTROL)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("system socket: %v", err)
|
|
||||||
}
|
|
||||||
info := &unix.CtlInfo{}
|
|
||||||
copy(info.Name[:], utunControlName)
|
|
||||||
if err = unix.IoctlCtlInfo(fd, info); err != nil {
|
|
||||||
log.Fatalf("CTLIOCGINFO: %v", err)
|
|
||||||
}
|
|
||||||
if err = unix.Connect(fd, &unix.SockaddrCtl{ID: info.Id, Unit: 0}); err != nil {
|
|
||||||
log.Fatalf("connect utun control: %v", err)
|
|
||||||
}
|
|
||||||
name, err := unix.GetsockoptString(fd, unix.AF_SYS_CONTROL, utunOptIfname)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("utun name: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, args := range [][]string{
|
|
||||||
{name, "inet", addr4, addr4, "netmask", "255.255.255.255", "up"},
|
|
||||||
{name, "inet6", addr6, "prefixlen", "128"},
|
|
||||||
} {
|
|
||||||
if out, err := exec.Command("ifconfig", args...).CombinedOutput(); err != nil {
|
|
||||||
log.Fatalf("ifconfig %s: %v: %s", strings.Join(args, " "), err, out)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return fd, name
|
|
||||||
}
|
|
||||||
|
|
||||||
// lanPrefixes applies Tailscale's attached-LAN rule to every interface but those in skip
|
|
||||||
func lanPrefixes(skip []string) (v4, v6 []netip.Prefix) {
|
|
||||||
ifs, err := net.Interfaces()
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
for _, i := range ifs {
|
|
||||||
if slices.Contains(skip, i.Name) || i.Flags&net.FlagLoopback != 0 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
addrs, _ := i.Addrs()
|
|
||||||
for _, a := range addrs {
|
|
||||||
n, ok := a.(*net.IPNet)
|
|
||||||
if !ok {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
ip, _ := netip.AddrFromSlice(n.IP)
|
|
||||||
ip = ip.Unmap()
|
|
||||||
ones, _ := n.Mask.Size()
|
|
||||||
pfx := netip.PrefixFrom(ip, ones).Masked()
|
|
||||||
// Tailscale skips single IPs. Link-local is our addition, every interface has the
|
|
||||||
// same fe80::/64 and claiming it would only break the harness's own host.
|
|
||||||
if pfx.IsSingleIP() || ip.IsLinkLocalUnicast() {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
if ip.Is4() {
|
|
||||||
v4 = append(v4, pfx)
|
|
||||||
} else {
|
|
||||||
v6 = append(v6, pfx)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
slices.SortFunc(v4, func(a, b netip.Prefix) int { return a.Addr().Compare(b.Addr()) })
|
|
||||||
slices.SortFunc(v6, func(a, b netip.Prefix) int { return a.Addr().Compare(b.Addr()) })
|
|
||||||
return v4, v6
|
|
||||||
}
|
|
||||||
|
|
||||||
func routes4(ps []netip.Prefix) string {
|
|
||||||
var b strings.Builder
|
|
||||||
for _, p := range ps {
|
|
||||||
mask := net.IP(net.CIDRMask(p.Bits(), 32)).String()
|
|
||||||
fmt.Fprintf(&b, "<dict><key>DestinationAddress</key><string>%s</string><key>SubnetMask</key><string>%s</string></dict>", p.Addr(), mask)
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func routes6(ps []netip.Prefix) string {
|
|
||||||
var b strings.Builder
|
|
||||||
for _, p := range ps {
|
|
||||||
fmt.Fprintf(&b, "<dict><key>DestinationAddress</key><string>%s</string><key>PrefixLength</key><integer>%d</integer></dict>", p.Addr(), p.Bits())
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *store) publish(ifName string, exclude bool, v4, v6 []netip.Prefix) {
|
|
||||||
routesKey, primary := "AdditionalRoutes", ""
|
|
||||||
if exclude {
|
|
||||||
// configd only steers excluded routes for a service with a default route that is primary.
|
|
||||||
// While this runs, everything not on a kept interface's subnet goes into the utun and dies.
|
|
||||||
routesKey = "ExcludedRoutes"
|
|
||||||
primary = "<key>Router</key><string>" + addr4 + "</string><key>OverridePrimary</key><integer>1</integer>"
|
|
||||||
}
|
|
||||||
|
|
||||||
const head = `<?xml version="1.0" encoding="UTF-8"?><plist version="1.0"><dict>`
|
|
||||||
s.set(s.k4, head+
|
|
||||||
"<key>InterfaceName</key><string>"+ifName+"</string>"+
|
|
||||||
"<key>Addresses</key><array><string>"+addr4+"</string></array>"+
|
|
||||||
"<key>SubnetMasks</key><array><string>255.255.255.255</string></array>"+primary+
|
|
||||||
"<key>"+routesKey+"</key><array>"+routes4(v4)+"</array></dict></plist>")
|
|
||||||
s.set(s.k6, head+
|
|
||||||
"<key>InterfaceName</key><string>"+ifName+"</string>"+
|
|
||||||
"<key>Addresses</key><array><string>"+addr6+"</string></array>"+
|
|
||||||
"<key>PrefixLength</key><array><integer>128</integer></array>"+
|
|
||||||
"<key>"+routesKey+"</key><array>"+routes6(v6)+"</array></dict></plist>")
|
|
||||||
|
|
||||||
log.Printf("published %s on %s, %s: %v %v", serviceID, ifName, routesKey, v4, v6)
|
|
||||||
}
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
mode := flag.String("mode", "claim", "claim: exit node without LAN access, the prefixes are routed into the vpn\n"+
|
|
||||||
"exclude: exit node with LAN access, the prefixes leave via the next interface and the vpn becomes primary")
|
|
||||||
keep := flag.String("keep", "en0", "comma separated interfaces whose prefixes are never published, keep the one your ssh session uses")
|
|
||||||
follow := flag.Bool("follow", true, "republish when interface prefixes change, as Tailscale does on link changes.\n"+
|
|
||||||
"Off, a route stays published after its interface is gone, which is how a leftover route is staged")
|
|
||||||
clear := flag.Bool("clear", false, "withdraw a service a crashed run left behind, then exit")
|
|
||||||
flag.Parse()
|
|
||||||
|
|
||||||
if *mode != "claim" && *mode != "exclude" {
|
|
||||||
log.Fatalf("unknown -mode %q", *mode)
|
|
||||||
}
|
|
||||||
if os.Geteuid() != 0 {
|
|
||||||
log.Fatal("needs root, to create the utun and write configd's dynamic store")
|
|
||||||
}
|
|
||||||
|
|
||||||
loadFrameworks()
|
|
||||||
s := openStore()
|
|
||||||
if *clear {
|
|
||||||
s.withdraw()
|
|
||||||
log.Print("withdrawn")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
fd, ifName := createUtun()
|
|
||||||
exclude := *mode == "exclude"
|
|
||||||
skip := append(strings.Split(*keep, ","), ifName)
|
|
||||||
|
|
||||||
v4, v6 := lanPrefixes(skip)
|
|
||||||
s.publish(ifName, exclude, v4, v6)
|
|
||||||
|
|
||||||
sig := make(chan os.Signal, 1)
|
|
||||||
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
|
||||||
tick := time.NewTicker(time.Second)
|
|
||||||
defer tick.Stop()
|
|
||||||
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-sig:
|
|
||||||
s.withdraw()
|
|
||||||
_ = unix.Close(fd)
|
|
||||||
log.Print("withdrawn")
|
|
||||||
return
|
|
||||||
case <-tick.C:
|
|
||||||
if !*follow {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
n4, n6 := lanPrefixes(skip)
|
|
||||||
if !slices.Equal(n4, v4) || !slices.Equal(n6, v6) {
|
|
||||||
v4, v6 = n4, n6
|
|
||||||
s.publish(ifName, exclude, v4, v6)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,76 +0,0 @@
|
|||||||
#!/bin/sh
|
|
||||||
# Reports where traffic to nebula peers goes before, during and after a vpnemu exit node.
|
|
||||||
#
|
|
||||||
# usage: sudo ./repro.sh -n <nebula binary> -c <nebula config> -p <peer vpn addr> [-p <peer>...]
|
|
||||||
# [-m claim|exclude] [-k <keep interfaces>]
|
|
||||||
#
|
|
||||||
# Each peer should answer pings over the overlay. A healthy run shows the nebula utun as egress
|
|
||||||
# and the ping working in all three phases.
|
|
||||||
set -u
|
|
||||||
|
|
||||||
MODE=claim
|
|
||||||
KEEP=en0
|
|
||||||
PEERS=""
|
|
||||||
NEBULA=""
|
|
||||||
CONFIG=""
|
|
||||||
while getopts n:c:p:m:k: o; do
|
|
||||||
case $o in
|
|
||||||
n) NEBULA=$OPTARG ;;
|
|
||||||
c) CONFIG=$OPTARG ;;
|
|
||||||
p) PEERS="$PEERS $OPTARG" ;;
|
|
||||||
m) MODE=$OPTARG ;;
|
|
||||||
k) KEEP=$OPTARG ;;
|
|
||||||
*) exit 2 ;;
|
|
||||||
esac
|
|
||||||
done
|
|
||||||
if [ -z "$NEBULA" ] || [ -z "$CONFIG" ] || [ -z "$PEERS" ]; then
|
|
||||||
sed -n '4,5p' "$0"
|
|
||||||
exit 2
|
|
||||||
fi
|
|
||||||
|
|
||||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
|
||||||
VPNEMU=${VPNEMU:-$HERE/vpnemu}
|
|
||||||
LOG=$(mktemp -t nebula-repro)
|
|
||||||
|
|
||||||
report() {
|
|
||||||
for p in $PEERS; do
|
|
||||||
case $p in
|
|
||||||
*:*) fam=-inet6 ping=ping6 ;;
|
|
||||||
*) fam=-inet ping="ping -t 3" ;;
|
|
||||||
esac
|
|
||||||
egress=$(route -n get $fam "$p" 2>/dev/null | awk '/interface:/{print $2}')
|
|
||||||
if $ping -c 2 "$p" >/dev/null 2>&1; then ok=ok; else ok=FAIL; fi
|
|
||||||
printf '%-8s %-24s egress=%-8s ping=%s\n' "$1" "$p" "${egress:-none}" "$ok"
|
|
||||||
done
|
|
||||||
}
|
|
||||||
|
|
||||||
cleanup() {
|
|
||||||
[ -n "${EMU:-}" ] && kill "$EMU" 2>/dev/null
|
|
||||||
[ -n "${NEB:-}" ] && kill "$NEB" 2>/dev/null
|
|
||||||
wait 2>/dev/null
|
|
||||||
}
|
|
||||||
trap cleanup EXIT INT TERM
|
|
||||||
|
|
||||||
"$NEBULA" -config "$CONFIG" >"$LOG" 2>&1 &
|
|
||||||
NEB=$!
|
|
||||||
sleep 3
|
|
||||||
if ! kill -0 $NEB 2>/dev/null; then
|
|
||||||
echo "nebula exited:"
|
|
||||||
tail -5 "$LOG"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
echo "nebula on $(grep -o 'interface=utun[0-9]*' "$LOG" | head -1 | cut -d= -f2), log in $LOG"
|
|
||||||
report before
|
|
||||||
|
|
||||||
"$VPNEMU" -mode "$MODE" -keep "$KEEP" &
|
|
||||||
EMU=$!
|
|
||||||
sleep 3
|
|
||||||
report during
|
|
||||||
|
|
||||||
kill $EMU
|
|
||||||
wait $EMU 2>/dev/null
|
|
||||||
EMU=
|
|
||||||
sleep 2
|
|
||||||
report after
|
|
||||||
|
|
||||||
grep -E 'level=(WARN|ERROR).*(route|Route)' "$LOG"
|
|
||||||
+5
-6
@@ -135,12 +135,12 @@ listen:
|
|||||||
# superpacket, so the receive scratch is batch * 64KiB per listening socket (~4MiB per routine at the
|
# superpacket, so the receive scratch is batch * 64KiB per listening socket (~4MiB per routine at the
|
||||||
# default of 64). Lower this to trade peak per-syscall throughput for memory on constrained hosts.
|
# default of 64). Lower this to trade peak per-syscall throughput for memory on constrained hosts.
|
||||||
#batch: 64
|
#batch: 64
|
||||||
# Linux only. Configure socket buffers for the udp side (outside), leave unset to use the system defaults. Values will be doubled by the kernel
|
# Configure socket buffers for the udp side (outside), leave unset to use the system defaults. Values will be doubled by the kernel
|
||||||
# Default is net.core.rmem_default and net.core.wmem_default (/proc/sys/net/core/rmem_default and /proc/sys/net/core/rmem_default)
|
# Default is net.core.rmem_default and net.core.wmem_default (/proc/sys/net/core/rmem_default and /proc/sys/net/core/rmem_default)
|
||||||
# Maximum is limited by memory in the system, SO_RCVBUFFORCE and SO_SNDBUFFORCE is used to avoid having to raise the system wide
|
# Maximum is limited by memory in the system, SO_RCVBUFFORCE and SO_SNDBUFFORCE is used to avoid having to raise the system wide
|
||||||
# max, net.core.rmem_max and net.core.wmem_max
|
# max, net.core.rmem_max and net.core.wmem_max
|
||||||
read_buffer: 3412512
|
#read_buffer: 10485760
|
||||||
write_buffer: 3412512
|
#write_buffer: 10485760
|
||||||
|
|
||||||
# On Windows only
|
# On Windows only
|
||||||
# When true, Nebula installs a WFP (Windows Filtering Platform) PERMIT filter scoped to UDP at the listener port.
|
# When true, Nebula installs a WFP (Windows Filtering Platform) PERMIT filter scoped to UDP at the listener port.
|
||||||
@@ -262,10 +262,9 @@ tun:
|
|||||||
drop_local_broadcast: false
|
drop_local_broadcast: false
|
||||||
# Toggles forwarding of multicast packets
|
# Toggles forwarding of multicast packets
|
||||||
drop_multicast: false
|
drop_multicast: false
|
||||||
# Sets the transmit queue length, if you notice lots of transmit drops on the tun it may help to raise this number. Default is 5000
|
# Sets the transmit queue length, if you notice lots of transmit drops on the tun it may help to raise this number. Default is 500
|
||||||
tx_queue: 5000
|
tx_queue: 500
|
||||||
# Default MTU for every packet, safe setting is (and the default) 1300 for internet based traffic
|
# Default MTU for every packet, safe setting is (and the default) 1300 for internet based traffic
|
||||||
# Anything above 8937, here or on a route below, is capped to 8937 with a warning
|
|
||||||
mtu: 1300
|
mtu: 1300
|
||||||
|
|
||||||
# the use_offloads setting controls if Nebula will attempt to enable GSO and GRO for the tun device. Linux only, not reloadable.
|
# the use_offloads setting controls if Nebula will attempt to enable GSO and GRO for the tun device. Linux only, not reloadable.
|
||||||
|
|||||||
+65
-17
@@ -967,33 +967,54 @@ func convertRule(l *slog.Logger, p any, table string, i int) (rule, error) {
|
|||||||
r.CAName = toString("ca_name", m)
|
r.CAName = toString("ca_name", m)
|
||||||
r.CASha = toString("ca_sha", m)
|
r.CASha = toString("ca_sha", m)
|
||||||
|
|
||||||
// Make sure group isn't an array
|
// A null value, `group:` with nothing after it, is the same as no group
|
||||||
if v, ok := m["group"].([]any); ok {
|
var singleGroup string
|
||||||
if len(v) > 1 {
|
if g, ok := m["group"]; ok && g != nil {
|
||||||
return r, errors.New("group should contain a single value, an array with more than one entry was provided")
|
// Make sure group isn't an array
|
||||||
|
v, isArray := g.([]any)
|
||||||
|
if isArray {
|
||||||
|
if len(v) > 1 {
|
||||||
|
return r, errors.New("group should contain a single value, an array with more than one entry was provided")
|
||||||
|
}
|
||||||
|
if len(v) == 0 {
|
||||||
|
return r, errors.New("group should contain a single value, an empty array was provided")
|
||||||
|
}
|
||||||
|
g = v[0]
|
||||||
}
|
}
|
||||||
|
|
||||||
l.Warn("group was an array with a single value, converting to simple value",
|
var err error
|
||||||
"table", table,
|
singleGroup, err = groupName(l, g, table, i)
|
||||||
"rule", i,
|
if err != nil {
|
||||||
)
|
return r, fmt.Errorf("group should contain a single value, %w", err)
|
||||||
m["group"] = v[0]
|
}
|
||||||
|
|
||||||
|
if isArray {
|
||||||
|
l.Warn("group was an array with a single value, converting to simple value",
|
||||||
|
"table", table,
|
||||||
|
"rule", i,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
singleGroup := toString("group", m)
|
// A null value, `groups:` with nothing after it, is the same as no groups
|
||||||
|
if rg, ok := m["groups"]; ok && rg != nil {
|
||||||
if rg, ok := m["groups"]; ok {
|
|
||||||
switch reflect.TypeOf(rg).Kind() {
|
switch reflect.TypeOf(rg).Kind() {
|
||||||
case reflect.Slice:
|
case reflect.Slice:
|
||||||
v := reflect.ValueOf(rg)
|
v := reflect.ValueOf(rg)
|
||||||
r.Groups = make([]string, v.Len())
|
r.Groups = make([]string, v.Len())
|
||||||
for i := 0; i < v.Len(); i++ {
|
for gi := 0; gi < v.Len(); gi++ {
|
||||||
r.Groups[i] = v.Index(i).Interface().(string)
|
name, err := groupName(l, v.Index(gi).Interface(), table, i)
|
||||||
|
if err != nil {
|
||||||
|
return r, fmt.Errorf("groups entry #%d should contain a single value, %w", gi, err)
|
||||||
|
}
|
||||||
|
r.Groups[gi] = name
|
||||||
}
|
}
|
||||||
case reflect.String:
|
|
||||||
r.Groups = []string{rg.(string)}
|
|
||||||
default:
|
default:
|
||||||
r.Groups = []string{fmt.Sprintf("%v", rg)}
|
name, err := groupName(l, rg, table, i)
|
||||||
|
if err != nil {
|
||||||
|
return r, fmt.Errorf("groups should contain an array or a single value, %w", err)
|
||||||
|
}
|
||||||
|
r.Groups = []string{name}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1009,6 +1030,33 @@ func convertRule(l *slog.Logger, p any, table string, i int) (rule, error) {
|
|||||||
return r, nil
|
return r, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// groupName reads a group name from config. YAML has already parsed an unquoted value by the time we see it, so `007`
|
||||||
|
// arrives as 7, `1.10` as 1.1, and a date as a time.Time, and the text that was written is gone. Strings are used as
|
||||||
|
// is. Ints and bools are converted so `group: 7` keeps working, with a warning to quote them. Anything else would
|
||||||
|
// become a name that may not match what was written, or matches nothing like "<nil>" or "map[a:b]", so it is rejected.
|
||||||
|
func groupName(l *slog.Logger, v any, table string, i int) (string, error) {
|
||||||
|
if v == nil {
|
||||||
|
return "", errors.New("a null was provided")
|
||||||
|
}
|
||||||
|
switch reflect.TypeOf(v).Kind() {
|
||||||
|
case reflect.String:
|
||||||
|
return reflect.ValueOf(v).String(), nil
|
||||||
|
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
|
||||||
|
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Bool:
|
||||||
|
l.Warn("group was not a string and should be quoted to match as written",
|
||||||
|
"table", table,
|
||||||
|
"rule", i,
|
||||||
|
"group", v,
|
||||||
|
)
|
||||||
|
return fmt.Sprintf("%v", v), nil
|
||||||
|
case reflect.Slice, reflect.Array:
|
||||||
|
return "", errors.New("an array was provided")
|
||||||
|
case reflect.Map:
|
||||||
|
return "", errors.New("a map was provided")
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("%v was read as a %T, quote it to use it as a group name", v, v)
|
||||||
|
}
|
||||||
|
|
||||||
// sanity returns an error if the rule would be evaluated in a way that would short-circuit a configured check on a wildcard value
|
// sanity returns an error if the rule would be evaluated in a way that would short-circuit a configured check on a wildcard value
|
||||||
// rules are evaluated as "port AND proto AND (ca_sha OR ca_name) AND (host OR group OR groups OR cidr) AND local_cidr"
|
// rules are evaluated as "port AND proto AND (ca_sha OR ca_name) AND (host OR group OR groups OR cidr) AND local_cidr"
|
||||||
func (r *rule) sanity() error {
|
func (r *rule) sanity() error {
|
||||||
|
|||||||
@@ -1439,6 +1439,56 @@ func TestAddFirewallRulesFromConfig(t *testing.T) {
|
|||||||
require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
|
require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
|
||||||
assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: []string{"a", "b"}, ip: "", localIp: ""}, mf.lastCall)
|
assert.Equal(t, addRuleCall{incoming: true, proto: firewall.ProtoAny, startPort: 1, endPort: 1, groups: []string{"a", "b"}, ip: "", localIp: ""}, mf.lastCall)
|
||||||
|
|
||||||
|
// Test group and groups values that used to crash or become a group that matches nothing: an empty array,
|
||||||
|
// a null, an array, or a map is rejected
|
||||||
|
badGroups := []struct {
|
||||||
|
key string
|
||||||
|
value any
|
||||||
|
err string
|
||||||
|
}{
|
||||||
|
{"group", []any{}, "group should contain a single value, an empty array was provided"},
|
||||||
|
{"group", []any{nil}, "group should contain a single value, a null was provided"},
|
||||||
|
{"group", []any{[]any{"a"}}, "group should contain a single value, an array was provided"},
|
||||||
|
{"group", map[string]any{"a": "b"}, "group should contain a single value, a map was provided"},
|
||||||
|
{"groups", []any{nil}, "groups entry #0 should contain a single value, a null was provided"},
|
||||||
|
{"groups", []any{"a", []any{"b"}}, "groups entry #1 should contain a single value, an array was provided"},
|
||||||
|
{"groups", []any{map[string]any{"a": "b"}}, "groups entry #0 should contain a single value, a map was provided"},
|
||||||
|
{"groups", map[string]any{"a": "b"}, "groups should contain an array or a single value, a map was provided"},
|
||||||
|
{"group", 1.1, "group should contain a single value, 1.1 was read as a float64, quote it to use it as a group name"},
|
||||||
|
{"group", []any{1.1}, "group should contain a single value, 1.1 was read as a float64, quote it to use it as a group name"},
|
||||||
|
{"groups", []any{"a", 1.1}, "groups entry #1 should contain a single value, 1.1 was read as a float64, quote it to use it as a group name"},
|
||||||
|
{"groups", time.Date(2001, 12, 14, 0, 0, 0, 0, time.UTC), "groups should contain an array or a single value, 2001-12-14 00:00:00 +0000 UTC was read as a time.Time, quote it to use it as a group name"},
|
||||||
|
}
|
||||||
|
for _, tc := range badGroups {
|
||||||
|
conf = config.NewC(test.NewLogger())
|
||||||
|
mf = &mockFirewall{}
|
||||||
|
conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", tc.key: tc.value}}}
|
||||||
|
require.EqualError(t, AddFirewallRulesFromConfig(l, true, conf, mf), "firewall.inbound rule #0; "+tc.err, "%s: %v", tc.key, tc.value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test int and bool groups entries are read as strings
|
||||||
|
conf = config.NewC(test.NewLogger())
|
||||||
|
mf = &mockFirewall{}
|
||||||
|
conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "groups": []any{1, true}}}}
|
||||||
|
require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
|
||||||
|
assert.Equal(t, []string{"1", "true"}, mf.lastCall.groups)
|
||||||
|
|
||||||
|
conf = config.NewC(test.NewLogger())
|
||||||
|
mf = &mockFirewall{}
|
||||||
|
conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", "group": 1}}}
|
||||||
|
require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
|
||||||
|
assert.Equal(t, []string{"1"}, mf.lastCall.groups)
|
||||||
|
|
||||||
|
// Test a null group or groups is the same as not providing it
|
||||||
|
for _, key := range []string{"group", "groups"} {
|
||||||
|
conf = config.NewC(test.NewLogger())
|
||||||
|
mf = &mockFirewall{}
|
||||||
|
conf.Settings["firewall"] = map[string]any{"inbound": []any{map[string]any{"port": "1", "proto": "any", key: nil, "host": "a"}}}
|
||||||
|
require.NoError(t, AddFirewallRulesFromConfig(l, true, conf, mf))
|
||||||
|
assert.Empty(t, mf.lastCall.groups)
|
||||||
|
assert.Equal(t, "a", mf.lastCall.host)
|
||||||
|
}
|
||||||
|
|
||||||
// Test Add error
|
// Test Add error
|
||||||
conf = config.NewC(test.NewLogger())
|
conf = config.NewC(test.NewLogger())
|
||||||
mf = &mockFirewall{}
|
mf = &mockFirewall{}
|
||||||
|
|||||||
@@ -24,11 +24,6 @@ type m = map[string]any
|
|||||||
const (
|
const (
|
||||||
Version uint8 = 1
|
Version uint8 = 1
|
||||||
Len = 16
|
Len = 16
|
||||||
|
|
||||||
// MaxOverhead is the most a payload grows on its way to the underlay.
|
|
||||||
// A relayed packet has two headers and two AEAD tags, one for the inner tunnel and another for the relay tunnel.
|
|
||||||
// Every supported cipher (today) has a 16 byte tag.
|
|
||||||
MaxOverhead = 2 * (Len + 16)
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type MessageType uint8
|
type MessageType uint8
|
||||||
|
|||||||
@@ -199,8 +199,8 @@ func (f *Interface) sendInsideMessage(hostinfo *HostInfo, pkt tio.Packet, nb []b
|
|||||||
}
|
}
|
||||||
|
|
||||||
err = tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
err = tio.SegmentSuperpacket(pkt, func(seg []byte) error {
|
||||||
//relay header + header + plaintext + AEAD tag + relay tag
|
//relay header + header + plaintext + AEAD tag (16 bytes for both AES-GCM and ChaCha20-Poly1305) + relay tag
|
||||||
scratch := sendBatch.Reserve(len(seg) + header.MaxOverhead)
|
scratch := sendBatch.Reserve(header.Len + header.Len + len(seg) + 16 + 16)
|
||||||
|
|
||||||
innerPacket := f.sendInsideEncrypt(hostinfo, ci, seg, scratch[header.Len:], nb)
|
innerPacket := f.sendInsideEncrypt(hostinfo, ci, seg, scratch[header.Len:], nb)
|
||||||
if innerPacket == nil {
|
if innerPacket == nil {
|
||||||
@@ -529,26 +529,16 @@ func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
|
useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
|
||||||
|
|
||||||
// The encrypt appends to out in place and a relayed packet is then wrapped in place,
|
|
||||||
// so out has to fit the whole packet up front or the encrypt reallocates out from under SendVia.
|
|
||||||
// We cap the MTU of tun devices and routes we create ourselves, so only a host that set a bigger MTU than we allow gets here.
|
|
||||||
need := header.Len + len(p) + ci.eKey.Overhead()
|
|
||||||
if useRelay {
|
|
||||||
// The relay tunnel runs the same cipher, and adds its own header and tag
|
|
||||||
need += header.Len + ci.eKey.Overhead()
|
|
||||||
}
|
|
||||||
if cap(out) < need {
|
|
||||||
if l, ok := logging.RateLimited(f.l, f.txOversizeLimiter); ok {
|
|
||||||
hostinfo.logger(l).Error("Dropping outbound packet, out buffer not large enough", "outCap", cap(out), "payloadLen", len(p), "relayed", useRelay)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
fullOut := out
|
fullOut := out
|
||||||
|
|
||||||
if useRelay {
|
if useRelay {
|
||||||
|
if len(out) < header.Len {
|
||||||
|
// out always has a capacity of mtu, but not always a length greater than the header.Len.
|
||||||
|
// Grow it to make sure the next operation works.
|
||||||
|
out = out[:header.Len]
|
||||||
|
}
|
||||||
// Save a header's worth of data at the front of the 'out' buffer.
|
// Save a header's worth of data at the front of the 'out' buffer.
|
||||||
out = out[header.Len:header.Len]
|
out = out[header.Len:]
|
||||||
}
|
}
|
||||||
|
|
||||||
if noiseutil.EncryptLockNeeded {
|
if noiseutil.EncryptLockNeeded {
|
||||||
|
|||||||
@@ -127,7 +127,6 @@ type Interface struct {
|
|||||||
|
|
||||||
udpTxErrLimiter *ratelimit.Limiter // udp direct transmit error log limiter
|
udpTxErrLimiter *ratelimit.Limiter // udp direct transmit error log limiter
|
||||||
udpRelayTxErrLimiter *ratelimit.Limiter // udp relay transmit error log limiter
|
udpRelayTxErrLimiter *ratelimit.Limiter // udp relay transmit error log limiter
|
||||||
txOversizeLimiter *ratelimit.Limiter // oversized outbound packet drop log limiter
|
|
||||||
|
|
||||||
// fatalErr holds the first unexpected reader error that caused shutdown.
|
// fatalErr holds the first unexpected reader error that caused shutdown.
|
||||||
// nil means "no fatal error" (yet)
|
// nil means "no fatal error" (yet)
|
||||||
@@ -211,10 +210,6 @@ func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
txOversizeLimiter, err := ratelimit.New(1, time.Second)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.routines <= 1 {
|
if c.routines <= 1 {
|
||||||
c.PinThreads = false //pinning is not useful unless there's more than one tun reader
|
c.PinThreads = false //pinning is not useful unless there's more than one tun reader
|
||||||
@@ -250,7 +245,6 @@ func NewInterface(ctx context.Context, c *InterfaceConfig) (*Interface, error) {
|
|||||||
pinThreads: c.PinThreads,
|
pinThreads: c.PinThreads,
|
||||||
udpTxErrLimiter: udpTxErrLimiter,
|
udpTxErrLimiter: udpTxErrLimiter,
|
||||||
udpRelayTxErrLimiter: udpRelayTxErrLimiter,
|
udpRelayTxErrLimiter: udpRelayTxErrLimiter,
|
||||||
txOversizeLimiter: txOversizeLimiter,
|
|
||||||
|
|
||||||
metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
|
metricHandshakes: metrics.GetOrRegisterHistogram("handshakes", nil, metrics.NewExpDecaySample(1028, 0.015)),
|
||||||
metricTxDropped: metrics.GetOrRegisterCounter("udp.tx.dropped", nil),
|
metricTxDropped: metrics.GetOrRegisterCounter("udp.tx.dropped", nil),
|
||||||
|
|||||||
+3
-1
@@ -160,7 +160,9 @@ func (f *Interface) readOutsidePackets(via ViaSender, packet []byte, rxc *rxCont
|
|||||||
case header.TestReply:
|
case header.TestReply:
|
||||||
// No-op, useful for the Roaming and connectionManager side-effects above
|
// No-op, useful for the Roaming and connectionManager side-effects above
|
||||||
case header.TestRequest:
|
case header.TestRequest:
|
||||||
if header.MaxOverhead+len(out) > len(rxc.scratch) {
|
const maxCipherOverhead = 16 //todo we use this too often, needs a real importable const
|
||||||
|
const maxOverhead = header.Len + header.Len + maxCipherOverhead + maxCipherOverhead
|
||||||
|
if maxOverhead+len(out) > len(rxc.scratch) {
|
||||||
// A reply that cannot fit in scratch is dropped no matter the log level.
|
// A reply that cannot fit in scratch is dropped no matter the log level.
|
||||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||||
hostinfo.logger(f.l).Debug("dropping oversized test request", "payloadLen", len(out), "from", via)
|
hostinfo.logger(f.l).Debug("dropping oversized test request", "payloadLen", len(out), "from", via)
|
||||||
|
|||||||
+4
-28
@@ -50,13 +50,7 @@ func (r Route) String() string {
|
|||||||
|
|
||||||
func makeRouteTree(l *slog.Logger, routes []Route, allowMTU bool) (*bart.Table[routing.Gateways], error) {
|
func makeRouteTree(l *slog.Logger, routes []Route, allowMTU bool) (*bart.Table[routing.Gateways], error) {
|
||||||
routeTree := new(bart.Table[routing.Gateways])
|
routeTree := new(bart.Table[routing.Gateways])
|
||||||
seen := make(map[netip.Prefix]bool, len(routes))
|
|
||||||
for _, r := range routes {
|
for _, r := range routes {
|
||||||
if seen[r.Cidr] {
|
|
||||||
l.Warn("route is listed more than once, only the last entry's via is used", "route", r)
|
|
||||||
}
|
|
||||||
seen[r.Cidr] = true
|
|
||||||
|
|
||||||
if !allowMTU && r.MTU > 0 {
|
if !allowMTU && r.MTU > 0 {
|
||||||
l.Warn("route MTU is not supported on this platform",
|
l.Warn("route MTU is not supported on this platform",
|
||||||
"goos", runtime.GOOS,
|
"goos", runtime.GOOS,
|
||||||
@@ -104,11 +98,7 @@ func parseRoutes(c *config.C, networks []netip.Prefix) ([]Route, error) {
|
|||||||
|
|
||||||
mtu, ok := rMtu.(int)
|
mtu, ok := rMtu.(int)
|
||||||
if !ok {
|
if !ok {
|
||||||
s, ok := rMtu.(string)
|
mtu, err = strconv.Atoi(rMtu.(string))
|
||||||
if !ok {
|
|
||||||
return nil, fmt.Errorf("entry %v.mtu in tun.routes is not an integer: %v", i+1, rMtu)
|
|
||||||
}
|
|
||||||
mtu, err = strconv.Atoi(s)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("entry %v.mtu in tun.routes is not an integer: %v", i+1, err)
|
return nil, fmt.Errorf("entry %v.mtu in tun.routes is not an integer: %v", i+1, err)
|
||||||
}
|
}
|
||||||
@@ -184,11 +174,7 @@ func parseUnsafeRoutes(c *config.C, networks []netip.Prefix) ([]Route, error) {
|
|||||||
if rMtu, ok := m["mtu"]; ok {
|
if rMtu, ok := m["mtu"]; ok {
|
||||||
mtu, ok = rMtu.(int)
|
mtu, ok = rMtu.(int)
|
||||||
if !ok {
|
if !ok {
|
||||||
s, ok := rMtu.(string)
|
mtu, err = strconv.Atoi(rMtu.(string))
|
||||||
if !ok {
|
|
||||||
return nil, fmt.Errorf("entry %v.mtu in tun.unsafe_routes is not an integer: %v", i+1, rMtu)
|
|
||||||
}
|
|
||||||
mtu, err = strconv.Atoi(s)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("entry %v.mtu in tun.unsafe_routes is not an integer: %v", i+1, err)
|
return nil, fmt.Errorf("entry %v.mtu in tun.unsafe_routes is not an integer: %v", i+1, err)
|
||||||
}
|
}
|
||||||
@@ -206,15 +192,10 @@ func parseUnsafeRoutes(c *config.C, networks []netip.Prefix) ([]Route, error) {
|
|||||||
|
|
||||||
metric, ok := rMetric.(int)
|
metric, ok := rMetric.(int)
|
||||||
if !ok {
|
if !ok {
|
||||||
s, ok := rMetric.(string)
|
_, err = strconv.ParseInt(rMetric.(string), 10, 32)
|
||||||
if !ok {
|
|
||||||
return nil, fmt.Errorf("entry %v.metric in tun.unsafe_routes is not an integer: %v", i+1, rMetric)
|
|
||||||
}
|
|
||||||
n, err := strconv.ParseInt(s, 10, 32)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("entry %v.metric in tun.unsafe_routes is not an integer: %v", i+1, err)
|
return nil, fmt.Errorf("entry %v.metric in tun.unsafe_routes is not an integer: %v", i+1, err)
|
||||||
}
|
}
|
||||||
metric = int(n)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if metric < 0 || metric > math.MaxInt32 {
|
if metric < 0 || metric > math.MaxInt32 {
|
||||||
@@ -267,15 +248,10 @@ func parseUnsafeRoutes(c *config.C, networks []netip.Prefix) ([]Route, error) {
|
|||||||
|
|
||||||
gatewayWeight, ok := rGatewayWeight.(int)
|
gatewayWeight, ok := rGatewayWeight.(int)
|
||||||
if !ok {
|
if !ok {
|
||||||
s, ok := rGatewayWeight.(string)
|
_, err = strconv.ParseInt(rGatewayWeight.(string), 10, 32)
|
||||||
if !ok {
|
|
||||||
return nil, fmt.Errorf("entry .weight in tun.unsafe_routes[%v].via[%v] is not an integer", i+1, ig+1)
|
|
||||||
}
|
|
||||||
w, err := strconv.ParseInt(s, 10, 32)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("entry .weight in tun.unsafe_routes[%v].via[%v] is not an integer", i+1, ig+1)
|
return nil, fmt.Errorf("entry .weight in tun.unsafe_routes[%v].via[%v] is not an integer", i+1, ig+1)
|
||||||
}
|
}
|
||||||
gatewayWeight = int(w)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if gatewayWeight < 1 || gatewayWeight > math.MaxInt32 {
|
if gatewayWeight < 1 || gatewayWeight > math.MaxInt32 {
|
||||||
|
|||||||
@@ -1,17 +1,13 @@
|
|||||||
package overlay
|
package overlay
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/header"
|
|
||||||
"github.com/slackhq/nebula/routing"
|
"github.com/slackhq/nebula/routing"
|
||||||
"github.com/slackhq/nebula/test"
|
"github.com/slackhq/nebula/test"
|
||||||
"github.com/slackhq/nebula/udp"
|
|
||||||
"github.com/stretchr/testify/assert"
|
"github.com/stretchr/testify/assert"
|
||||||
"github.com/stretchr/testify/require"
|
"github.com/stretchr/testify/require"
|
||||||
)
|
)
|
||||||
@@ -406,115 +402,3 @@ func Test_makeMultipathUnsafeRouteTree(t *testing.T) {
|
|||||||
routing.CalculateBucketsForGateways(expectedGateways)
|
routing.CalculateBucketsForGateways(expectedGateways)
|
||||||
assert.ElementsMatch(t, expectedGateways, r)
|
assert.ElementsMatch(t, expectedGateways, r)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Test_getMTU(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
c := config.NewC(l)
|
|
||||||
|
|
||||||
// unset
|
|
||||||
assert.Equal(t, DefaultMTU, getMTU(l, c))
|
|
||||||
|
|
||||||
// the largest a relayed packet can carry in one underlay buffer
|
|
||||||
require.Equal(t, udp.MTU, MaxMTU+header.MaxOverhead)
|
|
||||||
c.Settings["tun"] = map[string]any{"mtu": MaxMTU}
|
|
||||||
assert.Equal(t, MaxMTU, getMTU(l, c))
|
|
||||||
|
|
||||||
// too big is capped
|
|
||||||
c.Settings["tun"] = map[string]any{"mtu": 9000}
|
|
||||||
assert.Equal(t, MaxMTU, getMTU(l, c))
|
|
||||||
}
|
|
||||||
|
|
||||||
func Test_getAllRoutesFromConfigCapsMTU(t *testing.T) {
|
|
||||||
l := test.NewLogger()
|
|
||||||
c := config.NewC(l)
|
|
||||||
c.Settings["tun"] = map[string]any{
|
|
||||||
"routes": []any{
|
|
||||||
map[string]any{"mtu": "9000", "route": "10.0.0.0/29"},
|
|
||||||
map[string]any{"mtu": "1300", "route": "10.0.0.8/29"},
|
|
||||||
},
|
|
||||||
"unsafe_routes": []any{
|
|
||||||
map[string]any{"via": "127.0.0.1", "mtu": "9000", "route": "1.0.0.0/29"},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
changed, routes, err := getAllRoutesFromConfig(l, c, []netip.Prefix{netip.MustParsePrefix("10.0.0.0/24")}, true)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.True(t, changed)
|
|
||||||
|
|
||||||
mtus := map[string]int{}
|
|
||||||
for _, r := range routes {
|
|
||||||
mtus[r.Cidr.String()] = r.MTU
|
|
||||||
}
|
|
||||||
assert.Equal(t, map[string]int{"10.0.0.0/29": MaxMTU, "10.0.0.8/29": 1300, "1.0.0.0/29": MaxMTU}, mtus)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The route tree keeps one entry per CIDR, so a CIDR listed twice only routes by the last one. Say so instead of
|
|
||||||
// letting the earlier via, or on Windows the earlier metric, quietly lose
|
|
||||||
func Test_makeRouteTree_WarnsOnDuplicate(t *testing.T) {
|
|
||||||
buf := &bytes.Buffer{}
|
|
||||||
l := test.NewLoggerWithOutput(buf)
|
|
||||||
via := func(s string) routing.Gateways {
|
|
||||||
return routing.Gateways{routing.NewGateway(netip.MustParseAddr(s), 1)}
|
|
||||||
}
|
|
||||||
cidr := netip.MustParsePrefix("10.251.1.0/24")
|
|
||||||
|
|
||||||
_, err := makeRouteTree(l, []Route{
|
|
||||||
{Cidr: cidr, Via: via("10.250.0.2"), Install: true, Metric: 100},
|
|
||||||
{Cidr: netip.MustParsePrefix("10.251.2.0/24"), Via: via("10.250.0.2"), Install: true},
|
|
||||||
}, false)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Empty(t, buf.String())
|
|
||||||
|
|
||||||
tree, err := makeRouteTree(l, []Route{
|
|
||||||
{Cidr: cidr, Via: via("10.250.0.2"), Install: true, Metric: 100},
|
|
||||||
{Cidr: cidr, Via: via("10.250.0.3"), Install: true, Metric: 200},
|
|
||||||
}, false)
|
|
||||||
require.NoError(t, err)
|
|
||||||
assert.Equal(t, 1, strings.Count(buf.String(), "route is listed more than once, only the last entry's via is used"))
|
|
||||||
gw, ok := tree.Lookup(netip.MustParseAddr("10.251.1.1"))
|
|
||||||
require.True(t, ok)
|
|
||||||
assert.Equal(t, netip.MustParseAddr("10.250.0.3"), gw[0].Addr(), "the last entry wins")
|
|
||||||
}
|
|
||||||
|
|
||||||
// A quoted metric or weight is a number written as a string, it means that number. Anything else is an error, not a
|
|
||||||
// panic
|
|
||||||
func Test_parseUnsafeRoutes_QuotedNumbers(t *testing.T) {
|
|
||||||
c := config.NewC(test.NewLogger())
|
|
||||||
n := netip.MustParsePrefix("10.0.0.1/24")
|
|
||||||
route := func(metric, weight any) {
|
|
||||||
c.Settings["tun"] = map[string]any{"unsafe_routes": []any{map[string]any{
|
|
||||||
"route": "1.0.0.0/8",
|
|
||||||
"metric": metric,
|
|
||||||
"via": []any{map[string]any{"gateway": "10.0.0.2", "weight": weight}},
|
|
||||||
}}}
|
|
||||||
}
|
|
||||||
|
|
||||||
route("100", "5")
|
|
||||||
routes, err := parseUnsafeRoutes(c, []netip.Prefix{n})
|
|
||||||
require.NoError(t, err)
|
|
||||||
require.Len(t, routes, 1)
|
|
||||||
assert.Equal(t, 100, routes[0].Metric)
|
|
||||||
assert.Equal(t, "{addr: 10.0.0.2, weight: 5}", routes[0].Via[0].String())
|
|
||||||
|
|
||||||
route(1.5, 1)
|
|
||||||
_, err = parseUnsafeRoutes(c, []netip.Prefix{n})
|
|
||||||
require.EqualError(t, err, "entry 1.metric in tun.unsafe_routes is not an integer: 1.5")
|
|
||||||
|
|
||||||
route(1, true)
|
|
||||||
_, err = parseUnsafeRoutes(c, []netip.Prefix{n})
|
|
||||||
require.EqualError(t, err, "entry .weight in tun.unsafe_routes[1].via[1] is not an integer")
|
|
||||||
}
|
|
||||||
|
|
||||||
// An mtu that is neither a number nor a quoted one is an error, not a panic
|
|
||||||
func Test_parseRoutes_MTUNotANumber(t *testing.T) {
|
|
||||||
c := config.NewC(test.NewLogger())
|
|
||||||
n := netip.MustParsePrefix("10.0.0.1/24")
|
|
||||||
|
|
||||||
c.Settings["tun"] = map[string]any{"routes": []any{map[string]any{"route": "1.0.0.0/8", "mtu": 1500.5}}}
|
|
||||||
_, err := parseRoutes(c, []netip.Prefix{n})
|
|
||||||
require.EqualError(t, err, "entry 1.mtu in tun.routes is not an integer: 1500.5")
|
|
||||||
|
|
||||||
c.Settings["tun"] = map[string]any{"unsafe_routes": []any{map[string]any{"route": "1.0.0.0/8", "via": "10.0.0.2", "mtu": 1500.5}}}
|
|
||||||
_, err = parseUnsafeRoutes(c, []netip.Prefix{n})
|
|
||||||
require.EqualError(t, err, "entry 1.mtu in tun.unsafe_routes is not an integer: 1500.5")
|
|
||||||
}
|
|
||||||
+2
-24
@@ -7,27 +7,11 @@ import (
|
|||||||
"net/netip"
|
"net/netip"
|
||||||
|
|
||||||
"github.com/slackhq/nebula/config"
|
"github.com/slackhq/nebula/config"
|
||||||
"github.com/slackhq/nebula/header"
|
|
||||||
"github.com/slackhq/nebula/udp"
|
|
||||||
"github.com/slackhq/nebula/util"
|
"github.com/slackhq/nebula/util"
|
||||||
)
|
)
|
||||||
|
|
||||||
const DefaultMTU = 1300
|
const DefaultMTU = 1300
|
||||||
|
|
||||||
// MaxMTU is the largest tun.mtu, or route mtu, the underlay can carry.
|
|
||||||
// Every underlay buffer is udp.MTU bytes, and a relayed packet adds header.MaxOverhead to its plaintext.
|
|
||||||
const MaxMTU = udp.MTU - header.MaxOverhead
|
|
||||||
|
|
||||||
// getMTU reads tun.mtu, capping a value too big for the underlay to carry.
|
|
||||||
func getMTU(l *slog.Logger, c *config.C) int {
|
|
||||||
mtu := c.GetInt("tun.mtu", DefaultMTU)
|
|
||||||
if mtu > MaxMTU {
|
|
||||||
l.Warn("tun.mtu is too big for the underlay to carry, capping it", "mtu", mtu, "maxMTU", MaxMTU)
|
|
||||||
return MaxMTU
|
|
||||||
}
|
|
||||||
return mtu
|
|
||||||
}
|
|
||||||
|
|
||||||
type NameError struct {
|
type NameError struct {
|
||||||
Name string
|
Name string
|
||||||
Underlying error
|
Underlying error
|
||||||
@@ -43,7 +27,7 @@ type DeviceFactory func(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix,
|
|||||||
func NewDeviceFromConfig(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, routines int) (Device, error) {
|
func NewDeviceFromConfig(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, routines int) (Device, error) {
|
||||||
switch {
|
switch {
|
||||||
case c.GetBool("tun.disabled", false):
|
case c.GetBool("tun.disabled", false):
|
||||||
tun := newDisabledTun(vpnNetworks, c.GetInt("tun.tx_queue", 5000), c.GetBool("stats.message_metrics", false), l)
|
tun := newDisabledTun(vpnNetworks, c.GetInt("tun.tx_queue", 500), c.GetBool("stats.message_metrics", false), l)
|
||||||
return tun, nil
|
return tun, nil
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@@ -57,7 +41,7 @@ func NewFdDeviceFromConfig(fd *int) DeviceFactory {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func getAllRoutesFromConfig(l *slog.Logger, c *config.C, vpnNetworks []netip.Prefix, initial bool) (bool, []Route, error) {
|
func getAllRoutesFromConfig(c *config.C, vpnNetworks []netip.Prefix, initial bool) (bool, []Route, error) {
|
||||||
if !initial && !c.HasChanged("tun.routes") && !c.HasChanged("tun.unsafe_routes") {
|
if !initial && !c.HasChanged("tun.routes") && !c.HasChanged("tun.unsafe_routes") {
|
||||||
return false, nil, nil
|
return false, nil, nil
|
||||||
}
|
}
|
||||||
@@ -73,12 +57,6 @@ func getAllRoutesFromConfig(l *slog.Logger, c *config.C, vpnNetworks []netip.Pre
|
|||||||
}
|
}
|
||||||
|
|
||||||
routes = append(routes, unsafeRoutes...)
|
routes = append(routes, unsafeRoutes...)
|
||||||
for i, r := range routes {
|
|
||||||
if r.MTU > MaxMTU {
|
|
||||||
l.Warn("route mtu is too big for the underlay to carry, capping it", "route", r.Cidr, "mtu", r.MTU, "maxMTU", MaxMTU)
|
|
||||||
routes[i].MTU = MaxMTU
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true, routes, nil
|
return true, routes, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -68,7 +68,7 @@ func (t *tun) Activate() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) reload(c *config.C, initial bool) error {
|
func (t *tun) reload(c *config.C, initial bool) error {
|
||||||
change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
|
change, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -126,7 +126,7 @@ func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*t
|
|||||||
f: os.NewFile(uintptr(fd), ""),
|
f: os.NewFile(uintptr(fd), ""),
|
||||||
Device: name,
|
Device: name,
|
||||||
vpnNetworks: vpnNetworks,
|
vpnNetworks: vpnNetworks,
|
||||||
DefaultMTU: getMTU(l, c),
|
DefaultMTU: c.GetInt("tun.mtu", DefaultMTU),
|
||||||
l: l,
|
l: l,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,7 +167,7 @@ func newTunFromFd(c *config.C, l *slog.Logger, deviceFd int, vpnNetworks []netip
|
|||||||
f: file,
|
f: file,
|
||||||
Device: utunNameFromFd(deviceFd),
|
Device: utunNameFromFd(deviceFd),
|
||||||
vpnNetworks: vpnNetworks,
|
vpnNetworks: vpnNetworks,
|
||||||
DefaultMTU: getMTU(l, c),
|
DefaultMTU: c.GetInt("tun.mtu", DefaultMTU),
|
||||||
hostOwned: true,
|
hostOwned: true,
|
||||||
l: l,
|
l: l,
|
||||||
}
|
}
|
||||||
@@ -350,7 +350,7 @@ func (t *tun) activate6(network netip.Prefix) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) reload(c *config.C, initial bool) error {
|
func (t *tun) reload(c *config.C, initial bool) error {
|
||||||
change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
|
change, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -370,7 +370,7 @@ func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*t
|
|||||||
t := &tun{
|
t := &tun{
|
||||||
Device: deviceName,
|
Device: deviceName,
|
||||||
vpnNetworks: vpnNetworks,
|
vpnNetworks: vpnNetworks,
|
||||||
MTU: getMTU(l, c),
|
MTU: c.GetInt("tun.mtu", DefaultMTU),
|
||||||
l: l,
|
l: l,
|
||||||
fd: fd,
|
fd: fd,
|
||||||
shutdownR: shutdownR,
|
shutdownR: shutdownR,
|
||||||
@@ -510,7 +510,7 @@ func (t *tun) setMTU() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) reload(c *config.C, initial bool) error {
|
func (t *tun) reload(c *config.C, initial bool) error {
|
||||||
change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
|
change, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -68,7 +68,7 @@ func (t *tun) Activate() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) reload(c *config.C, initial bool) error {
|
func (t *tun) reload(c *config.C, initial bool) error {
|
||||||
change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
|
change, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -221,7 +221,7 @@ func newTunGeneric(c *config.C, l *slog.Logger, fd int, vnetHdr bool, offloadFla
|
|||||||
vnetHdr: vnetHdr,
|
vnetHdr: vnetHdr,
|
||||||
offloadFlags: offloadFlags,
|
offloadFlags: offloadFlags,
|
||||||
vpnNetworks: vpnNetworks,
|
vpnNetworks: vpnNetworks,
|
||||||
TXQueueLen: c.GetInt("tun.tx_queue", 5000),
|
TXQueueLen: c.GetInt("tun.tx_queue", 500),
|
||||||
useSystemRoutes: c.GetBool("tun.use_system_route_table", false),
|
useSystemRoutes: c.GetBool("tun.use_system_route_table", false),
|
||||||
useSystemRoutesBufferSize: c.GetInt("tun.use_system_route_table_buffer_size", 0),
|
useSystemRoutesBufferSize: c.GetInt("tun.use_system_route_table_buffer_size", 0),
|
||||||
routesFromSystem: map[netip.Prefix]routing.Gateways{},
|
routesFromSystem: map[netip.Prefix]routing.Gateways{},
|
||||||
@@ -244,7 +244,7 @@ func newTunGeneric(c *config.C, l *slog.Logger, fd int, vnetHdr bool, offloadFla
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) reload(c *config.C, initial bool) error {
|
func (t *tun) reload(c *config.C, initial bool) error {
|
||||||
routeChange, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
|
routeChange, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -256,7 +256,7 @@ func (t *tun) reload(c *config.C, initial bool) error {
|
|||||||
// Only the mtu changed. The routes are the same, parse them again so the ones without their own mtu pick up the
|
// Only the mtu changed. The routes are the same, parse them again so the ones without their own mtu pick up the
|
||||||
// new default. Without this an mtu change would remove them all
|
// new default. Without this an mtu change would remove them all
|
||||||
if !routeChange {
|
if !routeChange {
|
||||||
_, routes, err = getAllRoutesFromConfig(t.l, c, t.vpnNetworks, true)
|
_, routes, err = getAllRoutesFromConfig(c, t.vpnNetworks, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -276,7 +276,7 @@ func (t *tun) reload(c *config.C, initial bool) error {
|
|||||||
|
|
||||||
oldDefaultMTU := t.DefaultMTU
|
oldDefaultMTU := t.DefaultMTU
|
||||||
oldMaxMTU := t.MaxMTU
|
oldMaxMTU := t.MaxMTU
|
||||||
newDefaultMTU := getMTU(t.l, c)
|
newDefaultMTU := c.GetInt("tun.mtu", DefaultMTU)
|
||||||
newMaxMTU := newDefaultMTU
|
newMaxMTU := newDefaultMTU
|
||||||
for i, r := range routes {
|
for i, r := range routes {
|
||||||
if r.MTU == 0 {
|
if r.MTU == 0 {
|
||||||
|
|||||||
@@ -99,7 +99,7 @@ func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*t
|
|||||||
fd: fd,
|
fd: fd,
|
||||||
Device: deviceName,
|
Device: deviceName,
|
||||||
vpnNetworks: vpnNetworks,
|
vpnNetworks: vpnNetworks,
|
||||||
MTU: getMTU(l, c),
|
MTU: c.GetInt("tun.mtu", DefaultMTU),
|
||||||
l: l,
|
l: l,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -340,7 +340,7 @@ func (t *tun) doIoctlByName(ctl uintptr, value uint32) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) reload(c *config.C, initial bool) error {
|
func (t *tun) reload(c *config.C, initial bool) error {
|
||||||
change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
|
change, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*t
|
|||||||
fd: fd,
|
fd: fd,
|
||||||
Device: deviceName,
|
Device: deviceName,
|
||||||
vpnNetworks: vpnNetworks,
|
vpnNetworks: vpnNetworks,
|
||||||
MTU: getMTU(l, c),
|
MTU: c.GetInt("tun.mtu", DefaultMTU),
|
||||||
l: l,
|
l: l,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -319,7 +319,7 @@ func (t *tun) doIoctlByName(ctl uintptr, value uint32) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *tun) reload(c *config.C, initial bool) error {
|
func (t *tun) reload(c *config.C, initial bool) error {
|
||||||
change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
|
change, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ type TestTun struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*TestTun, error) {
|
func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*TestTun, error) {
|
||||||
_, routes, err := getAllRoutesFromConfig(l, c, vpnNetworks, true)
|
_, routes, err := getAllRoutesFromConfig(c, vpnNetworks, true)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
+6
-77
@@ -4,7 +4,6 @@ package overlay
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"crypto"
|
"crypto"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
@@ -76,7 +75,7 @@ func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*w
|
|||||||
t := &winTun{
|
t := &winTun{
|
||||||
Device: deviceName,
|
Device: deviceName,
|
||||||
vpnNetworks: vpnNetworks,
|
vpnNetworks: vpnNetworks,
|
||||||
MTU: getMTU(l, c),
|
MTU: c.GetInt("tun.mtu", DefaultMTU),
|
||||||
guid: *guid,
|
guid: *guid,
|
||||||
networkCategory: cat,
|
networkCategory: cat,
|
||||||
setCategory: setCat,
|
setCategory: setCat,
|
||||||
@@ -119,7 +118,7 @@ func newTun(c *config.C, l *slog.Logger, vpnNetworks []netip.Prefix, _ bool) (*w
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (t *winTun) reload(c *config.C, initial bool) error {
|
func (t *winTun) reload(c *config.C, initial bool) error {
|
||||||
change, routes, err := getAllRoutesFromConfig(t.l, c, t.vpnNetworks, initial)
|
change, routes, err := getAllRoutesFromConfig(c, t.vpnNetworks, initial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -139,7 +138,7 @@ func (t *winTun) reload(c *config.C, initial bool) error {
|
|||||||
|
|
||||||
if !initial {
|
if !initial {
|
||||||
// Remove first, if the system removes a wanted route hopefully it will be re-added next
|
// Remove first, if the system removes a wanted route hopefully it will be re-added next
|
||||||
err := t.removeRoutes(findRemovedSystemRoutes(routes, *oldRoutes))
|
err := t.removeRoutes(findRemovedRoutes(routes, *oldRoutes))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
util.LogWithContextIfNeeded("Failed to remove routes", err, t.l)
|
util.LogWithContextIfNeeded("Failed to remove routes", err, t.l)
|
||||||
}
|
}
|
||||||
@@ -188,27 +187,17 @@ func (t *winTun) addRoutes(logErrors bool) error {
|
|||||||
foundDefault4 := false
|
foundDefault4 := false
|
||||||
carriesV6 := slices.ContainsFunc(t.vpnNetworks, func(p netip.Prefix) bool { return p.Addr().Is6() })
|
carriesV6 := slices.ContainsFunc(t.vpnNetworks, func(p netip.Prefix) bool { return p.Addr().Is6() })
|
||||||
|
|
||||||
// A CIDR listed twice routes by its last entry, install only that one or each reload would flip between them. The
|
for _, r := range routes {
|
||||||
// same rule as systemRoutes
|
|
||||||
last := make(map[netip.Prefix]int, len(routes))
|
|
||||||
for i, r := range routes {
|
|
||||||
last[r.Cidr] = i
|
|
||||||
}
|
|
||||||
|
|
||||||
for i, r := range routes {
|
|
||||||
if len(r.Via) == 0 || !r.Install {
|
if len(r.Via) == 0 || !r.Install {
|
||||||
// We don't allow route MTUs so only install routes with a via
|
// We don't allow route MTUs so only install routes with a via
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if last[r.Cidr] != i {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
// A v6 unsafe_route is legal under a v4-only cert; uninstalled ones put nothing on the adapter.
|
// A v6 unsafe_route is legal under a v4-only cert; uninstalled ones put nothing on the adapter.
|
||||||
carriesV6 = carriesV6 || r.Cidr.Addr().Is6()
|
carriesV6 = carriesV6 || r.Cidr.Addr().Is6()
|
||||||
|
|
||||||
// Add our unsafe route as an on-link route to the nebula tun device.
|
// Add our unsafe route as an on-link route to the nebula tun device.
|
||||||
result, err := addRoute(luid, r)
|
err := luid.AddRoute(r.Cidr, unspecifiedNextHop(r.Cidr), uint32(r.Metric))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
|
retErr := util.NewContextualError("Failed to add route", map[string]any{"route": r}, err)
|
||||||
if logErrors {
|
if logErrors {
|
||||||
@@ -218,12 +207,7 @@ func (t *winTun) addRoutes(logErrors bool) error {
|
|||||||
return retErr
|
return retErr
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
switch result {
|
t.l.Info("Added route", "route", r)
|
||||||
case routeAdded:
|
|
||||||
t.l.Info("Added route", "route", r)
|
|
||||||
case routeMetricUpdated:
|
|
||||||
t.l.Info("Updated route metric", "route", r)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if !foundDefault4 {
|
if !foundDefault4 {
|
||||||
@@ -335,61 +319,6 @@ func (t *winTun) Close() error {
|
|||||||
return t.tun.Close()
|
return t.tun.Close()
|
||||||
}
|
}
|
||||||
|
|
||||||
// systemRoutes maps each CIDR to the route that puts it in the system table. A CIDR's last entry decides, including
|
|
||||||
// one that says not to install it
|
|
||||||
func systemRoutes(routes []Route) map[netip.Prefix]Route {
|
|
||||||
out := make(map[netip.Prefix]Route, len(routes))
|
|
||||||
for _, r := range routes {
|
|
||||||
if len(r.Via) > 0 && r.Install {
|
|
||||||
out[r.Cidr] = r
|
|
||||||
} else {
|
|
||||||
delete(out, r.Cidr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
// findRemovedSystemRoutes is the routes to delete from the system table. Windows deletes by destination and next hop,
|
|
||||||
// so only a CIDR nothing installs anymore goes, a changed metric is set on the route in place by addRoute
|
|
||||||
func findRemovedSystemRoutes(newRoutes, oldRoutes []Route) []Route {
|
|
||||||
keep := systemRoutes(newRoutes)
|
|
||||||
var removed []Route
|
|
||||||
for _, r := range systemRoutes(oldRoutes) {
|
|
||||||
if _, ok := keep[r.Cidr]; !ok {
|
|
||||||
removed = append(removed, r)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return removed
|
|
||||||
}
|
|
||||||
|
|
||||||
type routeResult int
|
|
||||||
|
|
||||||
const (
|
|
||||||
routeAdded routeResult = iota
|
|
||||||
routeMetricUpdated
|
|
||||||
routeAlreadyInstalled
|
|
||||||
)
|
|
||||||
|
|
||||||
// addRoute installs r on the interface. A reload re-adds every route to catch any the system dropped, and Windows
|
|
||||||
// refuses one it has with the same destination and next hop whatever its metric. One that is there with another
|
|
||||||
// metric, ours from before a metric change or someone else's, is brought to ours in place
|
|
||||||
func addRoute(luid winipcfg.LUID, r Route) (routeResult, error) {
|
|
||||||
nextHop := unspecifiedNextHop(r.Cidr)
|
|
||||||
err := luid.AddRoute(r.Cidr, nextHop, uint32(r.Metric))
|
|
||||||
if !errors.Is(err, windows.ERROR_OBJECT_ALREADY_EXISTS) {
|
|
||||||
return routeAdded, err
|
|
||||||
}
|
|
||||||
row, err := luid.Route(r.Cidr, nextHop)
|
|
||||||
if err != nil {
|
|
||||||
return routeAlreadyInstalled, err
|
|
||||||
}
|
|
||||||
if row.Metric != uint32(r.Metric) {
|
|
||||||
row.Metric = uint32(r.Metric)
|
|
||||||
return routeMetricUpdated, row.Set()
|
|
||||||
}
|
|
||||||
return routeAlreadyInstalled, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func unspecifiedNextHop(p netip.Prefix) netip.Addr {
|
func unspecifiedNextHop(p netip.Prefix) netip.Addr {
|
||||||
if p.Addr().Is4() {
|
if p.Addr().Is4() {
|
||||||
return netip.IPv4Unspecified()
|
return netip.IPv4Unspecified()
|
||||||
|
|||||||
@@ -1,168 +0,0 @@
|
|||||||
//go:build windows && !e2e_testing
|
|
||||||
|
|
||||||
package overlay
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"fmt"
|
|
||||||
"net/netip"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/slackhq/nebula/config"
|
|
||||||
"github.com/slackhq/nebula/test"
|
|
||||||
"github.com/stretchr/testify/assert"
|
|
||||||
"github.com/stretchr/testify/require"
|
|
||||||
"golang.org/x/sys/windows"
|
|
||||||
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
|
|
||||||
)
|
|
||||||
|
|
||||||
type routeTest struct {
|
|
||||||
c *config.C
|
|
||||||
tun *winTun
|
|
||||||
luid winipcfg.LUID
|
|
||||||
log *bytes.Buffer
|
|
||||||
}
|
|
||||||
|
|
||||||
// newRouteTest makes a wintun device of its own, before installing tun.unsafe_routes from cfg
|
|
||||||
func newRouteTest(t *testing.T, cfg string) *routeTest {
|
|
||||||
t.Helper()
|
|
||||||
if !windows.GetCurrentProcessToken().IsElevated() {
|
|
||||||
t.Skip("creating a wintun device needs an elevated process")
|
|
||||||
}
|
|
||||||
if err := checkWinTunExists(); err != nil {
|
|
||||||
t.Skipf("wintun.dll is not where nebula looks for it: %v", err)
|
|
||||||
}
|
|
||||||
rt := &routeTest{log: &bytes.Buffer{}}
|
|
||||||
l := test.NewLoggerWithOutput(rt.log)
|
|
||||||
rt.c = config.NewC(l)
|
|
||||||
require.NoError(t, rt.c.LoadString(cfg))
|
|
||||||
var err error
|
|
||||||
rt.tun, err = newTun(rt.c, l, []netip.Prefix{netip.MustParsePrefix("10.250.0.1/24")}, false)
|
|
||||||
require.NoError(t, err)
|
|
||||||
t.Cleanup(func() { _ = rt.tun.Close() })
|
|
||||||
rt.luid = winipcfg.LUID(rt.tun.tun.LUID())
|
|
||||||
return rt
|
|
||||||
}
|
|
||||||
|
|
||||||
func (rt *routeTest) metric(t *testing.T, cidr string) uint32 {
|
|
||||||
t.Helper()
|
|
||||||
p := netip.MustParsePrefix(cidr)
|
|
||||||
row, err := rt.luid.Route(p, unspecifiedNextHop(p))
|
|
||||||
require.NoError(t, err)
|
|
||||||
return row.Metric
|
|
||||||
}
|
|
||||||
|
|
||||||
func unsafeRoutes(routes ...string) string {
|
|
||||||
var b strings.Builder
|
|
||||||
b.WriteString("tun:\n dev: nebroutetest\n unsafe_routes:\n")
|
|
||||||
// cidr[@metric][!], the ! for install: false
|
|
||||||
for _, r := range routes {
|
|
||||||
r, noInstall := strings.CutSuffix(r, "!")
|
|
||||||
cidr, metric, _ := strings.Cut(r, "@")
|
|
||||||
fmt.Fprintf(&b, " - route: %s\n via: 10.250.0.2\n", cidr)
|
|
||||||
if metric != "" {
|
|
||||||
fmt.Fprintf(&b, " metric: %s\n", metric)
|
|
||||||
}
|
|
||||||
if noInstall {
|
|
||||||
b.WriteString(" install: false\n")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return b.String()
|
|
||||||
}
|
|
||||||
|
|
||||||
// A reload that adds a route re-adds the ones already installed, Windows refusing those as already there isn't a failure
|
|
||||||
func TestWinTun_ReloadKeepsInstalledRoutes(t *testing.T) {
|
|
||||||
forFamilies(t, func(t *testing.T, a, b string) {
|
|
||||||
rt := newRouteTest(t, unsafeRoutes(a))
|
|
||||||
require.NoError(t, rt.tun.Activate())
|
|
||||||
|
|
||||||
require.NoError(t, rt.c.ReloadConfigString(unsafeRoutes(a, b)))
|
|
||||||
assert.NotContains(t, rt.log.String(), "Failed to add route")
|
|
||||||
rt.metric(t, a)
|
|
||||||
rt.metric(t, b)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Windows calls a route the same by destination and next hop, so a changed metric is set on the installed route in
|
|
||||||
// place rather than deleted and added, which would leave a moment with no route
|
|
||||||
func TestWinTun_ReloadMetricChangeApplies(t *testing.T) {
|
|
||||||
forFamilies(t, func(t *testing.T, a, b string) {
|
|
||||||
rt := newRouteTest(t, unsafeRoutes(a+"@100"))
|
|
||||||
require.NoError(t, rt.tun.Activate())
|
|
||||||
require.Equal(t, uint32(100), rt.metric(t, a))
|
|
||||||
|
|
||||||
require.NoError(t, rt.c.ReloadConfigString(unsafeRoutes(a+"@200")))
|
|
||||||
assert.NotContains(t, rt.log.String(), "Failed to add route")
|
|
||||||
assert.NotContains(t, rt.log.String(), "Removed route")
|
|
||||||
assert.Equal(t, uint32(200), rt.metric(t, a))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// A route someone else put on the device with another metric is brought to ours, at startup too
|
|
||||||
func TestWinTun_ForeignRouteGetsOurMetric(t *testing.T) {
|
|
||||||
forFamilies(t, func(t *testing.T, a, b string) {
|
|
||||||
rt := newRouteTest(t, unsafeRoutes(a+"@100"))
|
|
||||||
p := netip.MustParsePrefix(a)
|
|
||||||
require.NoError(t, rt.luid.AddRoute(p, unspecifiedNextHop(p), 50))
|
|
||||||
|
|
||||||
require.NoError(t, rt.tun.Activate())
|
|
||||||
assert.Equal(t, uint32(100), rt.metric(t, a))
|
|
||||||
assert.Contains(t, rt.log.String(), "level=INFO msg=\"Updated route metric\"")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// A CIDR listed twice is installed once, by its last entry, and reloads leave it there instead of flipping between the
|
|
||||||
// two metrics
|
|
||||||
func TestWinTun_DuplicateCidrInstallsTheLastEntry(t *testing.T) {
|
|
||||||
forFamilies(t, func(t *testing.T, a, b string) {
|
|
||||||
rt := newRouteTest(t, unsafeRoutes(a+"@100", a+"@200"))
|
|
||||||
require.NoError(t, rt.tun.Activate())
|
|
||||||
assert.Equal(t, uint32(200), rt.metric(t, a))
|
|
||||||
|
|
||||||
require.NoError(t, rt.c.ReloadConfigString(unsafeRoutes(a+"@100", a+"@200", b)))
|
|
||||||
assert.Equal(t, uint32(200), rt.metric(t, a))
|
|
||||||
assert.NotContains(t, rt.log.String(), "Updated route metric")
|
|
||||||
assert.NotContains(t, rt.log.String(), "Failed to add route")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// Dropping the duplicate that wasn't installed leaves the installed route alone. Windows deletes by destination and
|
|
||||||
// next hop, deleting the dropped one would take the live route with it
|
|
||||||
func TestWinTun_DroppingAnUninstalledDuplicateKeepsTheRoute(t *testing.T) {
|
|
||||||
forFamilies(t, func(t *testing.T, a, b string) {
|
|
||||||
rt := newRouteTest(t, unsafeRoutes(a+"@100", a+"@200"))
|
|
||||||
require.NoError(t, rt.tun.Activate())
|
|
||||||
|
|
||||||
require.NoError(t, rt.c.ReloadConfigString(unsafeRoutes(a+"@200")))
|
|
||||||
assert.NotContains(t, rt.log.String(), "Removed route")
|
|
||||||
assert.Equal(t, uint32(200), rt.metric(t, a))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// A reload ends where a fresh start with the same config would, a CIDR whose last entry says not to install it is
|
|
||||||
// removed
|
|
||||||
func TestWinTun_ReloadMatchesAFreshStart(t *testing.T) {
|
|
||||||
forFamilies(t, func(t *testing.T, a, b string) {
|
|
||||||
cidr := netip.MustParsePrefix(a)
|
|
||||||
routes := unsafeRoutes(a+"@100", a+"@100!")
|
|
||||||
|
|
||||||
fresh := newRouteTest(t, routes)
|
|
||||||
require.NoError(t, fresh.tun.Activate())
|
|
||||||
_, err := fresh.luid.Route(cidr, unspecifiedNextHop(cidr))
|
|
||||||
require.Error(t, err, "a fresh start installed it")
|
|
||||||
require.NoError(t, fresh.tun.Close())
|
|
||||||
|
|
||||||
rt := newRouteTest(t, unsafeRoutes(a+"@100"))
|
|
||||||
require.NoError(t, rt.tun.Activate())
|
|
||||||
require.NoError(t, rt.c.ReloadConfigString(routes))
|
|
||||||
_, err = rt.luid.Route(cidr, unspecifiedNextHop(cidr))
|
|
||||||
assert.Error(t, err, "the reload left it installed")
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// forFamilies runs f with two unsafe_routes CIDRs of each address family, the tun's own network stays IPv4
|
|
||||||
func forFamilies(t *testing.T, f func(t *testing.T, a, b string)) {
|
|
||||||
t.Run("ipv4", func(t *testing.T) { f(t, "10.251.1.0/24", "10.251.2.0/24") })
|
|
||||||
t.Run("ipv6", func(t *testing.T) { f(t, "fd00:251:1::/64", "fd00:251:2::/64") })
|
|
||||||
}
|
|
||||||
@@ -30,7 +30,7 @@ func procyield(cycles uint32)
|
|||||||
|
|
||||||
const (
|
const (
|
||||||
packetsPerRing = 1024
|
packetsPerRing = 1024
|
||||||
// Fits a relayed packet at overlay.MaxMTU, which tun.mtu and route mtus are capped to. 17.6MB page locked per socket.
|
// Caps tun.mtu at MTU-32 direct, MTU-64 relayed, unenforced anywhere else. 17.6MB page locked per socket.
|
||||||
bytesPerPacket = MTU
|
bytesPerPacket = MTU
|
||||||
receiveSpins = 15
|
receiveSpins = 15
|
||||||
)
|
)
|
||||||
|
|||||||
Reference in new issue
Block a user