ocserv

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2025 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CommandResult

type CommandResult struct {
	Success  bool
	Stdout   string
	Stderr   string
	ExitCode int
	ErrorMsg string
}

CommandResult represents the result of a command execution

type ConfigFile

type ConfigFile struct {
	// Path is the file path that was read
	Path string

	// Settings is a map of configuration keys to their values
	// Keys may have multiple values (e.g., routes, dns)
	Settings map[string][]string

	// RawLines contains the raw lines from the file (for preservation)
	RawLines []string
}

ConfigFile represents a parsed ocserv configuration file

func (*ConfigFile) AllKeys

func (cfg *ConfigFile) AllKeys() []string

AllKeys returns all configuration keys

func (*ConfigFile) GetSetting

func (cfg *ConfigFile) GetSetting(key string) (string, bool)

GetSetting retrieves a single-value setting from the config

func (*ConfigFile) GetSettings

func (cfg *ConfigFile) GetSettings(key string) ([]string, bool)

GetSettings retrieves all values for a multi-value setting

func (*ConfigFile) HasSetting

func (cfg *ConfigFile) HasSetting(key string) bool

HasSetting checks if a setting exists

type ConfigReader

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

ConfigReader handles reading ocserv configuration files

func NewConfigReader

func NewConfigReader(logger zerolog.Logger) *ConfigReader

NewConfigReader creates a new ConfigReader instance

func (*ConfigReader) ListGroupConfigs

func (r *ConfigReader) ListGroupConfigs(ctx context.Context, baseDir string) ([]string, error)

ListGroupConfigs lists all available per-group configuration files

func (*ConfigReader) ListUserConfigs

func (r *ConfigReader) ListUserConfigs(ctx context.Context, baseDir string) ([]string, error)

ListUserConfigs lists all available per-user configuration files

func (*ConfigReader) ReadGroupConfig

func (r *ConfigReader) ReadGroupConfig(ctx context.Context, baseDir, groupname string) (*ConfigFile, error)

ReadGroupConfig reads a per-group configuration file

func (*ConfigReader) ReadOcservConf

func (r *ConfigReader) ReadOcservConf(ctx context.Context, path string) (*ConfigFile, error)

ReadOcservConf reads the main ocserv configuration file

func (*ConfigReader) ReadUserConfig

func (r *ConfigReader) ReadUserConfig(ctx context.Context, baseDir, username string) (*ConfigFile, error)

ReadUserConfig reads a per-user configuration file

type Event

type Event struct {
	Timestamp time.Time `json:"timestamp"`
	EventType string    `json:"event_type"` // "connect", "disconnect", "auth-failure"
	Username  string    `json:"username"`
	RemoteIP  string    `json:"remote_ip"`
	SessionID string    `json:"session_id,omitempty"`
	Reason    string    `json:"reason,omitempty"`
	Details   string    `json:"details,omitempty"`
}

Event represents a connection event from 'show events' command (streaming)

type IPBan

type IPBan struct {
	IP        string    `json:"ip"`
	Score     int       `json:"score"`
	BannedAt  time.Time `json:"banned_at"`
	ExpiresAt time.Time `json:"expires_at"`
	Reason    string    `json:"reason,omitempty"`
}

IPBan represents banned IP information from 'show ip bans' command

type IPBanPoints

type IPBanPoints struct {
	IP           string    `json:"ip"`
	Points       int       `json:"points"`
	LastActivity time.Time `json:"last_activity"`
	Events       []string  `json:"events,omitempty"`
}

IPBanPoints represents IP with accumulated violation points from 'show ip ban points' command

type IRoute

type IRoute struct {
	ID       int      `json:"ID"`       // 835257
	Username string   `json:"Username"` // "lpa"
	Vhost    string   `json:"vhost"`    // "default"
	Device   string   `json:"Device"`   // "vpns0"
	IP       string   `json:"IP"`       // "10.0.16.23"
	IRoutes  []string `json:"iRoutes"`  // [] or ["192.168.1.0/24"]
}

IRoute represents user-provided route information from 'show iroutes' command

type Manager

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

Manager provides high-level ocserv management with security

func NewManager

func NewManager(cfg *config.Config, logger zerolog.Logger) *Manager

NewManager creates a new ocserv manager

func (*Manager) ExecuteCommand

func (m *Manager) ExecuteCommand(ctx context.Context, commandType string, args []string) (*CommandResult, error)

