vpn

package
v1.7.2 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2026 License: Apache-2.0 Imports: 35 Imported by: 0

Documentation

Index

Constants

View Source
const FlowCountedMark uint32 = 0x80000000

Reserved only in the VPN pod's conntrack namespace. Other mark bits remain intact.

View Source
const LabIdentityMask uint32 = 0x00ffff00
View Source
const ProbePort = vpnprobe.Port

ProbePort is reachable through the WireGuard interface, never through the public UDP service. Keep this in sync with the participant VPN status API.

Variables

This section is empty.

Functions

func LabInterfaceIndex added in v1.1.0

func LabInterfaceIndex(iface string) (uint16, error)

LabInterfaceIndex rejects wildcard/injected interface names and bounds the index used for identifying the actual lab leg in the VPN namespace.

Types

type AccessAction

type AccessAction string

AccessAction determines whether a matching policy rule grants or revokes a route. Deny always wins when rules overlap.

const (
	AccessAllow AccessAction = "allow"
	AccessDeny  AccessAction = "deny"
)

type AccessPolicyRule

type AccessPolicyRule struct {
	Action      AccessAction
	ClientNames []string
	LabNames    []string
}

AccessPolicyRule is a group-scoped rule. Empty client or lab selectors mean every client or every lab respectively.

type AccessRule

type AccessRule struct {
	ClientName      string
	LabName         string
	SourceCIDR      string
	DestinationCIDR string
	LabInterface    string
	Action          AccessAction
}

AccessRule permits packets from one WireGuard client to one lab VPN CIDR. Response traffic is handled by the established-connection firewall rule.

func BuildAccessRules

func BuildAccessRules(clients []ClientAccessSnapshot, labs map[string]LabAccessSnapshot, policy []AccessPolicyRule) []AccessRule

BuildAccessRules derives a deterministic default-deny ACL containing each ready client-to-lab relation. Explicit DROP rules make blocked traffic observable; the chain's final implicit DROP still covers unknown traffic.

func (AccessRule) BindingID added in v1.1.0

func (r AccessRule) BindingID() string

BindingID identifies the names, endpoints and physical lab leg used by an allow rule. It is also the private persisted identity proof at cold start.

func (AccessRule) Identifier

func (r AccessRule) Identifier() string

Identifier is stable across reconciles and short enough for an iptables comment. It deliberately excludes network addresses, which can be reissued.

type AccessStatistics

type AccessStatistics struct {
	ClientName   string
	LabName      string
	Action       AccessAction
	Packets      int64
	Bytes        int64
	CounterReset bool
}

AccessStatistics is safe monitoring data for one client-to-lab relation. A counter reset is explicit instead of becoming a negative delta later.

func ProjectAccessStatistics

func ProjectAccessStatistics(rules []AccessRule, current map[string]TrafficCounter, previous map[string]TrafficCounter) []AccessStatistics

ProjectAccessStatistics associates kernel counters with the configured relation. Current counters are cumulative; previous lets the caller surface an explicit reset when iptables was recreated.

type ApplyResult added in v1.1.0

type ApplyResult struct{ Changed bool }

type ClientAccessSnapshot

type ClientAccessSnapshot struct {
	Name       string
	AssignedIP string
}

ClientAccessSnapshot is the observed VPN identity of one group client.

type Config

type Config struct {
	PrivateKey    string        `env:"PRIVATE_KEY,required"`
	ListenPort    int           `env:"LISTEN_PORT"`
	Namespace     string        `env:"NAMESPACE,required"`
	ClientSubnet  *net.IPNet    `env:"CLIENT_SUBNET,required"`
	StatsInterval time.Duration `env:"STATS_INTERVAL" envDefault:"30s"`
	WGInterface   string        `env:"WG_INTERFACE"     envDefault:"wg0"`
	// ExternalInterface is the uplink of the pod (the pod network), the one interface from which the WireGuard port is reachable:
	// the proxy delivers the clients' packets there. The lab interfaces (lab<N>) never are.
	ExternalInterface string `env:"EXTERNAL_INTERFACE" envDefault:"eth0"`
	VPNBaseNetwork    string `env:"VPN_BASE_NETWORK,required"`
	SupportEmail      string `env:"SUPPORT_EMAIL,required"`
}

func LoadConfig

func LoadConfig() (*Config, error)

type ConnFlow

