sysnet

package
v0.56.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 3, 2026 License: CC0-1.0 Imports: 11 Imported by: 5 modules, 8 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sysnet provides an abstraction of the OS networking system so that each specific integration (Linux, Windows, macOS, etc.) can be implemented once and reused across applications. This abstraction also makes it possible to build virtual implementations for testing.

Index

Constants

View Source
const (
	RuleValueKindPath   = RuleValuePath
	RuleValueKindPID    = RuleValuePID
	RuleValueKindName   = RuleValueName
	RuleValueKindRegex  = RuleValueRegex
	RuleValueKindOpaque = RuleValueOpaque
)

Alternate names keep the OwnerField and RuleValueKind type names visible at call sites.

View Source
const (
	OwnerFieldPID            = OwnerPID
	OwnerFieldProcessName    = OwnerProcessName
	OwnerFieldExecutablePath = OwnerExecutablePath
	OwnerFieldUID            = OwnerUID
	OwnerFieldGID            = OwnerGID
	OwnerFieldUserSID        = OwnerUserSID
)
View Source
const CapabilitySchemaVersion uint32 = 1

CapabilitySchemaVersion is the schema version used by CapabilityReport.

Variables

View Source
var (
	// ErrNotSupported means that the backend does not implement the requested
	// behavior.
	ErrNotSupported = errors.New("feature is not supported")

	ErrUnknownTun = errors.New("unknown tun")
)
View Source
var (
	// ErrUnavailable means that the backend implements the behavior, but a
	// known host condition blocks it.
	ErrUnavailable = errors.New("capability is unavailable")

	// ErrCapabilityUnknown means that the backend cannot establish whether the
	// behavior is currently available.
	ErrCapabilityUnknown = errors.New("capability availability is unknown")

	// ErrInvalidOptions means that input is structurally or syntactically
	// invalid.
	ErrInvalidOptions = errors.New("invalid options")
)
View Source
var ErrInvalidCapabilityReport = errors.New("invalid capability report")

ErrInvalidCapabilityReport identifies an inconsistent capability report.

Functions

func MatchConn added in v0.20.0

func MatchConn(c net.Conn, matcher Matcher) (bool, error)

MatchConn matches a connection incoming from LocalNet against provided matcher. It MUST NOT be used for any connections except one accepted from Listeners created via LocalNet owned by same System instance that was used to build this Matcher.

func ValidateCapabilityReport added in v0.55.0

func ValidateCapabilityReport(r CapabilityReport) error

ValidateCapabilityReport checks report consistency.

func ValidateTunCapabilityReport added in v0.55.0

func ValidateTunCapabilityReport(
	r TunCapabilityReport,
) error

ValidateTunCapabilityReport checks per-TUN report consistency.

Types

type AddressFamily added in v0.55.0

type AddressFamily string
const (
	FamilyNone AddressFamily = "none"
	FamilyIPv4 AddressFamily = "ipv4"
	FamilyIPv6 AddressFamily = "ipv6"
	FamilyDual AddressFamily = "dual"
)

type Capability added in v0.55.0

type Capability struct {
	State       CapabilityState
	Reasons     []CapabilityReason
	Detail      string
	Limitations []LimitationID
}

Capability describes one exact behavior and scope.

func (Capability) Clone added in v0.55.0

func (c Capability) Clone() Capability

Clone returns an independent copy of c.

type CapabilityReason added in v0.55.0

type CapabilityReason string

CapabilityReason is a stable, localizable reason code.

const (
	ReasonNotImplemented           CapabilityReason = "not_implemented"
	ReasonUnsupportedPlatform      CapabilityReason = "unsupported_platform"
	ReasonUnsupportedCombination   CapabilityReason = "unsupported_combination"
	ReasonDisabledByConfig         CapabilityReason = "disabled_by_config"
	ReasonMissingDependency        CapabilityReason = "missing_dependency"
	ReasonDependencyIncompatible   CapabilityReason = "dependency_incompatible"
	ReasonPermissionDenied         CapabilityReason = "permission_denied"
	ReasonResourceBusy             CapabilityReason = "resource_busy"
	ReasonNoUnderlay               CapabilityReason = "no_underlay"
	ReasonAddressFamilyUnavailable CapabilityReason = "address_family_unavailable"
	ReasonRecoveryRequired         CapabilityReason = "recovery_required"
	ReasonSystemClosed             CapabilityReason = "system_closed"
	ReasonProbeNotRun              CapabilityReason = "probe_not_run"
	ReasonProbeFailed              CapabilityReason = "probe_failed"
)

