internal

package
v0.0.0-...-851e5e8 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2024 License: GPL-3.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Success
	CodeSuccess          int64 = 1000
	CodeConnecting       int64 = 1001
	CodeConnected        int64 = 1002
	CodeDisconnected     int64 = 1003
	CodeInteraction      int64 = 1004
	CodeProxyNone        int64 = 1005
	CodeSuccessWithArg   int64 = 1006
	CodeSuccessWithoutAC int64 = 1007

	// Warning
	CodeNothingToDo      int64 = 2000
	CodeVPNRunning       int64 = 2002
	CodeVPNNotRunning    int64 = 2003
	CodeUFWDisabled      int64 = 2004
	CodeTokenInvalidated int64 = 2005

	// Error
	CodeFailure      int64 = 3000
	CodeUnauthorized int64 = 3001
	CodeFormatError  int64 = 3003
	// CodeConfigError is returned when config loading and/or saving fails.
	CodeConfigError                    int64 = 3004
	CodeEmptyPayloadError              int64 = 3005
	CodeOffline                        int64 = 3007
	CodeAccountExpired                 int64 = 3008
	CodeVPNMisconfig                   int64 = 3010
	CodeDaemonOffline                  int64 = 3013
	CodeGatewayError                   int64 = 3014
	CodeOutdated                       int64 = 3015
	CodeDependencyError                int64 = 3017
	CodeNoNewDataError                 int64 = 3019
	CodeNoVPNService                   int64 = 3020
	CodeExpiredRenewToken              int64 = 3021
	CodeTokenRenewError                int64 = 3022
	CodeKillSwitchError                int64 = 3023
	CodeBadRequest                     int64 = 3024
	CodeConflict                       int64 = 3025
	CodeInternalError                  int64 = 3026
	CodeOpenVPNAccountExpired          int64 = 3031
	CodeServerUnavailable              int64 = 3032
	CodeTagNonexisting                 int64 = 3033
	CodeDoubleGroupError               int64 = 3034
	CodeTokenLoginFailure              int64 = 3035
	CodeGroupNonexisting               int64 = 3036
	CodeAutoConnectServerNotObfuscated int64 = 3037
	CodeAutoConnectServerObfuscated    int64 = 3038
	CodeTokenInvalid                   int64 = 3039
	CodePrivateSubnetLANDiscovery      int64 = 3040
)
View Source
const (
	// ListenPID defines process id env key
	ListenPID = "LISTEN_PID"

	// ListenFDS defines systemDFile descriptors env key
	ListenFDS = "LISTEN_FDS"

	// ListenFDNames defines systemDFile descriptors names env key
	ListenFDNames = "LISTEN_FDNAMES"

	// Proto defines protocol to be used
	Proto = "unix"

	// TmpDir defines temporary storage directory
	TmpDir = "/tmp/"

	// NordvpnGroup that can access daemon socket
	NordvpnGroup = "nordvpn"

	// PermUserRWX user permission type to read write and execute
	PermUserRWX = 0700

	// PermUserRW user permission type to read and write
	PermUserRW = 0600

	// PermUserRWGroupRW permission type for user and group to read and write, everyone else - no access.
	PermUserRWGroupRW = 0660

	// PermUserRWGroupROthersR user permission type for user to read and write to it, everyone else can only read it.
	PermUserRWGroupROthersR = 0644

	// PermUserRWGroupROthersR allows user and group to read and write, other only read
	PermUserRWGroupRWOthersR = 0664

	// PermUserRWGroupROthersR user permission type for everyone to read and write to it.
	PermUserRWGroupRWOthersRW = 0666

	// PermUserRWXGroupRXOthersRX forbidding group and others to write to it
	PermUserRWXGroupRXOthersRX = 0755

	// ChattrExec is the chattr command executable name
	ChattrExec = "chattr"

	// Column is a tool to format data into columns for neater display in CLI
	ColumnExec = "column"

	// SttyExec is a tool to change or print CLI settings
	SttyExec = "stty"

	// SystemctlExec defines system controller executable
	SystemctlExec = "systemctl"

	// NetworkctlExec defines network controller executable
	NetworkctlExec = "networkctl"

	// ServerDateFormat defines api date format
	ServerDateFormat = "2006-01-02 15:04:05"

	// Fileshared defines filesharing process name
	Fileshare = "nordfileshare"

	Norduser  = "norduser"
	Norduserd = "norduserd"

	NorduserLogFile = "norduser" + LogFileExtension

	// FileshareHistoryFile is the storage file used by libdrop
	FileshareHistoryFile = "fileshare_history.db"

	FileshareSocket = TmpDir + "fileshare.sock"

	FileshareLogFileName = "nordfileshare" + LogFileExtension

	LogFileExtension = ".log"
)
View Source
const (
	// Development defines development environment
	Development Environment = "dev"
	// QA defines qa environment
	QA = "qa"
	// Production defines production environment
	Production = "prod"
	// Downloader modifies configs and servers jobs
	Downloader = "downloader"
)
View Source
const (
	ConnectSuccess    = "You are connected to %s (%s)!"
	ReconnectSuccess  = "You have been reconnected to %s (%s)"
	DisconnectSuccess = "You are disconnected from NordVPN."

	ProtocolErrorMessage   = "protocol: failed to parse %s"
	TechnologyErrorMessage = "technology: failed to parse %s"

	DaemonConnRefusedErrorMessage = "Cannot reach System Daemon."

	ServerUnavailableErrorMessage = "The specified server is not available at the moment or does not support your connection settings."
	TagNonexistentErrorMessage    = "The specified server does not exist."
	GroupNonexistentErrorMessage  = "The specified group does not exist."
	FilterNonExistentErrorMessage = "The specified filter does not exist."
	DoubleGroupErrorMessage       = "You cannot connect to a group and set the group option at the same time."

	DebugPrefix = "[Debug]"
	// DeferPrefix is used when logging errors in deferred or cleanup code.
	DeferPrefix = "[Defer]"
	// ErrorPrefix is used when logging errors, which impact control flow.
	ErrorPrefix = "[Error]"
	// WarningPrefix is used when logging errors, which don't impact control flow.
	WarningPrefix = "[Warning]"
	InfoPrefix    = "[Info]"

	// UnhandledMessage represents the default message for unhandled errors
	UnhandledMessage = "Something went wrong. Please try again. If the problem persists, contact our customer support."
)
View Source
const (
	NotificationConnected    = 0000
	NotificationReconnected  = 0001
	NotificationDisconnected = 0002
)

