Documentation
¶
Overview ¶
Package ovpm provides the implementation of core OVPM API.
ovpm can create and destroy OpenVPN servers, manage vpn users, handle certificates etc...
Index ¶
- Constants
- Variables
- func AdminPerms() []permset.Perm
- func ConnectionList() (list []clEntry, lastUpdate time.Time)
- func GetAvailableInterfaces() ([]string, error)
- func GetDetailedStatistics(filters StatisticFilters) ([]dbStatisticModel, error)
- func HostID2IP(hostid uint32) net.IP
- func IP2HostID(ip net.IP) uint32
- func IncrementIP(ip, mask string) (string, error)
- func InitializeFileWatcher() error
- func IsNetworkType(s string) bool
- func UserPerms() []permset.Perm
- type DB
- type DiskUsage
- type FileWatcher
- type InterfaceStats
- type InterfaceStatsResponse
- type Network
- func (n *Network) Associate(username string) error
- func (n *Network) Delete() error
- func (n *Network) Dissociate(username string) error
- func (n *Network) GetAssociatedUsernames() []string
- func (n *Network) GetAssociatedUsers() []*User
- func (n *Network) GetCIDR() string
- func (n *Network) GetCreatedAt() string
- func (n *Network) GetName() string
- func (n *Network) GetType() NetworkType
- func (n *Network) GetVia() string
- type NetworkInterface
- type NetworkInterfacesResponse
- type NetworkType
- type Server
- func (svr *Server) CAExpiresAt() time.Time
- func (svr *Server) CheckSerial(serial string) bool
- func (svr *Server) Deinit() error
- func (svr *Server) DumpClientConfig(username, path string) error
- func (svr *Server) DumpsClientConfig(username string) (string, error)
- func (svr *Server) Emit() error
- func (svr *Server) EmitWithRestart() error
- func (svr *Server) ExpiresAt() time.Time
- func (svr *Server) GetCACert() string
- func (svr *Server) GetCAKey() string
- func (svr *Server) GetCRL() string
- func (svr *Server) GetConnectedUsers() ([]User, error)
- func (svr *Server) GetCreatedAt() string
- func (svr *Server) GetDNS() string
- func (svr *Server) GetHostname() string
- func (svr *Server) GetKeepalivePeriod() string
- func (svr *Server) GetKeepaliveTimeout() string
- func (svr *Server) GetKey() string
- func (svr *Server) GetMask() string
- func (svr *Server) GetNet() string
- func (svr *Server) GetPort() string
- func (svr *Server) GetProto() string
- func (svr *Server) GetSerialNumber() string
- func (svr *Server) GetServerName() string
- func (svr *Server) GetSystemCA() (*pki.CA, error)
- func (svr *Server) Init(hostname string, port string, proto string, ipblock string, dns string, ...) error
- func (svr *Server) IsInitialized() bool
- func (svr *Server) IsUseLZO() bool
- func (svr *Server) Refresh() error
- func (svr *Server) RestartVPNProc()
- func (svr *Server) StartVPNProc()
- func (svr *Server) StopVPNProc()
- func (svr *Server) Update(ipblock string, dns string, useLzo *bool) error
- type SpeedStat
- type StatisticFilters
- type StatisticSummary
- type SystemStatus
- type User
- func (u *User) CheckPassword(password string) bool
- func (u *User) ConnectionStatus() (isConnected bool, connectedSince time.Time, bytesSent uint64, ...)
- func (u *User) Delete() error
- func (u *User) ExpiresAt() time.Time
- func (u *User) GetCert() string
- func (u *User) GetCreatedAt() string
- func (u *User) GetDescription() string
- func (u *User) GetHostID() uint32
- func (u *User) GetIPNet() string
- func (u *User) GetServerSerialNumber() string
- func (u *User) GetUsername() string
- func (u *User) IsAdmin() bool
- func (u *User) IsNoGW() bool
- func (u *User) Renew() error
- func (u *User) RenewToken() (string, error)
- func (u *User) ResetPassword(password string) error
- func (u *User) Update(password string, nogw bool, hostid uint32, admin bool, description string) error
- func (u *User) ValidateToken(token string) bool
- type UserStatistics
Constants ¶
const ( // DefaultVPNPort is the default OpenVPN port to listen. DefaultVPNPort = "1197" // DefaultVPNProto is the default OpenVPN protocol to use. DefaultVPNProto = UDPProto // DefaultVPNNetwork is the default OpenVPN network to use. DefaultVPNNetwork = "10.9.0.0/24" // DefaultVPNDNS is the default DNS to push to clients. DefaultVPNDNS = "8.8.8.8" // DefaultDaemonPort is the port OVPMD will listen by default if something else is not specified. DefaultDaemonPort = 9090 // DefaultKeepalivePeriod is the default ping period to check if the remote peer is alive. DefaultKeepalivePeriod = "2" // DefaultKeepaliveTimeout is the default ping timeout to assume that remote peer is down. DefaultKeepaliveTimeout = "4" )
const ( // User permissions CreateUserPerm permset.Perm = iota GetAnyUserPerm GetSelfPerm UpdateAnyUserPerm UpdateSelfPerm DeleteAnyUserPerm RenewAnyUserPerm GenConfigAnyUserPerm GenConfigSelfPerm // VPN permissions GetVPNStatusPerm InitVPNPerm UpdateVPNPerm RestartVPNPerm // Network permissions ListNetworksPerm CreateNetworkPerm DeleteNetworkPerm GetNetworkTypesPerm GetNetworkAssociatedUsersPerm AssociateNetworkUserPerm DissociateNetworkUserPerm // Statistic permissions ListStatisticPerm )
OVPM available permissions.
const ( TCPProto string = "tcp" UDPProto string = "udp" )
Possible VPN protocols.
Variables ¶
var Testing = false
Testing is used to determine whether we are testing or running normally. Set it to true when testing.
var Version = "development"
Version defines the version of ovpm.
Functions ¶
func AdminPerms ¶
AdminPerms returns the list of permissions that admin type user has.
func ConnectionList ¶
ConnectionList returns information about user's connections to the VPN server.
func GetAvailableInterfaces ¶
GetAvailableInterfaces возвращает список доступных интерфейсов из /proc/net/dev
func GetDetailedStatistics ¶
func GetDetailedStatistics(filters StatisticFilters) ([]dbStatisticModel, error)
GetDetailedStatistics возвращает детальные записи с различными фильтрами
func IncrementIP ¶
IncrementIP will return next ip address within the network.
func InitializeFileWatcher ¶
func InitializeFileWatcher() error
InitializeFileWatcher инициализирует глобальный FileWatcher
func IsNetworkType ¶
IsNetworkType returns if the s is a valid network type or not.
Types ¶
type DB ¶
DB represents a persistent storage.
type FileWatcher ¶
type FileWatcher struct {
// contains filtered or unexported fields
}
func GetFileWatcher ¶
func GetFileWatcher() *FileWatcher
GetFileWatcher возвращает глобальный экземпляр FileWatcher
func NewFileWatcher ¶
func NewFileWatcher(filename string) (*FileWatcher, error)
func NewStatisticFileWatcher ¶
func NewStatisticFileWatcher() (*FileWatcher, error)
func (*FileWatcher) Close ¶
func (fw *FileWatcher) Close()
func (*FileWatcher) GetStatistics ¶
func (fw *FileWatcher) GetStatistics() []SpeedStat
func (*FileWatcher) Watch ¶
func (fw *FileWatcher) Watch()
type InterfaceStats ¶
type InterfaceStats struct {
InterfaceName string `json:"interface_name"`
TXBytes uint64 `json:"tx_bytes"`
RXBytes uint64 `json:"rx_bytes"`
TXBytesPerSec uint64 `json:"tx_bytes_per_sec"`
RXBytesPerSec uint64 `json:"rx_bytes_per_sec"`
TXPackets uint64 `json:"tx_packets"`
RXPackets uint64 `json:"rx_packets"`
Timestamp time.Time `json:"timestamp"`
}
InterfaceStats представляет статистику сетевого интерфейса
type InterfaceStatsResponse ¶
type InterfaceStatsResponse struct {
Stats InterfaceStats `json:"stats"`
}
InterfaceStatsResponse представляет ответ со статистикой интерфейса
func GetInterfaceStats ¶
func GetInterfaceStats(interfaceName string) (*InterfaceStatsResponse, error)
GetInterfaceStats возвращает статистику для указанного интерфейса
type Network ¶
type Network struct {
// contains filtered or unexported fields
}
Network represents a VPN related network.
func CreateNewNetwork ¶
func CreateNewNetwork(name, cidr string, nettype NetworkType, via string) (*Network, error)
CreateNewNetwork creates a new network definition in the system.
func GetAllNetworks ¶
func GetAllNetworks() []*Network
GetAllNetworks returns all networks defined in the system.
func GetNetwork ¶
GetNetwork returns a network specified by its name.
func (*Network) Dissociate ¶
Dissociate breaks up the given users association to the said network.
func (*Network) GetAssociatedUsernames ¶
GetAssociatedUsernames returns network's associated user names.
func (*Network) GetAssociatedUsers ¶
GetAssociatedUsers returns network's associated users.
func (*Network) GetCreatedAt ¶
GetCreatedAt returns network's name.
func (*Network) GetType ¶
func (n *Network) GetType() NetworkType
GetType returns network's network type.
type NetworkInterface ¶
NetworkInterface представляет информацию о сетевом интерфейсе
type NetworkInterfacesResponse ¶
type NetworkInterfacesResponse struct {
Interfaces []NetworkInterface
}
NetworkInterfacesResponse представляет ответ со списком интерфейсов
func GetNetworkInterfaces ¶
func GetNetworkInterfaces() (*NetworkInterfacesResponse, error)
GetNetworkInterfaces возвращает список сетевых интерфейсов
type NetworkType ¶
type NetworkType uint
NetworkType distinguishes different types of networks that is defined in the networks table.
const ( UNDEFINEDNET NetworkType = iota SERVERNET ROUTE )
NetworkTypes
func GetAllNetworkTypes ¶
func GetAllNetworkTypes() []NetworkType
GetAllNetworkTypes returns all network types defined in the system.
func NetworkTypeFromString ¶
func NetworkTypeFromString(typ string) NetworkType
NetworkTypeFromString returns string representation of the network type.
func (NetworkType) Description ¶
func (nt NetworkType) Description() string
Description gives description about the network type.
func (NetworkType) String ¶
func (nt NetworkType) String() string
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server represents VPN server.
func TheServer ¶
func TheServer() *Server
TheServer returns a pointer to the server instance.
Server instance is a singleton instance that is initialized on the first call made to the TheServer().
func (*Server) CAExpiresAt ¶
CAExpiresAt returns the expiry date time of the CA.
func (*Server) CheckSerial ¶
CheckSerial takes a serial number and checks it against the current server's serial number.
func (*Server) Deinit ¶
Deinit deletes the VPN server from the database and frees the allocated resources.
func (*Server) DumpClientConfig ¶
DumpClientConfig generates .ovpn file for the given vpn user and dumps it to outPath.
func (*Server) DumpsClientConfig ¶
DumpsClientConfig generates .ovpn file for the given vpn user and returns it as a string.
func (*Server) Emit ¶
Emit generates all needed files for the OpenVPN server and dumps them to their corresponding paths defined in the config.
func (*Server) EmitWithRestart ¶
EmitWithRestart restarts vpnProc after calling EmitWithRestart().
func (*Server) GetConnectedUsers ¶
GetConnectedUsers will return a list of users who are currently connected to the VPN service.
func (*Server) GetCreatedAt ¶
GetCreatedAt returns server's created at.
func (*Server) GetHostname ¶
GetHostname returns vpn server's hostname.
func (*Server) GetKeepalivePeriod ¶
func (*Server) GetKeepaliveTimeout ¶
func (*Server) GetSerialNumber ¶
GetSerialNumber returns server's serial number.
func (*Server) GetServerName ¶
GetServerName returns server's name.
func (*Server) GetSystemCA ¶
GetSystemCA returns the system CA from the database if available.
func (*Server) Init ¶
func (svr *Server) Init(hostname string, port string, proto string, ipblock string, dns string, keepalivePeriod string, keepaliveTimeout string, useLZO bool) error
Init regenerates keys and certs for a Root CA, gets initial settings for the VPN server and saves them in the database.
'proto' can be either "udp" or "tcp" and if it's "" it defaults to "udp".
'ipblock' is a IP network in the CIDR form. VPN clients get their IP addresses from this network. It defaults to const 'DefaultVPNNetwork'.
'keepalivePeriod' is the ping period to check if the remote peer is alive. It defaults to const 'DefaultKeepalivePeriod'
'keeapliveTimeout' is the ping timeout to assume that remote peer is down. It defaults to const 'DefaultKeepaliveTimeout'
'useLZO' is used to determine whether to use the lzo compression algorithm to support older clients. It defaults to false due to security issues and deprecation
Please note that, Init is potentially destructive procedure, it will cause invalidation of existing .ovpn profiles of the current users. So it should be used carefully.
func (*Server) IsInitialized ¶
IsInitialized checks if there is a default VPN server configured in the database or not.
func (*Server) RestartVPNProc ¶
func (svr *Server) RestartVPNProc()
RestartVPNProc restarts the OpenVPN process.
func (*Server) StartVPNProc ¶
func (svr *Server) StartVPNProc()
StartVPNProc starts the OpenVPN process.
func (*Server) StopVPNProc ¶
func (svr *Server) StopVPNProc()
StopVPNProc stops the OpenVPN process.
type StatisticFilters ¶
type StatisticFilters struct {
StartDate time.Time `form:"start_date"`
EndDate time.Time `form:"end_date"`
CommonName string `form:"common_name"`
RealAddress string `form:"real_address"`
UserID uint `form:"user_id"`
SortBy string `form:"sort_by"`
SortOrder string `form:"sort_order"`
Limit int `form:"limit"`
Offset int `form:"offset"`
}
StatisticFilters структура для фильтров
type StatisticSummary ¶
type StatisticSummary struct {
CommonName string `json:"common_name"`
ConnectionCount int64 `json:"connection_count"`
TotalBytesReceived int64 `json:"total_bytes_received"`
TotalBytesSent int64 `json:"total_bytes_sent"`
TotalBytes int64 `json:"total_bytes"`
AvgConnectionDurationSecs float64 `json:"avg_connection_duration_seconds"`
}
StatisticSummary структура для результатов группировки
func GetStatisticList ¶
func GetStatisticList() ([]StatisticSummary, error)
func GetStatisticsByDateRange ¶
func GetStatisticsByDateRange(startDate, endDate *time.Time, commonNameFilter string) ([]StatisticSummary, error)
GetStatisticsByDateRange возвращает статистику за указанный период с группировкой по CommonName
type SystemStatus ¶
type SystemStatus struct {
CPUUsage float64
MemoryTotal uint64
MemoryUsed uint64
SwapTotal uint64
SwapUsed uint64
LoadAverage []float64
DiskUsage []DiskUsage
Timestamp time.Time
}
SystemStatus представляет данные о состоянии системы
func GetSystemStatus ¶
func GetSystemStatus() (*SystemStatus, error)
GetSystemStatus возвращает полную статистику системы
type User ¶
type User struct {
// contains filtered or unexported fields
}
User represents a vpn user.
func CreateNewUser ¶
func CreateNewUser(username, password string, nogw bool, hostid uint32, admin bool, description string) (*User, error)
CreateNewUser creates a new user with the given username and password in the database. If nogw is true, then ovpm doesn't push vpn server as the default gw for the user.
It also generates the necessary client keys and signs certificates with the current server's CA.
func GetAllUsers ¶
GetAllUsers returns all recorded users in the database.
func GetUserByToken ¶
GetUserByToken finds and returns the user with the given token from database.
func (*User) CheckPassword ¶
CheckPassword returns whether the given password is correct for the user.
func (*User) ConnectionStatus ¶
func (u *User) ConnectionStatus() (isConnected bool, connectedSince time.Time, bytesSent uint64, bytesReceived uint64, tx float32, rx float32)
ConnectionStatus returns information about user's connection to the VPN server.
func (*User) GetCreatedAt ¶
GetCreatedAt returns user's creation time.
func (*User) GetDescription ¶
func (*User) GetServerSerialNumber ¶
GetServerSerialNumber returns user's server serial number.
func (*User) IsNoGW ¶
IsNoGW returns whether user is set to get the vpn server as their default gateway.
func (*User) Renew ¶
Renew creates a key and a ceritificate signed by the current server's CA.
This is often used to sign users when the current CA is changed while there are still existing users in the database.
Also it can be used when a user cert is expired or user's private key stolen, missing etc.
func (*User) RenewToken ¶
RenewToken generates a new AuthToken and sets it to the db.
func (*User) ResetPassword ¶
ResetPassword resets the users password into the provided password.
func (*User) Update ¶
func (u *User) Update(password string, nogw bool, hostid uint32, admin bool, description string) error
Update updates the user's attributes and writes them to the database.
How this method works is similiar to PUT semantics of REST. It sets the user record fields to the provided function arguments.
func (*User) ValidateToken ¶
ValidateToken returns whether the given token is valid or not.
type UserStatistics ¶
type UserStatistics struct {
Username string `json:"username"`
UserID uint `json:"user_id"`
TotalConnections int64 `json:"total_connections"`
TotalBytesReceived int64 `json:"total_bytes_received"`
TotalBytesSent int64 `json:"total_bytes_sent"`
TotalBytes int64 `json:"total_bytes"`
AvgConnectionDurationSecs float64 `json:"avg_connection_duration_seconds"`
LastConnection time.Time `json:"last_connection"`
}
UserStatistics структура для статистики пользователя
func GetUserStatistics ¶
func GetUserStatistics(commonName string, startDate, endDate time.Time) (*UserStatistics, error)
GetUserStatistics возвращает статистику по конкретному пользователю
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
pb
Package pb is a reverse proxy.
|
Package pb is a reverse proxy. |
|
cmd
|
|
|
ovpm
command
|
|
|
ovpmd
command
|
|
|
Package permset provides primitives for permission management.
|
Package permset provides primitives for permission management. |
|
Package pki contains bits and pieces to work with OpenVPN PKI related operations.
|
Package pki contains bits and pieces to work with OpenVPN PKI related operations. |
|
Package supervisor provides a generic API to watch and manage Unix processes.
|
Package supervisor provides a generic API to watch and manage Unix processes. |
