mirror of
https://github.com/slackhq/nebula.git
synced 2026-08-15 09:07:00 +02:00
Compare commits
31 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8e320d5384 | |||
| e5d17af0de | |||
| f671406b82 | |||
| 448f06a378 | |||
| 8e607a91f4 | |||
| c72a37c16f | |||
| 610fcdb9bf | |||
| bb3c70da2e | |||
| 2f50b3c54f | |||
| 0824035906 | |||
| 510a8912a9 | |||
| 0496ef101e | |||
| ae9de47dd9 | |||
| 4eb86afa54 | |||
| f36db374ac | |||
| 7ac51c1af2 | |||
| dabce8a1b4 | |||
| 6b78e9cdb3 | |||
| b445d14ddb | |||
| 6606124bf9 | |||
| 05405bc261 | |||
| b033267d6e | |||
| 659d7fece6 | |||
| f2aef0d6eb | |||
| a2b9747b0f | |||
| 0e593ad582 | |||
| 28ecfcbc03 | |||
| e71059a410 | |||
| aec7f5f865 | |||
| 6d8e939648 | |||
| 326fc8758d |
@@ -60,4 +60,12 @@ jobs:
|
||||
working-directory: ./.github/workflows/smoke
|
||||
run: NAME="smoke-p256" ./smoke.sh
|
||||
|
||||
- name: setup docker image for multiport
|
||||
working-directory: ./.github/workflows/smoke
|
||||
run: NAME="smoke-multiport" MULTIPORT_TX=true MULTIPORT_RX=true MULTIPORT_HANDSHAKE=true ./build.sh
|
||||
|
||||
- name: run smoke
|
||||
working-directory: ./.github/workflows/smoke
|
||||
run: NAME="smoke-multiport" ./smoke.sh
|
||||
|
||||
timeout-minutes: 10
|
||||
|
||||
@@ -48,6 +48,10 @@ listen:
|
||||
|
||||
tun:
|
||||
dev: ${TUN_DEV:-tun0}
|
||||
multiport:
|
||||
tx_enabled: ${MULTIPORT_TX:-false}
|
||||
rx_enabled: ${MULTIPORT_RX:-false}
|
||||
tx_handshake: ${MULTIPORT_HANDSHAKE:-false}
|
||||
|
||||
firewall:
|
||||
inbound_action: reject
|
||||
|
||||
@@ -268,6 +268,10 @@ smoke-relay-docker: bin-docker
|
||||
cd .github/workflows/smoke/ && ./build-relay.sh
|
||||
cd .github/workflows/smoke/ && ./smoke-relay.sh
|
||||
|
||||
smoke-multiport-docker: bin-docker
|
||||
cd .github/workflows/smoke/ && NAME="smoke-multiport" MULTIPORT_TX=true MULTIPORT_RX=true MULTIPORT_HANDSHAKE=true ./build.sh
|
||||
cd .github/workflows/smoke/ && NAME="smoke-multiport" ./smoke.sh
|
||||
|
||||
smoke-docker-ipv6: export SMOKE_OVERLAY_IPV6 = 1
|
||||
smoke-docker-ipv6: smoke-docker
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
package config
|
||||
|
||||
type MultiPortConfig struct {
|
||||
Tx bool
|
||||
Rx bool
|
||||
TxBasePort uint16
|
||||
TxPorts int
|
||||
TxHandshake bool
|
||||
TxHandshakeDelay int64
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/flynn/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/handshake"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -55,6 +56,7 @@ func runTestHandshake(t *testing.T) (initR, respR *handshake.Result) {
|
||||
cert.Version2, initCreds, verifier,
|
||||
func() (uint32, error) { return 1000, nil },
|
||||
true, header.HandshakeIXPSK0,
|
||||
config.MultiPortConfig{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -62,6 +64,7 @@ func runTestHandshake(t *testing.T) (initR, respR *handshake.Result) {
|
||||
cert.Version2, respCreds, verifier,
|
||||
func() (uint32, error) { return 2000, nil },
|
||||
false, header.HandshakeIXPSK0,
|
||||
config.MultiPortConfig{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
|
||||
@@ -328,6 +328,47 @@ tun:
|
||||
# SO_RCVBUFFORCE is used to avoid having to raise the system wide max
|
||||
#use_system_route_table_buffer_size: 0
|
||||
|
||||
# EXPERIMENTAL: This option may change or disappear in the future.
|
||||
# Multiport spreads outgoing UDP packets across multiple UDP send ports,
|
||||
# which allows nebula to work around any issues on the underlay network.
|
||||
# Some example issues this could work around:
|
||||
# - UDP rate limits on a per flow basis.
|
||||
# - Partial underlay network failure in which some flows work and some don't
|
||||
# Agreement is done during the handshake to decide if multiport mode will
|
||||
# be used for a given tunnel (one side must have tx_enabled set, the other
|
||||
# side must have rx_enabled set)
|
||||
#
|
||||
# NOTE: you cannot use multiport on a host if you are relying on UDP hole
|
||||
# punching to get through a NAT or firewall.
|
||||
#
|
||||
# NOTE: Linux only (uses raw sockets to send). Also currently only works
|
||||
# with IPv4 underlay network remotes.
|
||||
#
|
||||
# The default values are listed below:
|
||||
#multiport:
|
||||
# This host support sending via multiple UDP ports.
|
||||
#tx_enabled: false
|
||||
#
|
||||
# This host supports receiving packets sent from multiple UDP ports.
|
||||
#rx_enabled: false
|
||||
#
|
||||
# How many UDP ports to use when sending. The lowest source port will be
|
||||
# listen.port and go up to (but not including) listen.port + tx_ports.
|
||||
#tx_ports: 100
|
||||
#
|
||||
# NOTE: All of your hosts must be running a version of Nebula that supports
|
||||
# multiport if you want to enable this feature. Older versions of Nebula
|
||||
# will be confused by these multiport handshakes.
|
||||
#
|
||||
# If handshakes are not getting a response, attempt to transmit handshakes
|
||||
# using random UDP source ports (to get around partial underlay network
|
||||
# failures).
|
||||
#tx_handshake: false
|
||||
#
|
||||
# How many unresponded handshakes we should send before we attempt to
|
||||
# send multiport handshakes.
|
||||
#tx_handshake_delay: 2
|
||||
|
||||
# Configure logging level
|
||||
logging:
|
||||
# trace, debug, info, warn, or error. Default is info and is reloadable.
|
||||
|
||||
@@ -3,6 +3,7 @@ package firewall
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
mathrand "math/rand"
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
@@ -65,3 +66,30 @@ func (fp Packet) MarshalJSON() ([]byte, error) {
|
||||
"Fragment": fp.Fragment,
|
||||
})
|
||||
}
|
||||
|
||||
// UDPSendPort calculates the UDP port to send from when using multiport mode.
|
||||
// The result will be from [0, numBuckets)
|
||||
func (fp Packet) UDPSendPort(numBuckets int) uint16 {
|
||||
if numBuckets <= 1 {
|
||||
return 0
|
||||
}
|
||||
|
||||
// If there is no port (like an ICMP packet), pick a random UDP send port
|
||||
if fp.LocalPort == 0 {
|
||||
return uint16(mathrand.Intn(numBuckets))
|
||||
}
|
||||
|
||||
// A decent enough 32bit hash function
|
||||
// Prospecting for Hash Functions
|
||||
// - https://nullprogram.com/blog/2018/07/31/
|
||||
// - https://github.com/skeeto/hash-prospector
|
||||
// [16 21f0aaad 15 d35a2d97 15] = 0.10760229515479501
|
||||
x := (uint32(fp.LocalPort) << 16) | uint32(fp.RemotePort)
|
||||
x ^= x >> 16
|
||||
x *= 0x21f0aaad
|
||||
x ^= x >> 15
|
||||
x *= 0xd35a2d97
|
||||
x ^= x >> 15
|
||||
|
||||
return uint16(x) % uint16(numBuckets)
|
||||
}
|
||||
|
||||
@@ -24,6 +24,14 @@ message NebulaHandshakeDetails {
|
||||
uint64 Cookie = 4 [deprecated = true];
|
||||
uint64 Time = 5;
|
||||
uint32 CertVersion = 8;
|
||||
// reserved for WIP multiport
|
||||
reserved 6, 7;
|
||||
|
||||
MultiPortDetails InitiatorMultiPort = 6;
|
||||
MultiPortDetails ResponderMultiPort = 7;
|
||||
}
|
||||
|
||||
message MultiPortDetails {
|
||||
bool RxSupported = 1;
|
||||
bool TxSupported = 2;
|
||||
uint32 BasePort = 3;
|
||||
uint32 TotalPorts = 4;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/flynn/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
@@ -71,6 +72,7 @@ func newTestMachine(
|
||||
cs.version, cs.getCredential,
|
||||
verifier, func() (uint32, error) { return localIndex, nil },
|
||||
initiator, header.HandshakeIXPSK0,
|
||||
config.MultiPortConfig{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return m
|
||||
|
||||
+43
-1
@@ -3,11 +3,13 @@ package handshake
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"math"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/flynn/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/header"
|
||||
)
|
||||
|
||||
@@ -39,6 +41,10 @@ type Result struct {
|
||||
HandshakeTime uint64
|
||||
MessageIndex uint64 // number of messages exchanged during the handshake
|
||||
Initiator bool
|
||||
|
||||
MultiportRx bool
|
||||
MultiportTx bool
|
||||
MultiportBasePort uint16
|
||||
}
|
||||
|
||||
// Machine drives a Noise handshake through N messages. It handles Noise
|
||||
@@ -67,6 +73,8 @@ type Machine struct {
|
||||
remoteCertSet bool
|
||||
payloadSet bool
|
||||
failed bool
|
||||
|
||||
multiport config.MultiPortConfig
|
||||
}
|
||||
|
||||
// NewMachine creates a handshake state machine. The subtype determines both
|
||||
@@ -80,6 +88,7 @@ func NewMachine(
|
||||
allocIndex IndexAllocator,
|
||||
initiator bool,
|
||||
subtype header.MessageSubType,
|
||||
multiport config.MultiPortConfig,
|
||||
) (*Machine, error) {
|
||||
info, err := subtypeInfoFor(subtype)
|
||||
if err != nil {
|
||||
@@ -108,6 +117,8 @@ func NewMachine(
|
||||
Initiator: initiator,
|
||||
Cipher: cred.cipherSuite,
|
||||
},
|
||||
|
||||
multiport: multiport,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -298,7 +309,7 @@ func (m *Machine) processPayload(msg []byte, flags msgFlags) error {
|
||||
}
|
||||
|
||||
// Assert the payload contains exactly what we expect
|
||||
hasPayloadData := payload.InitiatorIndex != 0 || payload.ResponderIndex != 0 || payload.Time != 0
|
||||
hasPayloadData := payload.InitiatorIndex != 0 || payload.ResponderIndex != 0 || payload.Time != 0 || payload.InitiatorMultiPort != nil || payload.ResponderMultiPort != nil
|
||||
if hasPayloadData != flags.expectsPayload {
|
||||
m.failed = true
|
||||
return ErrUnexpectedContent
|
||||
@@ -315,8 +326,22 @@ func (m *Machine) processPayload(msg []byte, flags msgFlags) error {
|
||||
var remoteIndex uint32
|
||||
if m.result.Initiator {
|
||||
remoteIndex = payload.ResponderIndex
|
||||
if payload.ResponderMultiPort != nil {
|
||||
m.result.MultiportRx = payload.ResponderMultiPort.RxSupported
|
||||
m.result.MultiportTx = payload.ResponderMultiPort.TxSupported
|
||||
if payload.ResponderMultiPort.BasePort <= math.MaxUint16 {
|
||||
m.result.MultiportBasePort = uint16(payload.ResponderMultiPort.BasePort)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
remoteIndex = payload.InitiatorIndex
|
||||
if payload.InitiatorMultiPort != nil {
|
||||
m.result.MultiportRx = payload.InitiatorMultiPort.RxSupported
|
||||
m.result.MultiportTx = payload.InitiatorMultiPort.TxSupported
|
||||
if payload.InitiatorMultiPort.BasePort <= math.MaxUint16 {
|
||||
m.result.MultiportBasePort = uint16(payload.InitiatorMultiPort.BasePort)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The payload presence check above can be satisfied by Time alone, so a payload
|
||||
// could still carry a zero index here. We need to reject it.
|
||||
@@ -397,11 +422,28 @@ func (m *Machine) marshalOutgoing(flags msgFlags) ([]byte, error) {
|
||||
|
||||
if m.result.Initiator {
|
||||
p.InitiatorIndex = m.result.LocalIndex
|
||||
if m.multiport.Rx || m.multiport.Tx {
|
||||
p.InitiatorMultiPort = &PayloadMultiPortDetails{
|
||||
RxSupported: m.multiport.Rx,
|
||||
TxSupported: m.multiport.Tx,
|
||||
BasePort: uint32(m.multiport.TxBasePort),
|
||||
TotalPorts: uint32(m.multiport.TxPorts),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
p.ResponderIndex = m.result.LocalIndex
|
||||
p.InitiatorIndex = m.result.RemoteIndex
|
||||
if m.multiport.Rx || m.multiport.Tx {
|
||||
p.ResponderMultiPort = &PayloadMultiPortDetails{
|
||||
RxSupported: m.multiport.Rx,
|
||||
TxSupported: m.multiport.Tx,
|
||||
BasePort: uint32(m.multiport.TxBasePort),
|
||||
TotalPorts: uint32(m.multiport.TxPorts),
|
||||
}
|
||||
}
|
||||
}
|
||||
p.Time = uint64(time.Now().UnixNano())
|
||||
|
||||
}
|
||||
if flags.expectsCert {
|
||||
cred := m.getCred(m.myVersion)
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/flynn/noise"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
ct "github.com/slackhq/nebula/cert_test"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -444,6 +445,7 @@ func TestMachineThreeMessagePattern(t *testing.T) {
|
||||
initCS.getCredential, v,
|
||||
func() (uint32, error) { return 1000, nil },
|
||||
true, header.HandshakeXXPSK0,
|
||||
config.MultiPortConfig{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
@@ -452,6 +454,7 @@ func TestMachineThreeMessagePattern(t *testing.T) {
|
||||
respCS.getCredential, v,
|
||||
func() (uint32, error) { return 2000, nil },
|
||||
false, header.HandshakeXXPSK0,
|
||||
config.MultiPortConfig{},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
|
||||
|
||||
@@ -20,6 +20,16 @@ type Payload struct {
|
||||
ResponderIndex uint32
|
||||
Time uint64
|
||||
CertVersion uint32
|
||||
|
||||
InitiatorMultiPort *PayloadMultiPortDetails
|
||||
ResponderMultiPort *PayloadMultiPortDetails
|
||||
}
|
||||
|
||||
type PayloadMultiPortDetails struct {
|
||||
RxSupported bool
|
||||
TxSupported bool
|
||||
BasePort uint32
|
||||
TotalPorts uint32
|
||||
}
|
||||
|
||||
// Proto field numbers for NebulaHandshakeDetails
|
||||
@@ -29,6 +39,17 @@ const (
|
||||
fieldResponderIndex = 3 // uint32
|
||||
fieldTime = 5 // uint64
|
||||
fieldCertVersion = 8 // uint32
|
||||
|
||||
fieldInitiatorMultiPort = 6 // MultiPortDetails
|
||||
fieldResponderMultiPort = 7 // MultiPortDetails
|
||||
)
|
||||
|
||||
// Proto field numbers for MultiPortDetails
|
||||
const (
|
||||
fieldMultiportRxSupported = 1 // bool
|
||||
fieldMultiportTxSupported = 2 // bool
|
||||
fieldMultiportBasePort = 3 // uint32
|
||||
fieldMultiportTotalPorts = 4 // uint32
|
||||
)
|
||||
|
||||
// MarshalPayload encodes a handshake payload in protobuf wire format compatible
|
||||
@@ -57,6 +78,16 @@ func MarshalPayload(out []byte, p Payload) []byte {
|
||||
details = protowire.AppendTag(details, fieldCertVersion, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, uint64(p.CertVersion))
|
||||
}
|
||||
if p.InitiatorMultiPort != nil {
|
||||
details = protowire.AppendTag(details, fieldInitiatorMultiPort, protowire.BytesType)
|
||||
details = protowire.AppendVarint(details, uint64(p.InitiatorMultiPort.size()))
|
||||
details = p.InitiatorMultiPort.marshal(details)
|
||||
}
|
||||
if p.ResponderMultiPort != nil {
|
||||
details = protowire.AppendTag(details, fieldResponderMultiPort, protowire.BytesType)
|
||||
details = protowire.AppendVarint(details, uint64(p.ResponderMultiPort.size()))
|
||||
details = p.ResponderMultiPort.marshal(details)
|
||||
}
|
||||
|
||||
out = protowire.AppendTag(out, 1, protowire.BytesType)
|
||||
out = protowire.AppendBytes(out, details)
|
||||
@@ -64,6 +95,23 @@ func MarshalPayload(out []byte, p Payload) []byte {
|
||||
return out
|
||||
}
|
||||
|
||||
func (p PayloadMultiPortDetails) marshal(details []byte) []byte {
|
||||
details = protowire.AppendTag(details, fieldMultiportRxSupported, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, protowire.EncodeBool(p.RxSupported))
|
||||
details = protowire.AppendTag(details, fieldMultiportTxSupported, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, protowire.EncodeBool(p.TxSupported))
|
||||
details = protowire.AppendTag(details, fieldMultiportBasePort, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, uint64(p.BasePort))
|
||||
details = protowire.AppendTag(details, fieldMultiportTotalPorts, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, uint64(p.TotalPorts))
|
||||
|
||||
return details
|
||||
}
|
||||
|
||||
func (p PayloadMultiPortDetails) size() int {
|
||||
return 4 + 2 + protowire.SizeVarint(uint64(p.BasePort)) + protowire.SizeVarint(uint64(p.TotalPorts))
|
||||
}
|
||||
|
||||
// UnmarshalPayload decodes a protobuf-encoded NebulaHandshake message.
|
||||
func UnmarshalPayload(b []byte) (Payload, error) {
|
||||
var p Payload
|
||||
@@ -161,6 +209,97 @@ func unmarshalPayloadDetails(p *Payload, b []byte) error {
|
||||
}
|
||||
p.CertVersion = uint32(v)
|
||||
b = b[n:]
|
||||
case fieldInitiatorMultiPort:
|
||||
if typ != protowire.BytesType {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
d, n := protowire.ConsumeBytes(b)
|
||||
if n < 0 {
|
||||
return errInvalidHandshakeMessage
|
||||
}
|
||||
b = b[n:]
|
||||
p.InitiatorMultiPort = new(PayloadMultiPortDetails)
|
||||
if err := unmarshalPayloadMultiPortDetails(p.InitiatorMultiPort, d); err != nil {
|
||||
return err
|
||||
}
|
||||
case fieldResponderMultiPort:
|
||||
if typ != protowire.BytesType {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
d, n := protowire.ConsumeBytes(b)
|
||||
if n < 0 {
|
||||
return errInvalidHandshakeMessage
|
||||
}
|
||||
b = b[n:]
|
||||
p.ResponderMultiPort = new(PayloadMultiPortDetails)
|
||||
if err := unmarshalPayloadMultiPortDetails(p.ResponderMultiPort, d); err != nil {
|
||||
return err
|
||||
}
|
||||
default:
|
||||
n := protowire.ConsumeFieldValue(num, typ, b)
|
||||
if n < 0 {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
b = b[n:]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unmarshalPayloadMultiPortDetails(p *PayloadMultiPortDetails, b []byte) error {
|
||||
for len(b) > 0 {
|
||||
num, typ, n := protowire.ConsumeTag(b)
|
||||
if n < 0 {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
b = b[n:]
|
||||
|
||||
// For known field numbers, reject any non-matching wire type as a
|
||||
// hard error rather than silently skipping. The caller will catch
|
||||
// missing-field cases downstream, but a wire-type mismatch on a tag
|
||||
// we know is a peer protocol violation worth flagging here.
|
||||
// Repeated occurrences of a singular field follow proto3 last-wins.
|
||||
switch num {
|
||||
case fieldMultiportRxSupported:
|
||||
if typ != protowire.VarintType {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
v, n := protowire.ConsumeVarint(b)
|
||||
if n < 0 || v > math.MaxUint32 {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
p.RxSupported = protowire.DecodeBool(v)
|
||||
b = b[n:]
|
||||
case fieldMultiportTxSupported:
|
||||
if typ != protowire.VarintType {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
v, n := protowire.ConsumeVarint(b)
|
||||
if n < 0 || v > math.MaxUint32 {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
p.TxSupported = protowire.DecodeBool(v)
|
||||
b = b[n:]
|
||||
case fieldMultiportBasePort:
|
||||
if typ != protowire.VarintType {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
v, n := protowire.ConsumeVarint(b)
|
||||
if n < 0 || v > math.MaxUint32 {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
p.BasePort = uint32(v)
|
||||
b = b[n:]
|
||||
case fieldMultiportTotalPorts:
|
||||
if typ != protowire.VarintType {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
v, n := protowire.ConsumeVarint(b)
|
||||
if n < 0 || v > math.MaxUint32 {
|
||||
return errInvalidHandshakeDetails
|
||||
}
|
||||
p.TotalPorts = uint32(v)
|
||||
b = b[n:]
|
||||
default:
|
||||
n := protowire.ConsumeFieldValue(num, typ, b)
|
||||
if n < 0 {
|
||||
|
||||
+16
-16
@@ -117,24 +117,24 @@ func TestPayloadUnknownFields(t *testing.T) {
|
||||
assert.Equal(t, uint32(88), got.ResponderIndex)
|
||||
})
|
||||
|
||||
t.Run("reserved fields 6 and 7 are skipped", func(t *testing.T) {
|
||||
// Fields 6 and 7 are reserved in the proto definition
|
||||
var details []byte
|
||||
details = protowire.AppendTag(details, fieldInitiatorIndex, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, 100)
|
||||
details = protowire.AppendTag(details, 6, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, 1)
|
||||
details = protowire.AppendTag(details, 7, protowire.VarintType)
|
||||
details = protowire.AppendVarint(details, 2)
|
||||
// t.Run("reserved fields 6 and 7 are skipped", func(t *testing.T) {
|
||||
// // Fields 6 and 7 are reserved in the proto definition
|
||||
// var details []byte
|
||||
// details = protowire.AppendTag(details, fieldInitiatorIndex, protowire.VarintType)
|
||||
// details = protowire.AppendVarint(details, 100)
|
||||
// details = protowire.AppendTag(details, 6, protowire.VarintType)
|
||||
// details = protowire.AppendVarint(details, 1)
|
||||
// details = protowire.AppendTag(details, 7, protowire.VarintType)
|
||||
// details = protowire.AppendVarint(details, 2)
|
||||
|
||||
var data []byte
|
||||
data = protowire.AppendTag(data, 1, protowire.BytesType)
|
||||
data = protowire.AppendBytes(data, details)
|
||||
// var data []byte
|
||||
// data = protowire.AppendTag(data, 1, protowire.BytesType)
|
||||
// data = protowire.AppendBytes(data, details)
|
||||
|
||||
got, err := UnmarshalPayload(data)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, uint32(100), got.InitiatorIndex)
|
||||
})
|
||||
// got, err := UnmarshalPayload(data)
|
||||
// require.NoError(t, err)
|
||||
// assert.Equal(t, uint32(100), got.InitiatorIndex)
|
||||
// })
|
||||
}
|
||||
|
||||
func TestPayloadBytesConsumed(t *testing.T) {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/cert"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"github.com/slackhq/nebula/handshake"
|
||||
"github.com/slackhq/nebula/header"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
@@ -71,6 +72,9 @@ type HandshakeManager struct {
|
||||
f *Interface
|
||||
l *slog.Logger
|
||||
|
||||
multiPort config.MultiPortConfig
|
||||
udpRaw *udp.RawConn
|
||||
|
||||
// can be used to trigger outbound handshake for the given vpnIp
|
||||
trigger chan netip.Addr
|
||||
}
|
||||
@@ -291,6 +295,7 @@ func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered
|
||||
|
||||
// Send the handshake to all known ips, stage 2 takes care of assigning the hostinfo.remote based on the first to reply
|
||||
var sentTo []netip.AddrPort
|
||||
var sentMultiport bool
|
||||
hostinfo.remotes.ForEach(hm.mainHostMap.GetPreferredRanges(), func(addr netip.AddrPort, _ bool) {
|
||||
hm.messageMetrics.Tx(header.Handshake, hh.machine.Subtype(), 1)
|
||||
err := hm.outside.WriteTo(stage0, addr)
|
||||
@@ -311,6 +316,29 @@ func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered
|
||||
} else {
|
||||
sentTo = append(sentTo, addr)
|
||||
}
|
||||
|
||||
// Attempt a multiport handshake if we are past the TxHandshakeDelay attempts
|
||||
if hm.multiPort.TxHandshake && hm.udpRaw != nil && hh.counter >= hm.multiPort.TxHandshakeDelay {
|
||||
sentMultiport = true
|
||||
// We need to re-allocate with 8 bytes at the start of SOCK_RAW
|
||||
raw := hostinfo.HandshakePacket[0x80]
|
||||
if raw == nil {
|
||||
raw = make([]byte, len(hostinfo.HandshakePacket[0])+udp.RawOverhead)
|
||||
copy(raw[udp.RawOverhead:], hostinfo.HandshakePacket[0])
|
||||
hostinfo.HandshakePacket[0x80] = raw
|
||||
}
|
||||
|
||||
hm.messageMetrics.Tx(header.Handshake, header.MessageSubType(hostinfo.HandshakePacket[0][1]), 1)
|
||||
err = hm.udpRaw.WriteTo(raw, udp.RandomSendPort.UDPSendPort(hm.multiPort.TxPorts), addr)
|
||||
if err != nil {
|
||||
hostinfo.logger(hm.l).Error("Failed to send handshake message",
|
||||
"error", err,
|
||||
"udpAddr", addr,
|
||||
"initiatorIndex", hostinfo.localIndexId,
|
||||
"handshake", hsFields,
|
||||
)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
// Don't be too noisy or confusing if we fail to send a handshake - if we don't get through we'll eventually log a timeout,
|
||||
@@ -320,6 +348,7 @@ func (hm *HandshakeManager) handleOutbound(vpnIp netip.Addr, lighthouseTriggered
|
||||
"udpAddrs", sentTo,
|
||||
"initiatorIndex", hostinfo.localIndexId,
|
||||
"handshake", hsFields,
|
||||
"multiportHandshake", sentMultiport,
|
||||
)
|
||||
} else if hm.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hostinfo.logger(hm.l).Debug("Handshake message sent",
|
||||
@@ -672,6 +701,7 @@ func (hm *HandshakeManager) buildStage0Packet(hh *HandshakeHostInfo) bool {
|
||||
v, cs.GetCredential,
|
||||
hm.certVerifier(), func() (uint32, error) { return hm.allocateIndex(hh) },
|
||||
true, header.HandshakeIXPSK0,
|
||||
hm.multiPort,
|
||||
)
|
||||
if err != nil {
|
||||
hm.f.l.Error("Failed to create handshake machine",
|
||||
@@ -713,6 +743,7 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
v, cs.GetCredential,
|
||||
hm.certVerifier(), func() (uint32, error) { return generateIndex(f.l) },
|
||||
false, header.HandshakeIXPSK0,
|
||||
hm.multiPort,
|
||||
)
|
||||
if err != nil {
|
||||
f.l.Error("Failed to create handshake machine", "from", via, "error", err)
|
||||
@@ -737,6 +768,12 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
return
|
||||
}
|
||||
|
||||
if !via.IsRelayed && result.MultiportTx && result.MultiportBasePort != via.UdpAddr.Port() {
|
||||
// The other side sent us a handshake from a different port, make sure
|
||||
// we send responses back to the BasePort
|
||||
via.UdpAddr = netip.AddrPortFrom(via.UdpAddr.Addr(), result.MultiportBasePort)
|
||||
}
|
||||
|
||||
remoteCert := result.RemoteCert
|
||||
if remoteCert == nil {
|
||||
f.l.Error("Handshake did not produce a peer certificate", "from", via)
|
||||
@@ -761,6 +798,8 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
relayForByAddr: map[netip.Addr]*Relay{},
|
||||
relayForByIdx: map[uint32]*Relay{},
|
||||
},
|
||||
multiportTx: hm.multiPort.Tx && result.MultiportRx,
|
||||
multiportRx: hm.multiPort.Rx && result.MultiportTx,
|
||||
}
|
||||
|
||||
msg := "Handshake message received"
|
||||
@@ -777,6 +816,8 @@ func (hm *HandshakeManager) beginHandshake(via ViaSender, packet []byte, h *head
|
||||
"initiatorIndex", result.RemoteIndex,
|
||||
"responderIndex", result.LocalIndex,
|
||||
"handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
|
||||
"multiportTx", hostinfo.multiportTx,
|
||||
"multiportRx", hostinfo.multiportRx,
|
||||
)
|
||||
|
||||
// packet aliases the listener's incoming buffer, so this copy must stay.
|
||||
@@ -867,6 +908,14 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
||||
return
|
||||
}
|
||||
|
||||
if !via.IsRelayed && result.MultiportTx && result.MultiportBasePort != via.UdpAddr.Port() {
|
||||
// The other side sent us a handshake from a different port, make sure
|
||||
// we send responses back to the BasePort
|
||||
via.UdpAddr = netip.AddrPortFrom(via.UdpAddr.Addr(), result.MultiportBasePort)
|
||||
}
|
||||
hostinfo.multiportTx = hm.multiPort.Tx && result.MultiportRx
|
||||
hostinfo.multiportRx = hm.multiPort.Rx && result.MultiportTx
|
||||
|
||||
// Handshake complete; build the ConnectionState now that we have keys and a verified peer cert.
|
||||
hostinfo.ConnectionState = newConnectionStateFromResult(result)
|
||||
|
||||
@@ -961,6 +1010,8 @@ func (hm *HandshakeManager) continueHandshake(via ViaSender, hh *HandshakeHostIn
|
||||
"handshake", m{"stage": uint64(machine.MessageIndex()), "style": header.SubTypeName(header.Handshake, machine.Subtype())},
|
||||
"durationNs", duration,
|
||||
"sentCachedPackets", len(hh.packetStore),
|
||||
"multiportTx", hostinfo.multiportTx,
|
||||
"multiportRx", hostinfo.multiportRx,
|
||||
)
|
||||
|
||||
hostinfo.vpnAddrs = vpnAddrs
|
||||
@@ -1102,6 +1153,10 @@ func (hm *HandshakeManager) handleCheckAndCompleteError(err error, existing, hos
|
||||
|
||||
switch err {
|
||||
case ErrAlreadySeen:
|
||||
if hostinfo.multiportRx {
|
||||
// The other host is sending to us with multiport, so only grab the IP
|
||||
via.UdpAddr = netip.AddrPortFrom(via.UdpAddr.Addr(), hostinfo.GetRemote().Port())
|
||||
}
|
||||
if existing.SetRemoteIfPreferred(f.hostMap, via) {
|
||||
f.SendMessageToVpnAddr(header.Test, header.TestRequest, hostinfo.vpnAddrs[0], []byte(""), make([]byte, 12, 12), make([]byte, mtu))
|
||||
}
|
||||
|
||||
@@ -254,6 +254,12 @@ type HostInfo struct {
|
||||
networks *bart.Table[NetworkType]
|
||||
relayState RelayState
|
||||
|
||||
// If true, we should send to this remote using multiport
|
||||
multiportTx bool
|
||||
|
||||
// If true, we will receive from this remote using multiport
|
||||
multiportRx bool
|
||||
|
||||
// HandshakePacket records the packets used to create this hostinfo
|
||||
// We need these to avoid replayed handshake packets creating new hostinfos which causes churn
|
||||
HandshakePacket map[uint8][]byte
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/slackhq/nebula/iputil"
|
||||
"github.com/slackhq/nebula/noiseutil"
|
||||
"github.com/slackhq/nebula/routing"
|
||||
"github.com/slackhq/nebula/udp"
|
||||
)
|
||||
|
||||
func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet, nb, out []byte, q int, localCache firewall.ConntrackCache) {
|
||||
@@ -73,7 +74,7 @@ func (f *Interface) consumeInsidePacket(packet []byte, fwPacket *firewall.Packet
|
||||
|
||||
dropReason := f.firewall.Drop(*fwPacket, false, hostinfo, f.pki.GetCAPool(), localCache)
|
||||
if dropReason == nil {
|
||||
f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, nb, out, q)
|
||||
f.sendNoMetrics(header.Message, 0, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, packet, nb, out, q, fwPacket)
|
||||
|
||||
} else {
|
||||
f.rejectInside(packet, out, q)
|
||||
@@ -122,7 +123,7 @@ func (f *Interface) rejectOutside(packet []byte, ci *ConnectionState, hostinfo *
|
||||
return
|
||||
}
|
||||
|
||||
f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q)
|
||||
f.sendNoMetrics(header.Message, 0, ci, hostinfo, netip.AddrPort{}, out, nb, packet, q, nil)
|
||||
}
|
||||
|
||||
// Handshake will attempt to initiate a tunnel with the provided vpn address. This is a no-op if the tunnel is already established or being established
|
||||
@@ -235,7 +236,7 @@ func (f *Interface) sendMessageNow(t header.MessageType, st header.MessageSubTyp
|
||||
return
|
||||
}
|
||||
|
||||
f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0)
|
||||
f.sendNoMetrics(header.Message, st, hostinfo.ConnectionState, hostinfo, netip.AddrPort{}, p, nb, out, 0, nil)
|
||||
}
|
||||
|
||||
// SendMessageToVpnAddr handles real addr:port lookup and sends to the current best known address for vpnAddr.
|
||||
@@ -267,12 +268,12 @@ func (f *Interface) SendMessageToHostInfo(t header.MessageType, st header.Messag
|
||||
|
||||
func (f *Interface) send(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, p, nb, out []byte) {
|
||||
f.messageMetrics.Tx(t, st, 1)
|
||||
f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0)
|
||||
f.sendNoMetrics(t, st, ci, hostinfo, netip.AddrPort{}, p, nb, out, 0, nil)
|
||||
}
|
||||
|
||||
func (f *Interface) sendTo(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte) {
|
||||
f.messageMetrics.Tx(t, st, 1)
|
||||
f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0)
|
||||
f.sendNoMetrics(t, st, ci, hostinfo, remote, p, nb, out, 0, nil)
|
||||
}
|
||||
|
||||
// SendVia sends a payload through a Relay tunnel. No authentication or encryption is done
|
||||
@@ -340,10 +341,27 @@ func (f *Interface) SendVia(via *HostInfo,
|
||||
f.connectionManager.RelayUsed(relay.LocalIndex)
|
||||
}
|
||||
|
||||
func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int) {
|
||||
func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType, ci *ConnectionState, hostinfo *HostInfo, remote netip.AddrPort, p, nb, out []byte, q int, udpPortGetter udp.SendPortGetter) {
|
||||
if ci.eKey == nil {
|
||||
return
|
||||
}
|
||||
|
||||
multiport := f.multiPort.Tx && hostinfo.multiportTx
|
||||
rawOut := out
|
||||
if multiport {
|
||||
if len(out) < udp.RawOverhead {
|
||||
// NOTE: This is because some spots in the code send us `out[:0]`, so
|
||||
// we need to expand the slice back out to get our 8 bytes back.
|
||||
out = out[:udp.RawOverhead]
|
||||
}
|
||||
// Preserve bytes needed for the raw socket
|
||||
out = out[udp.RawOverhead:]
|
||||
|
||||
if udpPortGetter == nil {
|
||||
udpPortGetter = udp.RandomSendPort
|
||||
}
|
||||
}
|
||||
|
||||
useRelay := !remote.IsValid() && !hostinfo.GetRemote().IsValid()
|
||||
fullOut := out
|
||||
|
||||
@@ -396,7 +414,13 @@ func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType
|
||||
}
|
||||
|
||||
if remote.IsValid() {
|
||||
err = f.writers[q].WriteTo(out, remote)
|
||||
if multiport {
|
||||
rawOut = rawOut[:len(out)+udp.RawOverhead]
|
||||
port := udpPortGetter.UDPSendPort(f.multiPort.TxPorts)
|
||||
err = f.udpRaw.WriteTo(rawOut, port, remote)
|
||||
} else {
|
||||
err = f.writers[q].WriteTo(out, remote)
|
||||
}
|
||||
if err != nil {
|
||||
hostinfo.logger(f.l).Error("Failed to write outgoing packet",
|
||||
"error", err,
|
||||
@@ -404,7 +428,13 @@ func (f *Interface) sendNoMetrics(t header.MessageType, st header.MessageSubType
|
||||
)
|
||||
}
|
||||
} else if hr := hostinfo.GetRemote(); hr.IsValid() {
|
||||
err = f.writers[q].WriteTo(out, hr)
|
||||
if multiport {
|
||||
rawOut = rawOut[:len(out)+udp.RawOverhead]
|
||||
port := udpPortGetter.UDPSendPort(f.multiPort.TxPorts)
|
||||
err = f.udpRaw.WriteTo(rawOut, port, hr)
|
||||
} else {
|
||||
err = f.writers[q].WriteTo(out, hr)
|
||||
}
|
||||
if err != nil {
|
||||
hostinfo.logger(f.l).Error("Failed to write outgoing packet",
|
||||
"error", err,
|
||||
|
||||
@@ -99,6 +99,9 @@ type Interface struct {
|
||||
// triggerShutdown is a function that will be run exactly once, when onFatal swaps something non-nil into fatalErr
|
||||
triggerShutdown func()
|
||||
|
||||
udpRaw *udp.RawConn
|
||||
multiPort config.MultiPortConfig
|
||||
|
||||
metricHandshakes metrics.Histogram
|
||||
messageMetrics *MessageMetrics
|
||||
cachedPacketMetrics *cachedPacketMetrics
|
||||
@@ -106,6 +109,15 @@ type Interface struct {
|
||||
l *slog.Logger
|
||||
}
|
||||
|
||||
type MultiPortConfig struct {
|
||||
Tx bool
|
||||
Rx bool
|
||||
TxBasePort uint16
|
||||
TxPorts int
|
||||
TxHandshake bool
|
||||
TxHandshakeDelay int64
|
||||
}
|
||||
|
||||
type EncWriter interface {
|
||||
SendVia(via *HostInfo,
|
||||
relay *Relay,
|
||||
@@ -249,6 +261,8 @@ func (f *Interface) activate() error {
|
||||
|
||||
metrics.GetOrRegisterGauge("routines", nil).Update(int64(f.routines))
|
||||
|
||||
metrics.GetOrRegisterGauge("multiport.tx_ports", nil).Update(int64(f.multiPort.TxPorts))
|
||||
|
||||
// Prepare n tun queues
|
||||
var reader io.ReadWriteCloser = f.inside
|
||||
for i := 0; i < f.routines; i++ {
|
||||
@@ -505,6 +519,8 @@ func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
|
||||
|
||||
udpStats := udp.NewUDPStatsEmitter(f.writers)
|
||||
|
||||
var rawStats func()
|
||||
|
||||
certExpirationGauge := metrics.GetOrRegisterGauge("certificate.ttl_seconds", nil)
|
||||
certInitiatingVersion := metrics.GetOrRegisterGauge("certificate.initiating_version", nil)
|
||||
certMaxVersion := metrics.GetOrRegisterGauge("certificate.max_version", nil)
|
||||
@@ -519,6 +535,13 @@ func (f *Interface) emitStats(ctx context.Context, i time.Duration) {
|
||||
certExpirationGauge.Update(int64(defaultCrt.NotAfter().Sub(time.Now()) / time.Second))
|
||||
certInitiatingVersion.Update(int64(defaultCrt.Version()))
|
||||
|
||||
if f.udpRaw != nil {
|
||||
if rawStats == nil {
|
||||
rawStats = udp.NewRawStatsEmitter(f.udpRaw)
|
||||
}
|
||||
rawStats()
|
||||
}
|
||||
|
||||
// Report the max certificate version we are capable of using
|
||||
if certState.v2Cert != nil {
|
||||
certMaxVersion.Update(int64(certState.v2Cert.Version()))
|
||||
|
||||
@@ -244,6 +244,39 @@ func Main(c *config.C, configTest bool, buildVersion string, l *slog.Logger, dev
|
||||
ifce.writers = udpConns
|
||||
lightHouse.ifce = ifce
|
||||
|
||||
loadMultiPortConfig := func(c *config.C) {
|
||||
ifce.multiPort.Rx = c.GetBool("tun.multiport.rx_enabled", false)
|
||||
|
||||
tx := c.GetBool("tun.multiport.tx_enabled", false)
|
||||
|
||||
if tx && ifce.udpRaw == nil {
|
||||
ifce.udpRaw, err = udp.NewRawConn(l, c.GetString("listen.host", "0.0.0.0"), port, uint16(port))
|
||||
if err != nil {
|
||||
l.Error("Failed to get raw socket for tun.multiport.tx_enabled", "error", err)
|
||||
ifce.udpRaw = nil
|
||||
tx = false
|
||||
}
|
||||
}
|
||||
|
||||
if tx {
|
||||
ifce.multiPort.TxBasePort = uint16(port)
|
||||
ifce.multiPort.TxPorts = c.GetInt("tun.multiport.tx_ports", 100)
|
||||
ifce.multiPort.TxHandshake = c.GetBool("tun.multiport.tx_handshake", false)
|
||||
ifce.multiPort.TxHandshakeDelay = int64(c.GetInt("tun.multiport.tx_handshake_delay", 2))
|
||||
ifce.udpRaw.ReloadConfig(c)
|
||||
}
|
||||
ifce.multiPort.Tx = tx
|
||||
|
||||
// TODO: if we upstream this, make this cleaner
|
||||
handshakeManager.udpRaw = ifce.udpRaw
|
||||
handshakeManager.multiPort = ifce.multiPort
|
||||
|
||||
l.Info("Multiport configured", "multiPort", ifce.multiPort)
|
||||
}
|
||||
|
||||
loadMultiPortConfig(c)
|
||||
c.RegisterReloadCallback(loadMultiPortConfig)
|
||||
|
||||
ifce.RegisterConfigChangeCallbacks(c)
|
||||
ifce.reloadDisconnectInvalid(c)
|
||||
ifce.reloadSendRecvError(c)
|
||||
|
||||
@@ -264,6 +264,15 @@ func (f *Interface) sendCloseTunnel(h *HostInfo) {
|
||||
func (f *Interface) handleHostRoaming(hostinfo *HostInfo, via ViaSender) {
|
||||
curRemote := hostinfo.GetRemote()
|
||||
if !via.IsRelayed && curRemote != via.UdpAddr {
|
||||
if hostinfo.multiportRx {
|
||||
// If the remote is sending with multiport, we aren't roaming unless
|
||||
// the IP has changed
|
||||
if curRemote.Addr().Compare(via.UdpAddr.Addr()) == 0 {
|
||||
return
|
||||
}
|
||||
// Keep the port from the original hostinfo, because the remote is transmitting from multiport ports
|
||||
via.UdpAddr = netip.AddrPortFrom(via.UdpAddr.Addr(), curRemote.Port())
|
||||
}
|
||||
if !f.lightHouse.GetRemoteAllowList().AllowAll(hostinfo.vpnAddrs, via.UdpAddr.Addr()) {
|
||||
if f.l.Enabled(context.Background(), slog.LevelDebug) {
|
||||
hostinfo.logger(f.l).Debug("lighthouse.remote_allow_list denied roaming", "newAddr", via.UdpAddr)
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package udp
|
||||
|
||||
import mathrand "math/rand"
|
||||
|
||||
type SendPortGetter interface {
|
||||
// UDPSendPort returns the port to use
|
||||
UDPSendPort(maxPort int) uint16
|
||||
}
|
||||
|
||||
type randomSendPort struct{}
|
||||
|
||||
func (randomSendPort) UDPSendPort(maxPort int) uint16 {
|
||||
return uint16(mathrand.Intn(maxPort))
|
||||
}
|
||||
|
||||
var RandomSendPort = randomSendPort{}
|
||||
@@ -0,0 +1,191 @@
|
||||
//go:build !android && !e2e_testing
|
||||
// +build !android,!e2e_testing
|
||||
|
||||
package udp
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/netip"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
|
||||
"github.com/rcrowley/go-metrics"
|
||||
"github.com/slackhq/nebula/config"
|
||||
"golang.org/x/net/ipv4"
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// RawOverhead is the number of bytes that need to be reserved at the start of
|
||||
// the raw bytes passed to (*RawConn).WriteTo. This is used by WriteTo to prefix
|
||||
// the IP and UDP headers.
|
||||
const RawOverhead = 28
|
||||
|
||||
type RawConn struct {
|
||||
sysFd int
|
||||
basePort uint16
|
||||
l *slog.Logger
|
||||
}
|
||||
|
||||
func NewRawConn(l *slog.Logger, ip string, port int, basePort uint16) (*RawConn, error) {
|
||||
syscall.ForkLock.RLock()
|
||||
// With IPPROTO_UDP, the linux kernel tries to deliver every UDP packet
|
||||
// received in the system to our socket. This constantly overflows our
|
||||
// buffer and marks our socket as having dropped packets. This makes the
|
||||
// stats on the socket useless.
|
||||
//
|
||||
// In contrast, IPPROTO_RAW is not delivered any packets and thus our read
|
||||
// buffer will not fill up and mark as having dropped packets. The only
|
||||
// difference is that we have to assemble the IP header as well, but this
|
||||
// is fairly easy since Linux does the checksum for us.
|
||||
//
|
||||
// TODO: How to get this working with Inet6 correctly? I was having issues
|
||||
// with the source address when testing before, probably need to `bind(2)`?
|
||||
fd, err := unix.Socket(unix.AF_INET, unix.SOCK_RAW, unix.IPPROTO_RAW)
|
||||
if err == nil {
|
||||
unix.CloseOnExec(fd)
|
||||
}
|
||||
syscall.ForkLock.RUnlock()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// We only want to send, not recv. This will hopefully help the kernel avoid
|
||||
// wasting time on us
|
||||
if err = unix.SetsockoptInt(fd, unix.SOL_SOCKET, unix.SO_RCVBUF, 0); err != nil {
|
||||
return nil, fmt.Errorf("unable to set SO_RCVBUF: %s", err)
|
||||
}
|
||||
|
||||
var lip [16]byte
|
||||
copy(lip[:], net.ParseIP(ip))
|
||||
|
||||
// TODO do we need to `bind(2)` so that we send from the correct address/interface?
|
||||
if err = unix.Bind(fd, &unix.SockaddrInet6{Addr: lip, Port: port}); err != nil {
|
||||
return nil, fmt.Errorf("unable to bind to socket: %s", err)
|
||||
}
|
||||
|
||||
return &RawConn{
|
||||
sysFd: fd,
|
||||
basePort: basePort,
|
||||
l: l,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// WriteTo must be called with raw leaving the first `udp.RawOverhead` bytes empty,
|
||||
// for the IP/UDP headers.
|
||||
func (u *RawConn) WriteTo(raw []byte, fromPort uint16, ip netip.AddrPort) error {
|
||||
var rsa unix.RawSockaddrInet4
|
||||
rsa.Family = unix.AF_INET
|
||||
rsa.Addr = ip.Addr().As4()
|
||||
|
||||
totalLen := len(raw)
|
||||
udpLen := totalLen - ipv4.HeaderLen
|
||||
|
||||
// IP header
|
||||
raw[0] = byte(ipv4.Version<<4 | (ipv4.HeaderLen >> 2 & 0x0f))
|
||||
raw[1] = 0 // tos
|
||||
binary.BigEndian.PutUint16(raw[2:4], uint16(totalLen))
|
||||
binary.BigEndian.PutUint16(raw[4:6], 0) // id (linux does it for us)
|
||||
binary.BigEndian.PutUint16(raw[6:8], 0) // frag options
|
||||
raw[8] = byte(64) // ttl
|
||||
raw[9] = byte(17) // protocol
|
||||
binary.BigEndian.PutUint16(raw[10:12], 0) // checksum (linux does it for us)
|
||||
binary.BigEndian.PutUint32(raw[12:16], 0) // src (linux does it for us)
|
||||
copy(raw[16:20], rsa.Addr[:]) // dst
|
||||
|
||||
// UDP header
|
||||
fromPort = u.basePort + fromPort
|
||||
binary.BigEndian.PutUint16(raw[20:22], uint16(fromPort)) // src port
|
||||
binary.BigEndian.PutUint16(raw[22:24], uint16(ip.Port())) // dst port
|
||||
binary.BigEndian.PutUint16(raw[24:26], uint16(udpLen)) // UDP length
|
||||
binary.BigEndian.PutUint16(raw[26:28], 0) // checksum (optional)
|
||||
|
||||
for {
|
||||
_, _, err := unix.Syscall6(
|
||||
unix.SYS_SENDTO,
|
||||
uintptr(u.sysFd),
|
||||
uintptr(unsafe.Pointer(&raw[0])),
|
||||
uintptr(len(raw)),
|
||||
uintptr(0),
|
||||
uintptr(unsafe.Pointer(&rsa)),
|
||||
uintptr(unix.SizeofSockaddrInet4),
|
||||
)
|
||||
|
||||
if err != 0 {
|
||||
return &net.OpError{Op: "sendto", Err: err}
|
||||
}
|
||||
|
||||
//TODO: handle incomplete writes
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u *RawConn) ReloadConfig(c *config.C) {
|
||||
b := c.GetInt("listen.write_buffer", 0)
|
||||
if b <= 0 {
|
||||
return
|
||||
}
|
||||
|
||||
if err := u.SetSendBuffer(b); err != nil {
|
||||
u.l.Error("Failed to set listen.write_buffer", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
s, err := u.GetSendBuffer()
|
||||
if err != nil {
|
||||
u.l.Warn("Failed to get listen.write_buffer", "error", err)
|
||||
return
|
||||
}
|
||||
|
||||
u.l.Info("listen.write_buffer was set", "size", s)
|
||||
}
|
||||
|
||||
func (u *RawConn) SetSendBuffer(n int) error {
|
||||
return unix.SetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_SNDBUFFORCE, n)
|
||||
}
|
||||
|
||||
func (u *RawConn) GetSendBuffer() (int, error) {
|
||||
return unix.GetsockoptInt(u.sysFd, unix.SOL_SOCKET, unix.SO_SNDBUF)
|
||||
}
|
||||
|
||||
func (u *RawConn) getMemInfo(meminfo *[unix.SK_MEMINFO_VARS]uint32) error {
|
||||
var vallen uint32 = 4 * unix.SK_MEMINFO_VARS
|
||||
_, _, err := unix.Syscall6(unix.SYS_GETSOCKOPT, uintptr(u.sysFd), uintptr(unix.SOL_SOCKET), uintptr(unix.SO_MEMINFO), uintptr(unsafe.Pointer(meminfo)), uintptr(unsafe.Pointer(&vallen)), 0)
|
||||
if err != 0 {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewRawStatsEmitter(rawConn *RawConn) func() {
|
||||
// Check if our kernel supports SO_MEMINFO before registering the gauges
|
||||
var gauges [unix.SK_MEMINFO_VARS]metrics.Gauge
|
||||
var meminfo [unix.SK_MEMINFO_VARS]uint32
|
||||
if err := rawConn.getMemInfo(&meminfo); err == nil {
|
||||
gauges = [unix.SK_MEMINFO_VARS]metrics.Gauge{
|
||||
metrics.GetOrRegisterGauge("raw.rmem_alloc", nil),
|
||||
metrics.GetOrRegisterGauge("raw.rcvbuf", nil),
|
||||
metrics.GetOrRegisterGauge("raw.wmem_alloc", nil),
|
||||
metrics.GetOrRegisterGauge("raw.sndbuf", nil),
|
||||
metrics.GetOrRegisterGauge("raw.fwd_alloc", nil),
|
||||
metrics.GetOrRegisterGauge("raw.wmem_queued", nil),
|
||||
metrics.GetOrRegisterGauge("raw.optmem", nil),
|
||||
metrics.GetOrRegisterGauge("raw.backlog", nil),
|
||||
metrics.GetOrRegisterGauge("raw.drops", nil),
|
||||
}
|
||||
} else {
|
||||
// return no-op because we don't support SO_MEMINFO
|
||||
return func() {}
|
||||
}
|
||||
|
||||
return func() {
|
||||
if err := rawConn.getMemInfo(&meminfo); err == nil {
|
||||
for j := 0; j < unix.SK_MEMINFO_VARS; j++ {
|
||||
gauges[j].Update(int64(meminfo[j]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//go:build !linux || android || e2e_testing
|
||||
// +build !linux android e2e_testing
|
||||
|
||||
package udp
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/netip"
|
||||
"runtime"
|
||||
|
||||
"github.com/slackhq/nebula/config"
|
||||
)
|
||||
|
||||
const RawOverhead = 0
|
||||
|
||||
type RawConn struct{}
|
||||
|
||||
func NewRawConn(l *slog.Logger, ip string, port int, basePort uint16) (*RawConn, error) {
|
||||
return nil, fmt.Errorf("multiport tx is not supported on %s", runtime.GOOS)
|
||||
}
|
||||
|
||||
func (u *RawConn) WriteTo(raw []byte, fromPort uint16, addr netip.AddrPort) error {
|
||||
return fmt.Errorf("multiport tx is not supported on %s", runtime.GOOS)
|
||||
}
|
||||
|
||||
func (u *RawConn) ReloadConfig(c *config.C) {}
|
||||
|
||||
func NewRawStatsEmitter(rawConn *RawConn) func() { return func() {} }
|
||||
Reference in New Issue
Block a user