ExecuteCommand executes a validated command

func (*Manager) GetConfigReader

func (m *Manager) GetConfigReader() *ConfigReader

GetConfigReader returns the config reader (for direct access if needed)

func (*Manager) GetOcctlManager

func (m *Manager) GetOcctlManager() *OcctlManager

GetOcctlManager returns the occtl manager (for direct access if needed)

func (*Manager) GetSystemctlManager

func (m *Manager) GetSystemctlManager() *SystemctlManager

GetSystemctlManager returns the systemctl manager (for direct access if needed)

func (*Manager) ListGroupConfigs

func (m *Manager) ListGroupConfigs(ctx context.Context, baseDir string) ([]string, error)

ListGroupConfigs lists all available per-group configuration files

func (*Manager) ListUserConfigs

func (m *Manager) ListUserConfigs(ctx context.Context, baseDir string) ([]string, error)

ListUserConfigs lists all available per-user configuration files

func (*Manager) ReadGroupConfig

func (m *Manager) ReadGroupConfig(ctx context.Context, baseDir, groupname string) (*ConfigFile, error)

ReadGroupConfig reads a per-group configuration file

func (*Manager) ReadOcservConf

func (m *Manager) ReadOcservConf(ctx context.Context, path string) (*ConfigFile, error)

ReadOcservConf reads the main ocserv configuration file

func (*Manager) ReadUserConfig

func (m *Manager) ReadUserConfig(ctx context.Context, baseDir, username string) (*ConfigFile, error)

ReadUserConfig reads a per-user configuration file

type OcctlManager

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

OcctlManager handles occtl operations

func NewOcctlManager

func NewOcctlManager(socketPath, sudoUser string, timeout time.Duration, logger zerolog.Logger) *OcctlManager

NewOcctlManager creates a new occtl manager

func (*OcctlManager) DisconnectID

func (m *OcctlManager) DisconnectID(ctx context.Context, id string) error

DisconnectID disconnects a user by session ID

func (*OcctlManager) DisconnectUser

func (m *OcctlManager) DisconnectUser(ctx context.Context, username string) error

DisconnectUser disconnects a user by username

func (*OcctlManager) Reload

func (m *OcctlManager) Reload(ctx context.Context) error

Reload sends reload signal to ocserv (handled via systemctl in Manager)

func (*OcctlManager) ShowID

func (m *OcctlManager) ShowID(ctx context.Context, id string) (*UserDetailed, error)

ShowID retrieves detailed information about a specific connection ID

func (*OcctlManager) ShowIPBanPoints

func (m *OcctlManager) ShowIPBanPoints(ctx context.Context) ([]IPBanPoints, error)

ShowIPBanPoints retrieves IPs with accumulated violation points

func (*OcctlManager) ShowIPBans

func (m *OcctlManager) ShowIPBans(ctx context.Context) ([]IPBan, error)

ShowIPBans retrieves list of banned IP addresses

func (*OcctlManager) ShowIRoutes

func (m *OcctlManager) ShowIRoutes(ctx context.Context) ([]IRoute, error)

ShowIRoutes retrieves user-provided routes for all connected users

func (*OcctlManager) ShowSession

func (m *OcctlManager) ShowSession(ctx context.Context, sessionID string) (*SessionInfo, error)

ShowSession retrieves information about a specific session ID

func (*OcctlManager) ShowSessionsAll

func (m *OcctlManager) ShowSessionsAll(ctx context.Context) ([]SessionInfo, error)

ShowSessionsAll retrieves all sessions

func (*OcctlManager) ShowSessionsValid

func (m *OcctlManager) ShowSessionsValid(ctx context.Context) ([]SessionInfo, error)

ShowSessionsValid retrieves valid (reconnectable) sessions

func (*OcctlManager) ShowStats

func (m *OcctlManager) ShowStats(ctx context.Context) (*ServerStats, error)

ShowStats retrieves server statistics

func (*OcctlManager) ShowStatus

func (m *OcctlManager) ShowStatus(ctx context.Context) (*ServerStatus, error)

ShowStatus retrieves server status

func (*OcctlManager) ShowStatusDetailed

func (m *OcctlManager) ShowStatusDetailed(ctx context.Context) (*ServerStatusDetailed, error)

ShowStatusDetailed retrieves detailed server status with all metrics