type CapabilityReport added in v0.55.0

type CapabilityReport struct {
	SchemaVersion      uint32
	Revision           uint64
	Operations         []OperationCapability
	DefaultTunProfiles []DefaultTunProfile
	Rules              []RuleCapability
	Ownership          []OwnerCapability
}

func (CapabilityReport) Clone added in v0.55.0

Clone returns a deep copy of r.

func (CapabilityReport) DefaultTunProfile added in v0.55.0

func (r CapabilityReport) DefaultTunProfile(
	key RoutingProfileKey,
) DefaultTunProfile

DefaultTunProfile returns the exact routing profile. A missing key is unknown.

func (CapabilityReport) Operation added in v0.55.0

func (r CapabilityReport) Operation(key OperationKey) Capability

Operation returns the exact operation capability. A missing key is unknown.

func (CapabilityReport) Rule added in v0.55.0

func (r CapabilityReport) Rule(ruleType string) RuleCapability

Rule returns the rule catalog entry. A missing type is unknown.

func (CapabilityReport) Validate added in v0.55.0

func (r CapabilityReport) Validate() error

Validate checks report consistency. Extension key values are accepted.

type CapabilityState added in v0.55.0

type CapabilityState uint8

CapabilityState describes whether a capability can be used on the current host. The zero value is intentionally unknown.

const (
	CapabilityUnknown CapabilityState = iota
	CapabilityUnsupported
	CapabilityUnavailable
	CapabilityAvailable
)

type DefaultTun added in v0.20.0

type DefaultTun interface {
	tun.Tun

	// SetDNS sets the current system DNS resolver, replacing the previous
	// resolver. A nil resolver stops managed DNS requests.
	// After DefaultTun is closed, DNS configuration associated with it should be
	// removed, and the previous system DNS configuration should be restored.
	// Native resolver-change failures must be returned.
	SetDNS(resolver dns.Interface) error
}

DefaultTun represents a Tun device intended to use as a default route for system traffic. It is also responsible for DNS requests processing because on may systems (e.g. android, linux with systremd-resolved, etc) DNS configuration must be binded to specific network interface. Some implementation of DefaultTun automatically intercept all DNS requests sent via it.

type DefaultTunOpts added in v0.20.0

type DefaultTunOpts struct {
	// Name requests a specific device name. An empty name lets the backend
	// select the name.
	Name string

	// TunAddrs specifies the addresses that should be owned by the TUN device,
	// for example: "10.0.0.2/32".
	// Loopback addrs passed here should be ignored.
	// If TunAddrs is void, implementation should pick some safe addr and subnet.
	TunAddrs []string

	// TunRoutes specifies the extra routes that should be owned by the TUN device,
	// for example: "0.0.0.0/0" and "::/0" for all routes.
	// Loopback subnets passed here should be ignored.
	TunRoutes []string

	// SourceRoutes selects preferred local source addresses for remote
	// destinations. IPv4 and IPv6 routes are independent. An empty list keeps
	// the system's default source-selection behavior.
	SourceRoutes []TunSourceRoute

	// MTU specifies the initial MTU for the TUN device. If MTU is 0 or too low,
	// implementation should use a sensible default.
	MTU int

	// DnsIP is an address to host DNS server on. It should be one of TunAddrs.
	// If not provided, some of addrs owned by DefaultTun should be picked.
	// Any DnsIP not included in TunAddrs should be ignored.
	DnsIP string

	// If Strict mode enabled, all traffic that not goes to DefaultTun device
	// (e.g. excluded) should be dropped insteade of passed to some other
	// suitable network interface.
	// Note that Strict mode toggling may be not supported on some systems.
	Strict bool

	// Exclude specifies a list of rules to identify traffic that SHOULD NOT go
	// to DefaultTun.
	// If Strict is enabled, excluded traffic should not go anywhere else and
	// should be just dropped instead. Note that Strict mode toggle may be not
	// supported on some systems.
	// Exclude is mutually exclusive with Include.
	Exclude []Rule

	// Include specifies a list of rules to identify traffic that SHOULD go to
	// DefaultTun while everything else bypass it.
	// If Strict is enabled, not included traffic should not go anywhere else and
	// should be just dropped instead. Note that Strict mode toggle may be not
	// supported on some systems.
	// Include is mutually exclusive with Exclude.
	Include []Rule
}