type ConnFlow struct {
	// ID is the kernel's identifier of the entry; Key is the caller's own handle
	// (an index into the dump the flow came from).
	ID       uint32
	Mark     uint32
	Key      int
	Src, Dst netip.Addr
}

ConnFlow is the original direction of one tracked connection: who opened it and to whom.

func RevokedFlows

func RevokedFlows(flows []ConnFlow, labCIDRs []string, rules []AccessRule, clientCIDRs ...[]string) []ConnFlow

RevokedFlows picks the tracked connections the access rules no longer allow: the ones a client opened to an address in a lab network (labCIDRs) whose (client, lab) relation has no allow rule now. FORWARD accepts established connections before the access chain is looked at, so changing the chain stops new connections only; an open SSH session or download lives on until its entry is removed from the conntrack table, after which its next packet is a new connection that the chain refuses.

Connections that do not start in a client's address and go to a lab (the pod's own traffic, connections between lab networks, anything the rules never covered) are left alone: they were never governed by a rule.

type ConntrackRevoker

type ConntrackRevoker struct {
	// contains filtered or unexported fields
}

ConntrackRevoker removes tracked connections the access rules no longer allow. The netlink socket lives in the netns of the calling process: for the VPN pod, the netns of wg0 and the lab ports, which is where FORWARD runs.

func NewConntrackRevoker

func NewConntrackRevoker() *ConntrackRevoker

func (*ConntrackRevoker) Close

func (c *ConntrackRevoker) Close()

func (*ConntrackRevoker) Revoke

func (c *ConntrackRevoker) Revoke(labCIDRs []string, rules []AccessRule, clientCIDRs ...[]string) (int, error)

Revoke deletes every connection RevokedFlows names and returns how many. A failure to delete one entry (it ended on its own meanwhile is not a failure) is returned after the rest were tried, so the reconcile that called it runs again.

type ForwardPlan added in v1.1.0

type ForwardPlan struct {
	Allows    []ForwardRule
	Decisions []AccessRule
}

func CompileForwardPlan added in v1.1.0

func CompileForwardPlan(clients []ClientAccessSnapshot, labs map[string]LabAccessSnapshot, policy []AccessPolicyRule) (ForwardPlan, error)

CompileForwardPlan keeps the complete decision matrix for compatible status, but emits only permitted, physically bound relations for the kernel.

type ForwardRule added in v1.1.0

type ForwardRule struct {
	ClientName, LabName string
	ClientCIDR, LabCIDR string
	LabInterface        string
	BindingID           string
}

type IPTablesManager

type IPTablesManager struct {
	BeforeRetire func(flowacct.CounterSnapshot) error
	AfterRetire  func([]string)
	// contains filtered or unexported fields
}

func NewIPTablesManager

func NewIPTablesManager(wgIface string) (*IPTablesManager, error)

func (*IPTablesManager) AccessCounters

func (m *IPTablesManager) AccessCounters() (map[string]TrafficCounter, error)

AccessCounters reads cumulative packet/byte counters from the dedicated chain and associates them with stable relation IDs.

func (*IPTablesManager) AllowDHCP

func (m *IPTablesManager) AllowDHCP(iface string) error

AllowDHCP opens DHCP on one lab interface (the pod runs a DHCP server there); DenyDHCP closes it.

func (*IPTablesManager) AllowPing

func (m *IPTablesManager) AllowPing(iface, addr string) error

AllowPing lets the devices of a lab ping the pod's own address on that lab's interface (and no other address of the pod); DenyPing takes it away with the interface.

func (*IPTablesManager) ApplyForwardPlan added in v1.1.0

func (m *IPTablesManager) ApplyForwardPlan(ctx context.Context, plan ForwardPlan) (ApplyResult, error)

func (*IPTablesManager) Cleanup

func (m *IPTablesManager) Cleanup()

func (*IPTablesManager) DenyDHCP

func (m *IPTablesManager) DenyDHCP(iface string)

func (*IPTablesManager) DenyPing

func (m *IPTablesManager) DenyPing(iface, addr string)

func (*IPTablesManager) GuardWireGuardPort

func (m *IPTablesManager) GuardWireGuardPort(uplink string, port int) (ipv6 bool, err error)

GuardWireGuardPort makes the WireGuard port of the pod reachable only through the uplink interface, where the wg-demux of the proxy delivers the clients' packets: a packet to that port from any other interface, the lab interfaces among them, is dropped (see wgguard.go). It must run before the WireGuard interface is created, so that the port is never open to the lab side. The result says whether IPv6 was guarded too (false: the pod has no ip6tables; the guard is then IPv4 only and the caller logs it).

