Documentation
¶
Index ¶
- Constants
- Variables
- func CheckPasswordHash(hashedPwd string, plainPwd string) error
- func CountIpsInInput(subnet string) (uint, error)
- func CreatePasswordHash(pwd string) (string, error)
- func GenerateToken(letters string, length int) (string, error)
- func GetLocalIp() (string, error)
- func GetOutboundIP() string
- func HashScramSha256Postgres(password string) (string, error)
- func IntContained(candidate int, slices ...[]int) bool
- func IsConnectionError(err error) bool
- func IsPlausibleEmail(mail string) bool
- func IsRpcConnectionError(err error) bool
- func JoinInt(ints []int, delimiter string) string
- func JoinUint64(uints []uint64, delimiter string) string
- func JoinWeekdays(days []time.Weekday, delimiter string) string
- func JsonToStruct(jsonData interface{}, jsonStruct interface{}) error
- func RemoveFromSlice(list []string, s string) []string
- func ServeRpc(logger scanUtils.Logger, ctx context.Context, name string, certFilePath string, ...) error
- func SplitNetworkIpV4(network string, targetSize uint32) ([]string, error)
- func SslSocket(listenAddress string, certFile string, keyFile string) (net.Listener, error)
- func TimeInRange(candidate time.Time, start time.Time, end time.Time) bool
- func TimezonesBetween(startClock string, endClock string, invalidDays []time.Weekday) [][]int
- func TlsConfigFactory() *tls.Config
- func TlsConfigFactoryPinned(publicKeyPath string) (*tls.Config, error)
- func ToSlice(s, sep string) []string
- func ToValidUtf8String(b []byte) string
- func TrimToUpper(slice []string) []string
- func Uint64Contained(candidate uint64, slices ...[]uint64) bool
- func UniqueInts(elements []int) []int
- func UniqueWeekdays(elements []time.Weekday) []time.Weekday
- func ValidPassword(password string, minLength int, requiresLower bool, requiresUpper bool, ...) bool
- func ValidUtf8String(str string) string
- type Client
- type Gracy
- type Json
- type JsonMap
- type Notifier
- type Smtp
- type SystemData
- type SystemMonitor
Constants ¶
const AlphaNum = "abcdefghijklmnopqrstuvwxyz0123456789"
const AlphaNumCaseSymbol = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-_!?§$%&/()=*+#,;.:<>|°^"
const AlphaNumDash = "abcdefghijklmnopqrstuvwxyz0123456789-"
const NetworkSizeSkip = 327168 // Networks larger than this will be dropped
const NetworkSizeSplit = 2048 // Networks larger than this will be split into smaller subnets
const ReconnectInterval = time.Second * 5
Variables ¶
var ErrNotifierShuttingDown = fmt.Errorf("notifier shutting down")
var ErrRpcCompatibility = fmt.Errorf("RPC client incompatible") // Error indicating that the RPC client is incompatible and needs to be updated
var ErrRpcConnectivity = fmt.Errorf("RPC server not available") // Error indicating connectivity error which might be gone already or temporary
var ErrRpcGeneric = fmt.Errorf("RPC endpoint not available") // Generic error returned by the RPC client, which may not contain sensitive details
Functions ¶
func CheckPasswordHash ¶
CheckPasswordHash compares a password hash generated by CreatePasswordHash() with a given plaintext password. Returns nil if password matches given hash.
func CountIpsInInput ¶
CountIpsInInput calculates the amount of possible IP addresses within a network range
func CreatePasswordHash ¶
CreatePasswordHash creates a salted password hash from a given password
func GenerateToken ¶
GenerateToken generates a random string based allowed letters and a given length
func GetLocalIp ¶
GetLocalIp retrieves the IP address of the local default interface
func GetOutboundIP ¶
func GetOutboundIP() string
GetOutboundIP gets preferred outbound ip of this machine by initializing a logical (fake) connection and reading the local address from it. By using UDP, the sample target does not actually need to exist, because no TCP handshake is required. Also the port does not matter.
func HashScramSha256Postgres ¶
HashScramSha256Postgres generates a Scram-Sha-256 hash in the format used by Postgres for storing user passwords
func IntContained ¶
IntContained checks whether a given int value is contained within one or multiple given slices
func IsConnectionError ¶
IsConnectionError detects whether a given error is one of the many types and sources of connectivity errors
func IsPlausibleEmail ¶
IsPlausibleEmail validates whether a given string is a plausible e-mail address
func IsRpcConnectionError ¶
IsRpcConnectionError validates a given error and checks whether it is a kind of error indicating connectivity issues
func JoinInt ¶
JoinInt converts a slice of ints into strings and concatenates them using the given delimiter
func JoinUint64 ¶
JoinUint64 converts a slice of int64's into strings and concatenates them using the given delimiter
func JoinWeekdays ¶
JoinWeekdays converts weekday integers into string and concatenates them using the given delimiter
func JsonToStruct ¶
func JsonToStruct(jsonData interface{}, jsonStruct interface{}) error
JsonToStruct parses JSON data (e.g. map[string]interface) and populates a referenced struct. ATTENTION: The JSON keys must either match the struct attribute names or the JSON struct tags to fill!
func RemoveFromSlice ¶
RemoveFromSlice removes a given element (and potential duplicates) from a slice and returns a new slice
func ServeRpc ¶
func ServeRpc( logger scanUtils.Logger, ctx context.Context, name string, certFilePath string, keyFilePath string, listenAddress string, ) error
ServeRpc loops to accept and process RPC connections until the passed context is terminated
func SplitNetworkIpV4 ¶
SplitNetworkIpV4 splits a larger network range into smaller subnets of given size. Returns original input if it is already smaller than the given target size.
func TimeInRange ¶
TimeInRange decides whether a given time is between two clocks, ignoring dates.
func TimezonesBetween ¶
TimezonesBetween calculates timezones that have a current time between earliest and latest. Each slice returned represents a from-to timezone range. Returns one timezone range if the time spawn does not cross midnight, or two otherwise. Timezone ranges are better than a simple list of timezones, because they also cover potential/rare half or three quarter step time zones, such as, 11.5. Returns the complete timezone range if start clock equals end clock.
func TlsConfigFactory ¶
TlsConfigFactory returns a secure SSL connection configuration
func TlsConfigFactoryPinned ¶
TlsConfigFactoryPinned returns an SSL client configuration that is verified by fingerprint matching against a provided public key file. This way a secure SSL connection can be established without relying on PKI.
func ToSlice ¶
ToSlice splits a string by separator. In contrast to Golang's own split function, this one returns an empty slice if the input string was empty. Golang's original function would return a slice with one entry being an empty string.
func ToValidUtf8String ¶
ToValidUtf8String returns a valid utf-8 string by replacing all invalid byte sequences with a hardcoded replacement character. Additionally, it gets rid of trailing null bytes and replaces none-trailing null bytes.
func TrimToUpper ¶
TrimToUpper converts slice elements to upper case and trim whitespaces
func Uint64Contained ¶
Uint64Contained checks whether a given int64 value is contained within one or multiple given slices
func UniqueWeekdays ¶
UniqueWeekdays gets rid of redundant elements
func ValidPassword ¶
func ValidPassword( password string, minLength int, requiresLower bool, requiresUpper bool, requiresNumber bool, requiresSymbol bool, ) bool
ValidPassword checks whether a given string matches password requirements
func ValidUtf8String ¶
ValidUtf8String returns a valid utf-8 string by replacing all invalid byte sequences with a hardcoded replacement character. Additionally, it gets rid of trailing null bytes and replaces none-trailing null bytes.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
func NewRpcClient ¶
NewRpcClient prepares an RPC client struct providing connectivity to an RPC server.
func (*Client) Call ¶
func (c *Client) Call(logger scanUtils.Logger, rpcEndpoint string, rpcArgs interface{}, rpcReply interface{}) error
Call executes an RPC call and writes back the response into rpcReply. In case of a connection issues, a re-connection loop is started in the background and an error returned. Users can subscribe to and wait for a re-connection notification (via Established()), or just retry later.
This function returns:
- nil, if everything went fine
- ErrRpcConnectivity, if something was wrong with the RPC connection
- rpc.ServerError, if the RPC request failed. Unfortunately, net/rpc converts all errors into this type.
func (*Client) Connect ¶
Connect tries to establish a connection (if no other goroutine does yet). Returns boolean indicating whether a connection could be established. Optionally, after the first try, the connection attempt can be continued in the background sending a notification to current subscribers on success. Subscribe via "Established()".
func (*Client) Established ¶
func (c *Client) Established() <-chan struct{}
Established returns a notification channel triggering when an RPC connection was (re)established. This can be used to block after connections issues until it re-connection. The channel will not trigger, if a connection is currently established and working!
type Gracy ¶
type Gracy struct {
// contains filtered or unexported fields
}
Gracy handles our graceful shutdown procedure. Fortunately, Gracy is more capable in doing so then Golang itself. Unfortunately, Golang does not execute registered deferred statements after an interrupt. Instead, it aborts affected Goroutines right away and jumps into the signal handling function. So, Gracy will keep track of everything you want to clean up instead.
func NewGracy ¶
func NewGracy() *Gracy
NewGracy yields a fresh Gracy keeping track of registered shutdown functions.
func (*Gracy) Promote ¶
func (g *Gracy) Promote()
Promote assigns Gracy as our default interrupt handler. In her duty, she will listen for interrupts and run all previously registered shutdown functions.
type Json ¶
type Json json.RawMessage
Json implements a scanner valuer interface for json.RawMessage as required by GORM to handle JSON data types. The JSON byte stream can be scanned into a given JSON struct for processing. https://gorm.io/docs/data_types.html
type JsonMap ¶
type JsonMap map[string]interface{}
JsonMap is a generic helper type to allow reading writing dynamic map structures. The map's value types can be arbitrary and arbitrarily deep. However, to work with the data after unmarshalling, the values must be known and casted into their real data types. https://www.alexedwards.net/blog/using-postgresql-jsonb
type Notifier ¶
type Notifier struct {
// contains filtered or unexported fields
}
Notifier allows to send a notification message to all current subscribers. Subscribers must subscribe *again*, if after each notification they received. In order to give them some time to subscribe again, the Notifier is initialized withe a certain broadcast interval. It will collect messages until the interval is triggered. Messages can be of any type.
func NewNotifier ¶
func NewNotifier(broadcastInterval time.Duration, fnSkip func(interface{}, interface{}) bool) *Notifier
NewNotifier initializes a new notifier that can be subscribed to. 'fnSkip' is a function that can be used to decide whether a new value shall be added to the list of messages to be broadcast. E.g. if you want to filter duplicates.
type Smtp ¶
type Smtp struct {
// SMTP settings
Server string `json:"server"`
Port uint16 `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
Subject string `json:"subject"`
Sender mail.Address `json:"sender"`
Recipients []mail.Address `json:"recipients"`
// Security settings
OpensslPath string `json:"openssl_path"`
SignatureCertPath string `json:"signature_cert"` // Sender certificate for e-mail signature
SignatureCert []byte `json:"-"` // Loaded sender certificate for e-mail signature
SignatureKeyPath string `json:"signature_key"` // Sender private key for e-mail signature
SignatureKey []byte `json:"-"` // Loaded sender private key for e-mail signature
EncryptionCertPaths []string `json:"recipient_certs"` // Encryption certificates for the recipients above
EncryptionCerts [][]byte `json:"-"` // Loaded encryption certificates for the recipients above
TempDir string `json:"temp_dir"`
}
func (*Smtp) UnmarshalJSON ¶
UnmarshalJSON reads a JSON file, validates values and populates the configuration struct
type SystemData ¶
type SystemMonitor ¶
type SystemMonitor struct {
// contains filtered or unexported fields
}
func NewSystemMonitor ¶
func NewSystemMonitor(ctxParent context.Context) *SystemMonitor
NewSystemMonitor initializes a new system resources monitor, regularly measuring the system utilization.
func (*SystemMonitor) Get ¶
func (sm *SystemMonitor) Get() SystemData
Get retrieves the last known system usage data
func (*SystemMonitor) Run ¶
func (sm *SystemMonitor) Run(interval time.Duration)
Run launches the system utilization monitor
func (*SystemMonitor) Shutdown ¶
func (sm *SystemMonitor) Shutdown()
Shutdown terminates the system usage monitor