DefaultTunOpts specifies configuration options for building a DefaultTun

func (*DefaultTunOpts) Copy added in v0.20.0

func (b *DefaultTunOpts) Copy() DefaultTunOpts

type DefaultTunProfile added in v0.55.0

type DefaultTunProfile struct {
	Key RoutingProfileKey
	Capability
	Rules []RuleBinding
}

type LimitationID added in v0.55.0

type LimitationID string

LimitationID identifies a documented limitation that does not weaken the named behavior.

type MatchQuality added in v0.55.0

type MatchQuality string
const (
	MatchQualityUnknown                 MatchQuality = "unknown"
	MatchQualityBestEffortTuple         MatchQuality = "best_effort_tuple"
	MatchQualityBestEffortLocalEndpoint MatchQuality = "best_effort_local_endpoint"
)

type Matcher added in v0.20.0

type Matcher interface {
	io.Closer

	Match(flow sockowner.FlowTuple) (bool, error)
}

Matcher instance is constructed by a System from a Rule and matches 5-tuple flow info. Matcher should be used only with outgoing traffic comes form System that was used to build it.

type MatcherProfile added in v0.55.0

type MatcherProfile struct {
	Key MatcherProfileKey
	Capability
	Quality MatchQuality
}

type MatcherProfileKey added in v0.55.0

type MatcherProfileKey struct {
	Family    AddressFamily
	Transport Transport
}

type Operation added in v0.55.0

type Operation string
const (
	OpAllocateIP         Operation = "allocate_ip"
	OpAllocateSubnet     Operation = "allocate_subnet"
	OpCreate             Operation = "create"
	OpCreateNamed        Operation = "create_named"
	OpSetMTU             Operation = "set_mtu"
	OpRename             Operation = "rename"
	OpSetAddresses       Operation = "set_addresses"
	OpAddAddress         Operation = "add_address"
	OpGetAddresses       Operation = "get_addresses"
	OpSetRoutes          Operation = "set_routes"
	OpAddRoute           Operation = "add_route"
	OpGetRoutes          Operation = "get_routes"
	OpReconfigureInPlace Operation = "reconfigure_in_place"
	OpSourceRoutes       Operation = "source_routes"
	OpDNSProvider        Operation = "dns_provider"
	OpDNSConfigure       Operation = "dns_configure"
	OpDNSPort53Exclusive Operation = "dns_port53_exclusive"
	OpDNSSystemExclusive Operation = "dns_system_exclusive"
	OpDialTCP            Operation = "dial_tcp"
	OpDialUDP            Operation = "dial_udp"
	OpPacketDialUDP      Operation = "packet_dial_udp"
	OpListenTCP          Operation = "listen_tcp"
	OpListenUDP          Operation = "listen_udp"
	OpListenPacketUDP    Operation = "listen_packet_udp"
	OpMulticastUDP       Operation = "multicast_udp"
	OpResolve            Operation = "resolve"
	OpInterfaces         Operation = "interfaces"
	OpQueryUDP           Operation = "query_udp"
	OpQueryTCP           Operation = "query_tcp"
)

type OperationCapability added in v0.55.0

type OperationCapability struct {
	Key OperationKey
	Capability
}

type OperationKey added in v0.55.0

type OperationKey struct {
	Target    Target
	Operation Operation
	Family    AddressFamily
}

type OwnerCapability added in v0.55.0

