package
0.0.0-20250306163500-5f3bb2705e1f
Repository: https://github.com/versoriumx/teleport.git
Documentation: pkg.go.dev
# Packages
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
No description provided by the author
TODO(nklaassen): evaluate the risks and utility of allowing traits to be used as regular expressions.
No description provided by the author
package socks implements a SOCKS5 handshake.
No description provided by the author
typical (TYPed predICAte Library) is a library for building better predicate expression parsers faster.
No description provided by the author
# Functions
AddrsFromStrings returns strings list converted to address list.
AllowWhitespace escapes all ANSI escape sequences except some whitespace characters (\n \t \v) from string and returns a string that is safe to print on the CLI.
AsBool converts string to bool, in case of the value is empty or unknown, defaults to false.
BcryptFromPassword delegates to bcrypt.GenerateFromPassword, but maintains the prior behavior of only hashing the first 72 bytes.
ByteCount converts a size in bytes to a human-readable string.
CalculateSPKI the hash value of the SPKI header in a certificate.
CanUserWriteTo attempts to check if a user has write access to certain path.
ChainHTTPMiddlewares wraps an http.Handler with a list of middlewares.
CheckCertificateFormatFlag checks if the certificate format is valid.
CheckSPKI the passed in pin against the calculated value from a certificate.
CheckVersion compares a version with a minimum version supported.
ChooseRandomString returns a random string from the given slice.
CipherSuiteMapping transforms Teleport formatted cipher suites strings into uint16 IDs.
ClickableURL fixes address in url to make sure it's clickable, e.g.
ClientIPFromConn extracts host from provided remote address.
Color formats the string in a terminal escape color.
CombineReadWriteCloser creates a CombinedReadWriteCloser from the provided [io.ReadCloser] and [io.WriteCloser] that implements [io.ReadWriteCloser].
CompileExpression compiles the given regex expression with Teleport's custom globbing and quoting logic.
CompressTarGzArchive creates a Tar Gzip archive in memory, reading the files using the provided file reader.
ContainsExpansion returns true if value contains expansion syntax, e.g.
No description provided by the author
CopyStringsMap returns a copy of the strings map.
CreateSyslogHook provides a [logrus.Hook] that sends output to syslog.
CreateTLSConfiguration sets up default TLS configuration.
CryptoRandomHex returns a hex-encoded random string generated with a crypto-strong pseudo-random generator.
DefaultCipherSuites returns the default list of cipher suites that Teleport supports.
DialAddrFromListenAddr returns dial address from listen address.
DNSName extracts DNS name from host:port string.
DualPipeNetConn creates a pipe to connect a client and a server.
EnsureLocalPath makes sure the path exists, or, if omitted results in the subpath in default gravity config directory, e.g.
EscapeControl escapes all ANSI escape sequences from string and returns a string that is safe to print on the CLI.
Extract extracts the contents of the specified tarball under dir.
FastMarshal uses the json-iterator library for fast JSON marshaling.
FastMarshal uses the json-iterator library for fast JSON marshaling with indentation.
FastUnmarshal uses the json-iterator library for fast JSON unmarshalling.
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.
FileExists checks whether a file exists at a given path.
FnCacheGet loads the result associated with the supplied key.
FormatAlert formats and colors the alert message if possible.
FormatErrorWithNewline returns user friendly error message from error.
FromAddr returns NetAddr from golang standard net.Addr.
FromSlice converts the provided slice to a map using the key function to determine the appropriate key per entry.
FSTryReadLock tries to grab write lock, returns ErrUnsuccessfulLockTry if lock is already acquired by someone else.
FSTryReadLockTimeout tries to grab read lock, it's doing it until locks is acquired, or timeout is expired, or context is expired.
FSTryWriteLock tries to grab write lock, returns ErrUnsuccessfulLockTry if lock is already acquired by someone else.
FSTryWriteLockTimeout tries to grab write lock, it's doing it until locks is acquired, or timeout is expired, or context is expired.
GenerateSelfSignedSigningCert generates self-signed certificate used for digital signatures.
GetAndReplaceRequestBody returns the request body and replaces the drained body reader with io.NopCloser allowing for further body processing by http transport.
GetAndReplaceResponseBody returns the response body and replaces the drained body reader with io.NopCloser allowing for further body processing.
GetAnyHeader returns the first non-empty value by the provided keys.
No description provided by the author
GetEC2NodeID returns the node ID to use for this EC2 instance when using Simplified Node Joining.
GetFreeTCPPorts returns n ports starting from port 20000.
GetHostUUIDPath returns the path to the host UUID file given the data directory.
GetIterations provides a simple way to add iterations to the test by setting environment variable "ITERATIONS", by default it returns 1.
GetListenerFile returns file associated with listener.
GetRawEC2IdentityDocument fetches the PKCS7 RSA2048 InstanceIdentityDocument from the IMDS for this EC2 instance.
GetSingleHeader will return the header value for the key if there is exactly one value present.
GlobToRegexp replaces glob-style standalone wildcard values with real .* regexp-friendly values, does not modify regexp-compatible values, quotes non-wildcard values.
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.
HasBTF checks that the kernel has been compiled with BTF support and that the type information can be opened.
HasPrefixAny determines if any of the string values have the given prefix.
Host extracts host from host:port string.
HostUUIDExistsLocally checks if dataDir/host_uuid file exists in local storage.
InitCertLeaves initializes the Leaf field for each cert in a slice of certs, to reduce per-handshake processing.
InitCLIParser configures kingpin command line args parser with some defaults common for all Teleport CLI tools.
InitLogger configures the global logger for a given purpose / verbosity level.
InitLoggerForTests initializes the standard logger for tests.
IsCertExpiredError specifies whether this error indicates expired SSH certificate.
IsConnectionRefused returns true if the given err is "connection refused" error.
IsDir is a helper function to quickly check if a given path is a valid directory.
IsExpiredCredentialError checks if an error corresponds to expired credentials.
IsFailedToSendCloseNotifyError returns true if the provided error is the "tls: failed to send closeNotify".
IsGroupMember returns whether currently logged user is a member of a group.
IsHandshakeFailedError specifies whether this error indicates failed handshake.
IsLocalhost returns true if this is a local hostname or ip.
IsOKNetworkError returns true if the provided error received from a network operation is one of those that usually indicate normal connection close.
IsPredicateError determines if the error is from failing to parse predicate expression by checking if the error as a string contains predicate keywords.
IsRedirect returns true if the status code is a 3xx code.
IsSelfSigned checks if the certificate is a self-signed certificate.
IsUntrustedCertErr checks if an error is an untrusted cert error.
IsUseOfClosedNetworkError returns true if the specified error indicates the use of a closed network connection.
IsValidHostname checks if a string represents a valid hostname.
IsValidUnixUser checks if a string represents a valid UNIX username.
JoinAddrSlices joins two addr slices and returns a resulting slice.
KernelVersion parses /proc/sys/kernel/osrelease and returns the kernel version of the host.
KubeResourceMatchesRegex checks whether the input matches any of the given expressions.
KubeResourceMatchesRegex checks whether the input matches any of the given expressions.
MajorSemver returns the major version as a semver string.
MarshalPrivateKey will return a PEM encoded crypto.Signer.
MarshalPublicKey returns a PEM encoded public key for a given crypto.Signer.
MatchString will match an input against the given expression.
MeetsVersion returns true if gotVer is empty or at least minVer.
MinTTL selects the smallest non-zero duration from a and b.
MinVerWithoutPreRelease compares semver strings, but skips prerelease.
MultiCloser implements io.Close, it sequentially calls Close() on each object.
MustParseAddr parses the provided string into NetAddr or panics on an error.
MustParseAddrList parses the provided list of strings into a NetAddr list or panics on error.
NetAddrsToStrings takes a list of netAddrs and returns a list of address strings.
NewBufferSyncPool returns a new instance of sync pool of bytes.Buffers that creates new buffers with preallocated underlying buffer of size.
NewCaptureNBytesWriter creates a new CaptureNBytesWriter.
NewCertPoolFromPath creates a new x509.CertPool from provided path.
NewCircularBuffer returns a new instance of a circular buffer that will hold size elements before it rotates.
NewCloseBroadcaster returns new instance of close broadcaster.
NewCloserConn returns new connection wrapper that when closed will also close passed closers.
NewConnWithAddr wraps a [net.Conn] optionally overriding the local and remote addresses with the provided ones, if non-nil.
NewConnWithSrcAddr wraps provided connection and overrides client remote address.
NewDefaultLinear creates a linear retry with reasonable default parameters for attempting to restart "critical but potentially load-inducing" operations, such as watcher or control stream resume.
NewFakeUID returns a new fake UID generator used in tests.
No description provided by the author
NewHMACAnonymizer returns a new HMAC-based anonymizer.
No description provided by the author
NewLoadBalancer returns new load balancer listening on frontend and redirecting requests to backends using round robin algo.
NewLogger creates a new empty logrus logger.
NewLoggerForTests creates a new logrus logger for test environments.
NewPipeNetConn constructs a new PipeNetConn, providing a net.Conn implementation synthesized from the supplied io.Reader, io.Writer & io.Closer.
NewRandomLoadBalancer returns new load balancer listening on frontend and redirecting requests to backends randomly.
NewRealUID returns a new real UID generator.
NewRepeatReader returns a repeat reader.
NewRoundRobin creates a new round-robin inst.
NewSliceSyncPool returns a new slice pool, using sync.Pool of pre-allocated or newly allocated slices of the predefined size and capacity.
NewSlogLoggerForTests creates a new slog logger for test environments.
NewStdlogger creates a new stdlib logger that uses the specified leveled logger for output and the given component as a logging prefix.
NewSyncBuffer returns new in memory buffer.
No description provided by the author
NewTracer returns a new tracer.
NewTrackingConn returns a net.Conn that can keep track of how much data was transmitted over it.
NewTrackingReader creates a TrackingReader around r.
NewTrackingWriter creates a TrackingWriter around w.
NilCloser returns closer if it's not nil otherwise returns a nop closer.
NodeIDFromIID returns the node ID that must be used for nodes joining with the given Instance Identity Document.
NoopHTTPMiddleware is a no-operation HTTPMiddleware that returns the original handler.
NopWriteCloser returns a WriteCloser with a no-op Close method wrapping the provided Writer w.
NormalizePath normalises path, evaluating symlinks and converting local paths to absolute.
ObeyIdleTimeout wraps an existing network connection, closing it if data isn't read often enough.
OpaqueAccessDenied returns a generic NotFound instead of AccessDenied so as to avoid leaking the existence of secret resources.
OpenFileAllowingUnsafeLinks opens a file, if the path includes a symlink, the returned os.File will be resolved to the actual file.
OpenFileNoUnsafeLinks opens a file, ensuring it's an actual file and not a directory or symlink.
ParseAddr takes strings like "tcp://host:port/path" and returns *NetAddr or an error.
ParseAddrs parses the provided slice of strings as a slice of NetAddr's.
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.
ParseHostPortAddr takes strings like "host:port" and returns *NetAddr or an error
If defaultPort == -1 it expects 'hostport' string to have it.
ParseKeyStorePEM parses signing key store from PEM encoded key pair.
ParseOnOff parses whether value is "on" or "off", parameterName is passed for error reporting purposes, defaultValue is returned when no value is set.
ParsePrivateKey parses a PEM encoded private key and returns a crypto.Signer.
ParsePrivateKeyDER parses unencrypted DER-encoded private key.
ParsePrivateKeyPEM parses PEM-encoded private key.
ParseProxyJump parses strings like user@host:port,bob@host:port.
ParsePublicKey parses a PEM encoded public key and returns a crypto.PublicKey.
ParseWebLinks partially implements RFC 8288 parsing, enough to support GitHub pagination links.
PercentUsed returns percentage of disk space used.
ProxyConn launches a double-copy loop that proxies traffic between the provided client and server connections.
RandomDuration returns a duration in a range [0, max).
ReadAtMost reads up to limit bytes from r, and reports an error when limit bytes are read.
ReadCertificates parses PEM encoded bytes that can contain one or multiple certificates and returns a slice of x509.Certificate.
ReadCertificatesFromPath parses PEM encoded certificates from provided path.
ReadHostUUID reads host UUID from the file in the data dir.
ReadOrMakeHostUUID looks for a hostid file in the data dir.
ReadPath reads file contents.
ReadYAML can unmarshal a stream of documents, used in tests.
No description provided by the author
RecursivelyCopy will copy a directory from src to dest, if the directory exists, files will be overwritten.
RegexMatchesAny returns true if [expression] matches any element of [inputs].
RegexpWithConfig compiles a regular expression given some configuration.
RemoveAllSecure is similar to [os.RemoveAll] but leverages [RemoveSecure] to delete files so that they are overwritten.
RemoveFileIfExist removes file if exits.
RemoveFromSlice makes a copy of the slice and removes the passed in values from the copy.
RemoveSecure attempts to securely delete the file by first overwriting the file with random data three times followed by calling os.Remove(filePath).
RenameHeader moves all values from the old header key to the new header key.
ReplaceInSlice replaces element old with new and returns a new slice.
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.
ReplaceRegexp replaces value in string, accepts regular expression and simplified wildcard syntax, it has several important differences 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 a NotFound error.
ReplaceRegexp replaces string in a given regexp.
ReplaceRequestBody drains the old request body and replaces it with a new one.
ReplaceUnspecifiedHost replaces unspecified "0.0.0.0" with localhost since "0.0.0.0" is never a valid principal (auth server explicitly removes it when issuing host certs) and when a reverse tunnel client used establishes SSH reverse tunnel connection the host is validated against the valid principal list.
Round returns the nearest integer, rounding half away from zero.
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 /.
RoundtripWithConn uses HTTP GET on the existing connection, used in tests as it only performs GET request on /.
SetupTLSConfig sets up cipher suites in existing TLS config.
SliceMatchesRegex checks if input matches any of the expressions.
SplitHostPort splits host and port and checks that host is not empty.
SplitIdentifiers splits list of identifiers by commas/spaces/newlines.
StatDir stats directory, returns error if file exists, but not a directory.
StatFile stats path, returns error if it exists but a directory.
StoreErrorOf stores the error returned by f within *err.
StremJSONArray streams the elements of a stream.Stream as a json array with optional indentation (used to stream to CLI).
StringMapsEqual returns true if two strings maps are equal.
StringSliceSubset returns true if b is a subset of a.
StringsSet creates set of string (map[string]struct{}) from a list of strings.
StringsSliceFromSet returns a sorted strings slice from set.
SwitchLoggingToSyslog configures the default logger to send output to syslog.
ThisFunction returns calling function name.
TLSCertLeaf is a helper function that extracts the parsed leaf *x509.Certificate from a tls.Certificate.
TLSConfig returns default TLS configuration strong defaults.
TLSDial dials and establishes TLS connection using custom dialer is similar to tls.DialWithDialer.
ToFieldsCondition converts a WhereExpr into a FieldsCondition.
ToJSON converts a single YAML document into a JSON document or returns an error.
ToLowerCaseASCII returns a lower-case version of in.
ToTTL converts expiration time to TTL duration relative to current time as provided by clock.
TryReadValueAsFile is a utility function to read a value from the disk if it looks like an absolute path, otherwise, treat it as a value.
UintSliceSubset returns true if b is a subset of a.
UnsafeSliceData is a wrapper around unsafe.SliceData which ensures that instead of ever returning "a non-nil pointer to an unspecified memory address" (see unsafe.SliceData documentation), an error is returned instead.
UpdateAppUsageTemplate updates usage template for kingpin applications by pre-parsing the arguments then applying any changes to the usage template if necessary.
UserMessageFromError returns user-friendly error message from error.
VerifyCertificateChain reads in chain of certificates and makes sure the chain from leaf to root is valid.
VerifyCertificateExpiry checks the certificate's expiration status.
VersionBeforeAlpha appends "-aa" to the version so that it comes before <version>-alpha.
WithLogFormat initializes the default logger with the provided format.
WrapLogger wraps an existing logger entry and returns a value satisfying the Logger interface.
WriteCloserWithContext converts ContextCloser to io.Closer, whenever new Close method will be called, the ctx will be passed to it.
WriteHostUUID writes host UUID into a file.
WriteJSON marshals multiple documents as a JSON list with indentation.
WriteJSONArray marshals values as a JSON array.
WriteJSONObject marshals m as a JSON object.
WriteYAML detects whether value is a list and marshals multiple documents delimited by `---`, otherwise, marshals a single value.
# Constants
Blue is an escape code for blue terminal color.
Bold is an escape code to format as bold or increased intensity.
CertExtensionAuthority specifies teleport authority's name that signed this domain.
CertExtensionRole specifies teleport role.
CertTeleportClusterName is a name of the teleport cluster.
CertTeleportUser specifies teleport user.
CertTeleportUserCA specifies teleport certificate authority.
CertTeleportUserCertificate is the certificate of the authenticated in user.
DefaultCertTTL sets the TTL of the self-signed certificate (1 year).
DefaultLRUCapacity is a capacity for LRU session cache.
ExtIntCertType is an internal extension used to propagate cert type.
ExtIntCertTypeHost indicates a host-type certificate.
ExtIntCertTypeUser indicates a user-type certificate.
FSLockRetryDelay is a delay between attempts to acquire lock.
Gray is an escape code for gray terminal color.
HostUUIDFile is the file name where the host UUID file is stored.
KubeCustomResource is the type that represents a Kubernetes CustomResource object.
LogFormatJSON configures logs to be emitted in json.
LogFormatText configures logs to be emitted in a human readable text format.
LoggingForCLI configures logging for user face utilities (tctl, tsh).
LoggingForDaemon configures logging for non-user interactive applications (teleport, tbot, tsh deamon).
PortStartingNumber is a starting port number for tests.
Red is an escape code for red terminal color.
SelfSignedCertsMsg is a helper message to point users towards helpful documentation.
Yellow is an escape code for yellow terminal color.
# Variables
ErrFnCacheClosed is returned from Get when the FnCache context is closed.
ErrLimitReached means that the read limit is reached.
ErrUnsuccessfulLockTry designates an error when we temporarily couldn't acquire lock (most probably it was already locked by someone else), another try might succeed.
FullJitter is a global jitter instance used for one-off jitters.
HalfJitter is a global jitter instance used for one-off jitters.
SafeConfig uses jsoniter's ConfigFastest settings but enables map key sorting to ensure CompareAndSwap checks consistently succeed.
SafeConfigWithIndent is equivalent to SafeConfig except with indentation enabled.
SeventhJitter is a global jitter instance used for one-off jitters.
# Structs
BufferSyncPool is a sync pool of bytes.Buffer.
CaptureNBytesWriter is an io.Writer thats captures up to first n bytes of the incoming data in memory, and then it ignores the rest of the incoming data.
CircularBuffer implements an in-memory circular buffer of predefined size.
CloseBroadcaster is a helper struct that implements io.Closer and uses channel to broadcast it's closed state once called.
CloserConn wraps connection and attaches additional closers to it.
CombinedReadWriteCloser wraps an [io.ReadCloser] and an [io.WriteCloser] to implement [io.ReadWriteCloser].
ConnWithAddr is a [net.Conn] wrapper that allows the local and remote address to be overridden.
FnCache is a helper for temporarily storing the results of regularly called functions.
No description provided by the author
hmacAnonymizer implements anonymization using HMAC.
InMemoryFile stores the required properties to emulate a File in memory It contains the File properties like name, size, mode It also contains the File contents It does not support folders.
JumpHost is a target jump host.
KeyStore is used to sign and decrypt data using X509 digital signatures.
LoadBalancer implements naive round robin TCP load balancer used in tests.
NetAddr is network address that includes network, optional path and host port.
PipeNetConn implements net.Conn from a provided io.Reader,io.Writer and io.Closer.
PortList is a list of TCP ports.
No description provided by the author
RegexpConfig defines the configuration of the regular expression matcher.
RepeatReader repeats the same byte count times without allocating any data, the single instance of the repeat reader is not goroutine safe.
RoundRobin is a helper for distributing load across multiple resources in a round-robin fashion.
SliceSyncPool is a sync pool of slices (usually large) of the same size to optimize memory usage, see sync.Pool for more details.
SyncBuffer is in memory bytes buffer that is safe for concurrent writes.
SyncMap is a generics version of a sync.Map.
SyncString is a string value that can be concurrently accessed.
No description provided by the author
Tracer helps to trace execution of functions.
TrackingConn is a net.Conn that keeps track of how much data was transmitted (TX) and received (RX) over the net.Conn.
TrackingReader is an io.Reader that counts the total number of bytes read.
TrackingWriter is an io.Writer that counts the total number of bytes written.
WebLinks holds the pagination links parsed out of a request header conforming to RFC 8288.
# Interfaces
Anonymizer defines an interface for anonymizing data.
FieldLoggerWithWriter describes a logger that can expose a writer to be used by stdlib loggers.
HTTPDoClient is an interface that defines the Do function of http.Client.
Logger describes a logger value.
ReadStatFS combines two interfaces: fs.ReadFileFS and fs.StatFS We need both when creating the archive to be able to: - read file contents - `ReadFile` provided by fs.ReadFileFS - set the correct file permissions - `Stat() ..
SlicePool manages a pool of slices in attempts to manage memory in go more efficiently and avoid frequent allocations.
Stater is extension interface of the net.Conn for implementations that track connection statistics.
TLSConn is a `net.Conn` that implements some of the functions defined by the `tls.Conn` struct.
UID provides an interface for generating unique identifiers.
WriteContextCloser provides close method with context.
# Type aliases
CloseFunc is a helper used to implement io.Closer on a closure.
DialWithContextFunc dials with context.
Fields represents a generic string-keyed map.
FieldsCondition is a boolean function on Fields.
HTTPMiddleware defines a HTTP middleware.
LeveledOutputFunc describes a function that emits given arguments at a specific level to an underlying logger.
LoggerOption enables customizing the global logger.
LoggingFormat defines the possible logging output formats.
LoggingPurpose specifies which kind of application logging is to be configured for.
OpenFileWithFlagsFunc defines a function used to open files providing options.