func (*IPTablesManager) KnownBindingIDs added in v1.1.0

func (m *IPTablesManager) KnownBindingIDs() map[string]bool

func (*IPTablesManager) ProtectInput

func (m *IPTablesManager) ProtectInput(uplink, probeAddr string, probePort int) (ipv6Filtered bool, err error)

ProtectInput installs the INPUT policy of the pod (see internal/podinput): nothing on the lab side can talk to the pod itself, the WireGuard side reaches only the status page on probeAddr:probePort and rate-limited ping of probeAddr, the uplink is open. It must run before any interface of the pod comes up. The result says whether IPv6 is filtered (true) or switched off (false). Every failing step is an error and the pod must not start.

func (*IPTablesManager) Quiesce added in v1.1.0

func (m *IPTablesManager) Quiesce(ctx context.Context) error

func (*IPTablesManager) ReadPairCounters added in v1.1.0

func (m *IPTablesManager) ReadPairCounters(ctx context.Context) (flowacct.CounterSnapshot, error)

func (*IPTablesManager) ReplaceAccessRules

func (m *IPTablesManager) ReplaceAccessRules(rules []AccessRule) error

ReplaceAccessRules replaces the allowed symmetric bindings in one gate commit; detached retired counters are persisted before a cleanup commit.

func (*IPTablesManager) RestoreCounterBindings added in v1.1.0

func (m *IPTablesManager) RestoreCounterBindings(rows []flowacct.PairCounters)

RestoreCounterBindings attaches private persisted identities to surviving native chains before the first policy reconcile. Endpoints are not needed to read an already identified cumulative counter.

func (*IPTablesManager) SetupForwardPolicy

func (m *IPTablesManager) SetupForwardPolicy() error

SetupForwardPolicy closes the access gate and rebuilds the private VPN FORWARD chain in one commit. An empty access chain must never fall through to established forwarding during a surviving-network-namespace restart.

func (*IPTablesManager) WithPairCounters added in v1.1.0

func (m *IPTablesManager) WithPairCounters(ctx context.Context, observe func(flowacct.CounterSnapshot) error) error

WithPairCounters holds the same lock as retirement until its snapshot has been folded, so an older sample cannot arrive after a binding was forgotten.

type LabAccessSnapshot

type LabAccessSnapshot struct {
	VPNCIDR   string
	Ready     bool
	Interface string
}

LabAccessSnapshot is the minimum observed state needed to safely permit a VPN route. A not-ready laboratory must never receive an allow rule.

type RuleCommand added in v1.1.0

type RuleCommand interface {
	Save(context.Context) ([]byte, error)
	Restore(context.Context, []byte) error
}

type Server

type Server struct {
	WG    *WGManager
	IPT   *IPTablesManager
	Probe *probeServer
}

Server holds the running VPN server components.

func InitServer

func InitServer(cfg *Config) (*Server, error)

InitServer configures the WireGuard interface and iptables for the VPN server. Call Cleanup when done (deferred in main).

func (*Server) Cleanup

func (s *Server) Cleanup()

Cleanup shuts down the WireGuard interface and removes iptables rules.

type TrafficCounter

type TrafficCounter struct {
	Packets int64
	Bytes   int64
}

TrafficCounter is the cumulative kernel counter attached to one firewall relation.

type WGManager

type WGManager struct {
	// contains filtered or unexported fields
}

func NewWGManager

func NewWGManager(iface string) (*WGManager, error)

func (*WGManager) AddPeer

func (m *WGManager) AddPeer(pubKeyBase64 string, allowedIP string) error

func (*WGManager) Close

func (m *WGManager) Close()

func (*WGManager) Device

func (m *WGManager) Device() (*wgtypes.Device, error)

func (*WGManager) Init

func (m *WGManager) Init(privKeyBase64 string, listenPort int) error

func (*WGManager) RemovePeer

func (m *WGManager) RemovePeer(pubKeyBase64 string) error

Directories

Path Synopsis
Package flowacct counts, and never inspects, the connections that VPN clients open to the lab networks of one group.
Package flowacct counts, and never inspects, the connections that VPN clients open to the lab networks of one group.

Jump to

Keyboard shortcuts

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