Documentation ¶
Index ¶
- Constants
- func AsBool(v string) bool
- func CalculateSPKI(cert *x509.Certificate) string
- func Capitalize(s string) string
- func CheckCertificateFormatFlag(s string) (string, error)
- func CheckSPKI(pin string, cert *x509.Certificate) error
- func CheckVersions(clientVersion string, minClientVersion string) error
- func CipherSuiteMapping(cipherSuites []string) ([]uint16, error)
- func ClickableURL(in string) string
- func Consolef(w io.Writer, component string, msg string, params ...interface{})
- func ContainsExpansion(val string) bool
- func CopyByteSlice(in []byte) []byte
- func CopyByteSlices(in [][]byte) [][]byte
- func CopyStringMap(a map[string]string) map[string]string
- func CopyStringMapInterface(a map[string]interface{}) map[string]interface{}
- func CopyStringMapSlices(a map[string][]string) map[string][]string
- func CopyStrings(in []string) []string
- func CreateCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error)
- func CreateEllipticCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error)
- func CreateTLSConfiguration(certFile, keyFile string, cipherSuites []uint16) (*tls.Config, error)
- func CryptoRandomHex(len int) (string, error)
- func Deduplicate(in []string) []string
- func DefaultCipherSuites() []uint16
- func DualPipeNetConn(srcAddr net.Addr, dstAddr net.Addr) (*PipeNetConn, *PipeNetConn)
- func EnsureLocalPath(customPath string, defaultLocalDir, defaultLocalPath string) (string, error)
- func EscapeControl(s string) string
- func Extract(r io.Reader, dir string) error
- func FSReadLock(f *os.File) error
- func FSTryWriteLock(f *os.File) error
- func FSUnlock(f *os.File) error
- func FSWriteLock(f *os.File) error
- func FastMarshal(v interface{}) ([]byte, error)
- func FastUnmarshal(data []byte, v interface{}) error
- func FatalError(err error)
- func GenerateOTPURL(typ string, label string, parameters map[string][]byte) string
- func GenerateQRCode(u string) ([]byte, error)
- func GenerateSelfSignedSigningCert(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
- func GetIterations() int
- func GetListenerFile(listener net.Listener) (*os.File, error)
- func GlobToRegexp(in string) string
- func GuessHostIP() (ip net.IP, err error)
- func Host(hostname string) (string, error)
- func HumanTimeFormat(d time.Time) string
- func InitCLIParser(appName, appHelp string) (app *kingpin.Application)
- func InitLogger(purpose LoggingPurpose, level log.Level, verbose ...bool)
- func InitLoggerForTests(verbose ...bool)
- func InterfaceMapsEqual(a, b map[string]interface{}) bool
- func IsCertExpiredError(err error) bool
- func IsDir(dirPath string) bool
- func IsFile(fp string) bool
- func IsGroupMember(gid int) (bool, error)
- func IsHandshakeFailedError(err error) bool
- func IsLocalhost(host string) bool
- func IsLoopback(host string) bool
- func IsSelfSigned(certificateChain []*x509.Certificate) bool
- func IsShellFailedError(err error) bool
- func JoinStringSlices(a []string, b []string) []string
- func ListenTLS(address string, certFile, keyFile string, cipherSuites []uint16) (net.Listener, error)
- func MinTTL(a, b time.Duration) time.Duration
- func MkdirAll(targetDirectory string, mode os.FileMode) error
- func MultiCloser(closers ...io.Closer) *multiCloser
- func NewHMACAnonymizer(key string) (*hmacAnonymizer, error)
- func NopWriteCloser(r io.Writer) io.WriteCloser
- func NormalizePath(path string) (string, error)
- func ObeyIdleTimeout(conn net.Conn, timeout time.Duration, ownerName string) net.Conn
- func ObjectToStruct(in interface{}, out interface{}) error
- func OpenFile(path string) (*os.File, error)
- func ParseAdvertiseAddr(advertiseIP string) (string, string, error)
- func ParseBool(value string) (bool, error)
- func ParseCertificatePEM(bytes []byte) (*x509.Certificate, error)
- func ParseCertificateRequestPEM(bytes []byte) (*x509.CertificateRequest, error)
- func ParseOnOff(parameterName, val string, defaultValue bool) (bool, error)
- func ParsePrivateKeyDER(der []byte) (crypto.Signer, error)
- func ParsePrivateKeyPEM(bytes []byte) (crypto.Signer, error)
- func ParseSessionsURI(in string) (*url.URL, error)
- func PercentUsed(path string) (float64, error)
- func PrintVersion()
- func RandomDuration(max time.Duration) time.Duration
- func ReadAll(r io.Reader, bufsize int) (out []byte, err error)
- func ReadCertificateChain(certificateChainBytes []byte) ([]*x509.Certificate, error)
- func ReadEnvironmentFile(filename string) ([]string, error)
- func ReadHostUUID(dataDir string) (string, error)
- func ReadOrMakeHostUUID(dataDir string) (string, error)
- func ReadPath(path string) ([]byte, error)
- func ReadToken(token string) (string, error)
- func ReadYAML(reader io.Reader) (interface{}, error)
- func RemoveFromSlice(slice []string, values ...string) []string
- func ReplaceInSlice(s []string, old string, new string) []string
- func ReplaceLocalhost(addr, replaceWith string) string
- func ReplaceRegexp(expression string, replaceWith string, input string) (string, error)
- func Round(x float64) float64
- func Roundtrip(addr string) (string, error)
- func RoundtripWithConn(conn net.Conn) (string, error)
- func SliceContainsStr(slice []string, value string) bool
- func SliceMatchesRegex(input string, expressions []string) (bool, error)
- func SplitHostPort(hostname string) (string, string, error)
- func SplitReaders(r1 io.Reader, r2 io.Reader) io.Reader
- func StartHTTPServer(addr NetAddr, h http.Handler) error
- func StatDir(path string) (os.FileInfo, error)
- func StringMapSlicesEqual(a, b map[string][]string) bool
- func StringMapsEqual(a, b map[string]string) bool
- func StringSliceSubset(a []string, b []string) error
- func StringSlicesEqual(a, b []string) bool
- func StringsSet(in []string) map[string]struct{}
- func SwitchLoggingtoSyslog() error
- func TLSConfig(cipherSuites []uint16) *tls.Config
- func TLSDial(ctx context.Context, dial DialWithContextFunc, network, addr string, ...) (*tls.Conn, error)
- func ThisFunction() string
- func ToJSON(data []byte) ([]byte, error)
- func ToTTL(c clockwork.Clock, tm time.Time) time.Duration
- func UTC(t *time.Time)
- func UintSliceSubset(a []uint16, b []uint16) error
- func UnmarshalWithSchema(schemaDefinition string, object interface{}, data []byte) error
- func UserMessageFromError(err error) string
- func VerifyCertificateChain(certificateChain []*x509.Certificate) error
- func WriteHostUUID(dataDir string, id string) error
- func WriteYAML(w io.Writer, values interface{}) error
- type AddrStorage
- type Anonymizer
- type BroadcastWriter
- type CertChecker
- type ChConn
- type CloseBroadcaster
- type CloserConn
- type DialWithContextFunc
- type FileAddrStorage
- type FileNode
- type JumpHost
- type Linear
- type LinearConfig
- type LoadBalancer
- type LoggingPurpose
- type NetAddr
- func DialAddrFromListenAddr(listenAddr NetAddr) NetAddr
- func FromAddr(a net.Addr) NetAddr
- func JoinAddrSlices(a []NetAddr, b []NetAddr) []NetAddr
- func MustParseAddr(a string) *NetAddr
- func ParseAddr(a string) (*NetAddr, error)
- func ParseAddrs(addrs []string) (result []NetAddr, err error)
- func ParseHostPortAddr(hostport string, defaultPort int) (*NetAddr, error)
- func (a *NetAddr) Equals(other NetAddr) bool
- func (a *NetAddr) FullAddress() string
- func (a *NetAddr) Host() string
- func (a *NetAddr) IsEmpty() bool
- func (a *NetAddr) IsLocal() bool
- func (a *NetAddr) IsLoopback() bool
- func (a *NetAddr) MarshalYAML() (interface{}, error)
- func (a *NetAddr) Network() string
- func (a *NetAddr) Port(defaultPort int) int
- func (a *NetAddr) Set(s string) error
- func (a *NetAddr) String() string
- func (a *NetAddr) UnmarshalYAML(unmarshal func(interface{}) error) error
- type NetAddrList
- type NetAddrVal
- type PipeNetConn
- func (nc *PipeNetConn) Close() error
- func (nc *PipeNetConn) LocalAddr() net.Addr
- func (nc *PipeNetConn) Read(buf []byte) (n int, e error)
- func (nc *PipeNetConn) RemoteAddr() net.Addr
- func (nc *PipeNetConn) SetDeadline(t time.Time) error
- func (nc *PipeNetConn) SetReadDeadline(t time.Time) error
- func (nc *PipeNetConn) SetWriteDeadline(t time.Time) error
- func (nc *PipeNetConn) Write(buf []byte) (n int, e error)
- type PortList
- type RemoveDirCloser
- type Retry
- type SigningKeyStore
- type Stater
- type Strings
- type SyncBuffer
- type SyncString
- type TLSCredentials
- type TimeoutConn
- type Tracer
- type TrackingConn
- type UID
- type WebLinks
- type WebSockWrapper
- type WebSocketMode
Constants ¶
const ( // DefaultLRUCapacity is a capacity for LRU session cache DefaultLRUCapacity = 1024 // DefaultCertTTL sets the TTL of the self-signed certificate (1 year) DefaultCertTTL = (24 * time.Hour) * 365 )
const ( // HumanTimeFormatString is a human readable date formatting HumanTimeFormatString = "Mon Jan _2 15:04 UTC" // CertTeleportUser specifies teleport user CertTeleportUser = "x-teleport-user" // CertTeleportUserCA specifies teleport certificate authority CertTeleportUserCA = "x-teleport-user-ca" // CertExtensionRole specifies teleport role CertExtensionRole = "x-teleport-role" // CertExtensionAuthority specifies teleport authority's name // that signed this domain CertExtensionAuthority = "x-teleport-authority" // HostUUIDFile is the file name where the host UUID file is stored HostUUIDFile = "host_uuid" // CertTeleportClusterName is a name of the teleport cluster CertTeleportClusterName = "x-teleport-cluster-name" // CertTeleportUserCertificate is the certificate of the authenticated in user. CertTeleportUserCertificate = "x-teleport-certificate" )
const ( WebSocketBinaryMode = iota WebSocketTextMode )
const ( // ConnectionTypeRequest is a request sent over a SSH channel that returns a // boolean which indicates the connection type (direct or tunnel). ConnectionTypeRequest = "x-teleport-connection-type" )
const PortStartingNumber = 20000
PortStartingNumber is a starting port number for tests
Variables ¶
This section is empty.
Functions ¶
func AsBool ¶
AsBool converts string to bool, in case of the value is empty or unknown, defaults to false
func CalculateSPKI ¶
func CalculateSPKI(cert *x509.Certificate) string
CalculateSPKI the hash value of the SPKI header in a certificate.
func Capitalize ¶
Capitalize returns a copy of the string with first rune converted to capital letter
func CheckCertificateFormatFlag ¶
CheckCertificateFormatFlag checks if the certificate format is valid.
func CheckSPKI ¶
func CheckSPKI(pin string, cert *x509.Certificate) error
CheckSPKI the passed in pin against the calculated value from a certificate.
func CheckVersions ¶
CheckVersions compares client and server versions and makes sure that the client version is greater than or equal to the minimum version supported by the server.
func CipherSuiteMapping ¶
CipherSuiteMapping transforms Teleport formatted cipher suites strings into uint16 IDs.
func ClickableURL ¶
ClickableURL fixes address in url to make sure it's clickable, e.g. it replaces "undefined" address like 0.0.0.0 used in network listeners format with loopback 127.0.0.1
func Consolef ¶ added in v1.0.0
Consolef prints the same message to a 'ui console' (if defined) and also to the logger with INFO priority
func ContainsExpansion ¶
ContainsExpansion returns true if value contains expansion syntax, e.g. $1 or ${10}
func CopyByteSlice ¶
CopyByteSlice returns a copy of the byte slice.
func CopyByteSlices ¶
CopyByteSlices returns a copy of the byte slices.
func CopyStringMap ¶
CopyStringMap makes a deep copy of a map[string]string and returns the copy.
func CopyStringMapInterface ¶
CopyStringMapInterface makes a deep copy of the passed in map[string]interface{} and returns the copy.
func CopyStringMapSlices ¶
CopyStringMapSlices makes a deep copy of the passed in map[string][]string and returns the copy.
func CopyStrings ¶
CopyStrings makes a deep copy of the passed in string slice and returns the copy.
func CreateCertificate ¶
CreateCertificate creates a valid 2048-bit RSA certificate.
func CreateEllipticCertificate ¶
func CreateEllipticCertificate(principal string, certType uint32) (*ssh.Certificate, ssh.Signer, error)
CreateEllipticCertificate creates a valid, but not supported, ECDSA SSH certificate. This certificate is used to make sure Teleport rejects such certificates.
func CreateTLSConfiguration ¶
CreateTLSConfiguration sets up default TLS configuration
func CryptoRandomHex ¶ added in v1.0.0
CryptoRandomHex returns hex encoded random string generated with crypto-strong pseudo random generator of the given bytes
func DefaultCipherSuites ¶
func DefaultCipherSuites() []uint16
DefaultCipherSuites returns the default list of cipher suites that Teleport supports. By default Teleport only support modern ciphers (Chacha20 and AES GCM) and key exchanges which support perfect forward secrecy (ECDHE).
Note that TLS_RSA_WITH_AES_128_GCM_SHA{256,384} have been dropped due to being banned by HTTP2 which breaks GRPC clients. For more information see: https://tools.ietf.org/html/rfc7540#appendix-A. These two can still be manually added if needed.
func DualPipeNetConn ¶
func DualPipeNetConn(srcAddr net.Addr, dstAddr net.Addr) (*PipeNetConn, *PipeNetConn)
DualPipeAddrConn creates a net.Pipe to connect a client and a server. The two net.Conn instances are wrapped in an addrConn which holds the source and destination addresses.
func EnsureLocalPath ¶
EnsureLocalPath makes sure the path exists, or, if omitted results in the subpath in default gravity config directory, e.g.
EnsureLocalPath("/custom/myconfig", ".gravity", "config") -> /custom/myconfig EnsureLocalPath("", ".gravity", "config") -> ${HOME}/.gravity/config
It also makes sure that base dir exists
func EscapeControl ¶
EscapeControl escapes all ANSI escape sequences from string and returns a string that is safe to print on the CLI. This is to ensure that malicious servers can not hide output. For more details, see:
func Extract ¶
Extract extracts the contents of the specified tarball under dir. The resulting files and directories are created using the current user context. Extract will only unarchive files into dir, and will fail if the tarball tries to write files outside of dir.
func FSReadLock ¶
FSReadLock grabs Flock-style filesystem lock on an open file in read (shared) mode
func FSTryWriteLock ¶
FSTryWriteLock tries to grab write lock, returns CompareFailed if lock is already grabbed
func FSWriteLock ¶
FSWriteLock grabs Flock-style filesystem lock on an open file in exclusive mode.
func FastMarshal ¶
FastMarshal uses the json-iterator library for fast JSON marshalling. Note, this function marshals floats with 6 digits precision.
func FastUnmarshal ¶
FastUnmarshal uses the json-iterator library for fast JSON unmarshalling. Note, this function marshals floats with 6 digits precision.
func FatalError ¶ added in v1.0.0
func FatalError(err error)
FatalError is for CLI front-ends: it detects gravitational/trace debugging information, sends it to the logger, strips it off and prints a clean message to stderr
func GenerateOTPURL ¶
GenerateOTPURL returns a OTP Key URL that can be used to construct a HOTP or TOTP key. For more details see: https://github.com/google/google-authenticator/wiki/Key-Uri-Format Example: otpauth://totp/foo:bar@baz.com?secret=qux
func GenerateQRCode ¶
GenerateQRCode takes in a OTP Key URL and returns a PNG-encoded QR code.
func GenerateSelfSignedSigningCert ¶
func GenerateSelfSignedSigningCert(entity pkix.Name, dnsNames []string, ttl time.Duration) ([]byte, []byte, error)
GenerateSelfSignedSigningCert generates self-signed certificate used for digital signatures
func GetIterations ¶
func GetIterations() int
GetIterations provides a simple way to add iterations to the test by setting environment variable "ITERATIONS", by default it returns 1
func GetListenerFile ¶
GetListenerFile returns file associated with listener
func GlobToRegexp ¶
GlobToRegexp replaces glob-style standalone wildcard values with real .* regexp-friendly values, does not modify regexp-compatible values, quotes non-wildcard values
func GuessHostIP ¶ added in v1.0.0
GuessIP tries to guess an IP address this machine is reachable at on the internal network, always picking IPv4 from the internal address space
If no internal IPs are found, it returns 127.0.0.1 but it never returns an address from the public IP space
func HumanTimeFormat ¶
HumanTimeFormat formats time as recognized by humans
func InitCLIParser ¶ added in v1.0.0
func InitCLIParser(appName, appHelp string) (app *kingpin.Application)
InitCLIParser configures kingpin command line args parser with some defaults common for all Teleport CLI tools
func InitLogger ¶
func InitLogger(purpose LoggingPurpose, level log.Level, verbose ...bool)
InitLogger configures the global logger for a given purpose / verbosity level
func InitLoggerForTests ¶ added in v1.0.0
func InitLoggerForTests(verbose ...bool)
func InterfaceMapsEqual ¶
InterfaceMapsEqual returns true if two interface maps are equal.
func IsCertExpiredError ¶
IsCertExpiredError specifies whether this error indicates expired SSH certificate
func IsDir ¶ added in v1.0.0
IsDir is a helper function to quickly check if a given path is a valid directory
func IsGroupMember ¶
IsGroupMember returns whether currently logged user is a member of a group
func IsHandshakeFailedError ¶ added in v1.0.0
IsHandshakeFailedError specifies whether this error indicates failed handshake
func IsLocalhost ¶ added in v1.0.0
IsLocalhost returns true if this is a local hostname or ip
func IsLoopback ¶ added in v1.0.0
IsLoopback returns 'true' if a given hostname resolves to local host's loopback interface
func IsSelfSigned ¶
func IsSelfSigned(certificateChain []*x509.Certificate) bool
IsSelfSigned checks if the certificate is a self-signed certificate. To check if a certificate is self signed, we make sure that only one certificate is in the chain and that the SubjectKeyId and AuthorityKeyId match.
From RFC5280: https://tools.ietf.org/html/rfc5280#section-4.2.1.1
The signature on a self-signed certificate is generated with the private key associated with the certificate's subject public key. (This proves that the issuer possesses both the public and private keys.) In this case, the subject and authority key identifiers would be identical, but only the subject key identifier is needed for certification path building.
func IsShellFailedError ¶ added in v1.0.0
IsShellFailedError specifies whether this error indicates failed attempt to start shell
func JoinStringSlices ¶
JoinStringSlices joins two string slices and returns a resulting slice
func ListenTLS ¶ added in v1.0.0
func ListenTLS(address string, certFile, keyFile string, cipherSuites []uint16) (net.Listener, error)
ListenTLS sets up TLS listener for the http handler, starts listening on a TCP socket and returns the socket which is ready to be used for http.Serve
func MultiCloser ¶
MultiCloser implements io.Close, it sequentially calls Close() on each object
func NewHMACAnonymizer ¶
NewHMACAnonymizer returns a new HMAC-based anonymizer
func NopWriteCloser ¶
func NopWriteCloser(r io.Writer) io.WriteCloser
NopWriteCloser returns a WriteCloser with a no-op Close method wrapping the provided Writer w
func NormalizePath ¶
NormalizePath normalises path, evaluating symlinks and converting local paths to absolute
func ObeyIdleTimeout ¶
ObeyIdleTimeout wraps an existing network connection with timeout-obeying Write() and Read() - it will drop the connection after 'timeout' on idle
Example: ObeyIdletimeout(conn, time.Second * 60, "api server").
func ObjectToStruct ¶
func ObjectToStruct(in interface{}, out interface{}) error
ObjectToStruct is converts any structure into JSON and then unmarshalls it into another structure.
Teleport configuration uses this (strange, at first) trick to convert from one struct type to another, if their fields are loosely compatible via their `json` tags
Example: assume you have two structs:
type A struct { Name string `json:"name"` Age int `json:"age"` }
type B struct { FullName string `json:"name"` }
Now you can convert B to A:
b := &B{ FullName: "Bob Dilan"} var a *A utils.ObjectToStruct(b, &a) fmt.Println(a.Name) > "Bob Dilan"
func ParseAdvertiseAddr ¶
ParseAdvertiseAddr validates advertise address, makes sure it's not an unreachable or multicast address returns address split into host and port, port could be empty if not specified
func ParseBool ¶
ParseBool parses string as boolean value, returns error in case if value is not recognized
func ParseCertificatePEM ¶
func ParseCertificatePEM(bytes []byte) (*x509.Certificate, error)
ParseCertificatePEM parses PEM-encoded certificate
func ParseCertificateRequestPEM ¶
func ParseCertificateRequestPEM(bytes []byte) (*x509.CertificateRequest, error)
ParseCertificateRequestPEM parses PEM-encoded certificate signing request
func ParseOnOff ¶
ParseOnOff parses whether value is "on" or "off", parameterName is passed for error reporting purposes, defaultValue is returned when no value is set
func ParsePrivateKeyDER ¶
ParsePrivateKeyDER parses unencrypted DER-encoded private key
func ParsePrivateKeyPEM ¶
ParsePrivateKeyPEM parses PEM-encoded private key
func ParseSessionsURI ¶
ParseSessionsURI parses uri per convention of session upload URIs file is a default scheme
func PercentUsed ¶
PercentUsed returns percentage of disk space used. The percentage of disk space used is calculated from (total blocks - free blocks)/total blocks. The value is rounded to the nearest whole integer.
func RandomDuration ¶ added in v1.0.0
RandomDuration returns a duration in a range [0, max)
func ReadAll ¶ added in v1.0.0
ReadAll is similarl to ioutil.ReadAll, except it doesn't use ever-increasing internal buffer, instead asking for the exact buffer size.
This is useful when you want to limit the sze of Read/Writes (websockets)
func ReadCertificateChain ¶
func ReadCertificateChain(certificateChainBytes []byte) ([]*x509.Certificate, error)
ReadCertificateChain parses PEM encoded bytes that can contain one or multiple certificates and returns a slice of x509.Certificate.
func ReadEnvironmentFile ¶
ReadEnvironmentFile will read environment variables from a passed in location. Lines that start with "#" or empty lines are ignored. Assignments are in the form name=value and no variable expansion occurs.
func ReadHostUUID ¶ added in v1.0.0
ReadHostUUID reads host UUID from the file in the data dir
func ReadOrMakeHostUUID ¶ added in v1.0.0
ReadOrMakeHostUUID looks for a hostid file in the data dir. If present, returns the UUID from it, otherwise generates one
func ReadToken ¶
ReadToken is a utility function to read the token from the disk if it looks like a path, otherwise, treat it as a value
func RemoveFromSlice ¶
RemoveFromSlice makes a copy of the slice and removes the passed in values from the copy.
func ReplaceInSlice ¶
ReplaceInSlice replaces element old with new and returns a new slice.
func ReplaceLocalhost ¶ added in v1.0.0
ReplaceLocalhost checks if a given address is link-local (like 0.0.0.0 or 127.0.0.1) and replaces it with the IP taken from replaceWith, preserving the original port
Both addresses are in "host:port" format The function returns the original value if it encounters any problems with parsing
func ReplaceRegexp ¶
ReplaceRegexp replaces value in string, accepts regular expression and simplified wildcard syntax, it has several important differeneces with standard lib regexp replacer: * Wildcard globs '*' are treated as regular expression .* expression * Expression is treated as regular expression if it starts with ^ and ends with $ * Full match is expected, partial replacements ignored * If there is no match, returns not found error
func Round ¶
Round returns the nearest integer, rounding half away from zero.
Special cases are:
Round(±0) = ±0 Round(±Inf) = ±Inf Round(NaN) = NaN
Note: Copied from Go standard library to support Go 1.9.7 releases. This function was added in the standard library in Go 1.10.
func Roundtrip ¶
Roundtrip is a single connection simplistic HTTP client that allows us to bypass a connection pool to test load balancing used in tests, as it only supports GET request on /
func RoundtripWithConn ¶
RoundtripWithConn uses HTTP GET on the existing connection, used in tests as it only performs GET request on /
func SliceContainsStr ¶
SliceContainsStr returns 'true' if the slice contains the given value
func SliceMatchesRegex ¶
SliceMatchesRegex checks if input matches any of the expressions. The match is always evaluated as a regex either an exact match or regexp.
func SplitHostPort ¶
SplitHostPort splits host and port and checks that host is not empty
func StringMapSlicesEqual ¶
StringMapSlicesEqual returns true if two maps of string slices are equal
func StringMapsEqual ¶
StringMapsEqual returns true if two strings maps are equal
func StringSliceSubset ¶
StringSliceSubset returns true if b is a subset of a.
func StringSlicesEqual ¶
StringSlicesEqual returns true if string slices equal
func StringsSet ¶
StringsSet creates set of string (map[string]struct{}) from a list of strings
func SwitchLoggingtoSyslog ¶
func SwitchLoggingtoSyslog() error
SwitchLoggingtoSyslog tells the logger to send the output to syslog. This code is behind a build flag because Windows does not support syslog.
func TLSDial ¶
func TLSDial(ctx context.Context, dial DialWithContextFunc, network, addr string, tlsConfig *tls.Config) (*tls.Conn, error)
TLSDial dials and establishes TLS connection using custom dialer is similar to tls.DialWithDialer
func ToJSON ¶
ToJSON converts a single YAML document into a JSON document or returns an error. If the document appears to be JSON the YAML decoding path is not used (so that error messages are JSON specific). Creds to: k8s.io for the code
func ToTTL ¶
ToTTL converts expiration time to TTL duration relative to current time as provided by clock
func UintSliceSubset ¶
UintSliceSubset returns true if b is a subset of a.
func UnmarshalWithSchema ¶
UnmarshalWithSchema processes YAML or JSON encoded object with JSON schema, sets defaults and unmarshals resulting object into given struct
func UserMessageFromError ¶ added in v1.0.0
UserMessageFromError returns user friendly error message from error
func VerifyCertificateChain ¶
func VerifyCertificateChain(certificateChain []*x509.Certificate) error
VerifyCertificateChain reads in chain of certificates and makes sure the chain from leaf to root is valid. This ensures that clients (web browsers and CLI) won't have problem validating the chain.
func WriteHostUUID ¶ added in v1.0.0
WriteHostUUID writes host UUID into a file
Types ¶
type AddrStorage ¶ added in v1.0.0
type AddrStorage interface { // SetAddresses saves addresses SetAddresses([]NetAddr) error // GetAddresses GetAddresses() ([]NetAddr, error) }
AddrStorage is used to store information locally for every client that connects in the cluster, so it can always have up-to-date info about auth servers
type Anonymizer ¶
type Anonymizer interface { // Anonymize returns anonymized string from the provided data Anonymize(data []byte) string }
Anonymizer defines an interface for anonymizing data
type BroadcastWriter ¶
type BroadcastWriter struct {
// contains filtered or unexported fields
}
BroadcastWriter broadcasts all writes to all writers
func NewBroadcastWriter ¶
func NewBroadcastWriter(writers ...io.Writer) *BroadcastWriter
NewBroadcastWriter returns new broadcast writer
type CertChecker ¶
type CertChecker struct { ssh.CertChecker // FIPS means in addition to checking the validity of the key or // certificate, also check that FIPS 140-2 algorithms were used. FIPS bool }
CertChecker is a drop-in replacement for ssh.CertChecker. In FIPS mode, checks if the certificate (or key) were generated with a supported algorithm.
func (*CertChecker) Authenticate ¶
func (c *CertChecker) Authenticate(conn ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error)
Authenticate checks the validity of a user certificate.
func (*CertChecker) CheckCert ¶
func (c *CertChecker) CheckCert(principal string, cert *ssh.Certificate) error
CheckCert checks certificate metadata and signature.
func (*CertChecker) CheckHostKey ¶
CheckHostKey checks the validity of a host certificate.
type ChConn ¶
ChConn is a net.Conn like object that uses SSH channel
func NewExclusiveChConn ¶
NewExclusiveChConn returns a new net.Conn implemented over SSH channel, whenever this connection closes
func (*ChConn) LocalAddr ¶
LocalAddr returns a local address of a connection Uses underlying net.Conn implementation
func (*ChConn) RemoteAddr ¶
RemoteAddr returns a remote address of a connection Uses underlying net.Conn implementation
func (*ChConn) SetDeadline ¶
SetDeadline sets a connection deadline ignored for the channel connection
func (*ChConn) SetReadDeadline ¶
SetReadDeadline sets a connection read deadline ignored for the channel connection
func (*ChConn) SetWriteDeadline ¶
SetWriteDeadline sets write deadline on a connection ignored for the channel connection
type CloseBroadcaster ¶ added in v1.0.0
CloseBroadcaster is a helper struct that implements io.Closer and uses channel to broadcast it's closed state once called
func NewCloseBroadcaster ¶ added in v1.0.0
func NewCloseBroadcaster() *CloseBroadcaster
NewCloseBroadcaster returns new instance of close broadcaster
func (*CloseBroadcaster) Close ¶ added in v1.0.0
func (b *CloseBroadcaster) Close() error
Close closes channel (once) to start broadcasting it's closed state
type CloserConn ¶
CloserConn wraps connection and attaches additional closers to it
func NewCloserConn ¶
func NewCloserConn(conn net.Conn, closers ...io.Closer) *CloserConn
NewCloserConn returns new connection wrapper that when closed will also close passed closers
func (*CloserConn) AddCloser ¶
func (c *CloserConn) AddCloser(closer io.Closer)
AddCloser adds any closer in ctx that will be called whenever server closes session channel
func (*CloserConn) Close ¶
func (c *CloserConn) Close() error
type DialWithContextFunc ¶
DialWithContext dials with context
type FileAddrStorage ¶ added in v1.0.0
type FileAddrStorage struct {
// contains filtered or unexported fields
}
FileAddrStorage is a file based address storage
func NewFileAddrStorage ¶ added in v1.0.0
func NewFileAddrStorage(filePath string) *FileAddrStorage
NewFileAddrStorage returns new instance of file-based address storage
func (*FileAddrStorage) GetAddresses ¶ added in v1.0.0
func (fs *FileAddrStorage) GetAddresses() ([]NetAddr, error)
GetAddresses returns saved address list
func (*FileAddrStorage) SetAddresses ¶ added in v1.0.0
func (fs *FileAddrStorage) SetAddresses(addrs []NetAddr) error
SetAddresses updates storage with new address list
type JumpHost ¶
type JumpHost struct { // Username to login as Username string // Addr is a target addr Addr NetAddr }
JumpHost is a target jump host
func ParseProxyJump ¶
ParseProxyJump parses strings like user@host:port,bob@host:port
type Linear ¶
type Linear struct { // LinearConfig is a linear retry config LinearConfig // contains filtered or unexported fields }
Linear is used to calculate retry period that follows the following logic: On the first error there is no delay on the next error, delay is FastLinear on all other errors, delay is SlowLinear
func NewLinear ¶
func NewLinear(cfg LinearConfig) (*Linear, error)
NewLinear returns a new instance of linear retry
func (*Linear) After ¶
After returns channel that fires with timeout defined in Duration method, as a special case if Duration is 0 returns a closed channel
type LinearConfig ¶
type LinearConfig struct { // First is a first element of the progression, // could be 0 First time.Duration // Step is a step of the progression, can't be 0 Step time.Duration // Max is a maximum value of the progression, // can't be 0 Max time.Duration }
LinearConfig sets up retry configuration using arithmetic progression
func (*LinearConfig) CheckAndSetDefaults ¶
func (c *LinearConfig) CheckAndSetDefaults() error
CheckAndSetDefaults checks and sets defaults
type LoadBalancer ¶
LoadBalancer implements naive round robin TCP load balancer used in tests.
func NewLoadBalancer ¶
func NewLoadBalancer(ctx context.Context, frontend NetAddr, backends ...NetAddr) (*LoadBalancer, error)
NewLoadBalancer returns new load balancer listening on frontend and redirecting requests to backends using round robin algo
func (*LoadBalancer) AddBackend ¶
func (l *LoadBalancer) AddBackend(b NetAddr)
AddBackend adds backend
func (*LoadBalancer) Close ¶
func (l *LoadBalancer) Close() error
func (*LoadBalancer) Listen ¶
func (l *LoadBalancer) Listen() error
Listen creates a listener on the frontend addr
func (*LoadBalancer) ListenAndServe ¶
func (l *LoadBalancer) ListenAndServe() error
ListenAndServe starts listening socket and serves connections on it
func (*LoadBalancer) RemoveBackend ¶
func (l *LoadBalancer) RemoveBackend(b NetAddr)
RemoveBackend removes backend
func (*LoadBalancer) Serve ¶
func (l *LoadBalancer) Serve() error
Serve starts accepting connections
func (*LoadBalancer) Wait ¶
func (l *LoadBalancer) Wait()
Wait is here to workaround issue https://github.com/golang/go/issues/10527 in tests
type LoggingPurpose ¶
type LoggingPurpose int
const ( LoggingForDaemon LoggingPurpose = iota LoggingForCLI LoggingForTests )
type NetAddr ¶
type NetAddr struct { // Addr is the host:port address, like "localhost:22" Addr string `json:"addr"` // AddrNetwork is the type of a network socket, like "tcp" or "unix" AddrNetwork string `json:"network,omitempty"` // Path is a socket file path, like '/var/path/to/socket' in "unix:///var/path/to/socket" Path string `json:"path,omitempty"` }
NetAddr is network address that includes network, optional path and host port
func DialAddrFromListenAddr ¶
DialAddrFromListenAddr returns dial address from listen address
func JoinAddrSlices ¶
JoinAddrSlices joins two addr slices and returns a resulting slice
func MustParseAddr ¶ added in v1.0.0
MustParseAddr parses the provided string into NetAddr or panics on an error
func ParseAddr ¶
ParseAddr takes strings like "tcp://host:port/path" and returns *NetAddr or an error
func ParseAddrs ¶
ParseAddrs parses the provided slice of strings as a slice of NetAddr's.
func ParseHostPortAddr ¶ added in v1.0.0
ParseHostPortAddr takes strings like "host:port" and returns *NetAddr or an error
If defaultPort == -1 it expects 'hostport' string to have it
func (*NetAddr) FullAddress ¶
FullAddress returns full address including network and address (tcp://0.0.0.0:1243)
func (*NetAddr) IsLoopback ¶ added in v1.0.0
IsLoopback returns true if this is a loopback address
func (*NetAddr) MarshalYAML ¶ added in v1.0.0
MarshalYAML defines how a network address should be marshalled to a string
func (*NetAddr) Port ¶
Port returns defaultPort if no port is set or is invalid, the real port otherwise
func (*NetAddr) UnmarshalYAML ¶
UnmarshalYAML defines how a string can be unmarshalled into a network address
type NetAddrList ¶
type NetAddrList []NetAddr
NetAddrList is a list of NetAddrs that supports helper methods for parsing from CLI tools
func (*NetAddrList) Addresses ¶ added in v1.0.0
func (nl *NetAddrList) Addresses() []string
Addresses returns a slice of strings converted from the addresses
func (*NetAddrList) String ¶
func (nl *NetAddrList) String() string
String returns debug-friendly representation of the tool
type NetAddrVal ¶
type NetAddrVal NetAddr
NetAddrVal can be used with flag package
func NewNetAddrVal ¶
func NewNetAddrVal(defaultVal NetAddr, val *NetAddr) *NetAddrVal
func (*NetAddrVal) Get ¶
func (a *NetAddrVal) Get() interface{}
func (*NetAddrVal) Set ¶
func (a *NetAddrVal) Set(s string) error
func (*NetAddrVal) String ¶
func (a *NetAddrVal) String() string
type PipeNetConn ¶
type PipeNetConn struct {
// contains filtered or unexported fields
}
PipeNetConn implemetns net.Conn from io.Reader,io.Writer and io.Closer
func NewPipeNetConn ¶
func NewPipeNetConn(reader io.Reader, writer io.Writer, closer io.Closer, fakelocalAddr net.Addr, fakeRemoteAddr net.Addr) *PipeNetConn
NewPipeNetConn returns a net.Conn like object using Pipe as an underlying implementation over reader, writer and closer
func (*PipeNetConn) Close ¶
func (nc *PipeNetConn) Close() error
func (*PipeNetConn) LocalAddr ¶
func (nc *PipeNetConn) LocalAddr() net.Addr
func (*PipeNetConn) RemoteAddr ¶
func (nc *PipeNetConn) RemoteAddr() net.Addr
func (*PipeNetConn) SetDeadline ¶
func (nc *PipeNetConn) SetDeadline(t time.Time) error
func (*PipeNetConn) SetReadDeadline ¶
func (nc *PipeNetConn) SetReadDeadline(t time.Time) error
func (*PipeNetConn) SetWriteDeadline ¶
func (nc *PipeNetConn) SetWriteDeadline(t time.Time) error
type PortList ¶ added in v1.0.0
type PortList []string
PortList is a list of TCP port
func GetFreeTCPPorts ¶ added in v1.0.0
GetFreeTCPPorts returns n ports starting from port 20000.
func (*PortList) Pop ¶ added in v1.0.0
Pop returns a value from the list, it panics if the value is not there
func (*PortList) PopInt ¶
PopInt returns a value from the list, it panics if not enough values were allocated
func (*PortList) PopIntSlice ¶
PopIntSlice returns a slice of values from the list, it panics if not enough ports were allocated
type RemoveDirCloser ¶
type RemoveDirCloser struct {
Path string
}
RemoveDirCloser removes directory and all it's contents when Close is called
func (*RemoveDirCloser) Close ¶
func (r *RemoveDirCloser) Close() error
Close removes directory and all it's contents
type Retry ¶
type Retry interface { // Reset resets retry state Reset() // Inc increments retry attempt Inc() // Duration returns retry duration, // could be 0 Duration() time.Duration // After returns time.Time channel // that fires after Duration delay, // could fire right away if Duration is 0 After() <-chan time.Time }
Retry is an interface that provides retry logic
type SigningKeyStore ¶
type SigningKeyStore struct {
// contains filtered or unexported fields
}
SigningKeyStore is used to sign using X509 digital signatures
func ParseSigningKeyStorePEM ¶
func ParseSigningKeyStorePEM(keyPEM, certPEM string) (*SigningKeyStore, error)
ParseSigningKeyStore parses signing key store from PEM encoded key pair
func (*SigningKeyStore) GetKeyPair ¶
func (ks *SigningKeyStore) GetKeyPair() (*rsa.PrivateKey, []byte, error)
type Stater ¶
Stater is extension interface of the net.Conn for implementations that track connection statistics.
type Strings ¶
type Strings []string
Strings is a list of string that can unmarshal from list of strings or a scalar string from scalar yaml or json property
func (Strings) MarshalJSON ¶
MarshalJSON marshals to scalar value if there is only one value in the list to list otherwise
func (Strings) MarshalYAML ¶
MarshalYAML marshals to scalar value if there is only one value in the list, marshals to list otherwise
func (*Strings) UnmarshalJSON ¶
UnmarshalJSON unmarshals scalar string or strings slice to Strings
func (*Strings) UnmarshalYAML ¶
UnmarshalYAML is used to allow Strings to unmarshal from scalar string value or from the list
type SyncBuffer ¶
type SyncBuffer struct {
// contains filtered or unexported fields
}
SyncBuffer is in memory bytes buffer that is safe for concurrent writes
func (*SyncBuffer) Bytes ¶
func (b *SyncBuffer) Bytes() []byte
Bytes returns contents of the buffer after this call, all writes will fail
func (*SyncBuffer) Close ¶
func (b *SyncBuffer) Close() error
Close closes reads and writes on the buffer
func (*SyncBuffer) String ¶
func (b *SyncBuffer) String() string
String returns contents of the buffer after this call, all writes will fail
type SyncString ¶
SyncString is a string value that can be concurrently accessed
type TLSCredentials ¶ added in v1.0.0
type TLSCredentials struct { // PublicKey in PEM format PublicKey []byte // PrivateKey in PEM format PrivateKey []byte Cert []byte }
TLSCredentials keeps the typical 3 components of a proper HTTPS configuration
func GenerateSelfSignedCert ¶ added in v1.0.0
func GenerateSelfSignedCert(hostNames []string) (*TLSCredentials, error)
GenerateSelfSignedCert generates a self signed certificate that is valid for given domain names and ips, returns PEM-encoded bytes with key and cert
type TimeoutConn ¶ added in v1.2.6
type TimeoutConn struct { net.Conn TimeoutDuration time.Duration // Name is only useful for debugging/logging, it's a convenient // way to tag every idle connection OwnerName string }
TimeoutConn wraps an existing net.Conn and adds read/write timeouts for it, allowing to implement "disconnect after XX of idle time" policy
Usage example: tc := utils.ObeyIdleTimeout(conn, time.Second * 30, "ssh connection") io.Copy(tc, xxx)
type Tracer ¶
type Tracer struct { // Started records starting time of the call Started time.Time // Description is arbitrary description Description string }
Tracer helps to trace execution of functions
type TrackingConn ¶
type TrackingConn struct { // net.Conn is the underlying net.Conn. net.Conn // contains filtered or unexported fields }
TrackingConn is a net.Conn that keeps track of how much data was transmitted (TX) and received (RX) over the net.Conn. A maximum of about 18446 petabytes can be kept track of for TX and RX before it rolls over. See https://golang.org/ref/spec#Numeric_types for more details.
func NewTrackingConn ¶
func NewTrackingConn(conn net.Conn) *TrackingConn
NewTrackingConn returns a net.Conn that can keep track of how much data was transmitted over it.
func (*TrackingConn) Stat ¶
func (s *TrackingConn) Stat() (uint64, uint64)
Stat returns the transmitted (TX) and received (RX) bytes over the net.Conn.
type UID ¶
type UID interface { // New returns a new UUID4. New() string }
UID provides an interface for generating unique identifiers.
type WebLinks ¶
type WebLinks struct { // NextPage is the next page of pagination links. NextPage string // PrevPage is the previous page of pagination links. PrevPage string // FirstPage is the first page of pagination links. FirstPage string // LastPage is the last page of pagination links. LastPage string }
WebLinks holds the pagination links parsed out of a request header conforming to RFC 8288.
func ParseWebLinks ¶
ParseWebLinks partially implements RFC 8288 parsing, enough to support GitHub pagination links. See https://tools.ietf.org/html/rfc8288 for more details on Web Linking and https://github.com/google/go-github for the API client that this function was original extracted from.
Link headers typically look like:
Link: <https://api.github.com/user/teams?page=2>; rel="next", <https://api.github.com/user/teams?page=34>; rel="last"
type WebSockWrapper ¶ added in v1.0.0
type WebSockWrapper struct { io.ReadWriteCloser sync.Mutex // contains filtered or unexported fields }
WebSockWrapper wraps the raw websocket and converts Write() calls to proper websocket.Send() working in binary or text mode. If text mode is selected, it converts the data passed to Write() into UTF8 bytes
We need this to make sure that the entire buffer in io.Writer.Write(buffer) is delivered as a single chunk to the web browser, instead of being split into multiple frames. This wrapper basically substitutes every Write() with Send() and every Read() with Receive()
func NewWebSockWrapper ¶ added in v1.0.0
func NewWebSockWrapper(ws *websocket.Conn, m WebSocketMode) *WebSockWrapper
func (*WebSockWrapper) Close ¶ added in v1.0.0
func (w *WebSockWrapper) Close() error
type WebSocketMode ¶ added in v1.0.0
type WebSocketMode int
WebSocketMode allows to create WebSocket wrappers working in text or binary mode
Source Files ¶
- addr.go
- anonymizer.go
- broadcaster.go
- buf.go
- cap.go
- certs.go
- checker.go
- cli.go
- conn.go
- conv.go
- copy.go
- disk.go
- environment.go
- equals.go
- fakeconn.go
- fs.go
- fs_unix.go
- jsontools.go
- linking.go
- listener.go
- loadbalancer.go
- node.go
- otp.go
- proxyjump.go
- rand.go
- replace.go
- retry.go
- round.go
- schema.go
- spki.go
- srv.go
- storage.go
- syslog.go
- time.go
- timeout.go
- tls.go
- tlsdial.go
- token.go
- uid.go
- unpack.go
- uri.go
- utils.go
- ver.go
- websocketwriter.go
- writer.go