func (*OcctlManager) ShowUser

func (m *OcctlManager) ShowUser(ctx context.Context, username string) ([]UserDetailed, error)

ShowUser retrieves detailed information about a specific user Note: Returns array - multiple elements if user has multiple active sessions

func (*OcctlManager) ShowUsers

func (m *OcctlManager) ShowUsers(ctx context.Context) ([]User, error)

ShowUsers retrieves list of connected users

func (*OcctlManager) ShowUsersDetailed

func (m *OcctlManager) ShowUsersDetailed(ctx context.Context) ([]UserDetailed, error)

ShowUsersDetailed retrieves detailed list of connected users with all information

func (*OcctlManager) UnbanIP

func (m *OcctlManager) UnbanIP(ctx context.Context, ip string) error

UnbanIP removes an IP address from the ban list

type ServerStats

type ServerStats struct {
	ActiveUsers      int
	TotalSessions    int64
	TotalBytesIn     uint64
	TotalBytesOut    uint64
	TLSDBSize        int
	TLSDBEntries     int
	IPLeaseDBSize    int
	IPLeaseDBEntries int
}

ServerStats represents ocserv statistics

func (*ServerStats) MarshalJSON

func (s *ServerStats) MarshalJSON() ([]byte, error)

MarshalJSON for ServerStats to handle large numbers

type ServerStatus

type ServerStatus struct {
	Status      string
	SecMod      string
	Compression string
	Uptime      int64
}

ServerStatus represents ocserv status

type ServerStatusDetailed

type ServerStatusDetailed struct {
	// Status
	Status          string `json:"Status"`                 // "online"
	ServerPID       int    `json:"Server PID"`             // 802
	SecModPID       int    `json:"Sec-mod PID"`            // 821
	SecModInstances int    `json:"Sec-mod instance count"` // 1

	// Uptime
	UpSince         string `json:"Up since"`     // "2025-09-12 14:37"
	UpSinceRelative string `json:"_Up since"`    // "40days"
	RawUpSince      int64  `json:"raw_up_since"` // 1757677078
	Uptime          int64  `json:"uptime"`       // 3498723 (seconds)

	// Sessions
	ActiveSessions int `json:"Active sessions"`               // 0
	TotalSessions  int `json:"Total sessions"`                // 44
	TotalAuthFails int `json:"Total authentication failures"` // 10
	IPsInBanList   int `json:"IPs in ban list"`               // 0

	// Stats reset
	LastStatsReset         string `json:"Last stats reset"`     // "2025-10-20 20:40"
	LastStatsResetRelative string `json:"_Last stats reset"`    // " 2days"
	RawLastStatsReset      int64  `json:"raw_last_stats_reset"` // 1760982020

	// Since last reset
	SessionsHandled      int `json:"Sessions handled"`             // 4
	TimedOutSessions     int `json:"Timed out sessions"`           // 0
	IdleTimedOutSessions int `json:"Timed out (idle) sessions"`    // 0
	ErrorClosedSessions  int `json:"Closed due to error sessions"` // 2
	AuthFailures         int `json:"Authentication failures"`      // 0

	// Timing stats
	AvgAuthTime    string `json:"Average auth time"` // "    0s"
	RawAvgAuthTime int    `json:"raw_avg_auth_time"` // 0 (seconds)
	MaxAuthTime    string `json:"Max auth time"`     // "    5s"
	RawMaxAuthTime int    `json:"raw_max_auth_time"` // 5

	AvgSessionTime    string `json:"Average session time"` // " 3h:43m"
	RawAvgSessionTime int    `json:"raw_avg_session_time"` // 13380 (seconds)
	MaxSessionTime    string `json:"Max session time"`     // " 1h:32m"
	RawMaxSessionTime int    `json:"raw_max_session_time"` // 5520 (seconds)

	// Network
	MinMTU int `json:"Min MTU"` // 1324
	MaxMTU int `json:"Max MTU"` // 1402

	// Traffic (since last reset)
	RX    string `json:"RX"`     // "110.0 MB"
	RawRX int64  `json:"raw_rx"` // 110013000 (bytes)
	TX    string `json:"TX"`     // "1.8 GB"
	RawTX int64  `json:"raw_tx"` // 1827434000 (bytes)
}

ServerStatusDetailed represents complete server status from 'show status' command

type ServiceStatus