Variables

View Source
var (
	PlatformSupportsIPv4 = true
	PlatformSupportsIPv6 = true
)
View Source
var (
	// RunDir defines default socket directory
	RunDir = PrefixCommonPath("/run/nordvpn")

	// LogPath defines where logs are located if systemd isn't used
	LogPath = PrefixDataPath("/var/log/nordvpn")

	// AppDataPath defines path where app data is stored
	AppDataPath = PrefixDataPath("/var/lib/nordvpn")

	// AppDataPathCommon defines path where common app data files are stored. These files may
	// be removed after every app update
	AppDataPathCommon = PrefixCommonPath("/var/lib/nordvpn")

	// AppDataPathStatic defines path where static app data (such as helper executables) are
	// stored. Normally it is the same as AppDataPath
	AppDataPathStatic = PrefixStaticPath("/var/lib/nordvpn")

	DatFilesPath = filepath.Join(AppDataPath, "data")

	DatFilesPathCommon = filepath.Join(AppDataPathCommon, "data")

	BakFilesPath = filepath.Join(AppDataPath, "backup")

	// OvpnTemplatePath defines filename of ovpn template file
	OvpnTemplatePath = filepath.Join(DatFilesPathCommon, "ovpn_template.xslt")

	// OvpnObfsTemplatePath defines filename of ovpn obfuscated template file
	OvpnObfsTemplatePath = filepath.Join(DatFilesPathCommon, "ovpn_xor_template.xslt")

	// ConfigDirectory is used for configuration files storage. Hardcoded only for nordfileshared, in
	// other cases consider using os.UserConfigDir instead.
	ConfigDirectory = filepath.Join(".config", "nordvpn")

	// LogFilePath defines CLI log path
	LogFilePath = filepath.Join("nordvpn", "cli.log")

	// DaemonSocket defines system daemon socket file location
	DaemonSocket = filepath.Join(RunDir, "/nordvpnd.sock")

	// DaemonPid defines daemon PID file location
	DaemonPid = filepath.Join(RunDir, "/nordvpnd.pid")

	FileshareBinaryPath = filepath.Join(AppDataPathStatic, Fileshare)

	NorduserBinaryPath = filepath.Join(AppDataPathStatic, Norduserd)
)
View Source
var (
	ErrDaemonConnectionRefused = errors.New(DaemonConnRefusedErrorMessage)
	ErrSocketAccessDenied      = errors.New("Permission denied accessing " + DaemonSocket)
	ErrSocketNotFound          = errors.New(DaemonSocket + " not found")
	ErrUnhandled               = errors.New(UnhandledMessage)
	ErrGateway                 = errors.New("can't find gateway")
	ErrStdin                   = errors.New("Stdin: missing argument")
	ErrServerIsUnavailable     = errors.New(ServerUnavailableErrorMessage)
	ErrTagDoesNotExist         = errors.New(TagNonexistentErrorMessage)
	ErrGroupDoesNotExist       = errors.New(GroupNonexistentErrorMessage)
	ErrDoubleGroup             = errors.New(DoubleGroupErrorMessage)
	// ErrAlreadyLoggedIn is returned on repeated logins
	ErrAlreadyLoggedIn = errors.New("you are already logged in")
	// ErrNotLoggedIn is returned when the caller is expected to be logged in
	// but is not
	ErrNotLoggedIn = errors.New("you are not logged in")
)
View Source
var ErrNoPermission error = fmt.Errorf("requesting user does not have permissions")

