utils

package
v0.12.0-unstable43 Latest Latest
Warning

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

Go to latest
Published: Nov 6, 2023 License: Apache-2.0 Imports: 52 Imported by: 0

Documentation

Index

Constants

View Source
const (
	GUEST = 0
	USER  = 1
	ADMIN = 2
)
View Source
const (
	DEBUG   = 0
	INFO    = 1
	WARNING = 2
	ERROR   = 3
)
View Source
const (
	STRICT  = 1
	NORMAL  = 2
	LENIENT = 3
)

Variables

View Source
var AlphaNumRunes = []rune("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
View Source
var BannedIPs = sync.Map{}
View Source
var Blue = "\033[34m"
View Source
var CONFIGFOLDER = "/var/lib/cosmos/"
View Source
var ConfigLock sync.Mutex
View Source
var Cyan = "\033[36m"
View Source
var DefaultConfig = Config{
	LoggingLevel:     "INFO",
	NewInstall:       true,
	AutoUpdate:       true,
	BlockedCountries: []string{},
	HTTPConfig: HTTPConfig{
		HTTPSCertificateMode:    "DISABLED",
		GenerateMissingAuthCert: true,
		HTTPPort:                "80",
		HTTPSPort:               "443",
		Hostname:                "0.0.0.0",
		ProxyConfig: ProxyConfig{
			Routes: []ProxyRouteConfig{},
		},
	},
	DockerConfig: DockerConfig{
		DefaultDataPath: "/usr",
	},
	MarketConfig: MarketConfig{
		Sources: []MarketSource{},
	},
	ConstellationConfig: ConstellationConfig{
		Enabled:     false,
		DNSDisabled: false,
		DNSFallback: "8.8.8.8:53",
		DNSAdditionalBlocklists: []string{
			"https://s3.amazonaws.com/lists.disconnect.me/simple_tracking.txt",
			"https://s3.amazonaws.com/lists.disconnect.me/simple_ad.txt",
			"https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts",
			"https://raw.githubusercontent.com/StevenBlack/hosts/master/alternates/fakenews-only/hosts",
		},
	},
}
View Source
var Gray = "\033[37m"
View Source
var Green = "\033[32m"
View Source
var HTTPSCertModeList = map[string]string{
	"DISABLED":    "DISABLED",
	"PROVIDED":    "PROVIDED",
	"SELFSIGNED":  "SELFSIGNED",
	"LETSENCRYPT": "LETSENCRYPT",
}
View Source
var IsHTTPS = false
View Source
var LetsEncryptErrors = []string{}
View Source
var LoggingLevelLabels = map[LoggingLevel]int{
	"DEBUG":   DEBUG,
	"INFO":    INFO,
	"WARNING": WARNING,
	"ERROR":   ERROR,
}
View Source
var NeedsRestart = false
View Source
var NewVersionAvailable = false
View Source
var ProxyModeList = map[string]string{
	"PROXY":    "PROXY",
	"SPA":      "SPA",
	"STATIC":   "STATIC",
	"SERVAPP":  "SERVAPP",
	"REDIRECT": "REDIRECT",
}
View Source
var Purple = "\033[35m"
View Source
var PushShieldMetrics func(string)
View Source
var ReBootstrapContainer func(string) error
View Source
var Red = "\033[31m"
View Source
var Reset = "\033[0m"
View Source
var RestartHTTPServer func()
View Source
var Template = `` /* 1110-byte string literal not displayed */
View Source
var UpdateAvailable = map[string]bool{}
View Source
var Validate = validator.New()
View Source
var White = "\033[97m"
View Source
var Yellow = "\033[33m"

Functions

func AcceptHeader

func AcceptHeader(accept string) func(next http.Handler) http.Handler

func AdminOnly

func AdminOnly(w http.ResponseWriter, req *http.Request) error

func AdminOnlyWithRedirect

func AdminOnlyWithRedirect(w http.ResponseWriter, req *http.Request) error

func AdminOrItselfOnly

func AdminOrItselfOnly(w http.ResponseWriter, req *http.Request, nickname string) error

func BandwithLimiterMiddleware

func BandwithLimiterMiddleware(max int64) func(next http.Handler) http.Handler

func BlockBannedIPs added in v0.12.0

func BlockBannedIPs(next http.Handler) http.Handler

func BlockByCountryMiddleware

func BlockByCountryMiddleware(blockedCountries []string, CountryBlacklistIsWhitelist bool) func(http.Handler) http.Handler

BlockByCountryMiddleware returns a middleware function that blocks requests from specified countries.

func BlockPostWithoutReferer

func BlockPostWithoutReferer(next http.Handler) http.Handler

blockPostWithoutReferer blocks POST requests without a Referer header

func BufferedDBWrite added in v0.12.0

func BufferedDBWrite(collectionName string, object map[string]interface{})

func CORSHeader

func CORSHeader(origin string) func(next http.Handler) http.Handler

func CheckDNS

func CheckDNS(url string) error

func CleanBannedIPs added in v0.12.0

func CleanBannedIPs()

func CreateDefaultConfigFileIfNecessary

func CreateDefaultConfigFileIfNecessary() bool

func DB

func DB() error

func Debug

func Debug(message string)

func DisconnectDB

func DisconnectDB()

func DoErr added in v0.11.0

func DoErr(format string, a ...interface{}) string

func DoLetsEncrypt

func DoLetsEncrypt() (string, string)

func DoSuccess added in v0.11.0

func DoSuccess(format string, a ...interface{}) string

func DoWarn added in v0.11.0

func DoWarn(format string, a ...interface{}) string

func DownloadFile added in v0.10.0

func DownloadFile(url string) (string, error)

func EnsureHostname

func EnsureHostname(next http.Handler) http.Handler

func Error

func Error(message string, err error)

func Fatal

func Fatal(message string, err error)

func FileExists

func FileExists(path string) bool

func GenerateEd25519Certificates

func GenerateEd25519Certificates() (string, string)

func GenerateRSAWebCertificates

func GenerateRSAWebCertificates(domains []string) (string, string)

func GenerateRandomString

func GenerateRandomString(n int) string

func GetAllHostnames

func GetAllHostnames(applyWildCard bool, removePorts bool) []string

func GetAvailableRAM

func GetAvailableRAM() uint64

func GetCPUUsage

func GetCPUUsage() []float64

func GetClientIP added in v0.9.17

func GetClientIP(req *http.Request) string

func GetCollection

func GetCollection(applicationId string, collection string) (*mongo.Collection, error)

func GetConfigFileName

func GetConfigFileName() string

func GetIPLocation

func GetIPLocation(ip string) (string, error)

GetIPLocation returns the ISO country code for a given IP address.

func GetPrivateAuthKey

func GetPrivateAuthKey() string

func GetPublicAuthKey

func GetPublicAuthKey() string

func GetRAMUsage

func GetRAMUsage() uint64

func GetRootAppId

func GetRootAppId() string

func GetServerURL

func GetServerURL() string

func HTTPError

func HTTPError(w http.ResponseWriter, message string, code int, userCode string)

func HasAnyNewItem

func HasAnyNewItem(after []string, before []string) bool

func IPInRange added in v0.10.0

func IPInRange(ipStr, cidrStr string) (bool, error)

func ImageToBase64

func ImageToBase64(path string) (string, error)

func IncrementIPAbuseCounter added in v0.12.0

func IncrementIPAbuseCounter(ip string)

func InitDBBuffers added in v0.12.0

func InitDBBuffers()

func IsAdmin

func IsAdmin(req *http.Request) bool

func IsDomain added in v0.10.0

func IsDomain(domain string) bool

func IsEmailEnabled

func IsEmailEnabled() bool

func IsValidHostname

func IsValidHostname(hostname string) bool

func LetsEncryptValidOnly

func LetsEncryptValidOnly(hostnames []string, acceptWildcard bool) []string

func LoadBaseMainConfig

func LoadBaseMainConfig(config Config)

func Log

func Log(message string)

func LoggedInOnly

func LoggedInOnly(w http.ResponseWriter, req *http.Request) error

func LoggedInOnlyWithRedirect

func LoggedInOnlyWithRedirect(w http.ResponseWriter, req *http.Request) error

func LoggedInWeakOnly

func LoggedInWeakOnly(w http.ResponseWriter, req *http.Request) error

func MajorError added in v0.12.0

func MajorError(message string, err error)

func MarkAsRead added in v0.12.0

func MarkAsRead(w http.ResponseWriter, req *http.Request)

func Max

func Max(x, y int) int

func MiddlewareTimeout

func MiddlewareTimeout(timeout time.Duration) func(next http.Handler) http.Handler

func NotifGet added in v0.12.0

func NotifGet(w http.ResponseWriter, req *http.Request)

func RestartServer

func RestartServer()

func Restrictions added in v0.10.0

func Restrictions(RestrictToConstellation bool, WhitelistInboundIPs []string) func(next http.Handler) http.Handler

func Sanitize

func Sanitize(s string) string

func SanitizeSafe

func SanitizeSafe(s string) string

func SaveConfigTofile

func SaveConfigTofile(config Config)

func SendEmail

func SendEmail(recipients []string, subject string, body string) error

func SetBaseMainConfig

func SetBaseMainConfig(config Config)

func SetSecurityHeaders

func SetSecurityHeaders(next http.Handler) http.Handler

func StringArrayContains

func StringArrayContains(a []string, b string) bool

func StringArrayEquals

func StringArrayEquals(a []string, b []string) bool

func TriggerEvent added in v0.12.0

func TriggerEvent(eventId string, label string, level string, object string, data map[string]interface{})

func Warn

func Warn(message string)

func WriteNotification added in v0.12.0

func WriteNotification(notification Notification)

func WriteToDatabase added in v0.12.0

func WriteToDatabase(collection *mongo.Collection, objects []map[string]interface{}) error

Types

type AddionalFiltersConfig added in v0.9.9

type AddionalFiltersConfig struct {
	Type  string
	Name  string
	Value string
}

type Alert added in v0.12.0

type Alert struct {
	Name           string
	Enabled        bool
	Period         string
	TrackingMetric string
	Condition      AlertCondition
	Actions        []AlertAction
	LastTriggered  time.Time
	Throttled      bool
	Severity       string
}

type AlertAction added in v0.12.0

type AlertAction struct {
	Type   string
	Target string
}

type AlertCondition added in v0.12.0

type AlertCondition struct {
	Operator string
	Value    int
	Percent  bool
}

type AlertMetricTrack added in v0.12.0

type AlertMetricTrack struct {
	Key    string
	Object string
	Max    uint64
}

type CertUser

type CertUser struct {
	Email        string
	Registration *registration.Resource
	// contains filtered or unexported fields
}

func (*CertUser) GetEmail

func (u *CertUser) GetEmail() string

func (*CertUser) GetPrivateKey

func (u *CertUser) GetPrivateKey() crypto.PrivateKey

func (CertUser) GetRegistration

func (u CertUser) GetRegistration() *registration.Resource

type Config

type Config struct {
	LoggingLevel                LoggingLevel `required,validate:"oneof=DEBUG INFO WARNING ERROR"`
	MongoDB                     string
	DisableUserManagement       bool
	NewInstall                  bool        `validate:"boolean"`
	HTTPConfig                  HTTPConfig  `validate:"required,dive,required"`
	EmailConfig                 EmailConfig `validate:"required,dive,required"`
	DockerConfig                DockerConfig
	BlockedCountries            []string
	CountryBlacklistIsWhitelist bool
	ServerCountry               string
	RequireMFA                  bool
	AutoUpdate                  bool
	OpenIDClients               []OpenIDClient
	MarketConfig                MarketConfig
	HomepageConfig              HomepageConfig
	ThemeConfig                 ThemeConfig
	ConstellationConfig         ConstellationConfig
	MonitoringDisabled          bool
	MonitoringAlerts            map[string]Alert
}
var BaseMainConfig Config
var MainConfig Config

func GetBaseMainConfig

func GetBaseMainConfig() Config

func GetMainConfig

func GetMainConfig() Config

func ReadConfigFromFile

func ReadConfigFromFile() Config

type ConstellationConfig added in v0.10.0

type ConstellationConfig struct {
	Enabled                 bool
	SlaveMode               bool
	PrivateNode             bool
	DNSDisabled             bool
	DNSPort                 string
	DNSFallback             string
	DNSBlockBlacklist       bool
	DNSAdditionalBlocklists []string
	CustomDNSEntries        []ConstellationDNSEntry
	NebulaConfig            NebulaConfig
	ConstellationHostname   string
}

type ConstellationDNSEntry added in v0.10.0

type ConstellationDNSEntry struct {
	Type  string
	Key   string
	Value string
}

type ConstellationDevice added in v0.10.0

type ConstellationDevice struct {
	Nickname       string `json:"nickname"`
	DeviceName     string `json:"deviceName"`
	PublicKey      string `json:"publicKey"`
	IP             string `json:"ip"`
	IsLighthouse   bool   `json:"isLighthouse"`
	IsRelay        bool   `json:"isRelay"`
	PublicHostname string `json:"publicHostname"`
	Port           string `json:"port"`
	Blocked        bool   `json:"blocked"`
	Fingerprint    string `json:"fingerprint"`
	APIKey         string `json:"-"`
}

type Device added in v0.10.0

type Device struct {
	DeviceName string `json:"deviceName",validate:"required,min=3,max=32,alphanum"`
	Nickname   string `json:"nickname",validate:"required,min=3,max=32,alphanum"`
	PublicKey  string `json:"publicKey",omitempty`
	PrivateKey string `json:"privateKey",omitempty`
	IP         string `json:"ip",validate:"required,ipv4"`
}

type DiskStatus

type DiskStatus struct {
	Path       string
	TotalBytes uint64
	UsedBytes  uint64
}

func GetDiskUsage

func GetDiskUsage() []DiskStatus

type DockerConfig

type DockerConfig struct {
	SkipPruneNetwork bool
	DefaultDataPath  string
}

type EmailConfig

type EmailConfig struct {
	Enabled  bool
	Host     string
	Port     string
	Username string
	Password string
	From     string
	UseTLS   bool
}

type FileStats

type FileStats struct {
	Name    string      `json:"name"`
	Path    string      `json:"path"`
	Size    int64       `json:"size"`
	Mode    os.FileMode `json:"mode"`
	ModTime time.Time   `json:"modTime"`
	IsDir   bool        `json:"isDir"`
}

type HTTPConfig

type HTTPConfig struct {
	TLSCert                      string `validate:"omitempty,contains=\n`
	TLSKey                       string
	TLSKeyHostsCached            []string
	TLSValidUntil                time.Time
	AuthPrivateKey               string
	AuthPublicKey                string
	GenerateMissingAuthCert      bool
	HTTPSCertificateMode         string
	DNSChallengeProvider         string
	ForceHTTPSCertificateRenewal bool
	HTTPPort                     string `validate:"required,containsany=0123456789,min=1,max=6"`
	HTTPSPort                    string `validate:"required,containsany=0123456789,min=1,max=6"`
	ProxyConfig                  ProxyConfig
	Hostname                     string `validate:"required,excludesall=0x2C/ "`
	SSLEmail                     string `validate:"omitempty,email"`
	UseWildcardCertificate       bool
	OverrideWildcardDomains      string `validate:"omitempty,excludesall=/ "`
	AcceptAllInsecureHostname    bool
	DNSChallengeConfig           map[string]string `json:"DNSChallengeConfig,omitempty"`
	UseForwardedFor              bool
}

type HTTPErrorResult

type HTTPErrorResult struct {
	Status  string `json:"status"`
	Message string `json:"message"`
	Code    string `json:"code"`
}

type HomepageConfig

type HomepageConfig struct {
	Background string
	Widgets    []string
	Expanded   bool
}

type LoggingLevel

type LoggingLevel string

type MarketConfig

type MarketConfig struct {
	Sources []MarketSource
}

type MarketSource

type MarketSource struct {
	Name string
	Url  string
}

type MyUser

type MyUser struct {
	Email        string
	Registration *registration.Resource
	// contains filtered or unexported fields
}

You'll need a user or account type that implements acme.User

func (*MyUser) GetEmail

func (u *MyUser) GetEmail() string

func (*MyUser) GetPrivateKey

func (u *MyUser) GetPrivateKey() crypto.PrivateKey

func (MyUser) GetRegistration

func (u MyUser) GetRegistration() *registration.Resource

type NebulaConfig added in v0.10.0

type NebulaConfig struct {
	PKI struct {
		CA        string   `yaml:"ca"`
		Cert      string   `yaml:"cert"`
		Key       string   `yaml:"key"`
		Blocklist []string `yaml:"blocklist"`
	} `yaml:"pki"`

	StaticHostMap map[string][]string `yaml:"static_host_map"`

	Lighthouse struct {
		AMLighthouse bool     `yaml:"am_lighthouse"`
		Interval     int      `yaml:"interval"`
		Hosts        []string `yaml:"hosts"`
	} `yaml:"lighthouse"`

	Listen struct {
		Host string `yaml:"host"`
		Port int    `yaml:"port"`
	} `yaml:"listen"`

	Punchy struct {
		Punch   bool `yaml:"punch"`
		Respond bool `yaml:"respond"`
	} `yaml:"punchy"`

	Relay struct {
		AMRelay   bool     `yaml:"am_relay"`
		UseRelays bool     `yaml:"use_relays"`
		Relays    []string `yaml:"relays"`
	} `yaml:"relay"`

	TUN struct {
		Disabled           bool     `yaml:"disabled"`
		Dev                string   `yaml:"dev"`
		DropLocalBroadcast bool     `yaml:"drop_local_broadcast"`
		DropMulticast      bool     `yaml:"drop_multicast"`
		TxQueue            int      `yaml:"tx_queue"`
		MTU                int      `yaml:"mtu"`
		Routes             []string `yaml:"routes"`
		UnsafeRoutes       []string `yaml:"unsafe_routes"`
	} `yaml:"tun"`

	Logging struct {
		Level  string `yaml:"level"`
		Format string `yaml:"format"`
	} `yaml:"logging"`

	Firewall struct {
		OutboundAction string                `yaml:"outbound_action"`
		InboundAction  string                `yaml:"inbound_action"`
		Conntrack      NebulaConntrackConfig `yaml:"conntrack"`
		Outbound       []NebulaFirewallRule  `yaml:"outbound"`
		Inbound        []NebulaFirewallRule  `yaml:"inbound"`
	} `yaml:"firewall"`
}

type NebulaConntrackConfig added in v0.10.0

type NebulaConntrackConfig struct {
	TCPTimeout     string `yaml:"tcp_timeout"`
	UDPTimeout     string `yaml:"udp_timeout"`
	DefaultTimeout string `yaml:"default_timeout"`
}

type NebulaFirewallRule added in v0.10.0

type NebulaFirewallRule struct {
	Port   string   `yaml:"port"`
	Proto  string   `yaml:"proto"`
	Host   string   `yaml:"host"`
	Groups []string `yaml:"groups,omitempty"omitempty"`
}

type NetworkStatus

type NetworkStatus struct {
	BytesSent uint64
	BytesRecv uint64
}

func GetNetworkUsage

func GetNetworkUsage() NetworkStatus

type Notification added in v0.12.0

type Notification struct {
	ID        primitive.ObjectID `bson:"_id,omitempty"`
	Title     string
	Message   string
	Icon      string
	Link      string
	Date      time.Time
	Level     string
	Read      bool
	Recipient string
	Actions   []NotificationActions
}

type NotificationActions added in v0.12.0

type NotificationActions struct {
	Text string
	Link string
}

type OpenIDClient

type OpenIDClient struct {
	ID       string `json:"id"`
	Secret   string `json:"secret"`
	Redirect string `json:"redirect"`
}

type ProxyConfig

type ProxyConfig struct {
	Routes []ProxyRouteConfig
}

type ProxyMode

type ProxyMode string

type ProxyRouteConfig

type ProxyRouteConfig struct {
	Disabled                  bool
	Name                      string `validate:"required"`
	Description               string
	UseHost                   bool
	Host                      string
	UsePathPrefix             bool
	PathPrefix                string
	Timeout                   time.Duration
	ThrottlePerMinute         int
	CORSOrigin                string
	StripPathPrefix           bool
	MaxBandwith               int64
	AuthEnabled               bool
	AdminOnly                 bool
	Target                    string `validate:"required"`
	SmartShield               SmartShieldPolicy
	Mode                      ProxyMode
	BlockCommonBots           bool
	BlockAPIAbuse             bool
	AcceptInsecureHTTPSTarget bool
	HideFromDashboard         bool
	DisableHeaderHardening    bool
	VerboseForwardHeader      bool
	AddionalFilters           []AddionalFiltersConfig
	RestrictToConstellation   bool
	OverwriteHostHeader       string
	WhitelistInboundIPs       []string
}

type Role

type Role int

type SmartShieldPolicy

type SmartShieldPolicy struct {
	Enabled               bool
	PolicyStrictness      int
	PerUserTimeBudget     float64
	PerUserRequestLimit   int
	PerUserByteLimit      int64
	PerUserSimultaneous   int
	MaxGlobalSimultaneous int
	PrivilegedGroups      int
}

type ThemeConfig

type ThemeConfig struct {
	PrimaryColor   string
	SecondaryColor string
}

type User

type User struct {
	ID                    primitive.ObjectID `json:"-" bson:"_id,omitempty"`
	Nickname              string             `validate:"required" json:"nickname"`
	Password              string             `validate:"required" json:"-"`
	RegisterKey           string             `json:"registerKey"`
	RegisterKeyExp        time.Time          `json:"registerKeyExp"`
	Role                  Role               `validate:"required" json:"role"`
	PasswordCycle         int                `json:"-"`
	Link                  string             `json:"link"`
	Email                 string             `validate:"email" json:"email"`
	RegisteredAt          time.Time          `json:"registeredAt"`
	LastPasswordChangedAt time.Time          `json:"lastPasswordChangedAt"`
	CreatedAt             time.Time          `json:"createdAt"`
	LastLogin             time.Time          `json:"lastLogin"`
	MFAKey                string             `json:"-"`
	Was2FAVerified        bool               `json:"-"`
	MFAState              int                `json:"-"` // 0 = done, 1 = needed, 2 = not set
}

func ListAllUsers added in v0.12.0

func ListAllUsers(role string) []User

Jump to

Keyboard shortcuts

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