type ServiceStatus struct {
	Active      bool
	State       string // "running", "dead", "failed", etc.
	SubState    string // "running", "exited", etc.
	Description string
	MainPID     int
	LoadState   string // "loaded", "not-found", etc.
}

ServiceStatus represents the status of a systemd service

type SessionInfo

type SessionInfo struct {
	Session     string `json:"Session"`      // "0/zuQ1"
	FullSession string `json:"Full session"` // "0/zuQ1RjBWv5J/hneJun8+sesWs="
	Created     string `json:"Created"`      // "2025-10-23 02:30"
	State       string `json:"State"`        // "authenticated"
	Username    string `json:"Username"`     // "lpa"
	Groupname   string `json:"Groupname"`    // "(none)"
	Vhost       string `json:"vhost"`        // "default"
	UserAgent   string `json:"User-Agent"`   // "AnyConnect AppleSSLVPN_Darwin_ARM (iPhone) 5.1.11.347"
	RemoteIP    string `json:"Remote IP"`    // "90.156.164.225"
	Location    string `json:"Location"`     // "unknown"

	// Session flags
	SessionIsOpen int `json:"session_is_open"` // 1 or 0
	TLSAuthOK     int `json:"tls_auth_ok"`     // 1 or 0
	InUse         int `json:"in_use"`          // 1 or 0
}

SessionInfo represents session information from 'show sessions' or 'show session' commands

type SystemctlManager

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

SystemctlManager handles systemctl operations for ocserv service

func NewSystemctlManager

func NewSystemctlManager(serviceName, sudoUser string, timeout time.Duration, logger zerolog.Logger) *SystemctlManager

NewSystemctlManager creates a new systemctl manager

func (*SystemctlManager) IsActive

func (m *SystemctlManager) IsActive(ctx context.Context) (bool, error)

IsActive checks if the service is active

func (*SystemctlManager) IsEnabled

func (m *SystemctlManager) IsEnabled(ctx context.Context) (bool, error)

IsEnabled checks if the service is enabled

func (*SystemctlManager) Reload

func (m *SystemctlManager) Reload(ctx context.Context) error

Reload reloads the ocserv service configuration

func (*SystemctlManager) Restart

func (m *SystemctlManager) Restart(ctx context.Context) error

Restart restarts the ocserv service

func (*SystemctlManager) Start

func (m *SystemctlManager) Start(ctx context.Context) error

Start starts the ocserv service

func (*SystemctlManager) Status

func (m *SystemctlManager) Status(ctx context.Context) (*ServiceStatus, error)

Status gets the current status of the ocserv service

func (*SystemctlManager) Stop

func (m *SystemctlManager) Stop(ctx context.Context) error

Stop stops the ocserv service

type User

type User struct {
	ID                int         `json:"ID"`
	Username          string      `json:"Username"`
	Groupname         string      `json:"Groupname"`
	State             string      `json:"State"`
	VHost             string      `json:"vhost"`
	Device            string      `json:"Device"`
	MTU               string      `json:"MTU"`
	RemoteIP          string      `json:"Remote IP"`
	Location          string      `json:"Location"`
	LocalDeviceIP     string      `json:"Local Device IP"`
	IPv4              string      `json:"IPv4"`
	PtPIPv4           string      `json:"P-t-P IPv4"`
	IPv6              string      `json:"IPv6"`
	PtPIPv6           string      `json:"P-t-P IPv6"`
	UserAgent         string      `json:"User-Agent"`
	RX                string      `json:"RX"`
	TX                string      `json:"TX"`
	ReadableRX        string      `json:"_RX"`
	ReadableTX        string      `json:"_TX"`
	AverageRX         string      `json:"Average RX"`
	AverageTX         string      `json:"Average TX"`
	DPD               string      `json:"DPD"`
	KeepAlive         string      `json:"KeepAlive"`
	Hostname          string      `json:"Hostname"`
	ConnectedAt       string      `json:"Connected at"`
	ConnectedDuration string      `json:"_Connected at"`
	RawConnectedAt    int64       `json:"raw_connected_at"`
	FullSession       string      `json:"Full session"`
	Session           string      `json:"Session"`
	TLSCiphersuite    string      `json:"TLS ciphersuite"`
	DTLSCipher        string      `json:"DTLS cipher"`
	CSTPCompression   string      `json:"CSTP compression"`
	DTLSCompression   string      `json:"DTLS compression"`
	DNS               []string    `json:"DNS"`
	NBNS              []string    `json:"NBNS"`
	SplitDNSDomains   []string    `json:"Split-DNS-Domains"`
	Routes            interface{} `json:"Routes"` // Can be []string or string (e.g. "defaultroute")
	NoRoutes          []string    `json:"No-routes"`
	IRoutes           []string    `json:"iRoutes"`
	RestrictedRoutes  string      `json:"Restricted to routes"`
	RestrictedPorts   []string    `json:"Restricted to ports"`
}