type OwnerCapability struct {
	Key MatcherProfileKey
	Capability
	Quality MatchQuality
	Fields  []OwnerFieldCapability
}

type OwnerField added in v0.55.0

type OwnerField string
const (
	OwnerPID            OwnerField = "pid"
	OwnerProcessName    OwnerField = "process_name"
	OwnerExecutablePath OwnerField = "executable_path"
	OwnerUID            OwnerField = "uid"
	OwnerGID            OwnerField = "gid"
	OwnerUserSID        OwnerField = "user_sid"
)

type OwnerFieldCapability added in v0.55.0

type OwnerFieldCapability struct {
	Field OwnerField
	Capability
}

type RoutingMode added in v0.55.0

type RoutingMode string
const (
	RoutingFull    RoutingMode = "full"
	RoutingExclude RoutingMode = "exclude"
	RoutingInclude RoutingMode = "include"
)

type RoutingProfileKey added in v0.55.0

type RoutingProfileKey struct {
	Family AddressFamily
	Mode   RoutingMode
	Strict bool
}

type Rule

type Rule struct {
	Type, Rule string
}

A Rule matches IP packets and connections to check if they are owned by a specific process, user, application, or other entity. For example: Type="app", Rule="org.mozilla.firefox". Different System implementations can support different rule types and use contexts. Callers must inspect System.Capabilities and use CheckRule.

type RuleBinding added in v0.55.0

type RuleBinding struct {
	Type string
	Capability
}

type RuleCapability added in v0.55.0

type RuleCapability struct {
	Type        string
	Description string
	ValueKind   RuleValueKind
	SemanticsID string
	Validation  Capability
	Completion  Capability
	Matchers    []MatcherProfile
}

type RuleContext added in v0.55.0

type RuleContext struct {
	Routing *RoutingProfileKey
	Matcher *MatcherProfileKey
}

RuleContext selects the exact use of a rule. Exactly one field must be set.

func (RuleContext) Clone added in v0.55.0

func (c RuleContext) Clone() RuleContext

Clone returns an independent copy of c.

type RuleValueKind added in v0.55.0

type RuleValueKind string
const (
	RuleValuePath   RuleValueKind = "path"
	RuleValuePID    RuleValueKind = "pid"
	RuleValueName   RuleValueKind = "name"
	RuleValueRegex  RuleValueKind = "regex"
	RuleValueOpaque RuleValueKind = "opaque"
)

type System

