Documentation
¶
Overview ¶
Package tstun creates a tuntap device, working around OS-specific quirks if necessary.
Index ¶
- Constants
- Variables
- func Diagnose(logf logger.Logf, tunName string, err error)
- func New(logf logger.Logf, tunName string) (tun.Device, string, error)
- func NewFake() tun.Device
- type FilterFunc
- type GROFilterFunc
- type SetIPer
- type TUNMTU
- type WireMTU
- type Wrapper
- func (t *Wrapper) ApplyGROKnobs(knobs *controlknobs.Knobs)
- func (t *Wrapper) BatchSize() int
- func (t *Wrapper) Close() error
- func (t *Wrapper) Events() <-chan tun.Event
- func (t *Wrapper) EventsUpDown() chan tun.Event
- func (t *Wrapper) File() *os.File
- func (t *Wrapper) ForTest() *forTest
- func (t *Wrapper) GetFilter() *filter.Filter
- func (t *Wrapper) GetJailedFilter() *filter.Filter
- func (t *Wrapper) IdleDuration() time.Duration
- func (t *Wrapper) InjectInboundCopy(packet []byte) error
- func (t *Wrapper) InjectInboundDirect(buf []byte, offset int) error
- func (t *Wrapper) InjectInboundPacketBuffer(pkt *netstack_PacketBuffer, slab []byte, packets []tun.ReadPacket, ...) error
- func (t *Wrapper) InjectOutbound(pkt []byte) error
- func (t *Wrapper) InjectOutboundContext(ctx context.Context, pkt []byte) error
- func (t *Wrapper) InjectOutboundPacketBuffer(pkt *netstack_PacketBuffer) error
- func (t *Wrapper) InjectOutboundPacketBufferContext(ctx context.Context, pkt *netstack_PacketBuffer) error
- func (t *Wrapper) InjectionQueue() tun.Queue
- func (t *Wrapper) InstallCaptureHook(cb packet.CaptureCallback)
- func (t *Wrapper) MTU() (int, error)
- func (t *Wrapper) Name() (string, error)
- func (t *Wrapper) Queues() []tun.Queue
- func (t *Wrapper) Read(slab []byte, packets []tun.ReadPacket) (int, error)deprecated
- func (t *Wrapper) SetConnRejectCallback(fn func(connreject.Event))
- func (t *Wrapper) SetConnectionCounter(fn netlogfunc.ConnectionCounter)
- func (t *Wrapper) SetDiscoKey(k key.DiscoPublic)
- func (t *Wrapper) SetFilter(filt *filter.Filter)
- func (t *Wrapper) SetJailedFilter(filt *filter.Filter)
- func (t *Wrapper) SetLinkFeaturesPostUp(knobs *controlknobs.Knobs)
- func (t *Wrapper) SetPeerRoutes(native4, native6 netip.Addr, routes *bart.Table[*routemanager.PeerRoute])
- func (t *Wrapper) SetWGConfig(wcfg *wgcfg.Config)
- func (w *Wrapper) Start()
- func (t *Wrapper) TryInjectOutbound(pkt []byte) error
- func (t *Wrapper) Unwrap() tun.Device
- func (t *Wrapper) Write(buffs [][]byte, offset int) (int, error)
- func (t *Wrapper) WriteTo(flow int, buffs [][]byte, offset int) (int, error)
Constants ¶
const FakeTUNName = "FakeTUN"
FakeTUNName is the name of the fake TUN device.
const MaxPacketSize = device.MaxContentSize
MaxPacketSize is the maximum size (in bytes) of a packet that can be injected into a tstun.Wrapper.
const TAPDebug = false
TAPDebug is whether super verbose TAP debugging is enabled.
const WritePacketStartOffset = device.MessageTransportHeaderSize
WritePacketStartOffset is the minimal amount of leading space that must exist before &packet[offset] in a packet passed to tun.Device.Write, which includes "injected" packet code paths. This leading space is required by tun.Device implementations.
TODO(jwhited): consider collapsing with and renaming tun.ReadPacketSpacing for simplicity's sake. Exact math between tun.Device implementation and direction varies, but we can just pick the maximum value to reduce cognitive burden.
Variables ¶
var ( // ErrClosed is returned when attempting an operation on a closed Wrapper. ErrClosed = errors.New("device closed") // ErrFiltered is returned when the acted-on packet is rejected by a filter. ErrFiltered = errors.New("packet dropped by filter") )
var CreateTAP feature.Hook[func(logf logger.Logf, tapName, bridgeName string) (tun.Device, error)]
CreateTAP is the hook maybe set by feature/tap.
var ErrInjectionQueueFull = fmt.Errorf("injection queue full: %w", syscall.ENOBUFS)
ErrInjectionQueueFull is returned when a full injection queue forced a best-effort packet to be dropped rather than queued. It wraps syscall.ENOBUFS, the platform's "no buffer space available" errno, so callers can test for buffer exhaustion without knowing this package's type:
errors.Is(err, syscall.ENOBUFS)
Dropped packets are already counted as reason="queue_full" in the tailscaled_outbound_dropped_packets_total usermetric, so callers need not log this error.
HookPollTUNDevStats is the hook maybe set by feature/tundevstats.
HookSetLinkAttrs is the hook maybe set by feature/linkspeed.
var WireMTUsToProbe = []WireMTU{ WireMTU(safeTUNMTU), TUNToWireMTU(safeTUNMTU), 1400, 1500, 8000, 9000, }
WireMTUsToProbe is a list of the on-the-wire MTUs we want to probe. Each time magicsock discovery begins, it will send a set of pings, one of each size listed below.
Functions ¶
func Diagnose ¶
Diagnose tries to explain a tuntap device creation failure. It pokes around the system and logs some diagnostic info that might help debug why tun creation failed. Because device creation has already failed and the program's about to end, log a lot.
The tunName is the name of the tun device that was requested but failed. The err error is how the tun creation failed.
Types ¶
type FilterFunc ¶
FilterFunc is a packet-filtering function with access to the Wrapper device. It must not hold onto the packet struct, as its backing storage will be reused.
Must be safe to call concurrently.
type GROFilterFunc ¶ added in v1.74.0
GROFilterFunc is a FilterFunc extended with a *gro.GRO, enabling increased throughput where GRO is supported by a packet.Parsed interceptor, e.g. netstack/gVisor, and we are handling a vector of packets. Callers must pass a nil g for the first packet in a given vector, and continue passing the returned *gro.GRO for all remaining packets in said vector. If the returned *gro.GRO is non-nil after the last packet for a given vector is passed through the GROFilterFunc, the caller must also call Flush() on it to deliver any previously Enqueue()'d packets.
Must be safe to call concurrently.
type SetIPer ¶ added in v1.80.0
type SetIPer interface {
// SetIP sets the IP addresses of the TAP device.
SetIP(ipV4, ipV6 netip.Addr) error
}
SetIPer is the interface expected to be implemented by the TAP implementation of tun.Device.
type TUNMTU ¶ added in v1.52.0
type TUNMTU uint32
TUNMTU is the MTU for the tailscale TUN.
func DefaultTUNMTU ¶ added in v1.52.0
func DefaultTUNMTU() TUNMTU
DefaultTUNMTU returns the MTU we use to set the Tailscale TUN MTU. It is also the path MTU that we default to if we have no information about the path to a peer.
1. If set, the value of TS_DEBUG_MTU clamped to a maximum of MaxTUNMTU 2. If TS_DEBUG_ENABLE_PMTUD is set, the maximum size MTU we probe, minus wg overhead 3. If TS_DEBUG_ENABLE_PMTUD is not set, the Safe MTU
func WireToTUNMTU ¶ added in v1.52.0
WireToTUNMTU takes the MTU of an underlying network device and returns the largest possible MTU for a Tailscale TUN operating on top of that device, given that we have to add wireguard headers.
type WireMTU ¶ added in v1.52.0
type WireMTU uint32
WireMTU is the MTU for the underlying network devices.
func DefaultWireMTU ¶ added in v1.52.0
func DefaultWireMTU() WireMTU
DefaultWireMTU returns the default TUN MTU, adjusted for wireguard overhead.
func SafeWireMTU ¶ added in v1.52.0
func SafeWireMTU() WireMTU
SafeWireMTU returns the wire MTU that is safe to use if we have no information about the path MTU to this peer.
func TUNToWireMTU ¶ added in v1.52.0
TUNToWireMTU takes the MTU that the Tailscale TUN presents to the user and returns the on-the-wire MTU necessary to transmit the largest packet that will fit through the TUN, given that we have to add wireguard headers.
type Wrapper ¶
type Wrapper struct {
// PreFilterPacketInboundFromWireGuard is the inbound filter function that runs before the main filter
// and therefore sees the packets that may be later dropped by it.
PreFilterPacketInboundFromWireGuard FilterFunc
// PostFilterPacketInboundFromWireGuardAppConnector runs after the filter, but before PostFilterPacketInboundFromWireGuard.
// Non-app connector traffic is passed along. Invalid app connector traffic is dropped.
// It may be set while the Wrapper is running.
PostFilterPacketInboundFromWireGuardAppConnector syncs.AtomicValue[FilterFunc]
// PostFilterPacketInboundFromWireGuard is the inbound filter function that runs after the main filter.
PostFilterPacketInboundFromWireGuard GROFilterFunc
// PreFilterPacketOutboundToWireGuardNetstackIntercept is a filter function that runs before the main filter
// for packets from the local system. This filter is populated by netstack to hook
// packets that should be handled by netstack. If set, this filter runs before
// PreFilterFromTunToEngine.
PreFilterPacketOutboundToWireGuardNetstackIntercept GROFilterFunc
// PreFilterPacketOutboundToWireGuardEngineIntercept is a filter function that runs before the main filter
// for packets from the local system. This filter is populated by wgengine to hook
// packets which it handles internally. If both this and PreFilterFromTunToNetstack
// filter functions are non-nil, this filter runs second.
PreFilterPacketOutboundToWireGuardEngineIntercept FilterFunc
// PreFilterPacketOutboundToWireGuardAppConnectorIntercept runs after PreFilterPacketOutboundToWireGuardEngineIntercept
// for app connector specific traffic. Non-app connector traffic is passed along. Invalid app connector traffic is
// dropped. It may be set while the Wrapper is running.
PreFilterPacketOutboundToWireGuardAppConnectorIntercept syncs.AtomicValue[FilterFunc]
// PostFilterPacketOutboundToWireGuard is the outbound filter function that runs after the main filter.
PostFilterPacketOutboundToWireGuard FilterFunc
// OnTSMPPongReceived, if non-nil, is called whenever a TSMP pong arrives.
OnTSMPPongReceived func(packet.TSMPPongReply)
// OnICMPEchoResponseReceived, if non-nil, is called whenever a ICMP echo response
// arrives. If the packet is to be handled internally this returns true,
// false otherwise.
OnICMPEchoResponseReceived func(*packet.Parsed) bool
// OnUnmappedTransitIPMessage, if non-nil, is called when a TSMP message is
// received indicating that a packet was rejected by a connector due to a
// missing transit IP->real IP mapping. It may be set while the Wrapper
// is running.
OnUnmappedTransitIPMessage syncs.AtomicValue[func(packet.TailscaleRejectedHeader)]
// PeerAPIPort, if non-nil, returns the peerapi port that's
// running for the given IP address.
PeerAPIPort func(netip.Addr) (port uint16, ok bool)
// contains filtered or unexported fields
}
Wrapper augments a tun.Device with packet filtering and injection.
A Wrapper starts in a "corked" mode where Read calls are blocked until the Wrapper's Start method is called.
func (*Wrapper) ApplyGROKnobs ¶ added in v1.100.0
func (t *Wrapper) ApplyGROKnobs(knobs *controlknobs.Knobs)
ApplyGROKnobs applies the [tailcfg.NodeAttrDisableTUNUDPGRO] and [tailcfg.NodeAttrDisableTUNTCPGRO] knob values (via knobs, which must be non-nil) to t's underlying device. It is intended to be called when a control-plane node attribute change is detected after [SetLinkFeaturesPostUp] has already run.
Note: wireguard-go's GRO disablement is one-way (sticky); ApplyGROKnobs can move TUN UDP/TCP GRO from enabled to disabled, but the reverse requires a client restart.
func (*Wrapper) Close ¶
Close closes the Wrapper and the underlying tun.Device.
It requires that tdev.Close return any read blocked in one of tdev's queues: wireguard-go's device.Close waits for the goroutines parked there.
func (*Wrapper) Events ¶
Events returns a TUN event channel that contains all non-Up, non-Down events. It is named Events because it is the set of events that we want to expose to wireguard-go, and Events is the name specified by the wireguard-go tun.Device interface.
func (*Wrapper) EventsUpDown ¶
EventsUpDown returns a TUN event channel that contains all Up and Down events.
func (*Wrapper) ForTest ¶ added in v1.106.0
func (t *Wrapper) ForTest() *forTest
ForTest returns a handle to test-only methods on t. The resulting type is unexported to make it very obvious in godoc that this is not stable API. This method panics if called outside of tests, which also centralizes all must-be-in-tests validation.
func (*Wrapper) GetJailedFilter ¶ added in v1.66.0
func (*Wrapper) IdleDuration ¶
IdleDuration reports how long it's been since the last read or write to this device.
Its value should only be presumed accurate to roughly 10ms granularity. If there's never been activity, the duration is since the wrapper was created.
func (*Wrapper) InjectInboundCopy ¶
InjectInboundCopy takes a packet without leading space, reallocates it to conform to the InjectInboundDirect interface and calls InjectInboundDirect on it. Injecting a nil packet is a no-op.
Injecting packets from a valid peer will lead to TUN queue switching, and TCP reorders.
func (*Wrapper) InjectInboundDirect ¶
InjectInboundDirect makes the Wrapper device behave as if a packet with the given contents was received from the network. It blocks and does not take ownership of the packet. The injected packet will not pass through inbound filters.
The packet contents are to start at &buf[offset]. offset must be greater or equal to WritePacketStartOffset. The space before &buf[offset] will be used by WireGuard.
Injecting packets from a valid peer will lead to TUN queue switching, and TCP reorders.
func (*Wrapper) InjectInboundPacketBuffer ¶ added in v1.26.0
func (t *Wrapper) InjectInboundPacketBuffer(pkt *netstack_PacketBuffer, slab []byte, packets []tun.ReadPacket, writeBufs [][]byte) error
InjectInboundPacketBuffer makes the Wrapper device behave as if a packet (pkt) with the given contents was received from the network. It takes ownership of one reference count on pkt. The injected packet will not pass through inbound filters.
pkt will be copied into slab, and potentially GSO split, before writing to the underlying tun.Device. Therefore, callers must allocate and pass a slab slice that is sized for holding:
pkt.Data.Size() + (N * network headers len) + ((N+1) * [WritePacketStartOffset])
N is 1 when the originating netstack does not support GSO, otherwise N should be conn.IdealBatchSize. Similarly, callers must pass packets and writeBufs sized to N.
tun.ReadPacket is the shape required by tun.GSOSplit, but is admittedly confusing in the context of the direction of our eventual i/o op, tun.Device.Write. This is purely historical, as tun.GSOSplit was initially only used post-tun.Device.Read heading out to the network, but we are using it in the opposite direction here.
This path is typically used to deliver synthesized packets to the host networking stack. Injecting packets from a valid peer will lead to TUN queue switching and TCP reorders.
func (*Wrapper) InjectOutbound ¶
InjectOutbound makes the Wrapper device behave as if a packet with the given contents was sent to the network. It blocks until the packet can be queued or the Wrapper closes, and takes ownership of the packet. Only reads from InjectionQueue can make space. The injected packet will not pass through outbound filter rules, but UDP/SCTP flow state is recorded so inbound replies are admitted. Injecting an empty packet is a no-op.
func (*Wrapper) InjectOutboundContext ¶ added in v1.106.0
InjectOutboundContext is InjectOutbound with a cancellable wait for queue space. Cancellation does not retract a packet that has already been queued.
func (*Wrapper) InjectOutboundPacketBuffer ¶ added in v1.24.0
InjectOutboundPacketBuffer is InjectOutbound for a PacketBuffer. It takes ownership of one reference even on error. The packet may be mutated, and its reference is released after InjectionQueue consumes it or the Wrapper discards it.
func (*Wrapper) InjectOutboundPacketBufferContext ¶ added in v1.106.0
func (t *Wrapper) InjectOutboundPacketBufferContext(ctx context.Context, pkt *netstack_PacketBuffer) error
InjectOutboundPacketBufferContext is InjectOutboundPacketBuffer with a cancellable wait for queue space. Cancellation does not retract a packet that has already been queued. It takes ownership of one reference even on error.
func (*Wrapper) InjectionQueue ¶ added in v1.106.0
InjectionQueue returns tun.Queue carrying injected packets.
func (*Wrapper) InstallCaptureHook ¶ added in v1.38.0
func (t *Wrapper) InstallCaptureHook(cb packet.CaptureCallback)
func (*Wrapper) Queues ¶ added in v1.106.0
Queues implements tun.MultiQueueDevice with one queue per queue of the underlying device, followed by the queue carrying injected packets.
func (*Wrapper) Read
deprecated
Read implements tun.Device.Read.
Deprecated: Injected packets arrive on their own queue. Read Wrapper.Queues instead.
func (*Wrapper) SetConnRejectCallback ¶ added in v1.104.0
func (t *Wrapper) SetConnRejectCallback(fn func(connreject.Event))
SetConnRejectCallback installs a callback that is invoked when the Wrapper emits an outbound TSMP reject for an inbound peer connection that was dropped by the packet filter. The callback receives a fully populated connreject.Event of connreject.Incoming direction.
A nil fn unsets any previously installed callback.
func (*Wrapper) SetConnectionCounter ¶ added in v1.90.0
func (t *Wrapper) SetConnectionCounter(fn netlogfunc.ConnectionCounter)
SetConnectionCounter specifies a per-connection statistics aggregator. Nil may be specified to disable statistics gathering.
func (*Wrapper) SetDiscoKey ¶ added in v1.14.6
func (t *Wrapper) SetDiscoKey(k key.DiscoPublic)
SetDiscoKey sets the current discovery key.
It is only used for filtering out bogus traffic when network stack(s) get confused; see Issue 1526.
func (*Wrapper) SetJailedFilter ¶ added in v1.66.0
func (*Wrapper) SetLinkFeaturesPostUp ¶ added in v1.74.0
func (t *Wrapper) SetLinkFeaturesPostUp(knobs *controlknobs.Knobs)
SetLinkFeaturesPostUp configures link features on t based on select TS_TUN_ environment variables, control-plane node attributes (via knobs, which may be nil), and OS feature tests. Callers should ensure t is up prior to calling, otherwise OS feature tests may be inconclusive.
func (*Wrapper) SetPeerRoutes ¶ added in v1.102.0
func (t *Wrapper) SetPeerRoutes(native4, native6 netip.Addr, routes *bart.Table[*routemanager.PeerRoute])
SetPeerRoutes is called whenever this node's Tailscale addresses or the route manager's outbound table change. native4 and native6 are this node's own Tailscale addresses, and routes maps each peer's addresses and routed prefixes to its route attributes.
A nil routes table disables all per-packet peer processing (NAT rewrites and jailed-filter selection); callers pass nil when no current peer has any such attributes, which keeps the common per-packet path to a nil check.
Unchanged values are a cheap no-op, so callers can call it unconditionally whenever the inputs might have changed: the routes table is an immutable snapshot whose pointer identity means its contents are unchanged.
func (*Wrapper) SetWGConfig ¶ added in v1.40.0
SetWGConfig is called when a new NetworkMap is received. Its only remaining job is updating the TAP device's IP addresses; the per-peer route attributes arrive via Wrapper.SetPeerRoutes.
func (*Wrapper) Start ¶ added in v1.52.0
func (w *Wrapper) Start()
Start unblocks any queue reads that have already started and makes the Wrapper functional.
Start must be called exactly once after the various Tailscale subsystems have been wired up to each other.
func (*Wrapper) TryInjectOutbound ¶ added in v1.106.0
TryInjectOutbound is InjectOutbound, but drops pkt rather than waiting for queue space. Use it for best-effort replies generated while processing packets, which must not stall behind the injection queue's reader. Dropped packets are counted as queue_full outbound drops, and the returned error matches syscall.ENOBUFS via errors.Is on platforms that define it, so callers can test for buffer exhaustion generically.
func (*Wrapper) Write ¶
Write accepts incoming packets. It is equivalent to Wrapper.WriteTo with a zero flow.
func (*Wrapper) WriteTo ¶ added in v1.106.0
WriteTo implements tun.MultiQueueDevice. The packets begin at buffs[:][offset:], like wireguard-go/tun.Device.Write. Write is called per-peer via wireguard-go/device.Peer.RoutineSequentialReceiver, so it MUST be thread-safe.
Packets are dispatched to the write queue selected by flow.