User represents a connected VPN user

type UserDetailed

type UserDetailed struct {
	// Identity
	ID        int    `json:"ID"`
	Username  string `json:"Username"`
	Groupname string `json:"Groupname"`
	State     string `json:"State"` // "connected", "authenticated"
	Vhost     string `json:"vhost"` // "default" or virtual host name

	// Network
	Device        string `json:"Device"`          // "vpns0"
	MTU           string `json:"MTU"`             // "1402"
	RemoteIP      string `json:"Remote IP"`       // Client's real IP
	Location      string `json:"Location"`        // GeoIP location or "unknown"
	LocalDeviceIP string `json:"Local Device IP"` // Server's interface IP

	// VPN IPs
	IPv4    string `json:"IPv4"`       // "10.0.16.23"
	PtPIPv4 string `json:"P-t-P IPv4"` // "10.0.16.1"
	IPv6    string `json:"IPv6"`       // "fc00::1:8651"
	PtPIPv6 string `json:"P-t-P IPv6"` // "fc00::1:8601"

	// Client info
	UserAgent string `json:"User-Agent"`         // "AnyConnect AppleSSLVPN_Darwin_ARM (iPhone) 5.1.11.347"
	Hostname  string `json:"Hostname,omitempty"` // "localhost" (optional)

	// Traffic stats
	RX          string `json:"RX"`         // "0"
	TX          string `json:"TX"`         // "96"
	RXFormatted string `json:"_RX"`        // "0 bytes"
	TXFormatted string `json:"_TX"`        // "96 bytes"
	AverageRX   string `json:"Average RX"` // "0 bytes/s"
	AverageTX   string `json:"Average TX"` // "32 bytes/s"

	// Connection params
	DPD       string `json:"DPD"`       // "90"
	KeepAlive string `json:"KeepAlive"` // "32400"

	// Connection time
	ConnectedAt         string `json:"Connected at"`     // "2025-10-23 02:32"
	ConnectedAtRelative string `json:"_Connected at"`    // "    3s"
	RawConnectedAt      int64  `json:"raw_connected_at"` // 1761175942 (Unix timestamp)

	// Session
	FullSession string `json:"Full session"` // "0/zuQ1RjBWv5J/hneJun8+sesWs="
	Session     string `json:"Session"`      // "0/zuQ1"

	// Security
	TLSCiphersuite string `json:"TLS ciphersuite"`       // "(TLS1.3)-(ECDHE-SECP256R1)-(RSA-PSS-RSAE-SHA256)-(AES-256-GCM)"
	DTLSCipher     string `json:"DTLS cipher,omitempty"` // "(DTLS1.2)-(ECDHE-RSA)-(AES-256-GCM)" (optional)

	// Compression
	CSTPCompression string `json:"CSTP compression,omitempty"` // "lzs" (optional)
	DTLSCompression string `json:"DTLS compression,omitempty"` // "lzs" (optional)

	// Network config
	DNS             []string    `json:"DNS"`               // ["10.0.16.1", "fc00::1:8601"]
	NBNS            []string    `json:"NBNS"`              // []
	SplitDNSDomains []string    `json:"Split-DNS-Domains"` // []
	Routes          interface{} `json:"Routes"`            // "defaultroute" or []string
	NoRoutes        []string    `json:"No-routes"`         // []
	IRoutes         []string    `json:"iRoutes"`           // []

	// Restrictions
	RestrictedToRoutes string   `json:"Restricted to routes"` // "False" or "True"
	RestrictedToPorts  []string `json:"Restricted to ports"`  // []
}

UserDetailed represents complete user information from 'show user' command Based on production ocserv 1.3.0 JSON output

Directories

Path Synopsis
Package testutil provides test utilities for integration testing
Package testutil provides test utilities for integration testing

Jump to

Keyboard shortcuts

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