type System interface {
	// System closing should lead to closing all Tun and Network instances
	// created via it.
	io.Closer

	// Capabilities returns an independently owned snapshot of system
	// capabilities. It does not change host state.
	Capabilities() CapabilityReport

	// CapabilitiesForTun returns an independently owned capability snapshot for
	// a live TUN created by this System. It returns ErrUnknownTun for foreign,
	// stale, or closed objects.
	CapabilitiesForTun(tunDevice tun.Tun) (TunCapabilityReport, error)

	// CheckTunOpts validates regular TUN options without changing host state.
	CheckTunOpts(opts TunOpts) ValidationReport

	// CheckDefaultTunOpts validates default-TUN options without changing host
	// state.
	CheckDefaultTunOpts(opts DefaultTunOpts) ValidationReport

	// CheckRule validates a rule in one exact use context without changing host
	// state.
	CheckRule(rule Rule, context RuleContext) ValidationReport

	// CompleteRule returns bounded completion suggestions for a rule in one
	// exact use context.
	CompleteRule(rule Rule, context RuleContext) ([]string, error)

	// AllocIP returns an IP address allocator for the system.
	AllocIP() subnet.IPAllocator
	// AllocSubnet returns a subnet allocator for the system.
	AllocSubnet() subnet.SubnetAllocator

	// OutDNS is the interface for handling outgoing DNS requests.
	// It should bypass any DefaultTun created via this System.
	OutDNS() dns.Interface

	// OutNet is an outbound Network interface. All traffic goes through it should
	// bypass any DefaultTun instance built by this System.
	// In some System implementations OutNet MAY be a same Network instance with
	// LocalNet but users should not assume or expect this.
	// System implementations that cannot provide one should return
	// gonnect.RejectNetwork.
	OutNet() gonnect.Network

	// LocalNet is a loopback Network interface.
	// In some System implementations LocalNet MAY be a same Network instance with
	// OutNet but users should not assume or expect this.
	// System implementations that cannot provide one should return
	// gonnect.RejectNetwork.
	LocalNet() gonnect.Network

	// BuildMatcher builds a new Matcher from provided rule. Built Matcher should
	// Matcher instances created this way are intended to use for filtering
	// traffic that comes from Tuns built by this System and for Connections
	// accepted via LocalNet.
	BuildMatcher(rule Rule) (Matcher, error)

	// BuildDefaultTun constructs a DefaultTun instance with specified options.
	// BuildDefaultTun may be called multiple times, but only one latest
	// DefaultTun should be used at a time. It is recommended for System
	// implementations to close previous DefaultTun and associated artifacts when
	// a new one is created.
	BuildDefaultTun(opts DefaultTunOpts) (DefaultTun, error)

	// DefaultTunWarnings returns current warnings for a DefaultTun returned by
	// this System. Unknown, stale, closed, or unsupported DefaultTun values
	// should return nil.
	DefaultTunWarnings(defaultTun DefaultTun) []Warning

	// BuildTun constructs a tun.Tun instance with specified options.
	// BuildTun can be unsupported on some systems. Check the exact creation
	// capability and validate the options before use.
	BuildTun(opts TunOpts) (tun.Tun, error)

	// TunWarnings returns current warnings for a regular Tun returned by this
	// System. Unknown, stale, closed, or unsupported Tun values should return
	// nil.
	TunWarnings(tun tun.Tun) []Warning

	// SetTunMTU updates MTU of provided Tun.
	// It should work only for Tuns built via this System instance. For others
	// ErrUnknownTun should be returned.
	// If MTU is 0 or too low, implementation should use a sensible default.
	// Dynamic Tun params update may not be available on some systems.
	SetTunMTU(tun tun.Tun, MTU int) error

	// SetTunAddrs updates list off addrs of provided Tun.
	// It should work only for Tuns built via this System instance. For others
	// ErrUnknownTun should be returned.
	// Dynamic Tun params update may not be available on some systems.
	SetTunAddrs(tun tun.Tun, addrs []string) error

	// AddTunAddr updates list off addrs of provided Tun.
	// It should work only for Tuns built via this System instance. For others
	// ErrUnknownTun should be returned.
	// Dynamic Tun params update may not be available on some systems.
	AddTunAddr(tun tun.Tun, addr string) error

	// GetTunAddrs returns list off addrs of provided Tun.
	// It should work only for Tuns built via this System instance. For others
	// ErrUnknownTun should be returned.
	// Dynamic Tun params fetching may not be available on some systems.
	GetTunAddrs(tun tun.Tun) ([]string, error)

	// SetTunRoutes updates list off routes of provided Tun.
	// It should work only for Tuns built via this System instance. For others
	// ErrUnknownTun should be returned.
	// Dynamic Tun params update may not be available on some systems.
	SetTunRoutes(tun tun.Tun, routes []string) error

	// AddTunRoute updates list off routes of provided Tun.
	// It should work only for Tuns built via this System instance. For others
	// ErrUnknownTun should be returned.
	// Dynamic Tun params update may not be available on some systems.
	AddTunRoute(tun tun.Tun, route string) error

	// GetTunRoutes returns the routes of the provided TUN.
	// It should work only for Tuns built via this System instance. For others
	// ErrUnknownTun should be returned.
	// Dynamic Tun params fetching may not be available on some systems.
	GetTunRoutes(tun tun.Tun) ([]string, error)

	// SetTunName updates name of provided Tun.
	// It should work only for Tuns built via this System instance. For others
	// ErrUnknownTun should be returned.
	// Dynamic TUN parameter updates can differ between regular and default TUNs.
	SetTunName(tun tun.Tun, name string) error
}

System provides the networking operations for one platform integration.

type Target added in v0.55.0