Functions

func CliDimensions

func CliDimensions() ([]string, error)

Gets the size of CLI window

func Columns

func Columns(input []string) (string, error)

Columns formats a list of strings to a tidy column representation

func Contains

func Contains[T comparable](l []T, element T) bool

func DBUSSessionBusAddress

func DBUSSessionBusAddress(id int64) (string, error)

DBUSSessionBusAddress finds user dbus session bus address

func Decrypt

func Decrypt(data []byte, passphrase string) ([]byte, error)

func Encrypt

func Encrypt(data []byte, passphrase string) ([]byte, error)

func EnsureDir

func EnsureDir(path string) error

func FileCopy

func FileCopy(src, dst string) error

FileCopy copies a file in path src to path dst

func FileCreate

func FileCreate(path string, permissions os.FileMode) (*os.File, error)

FileCreate with the given permissions, but leave the closing to the caller.

func FileCreateForUser

func FileCreateForUser(path string, permissions os.FileMode, uid int, gid int) (*os.File, error)

FileCreateForUser but leave closing to the caller.

func FileDelete

func FileDelete(path string) error

FileDelete deletes file from system

func FileExists

func FileExists(path string) bool

FileExists checks if the given file exists or not

func FileLock

func FileLock(filepath string) error

FileLock adds i attribute from a file

func FileRead

func FileRead(file string) ([]byte, error)

FileRead reads all file

func FileSha256

func FileSha256(filepath string) (sum []byte, err error)

func FileTemp

func FileTemp(name string, content []byte) (*os.File, error)

FileTemp creates temp file, writes given content to it and returns path to temp file

func FileUnlock

func FileUnlock(filepath string) error

FileUnlock removes ia attributes from a file

func FileWritable

func FileWritable(path string) bool

FileWritable checks if the given file exists and is writable by its owner

func FileWrite

func FileWrite(path string, contents []byte, permissions os.FileMode) error

FileWrite writes the given string array to file, previously flushing it clean

func Filter

func Filter[E any](s []E, f func(E) bool) []E

Filter returns a new slice with only the elements, for which f returned true.

func Find

func Find[T comparable](l []T, element T) *T

func GetConfigDirPath

func GetConfigDirPath(homeDirectory string) (string, error)

GetConfigDirPath returns the directory used to store local user config and logs

func GetFilesharedPid

func GetFilesharedPid(uid int) string

GetFilesharedPid to save fileshare daemon pid

func GetNorduserSocketFork

func GetNorduserSocketFork(uid int) string

func GetNorduserSocketSnap

func GetNorduserSocketSnap(uid uint32) string

func GetNorduserdLogPath

func GetNorduserdLogPath(uid string) string

GetNorduserdLogPath when logs aren't handled by systemd

func GetNorduserdSocket

func GetNorduserdSocket(uid int) string

GetNorduserdSocket to communicate with norduser daemon

func GetNordvpnGid

func GetNordvpnGid() (int, error)

GetNordvpnGid returns id of group defined in NordvpnGroup

func GetSignalChan

func GetSignalChan() <-chan os.Signal

func GetSupportedIPTables

func GetSupportedIPTables() []string

func IntsToStrings

func IntsToStrings(numbers []int) []string

func IsCommandAvailable

func IsCommandAvailable(command string) bool

checks if command is in PATH

func IsDevEnv

func IsDevEnv(env string) bool

IsDevEnv short hand of condition check, for clear reading

func IsNetworkLinkUnmanaged

func IsNetworkLinkUnmanaged(link string) bool

func IsProdEnv

func IsProdEnv(env string) bool

IsProdEnv short hand of condition check, for clear reading

func IsServiceActive

func IsServiceActive(service string) bool

IsServiceActive check if given service is active

func MachineID

func MachineID() uuid.UUID

MachineID return unique machine identification id

func ManualListener

func ManualListener(socket string, perm fs.FileMode) func() (net.Listener, error)

ManualListener returns manually created listener with provided permissions

func ManualListenerIfNotInUse

func ManualListenerIfNotInUse(socket string, perm fs.FileMode, pidfile string) func() (net.Listener, error)

ManualListenerIfNotInUse returns manually created listener with provided permissions, it also detects if this socket is in use by another process, and returns an appropriate error if it is.

func Obfuscate

func Obfuscate(text string) string

Obfuscate given string

func PrefixCommonPath

func PrefixCommonPath(p string) string

PrefixCommonPath is supposed to be used for files which are version specific and not persistent

func PrefixDataPath

func PrefixDataPath(p string) string

PrefixDataPath is supposed to be used for files which are non version specific and persistent

func PrefixStaticPath

func PrefixStaticPath(p string) string

PrefixStaticPath is supposed to be used for files which are version specific and persistent

func SnakeCase

func SnakeCase(name string) string

func StringToUcred

func StringToUcred(ucredStr string) (unix.Ucred, error)

StringToUcred to convert string received from AuthType back to unix.Ucred

func StringsContains

func StringsContains(haystack []string, needle string) bool

func StringsGetNext

func StringsGetNext(haystack []string, needle string) string

func StringsToInterfaces

func StringsToInterfaces(strings []string) []interface{}

func SystemDListener

func SystemDListener() (net.Listener, error)

SystemDListener returns systemd defined, socket activated listener

func SystemUsers

func SystemUsers() ([]string, error)

SystemUsers returns all non-root user names

func SystemUsersIDs

func SystemUsersIDs() ([]int64, error)

SystemUsersIDs returns all non-root user ids

func Timezone

func Timezone() string

Timezone returns system timezone

func Title

func Title(name string) string

func UpdateFilePermissions

func UpdateFilePermissions(name string, mode os.FileMode)

UpdateFilePermissions sets permissions of a given file if it exists and logs the error to stdout

func WaitSignal

func WaitSignal()

WaitSignal for app to shutdown

Types

type DaemonAuthenticator

type DaemonAuthenticator struct{}

func NewDaemonAuthenticator

func NewDaemonAuthenticator() DaemonAuthenticator

func (DaemonAuthenticator) Authenticate

func (DaemonAuthenticator) Authenticate(ucred *unix.Ucred) error

type Environment

type Environment string

type FileshareAuthenticator

type FileshareAuthenticator struct {
	DaemonAuthenticator
	// contains filtered or unexported fields
}

func NewFileshareAuthenticator

func NewFileshareAuthenticator(controlingUserUUID uint32) FileshareAuthenticator

func (FileshareAuthenticator) Authenticate

func (f FileshareAuthenticator) Authenticate(ucred *unix.Ucred) error

type LimitListener

type LimitListener struct {
	net.Listener
	// contains filtered or unexported fields
}

LimitListener customized limiting listener

func NewLimitListener

func NewLimitListener(ol net.Listener) *LimitListener

func (*LimitListener) Accept

func (l *LimitListener) Accept() (net.Conn, error)

Accept intercept original connection to extract user credetials

type NetLink struct {
	Name    string
	Address string
	Index   int
}
func NetworkLinks() ([]NetLink, error)

type SocketAuthenticator

type SocketAuthenticator interface {
	Authenticate(ucred *unix.Ucred) error
}

SocketAuthenticator provides abstraction over various authentication types.

type UcredAuth

type UcredAuth unix.Ucred

UcredAuth is a wrapper to use unix.Ucred as gRPC credentials.AuthInfo

func (UcredAuth) AuthType

func (u UcredAuth) AuthType() string

AuthType returns "pid:uid:gid", for example "5555:1000:1000" Use StringToUcred to convert string back to unix.Ucred

type UnixSocketCredentials

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

UnixSocketCredentials is used to retrieve linux user ID from unix socket connection between client and daemon Implements credentials.TransportCredentials to be passed to gRPC server initialization

func NewUnixSocketCredentials

func NewUnixSocketCredentials(authenticator SocketAuthenticator) *UnixSocketCredentials

func (*UnixSocketCredentials) ClientHandshake

ClientHandshake is a stub to implement credentials.TransportCredentials

func (*UnixSocketCredentials) Clone

Clone is a stub to implement credentials.TransportCredentials

func (*UnixSocketCredentials) Info

Info is a stub to implement credentials.TransportCredentials

func (*UnixSocketCredentials) OverrideServerName

func (cr *UnixSocketCredentials) OverrideServerName(string) error

OverrideServerName is a stub to implement credentials.TransportCredentials

func (*UnixSocketCredentials) ServerHandshake

func (cr *UnixSocketCredentials) ServerHandshake(c net.Conn) (net.Conn, credentials.AuthInfo, error)

ServerHandshake is called when client connects to daemon. We retrieve user ID which opened the client here.

Jump to

Keyboard shortcuts

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