type Target string
const (
	TargetSystem     Target = "system"
	TargetTun        Target = "tun"
	TargetDefaultTun Target = "default_tun"
	TargetOutNet     Target = "out_net"
	TargetLocalNet   Target = "local_net"
	TargetOutDNS     Target = "out_dns"
)

type Transport added in v0.55.0

type Transport string
const (
	TransportTCP Transport = "tcp"
	TransportUDP Transport = "udp"
)

type TunCapabilityReport added in v0.55.0

type TunCapabilityReport struct {
	SystemRevision   uint64
	InstanceRevision uint64
	Operations       []OperationCapability
}

func (TunCapabilityReport) Clone added in v0.55.0

Clone returns a deep copy of r.

func (TunCapabilityReport) Operation added in v0.55.0

func (r TunCapabilityReport) Operation(key OperationKey) Capability

Operation returns the exact per-TUN operation capability. A missing key is unknown.

func (TunCapabilityReport) Validate added in v0.55.0

func (r TunCapabilityReport) Validate() error

Validate checks per-TUN report consistency.

type TunOpts added in v0.20.0

type TunOpts struct {
	// Name requests a specific device name. An empty name lets the backend
	// select the name.
	Name string

	// TunAddrs specifies the addresses that should be owned by the TUN device,
	// for example: "10.0.0.2/32".
	// Loopback addrs passed here should be ignored.
	// If TunAddrs is void, there will be no
	TunAddrs []string

	// TunRoutes specifies the extra routes that should be owned by the TUN device,
	// for example: "0.0.0.0/0" and "::/0" for all routes.
	// Loopback subnets passed here should be ignored.
	TunRoutes []string

	// MTU specifies the initial MTU for the TUN device. If MTU is 0 or too low,
	// implementation should use a sensible default.
	MTU int
}

TunOpts specifies configuration options for building a regular Tun.

func (*TunOpts) Copy added in v0.24.0

func (b *TunOpts) Copy() TunOpts

Copy returns an independent copy of b.

type TunSourceRoute added in v0.50.0

type TunSourceRoute struct {
	// Destination selects this source route. When more than one route matches,
	// the route with the longest prefix has priority.
	Destination netip.Prefix

	// Source is a local address assigned to the TUN.
	Source netip.Addr
}

TunSourceRoute selects a preferred local source address for a remote destination routed through a default TUN.

type ValidationError added in v0.55.0

type ValidationError struct {
	Issue ValidationIssue
}

ValidationError is the typed form of one ValidationIssue.

func (*ValidationError) Error added in v0.55.0

func (e *ValidationError) Error() string

func (*ValidationError) Unwrap added in v0.55.0

func (e *ValidationError) Unwrap() []error

Unwrap preserves both the category sentinel and an underlying native cause.

type ValidationIssue added in v0.55.0

type ValidationIssue struct {
	Path   string
	Reason CapabilityReason
	State  CapabilityState
	Detail string
	Err    error
}

ValidationIssue describes one blocking or indeterminate validation result.

type ValidationReport added in v0.55.0

type ValidationReport struct {
	CapabilityRevision uint64
	Issues             []ValidationIssue
}

ValidationReport is an advisory validation result tied to one capability snapshot.

func (ValidationReport) Clone added in v0.55.0

Clone returns an independent copy of r. Error values are immutable and are shared.

func (ValidationReport) Err added in v0.55.0

func (r ValidationReport) Err() error

Err converts all issues to a joined typed error. It returns nil when the report has no issues.

type Warning added in v0.35.0

type Warning string

Warning identifies a non-fatal runtime condition reported by a System.

Warning values are stable identifiers. They are not final user-facing text.

const (
	// WarningDefaultTunDNSRouteNotExclusive means the System cannot prove that
	// system DNS traffic is routed only to the DefaultTun DNS provider.
	WarningDefaultTunDNSRouteNotExclusive Warning = "default_tun_dns_route_not_exclusive"
)

Directories

Path Synopsis
Package sysnetdebug provides a channel-driven sysnet implementation for tests.
Package sysnetdebug provides a channel-driven sysnet implementation for tests.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL