client

package
v11.3.3 Latest Latest
Warning

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

Go to latest
Published: Dec 13, 2022 License: Apache-2.0 Imports: 96 Imported by: 0

Documentation

Index

Constants

View Source
const (
	AddKeysToAgentAuto = "auto"
	AddKeysToAgentNo   = "no"
	AddKeysToAgentYes  = "yes"
	AddKeysToAgentOnly = "only"
)
View Source
const (
	// LoginSuccessRedirectURL is a redirect URL when login was successful without errors.
	LoginSuccessRedirectURL = "/web/msg/info/login_success"

	// LoginFailedRedirectURL is the default redirect URL when an SSO error was encountered.
	LoginFailedRedirectURL = "/web/msg/error/login"

	// LoginFailedBadCallbackRedirectURL is a redirect URL when an SSO error specific to
	// auth connector's callback was encountered.
	LoginFailedBadCallbackRedirectURL = "/web/msg/error/login/callback"

	// LoginFailedUnauthorizedRedirectURL is a redirect URL for when an SSO authenticates successfully,
	// but the user has no matching roles in Teleport.
	LoginFailedUnauthorizedRedirectURL = "/web/msg/error/login/auth"
)
View Source
const (
	// HTTPS is https prefix
	HTTPS = "https"
	// WSS is secure web sockets prefix
	WSS = "wss"
)

Variables

View Source
var HasPlatformSupport = &hasPlatformSupport
View Source
var PromptMFAStandalone = &promptMFAStandalone
View Source
var PromptWebauthn = &promptWebauthn

WithAllCerts lists all known CertOptions.

Functions

func GetKubeTLSServerName

func GetKubeTLSServerName(k8host string) string

GetKubeTLSServerName returns k8s server name used in KUBECONFIG to leverage TLS Routing.

func GetPaginatedSessions

func GetPaginatedSessions(ctx context.Context, fromUTC, toUTC time.Time, pageSize int, order types.EventOrder, max int, authClient auth.ClientI) ([]apievents.AuditEvent, error)

GetPaginatedSessions grabs up to 'max' sessions.

func GetWebConfig

func GetWebConfig(ctx context.Context, proxyAddr string, insecure bool) (*webclient.WebConfig, error)

GetWebConfig is used by teleterm to fetch webconfig.js from proxies

func HostCredentials

func HostCredentials(ctx context.Context, proxyAddr string, insecure bool, req types.RegisterUsingTokenRequest) (*proto.Certs, error)

HostCredentials is used to fetch host credentials for a node.

func InsecureSkipHostKeyChecking

func InsecureSkipHostKeyChecking(host string, remote net.Addr, key ssh.PublicKey) error

InsecureSkipHostKeyChecking is used when the user passes in "StrictHostKeyChecking yes".

func IsErrorResolvableWithRelogin

func IsErrorResolvableWithRelogin(err error) bool

func NewInsecureWebClient

func NewInsecureWebClient() *http.Client

func NewKeyStoreCertChecker

func NewKeyStoreCertChecker(keyStore sshKnowHostGetter, host string) ssh.HostKeyCallback

NewKeyStoreCertChecker returns a new certificate checker using trusted certs from key store

func ParseLabelSpec

func ParseLabelSpec(spec string) (map[string]string, error)

ParseLabelSpec parses a string like 'name=value,"long name"="quoted value"` into a map like { "name" -> "value", "long name" -> "quoted value" }

func ParseSearchKeywords

func ParseSearchKeywords(spec string, customDelimiter rune) []string

ParseSearchKeywords parses a string ie: foo,bar,"quoted value"` into a slice of strings: ["foo", "bar", "quoted value"]. Almost a replica to ParseLabelSpec, but with few modifications such as allowing a custom delimiter. Defaults to comma delimiter if not defined.

func PlayFile

func PlayFile(ctx context.Context, tarFile io.Reader, sid string) error

PlayFile plays the recorded session from a tar file

func PromptMFAChallenge

PromptMFAChallenge prompts the user to complete MFA authentication challenges.

func ProxyHost

func ProxyHost(proxyHost string) string

ProxyHost returns the hostname of the proxy server (without any port numbers)

func RetryWithRelogin

func RetryWithRelogin(ctx context.Context, tc *TeleportClient, fn func() error) error

RetryWithRelogin is a helper error handling method, attempts to relogin and retry the function once.

func SSHAgentLogin

func SSHAgentLogin(ctx context.Context, login SSHLoginDirect) (*auth.SSHLoginResponse, error)

SSHAgentLogin is used by tsh to fetch local user credentials.

func SSHAgentMFALogin

func SSHAgentMFALogin(ctx context.Context, login SSHLoginMFA) (*auth.SSHLoginResponse, error)

SSHAgentMFALogin requests a MFA challenge via the proxy. If the credentials are valid, the proxy will return a challenge. We then prompt the user to provide 2nd factor and pass the response to the proxy. If the authentication succeeds, we will get a temporary certificate back.

func SSHAgentPasswordlessLogin

func SSHAgentPasswordlessLogin(ctx context.Context, login SSHLoginPasswordless) (*auth.SSHLoginResponse, error)

SSHAgentPasswordlessLogin requests a passwordless MFA challenge via the proxy. weblogin.CustomPrompt (or a default prompt) is used for interaction with the end user.

Returns the SSH certificate if authn is successful or an error.

func SSHAgentSSOLogin

func SSHAgentSSOLogin(ctx context.Context, login SSHLoginSSO, config *RedirectorConfig) (*auth.SSHLoginResponse, error)

SSHAgentSSOLogin is used by tsh to fetch user credentials using OpenID Connect (OIDC) or SAML.

func Status

func Status(profileDir, proxyHost string) (*ProfileStatus, []*ProfileStatus, error)

Status returns the active profile as well as a list of available profiles. If no profile is active, Status returns a nil error and nil profile.

func Username

func Username() (string, error)

Username returns the current user's username

func ValidateAgentKeyOption

func ValidateAgentKeyOption(supplied string) error

ValidateAgentKeyOption validates that a string is a valid option for the AddKeysToAgent parameter.

func VirtualPathEnvName

func VirtualPathEnvName(kind VirtualPathKind, params VirtualPathParams) string

VirtualPathEnvName formats a single virtual path environment variable name.

func VirtualPathEnvNames

func VirtualPathEnvNames(kind VirtualPathKind, params VirtualPathParams) []string

VirtualPathEnvNames determines an ordered list of environment variables that should be checked to resolve an env var override. Params may be nil to indicate no additional arguments are to be specified or accepted.

Types

type AgentForwardingMode

type AgentForwardingMode int

AgentForwardingMode describes how the user key agent will be forwarded to a remote machine, if at all.

const (
	ForwardAgentNo AgentForwardingMode = iota
	ForwardAgentYes
	ForwardAgentLocal
)

type AuthenticateSSHUserRequest

type AuthenticateSSHUserRequest struct {
	// User is a teleport username
	User string `json:"user"`
	// Password for the user, to authenticate in case no MFA check was
	// performed.
	Password string `json:"password"`
	// WebauthnChallengeResponse is a signed WebAuthn credential assertion.
	WebauthnChallengeResponse *wanlib.CredentialAssertionResponse `json:"webauthn_challenge_response"`
	// TOTPCode is a code from the TOTP device.
	TOTPCode string `json:"totp_code"`
	// PubKey is a public key user wishes to sign
	PubKey []byte `json:"pub_key"`
	// TTL is a desired TTL for the cert (max is still capped by server,
	// however user can shorten the time)
	TTL time.Duration `json:"ttl"`
	// Compatibility specifies OpenSSH compatibility flags.
	Compatibility string `json:"compatibility,omitempty"`
	// RouteToCluster is an optional cluster name to route the response
	// credentials to.
	RouteToCluster string
	// KubernetesCluster is an optional k8s cluster name to route the response
	// credentials to.
	KubernetesCluster string
	// AttestationStatement is an attestation statement associated with the given public key.
	AttestationStatement *keys.AttestationStatement `json:"attestation_statement,omitempty"`
}

AuthenticateSSHUserRequest are passed by web client to authenticate against teleport server and receive a temporary cert signed by auth server authority.

type AuthenticateWebUserRequest

type AuthenticateWebUserRequest struct {
	// User is a teleport username.
	User string `json:"user"`
	// WebauthnAssertionResponse is a signed WebAuthn credential assertion.
	WebauthnAssertionResponse *wanlib.CredentialAssertionResponse `json:"webauthnAssertionResponse,omitempty"`
}

type CachePolicy

type CachePolicy struct {
	// CacheTTL defines cache TTL
	CacheTTL time.Duration
	// NeverExpire never expires local cache information
	NeverExpires bool
}

CachePolicy defines cache policy for local clients

type CertCachePolicy

type CertCachePolicy int

CertCachePolicy describes what should happen to the certificate cache when a user certificate is re-issued

const (
	// CertCacheDrop indicates that all user certificates should be dropped as
	// part of the re-issue process. This can be necessary if the roles
	// assigned to the user are expected to change as a part of the re-issue.
	CertCacheDrop CertCachePolicy = 0

	// CertCacheKeep indicates that all user certificates (except those
	// explicitly updated by the re-issue) should be preserved across the
	// re-issue process.
	CertCacheKeep CertCachePolicy = 1
)

type CertOption

type CertOption interface {
	// contains filtered or unexported methods
}

CertOption is an additional step to run when loading/deleting user certificates.

type Config

type Config struct {
	// Username is the Teleport account username (for logging into Teleport proxies)
	Username string
	// ExplicitUsername is true if Username was initially set by the end-user
	// (for example, using command-line flags).
	ExplicitUsername bool

	// Remote host to connect
	Host string

	// SearchKeywords host to connect
	SearchKeywords []string

	// PredicateExpression host to connect
	PredicateExpression string

	// Labels represent host Labels
	Labels map[string]string

	// Namespace is nodes namespace
	Namespace string

	// HostLogin is a user login on a remote host
	HostLogin string

	// HostPort is a remote host port to connect to. This is used for **explicit**
	// port setting via -p flag, otherwise '0' is passed which means "use server default"
	HostPort int

	// JumpHosts if specified are interpreted in a similar way
	// as -J flag in ssh - used to dial through
	JumpHosts []utils.JumpHost

	// WebProxyAddr is the host:port the web proxy can be accessed at.
	WebProxyAddr string

	// SSHProxyAddr is the host:port the SSH proxy can be accessed at.
	SSHProxyAddr string

	// KubeProxyAddr is the host:port the Kubernetes proxy can be accessed at.
	KubeProxyAddr string

	// PostgresProxyAddr is the host:port the Postgres proxy can be accessed at.
	PostgresProxyAddr string

	// MongoProxyAddr is the host:port the Mongo proxy can be accessed at.
	MongoProxyAddr string

	// MySQLProxyAddr is the host:port the MySQL proxy can be accessed at.
	MySQLProxyAddr string

	// KeyTTL is a time to live for the temporary SSH keypair to remain valid:
	KeyTTL time.Duration

	// InsecureSkipVerify is an option to skip HTTPS cert check
	InsecureSkipVerify bool

	// SkipLocalAuth tells the client to use AuthMethods parameter for authentication and NOT
	// use its own SSH agent or ask user for passwords. This is used by external programs linking
	// against Teleport client and obtaining credentials from elsewhere.
	SkipLocalAuth bool

	// UseKeyPrincipals forces the use of the username from the key principals rather than using
	// the current user username.
	UseKeyPrincipals bool

	// Agent is used when SkipLocalAuth is true
	Agent agent.ExtendedAgent

	// PreloadKey is a key with which to initialize a local in-memory keystore.
	PreloadKey *Key

	// ForwardAgent is used by the client to request agent forwarding from the server.
	ForwardAgent AgentForwardingMode

	// EnableX11Forwarding specifies whether X11 forwarding should be enabled.
	EnableX11Forwarding bool

	// X11ForwardingTimeout can be set to set a X11 forwarding timeout in seconds,
	// after which any X11 forwarding requests in that session will be rejected.
	X11ForwardingTimeout time.Duration

	// X11ForwardingTrusted specifies the X11 forwarding security mode.
	X11ForwardingTrusted bool

	// AuthMethods are used to login into the cluster. If specified, the client will
	// use them in addition to certs stored in its local agent (from disk)
	AuthMethods []ssh.AuthMethod

	// TLSConfig is TLS configuration, if specified, the client
	// will use this TLS configuration to access API endpoints
	TLS *tls.Config

	// DefaultPrincipal determines the default SSH username (principal) the client should be using
	// when connecting to auth/proxy servers. Usually it's returned with a certificate,
	// but this variables provides a default (used by the web-based terminal client)
	DefaultPrincipal string

	Stdout io.Writer
	Stderr io.Writer
	Stdin  io.Reader

	// ExitStatus carries the returned value (exit status) of the remote
	// process execution (via SSH exec)
	ExitStatus int

	// SiteName specifies site to execute operation,
	// if omitted, first available site will be selected
	SiteName string

	// KubernetesCluster specifies the kubernetes cluster for any relevant
	// operations. If empty, the auth server will choose one using stable (same
	// cluster every time) but unspecified logic.
	KubernetesCluster string

	// DatabaseService specifies name of the database proxy server to issue
	// certificate for.
	DatabaseService string

	// LocalForwardPorts are the local ports tsh listens on for port forwarding
	// (parameters to -L ssh flag).
	LocalForwardPorts ForwardedPorts

	// DynamicForwardedPorts are the list of ports tsh listens on for dynamic
	// port forwarding (parameters to -D ssh flag).
	DynamicForwardedPorts DynamicForwardedPorts

	// HostKeyCallback will be called to check host keys of the remote
	// node, if not specified will be using CheckHostSignature function
	// that uses local cache to validate hosts
	HostKeyCallback ssh.HostKeyCallback

	// KeyDir defines where temporary session keys will be stored.
	// if empty, they'll go to ~/.tsh
	KeysDir string

	// Env is a map of environmnent variables to send when opening session
	Env map[string]string

	// Interactive, when set to true, tells tsh to launch a remote command
	// in interactive mode, i.e. attaching the temrinal to it
	Interactive bool

	// ClientAddr (if set) specifies the true client IP. Usually it's not needed (since the server
	// can look at the connecting address to determine client's IP) but for cases when the
	// client is web-based, this must be set to HTTP's remote addr
	ClientAddr string

	// CachePolicy defines local caching policy in case if discovery goes down
	// by default does not use caching
	CachePolicy *CachePolicy

	// CertificateFormat is the format of the SSH certificate.
	CertificateFormat string

	// AuthConnector is the name of the authentication connector to use.
	AuthConnector string

	// AuthenticatorAttachment is the desired authenticator attachment.
	AuthenticatorAttachment wancli.AuthenticatorAttachment

	// PreferOTP prefers OTP in favor of other MFA methods.
	// Useful in constrained environments without access to USB or platform
	// authenticators, such as remote hosts or virtual machines.
	PreferOTP bool

	// CheckVersions will check that client version is compatible
	// with auth server version when connecting.
	CheckVersions bool

	// BindAddr is an optional host:port to bind to for SSO redirect flows.
	BindAddr string

	// NoRemoteExec will not execute a remote command after connecting to a host,
	// will block instead. Useful when port forwarding. Equivalent of -N for OpenSSH.
	NoRemoteExec bool

	// Browser can be used to pass the name of a browser to override the system default
	// (not currently implemented), or set to 'none' to suppress browser opening entirely.
	Browser string

	// AddKeysToAgent specifies how the client handles keys.
	//	auto - will attempt to add keys to agent if the agent supports it
	//	only - attempt to load keys into agent but don't write them to disk
	//	on - attempt to load keys into agent
	//	off - do not attempt to load keys into agent
	AddKeysToAgent string

	// EnableEscapeSequences will scan Stdin for SSH escape sequences during
	// command/shell execution. This also requires Stdin to be an interactive
	// terminal.
	EnableEscapeSequences bool

	// MockSSOLogin is used in tests for mocking the SSO login response.
	MockSSOLogin SSOLoginFunc

	// HomePath is where tsh stores profiles
	HomePath string

	// TLSRoutingEnabled indicates that proxy supports ALPN SNI server where
	// all proxy services are exposed on a single TLS listener (Proxy Web Listener).
	TLSRoutingEnabled bool

	// Reason is a reason attached to started sessions meant to describe their intent.
	Reason string

	// Invited is a list of people invited to a session.
	Invited []string

	// DisplayParticipantRequirements is set if debug information about participants requirements
	// should be printed in moderated sessions.
	DisplayParticipantRequirements bool

	// ExtraProxyHeaders is a collection of http headers to be included in requests to the WebProxy.
	ExtraProxyHeaders map[string]string

	// AllowStdinHijack allows stdin hijack during MFA prompts.
	// Stdin hijack provides a better login UX, but it can be difficult to reason
	// about and is often a source of bugs.
	// Do not set this options unless you deeply understand what you are doing.
	AllowStdinHijack bool

	// Tracer is the tracer to create spans with
	Tracer oteltrace.Tracer

	// PrivateKeyPolicy is a key policy that this client will try to follow during login.
	PrivateKeyPolicy keys.PrivateKeyPolicy

	// LoadAllCAs indicates that tsh should load the CAs of all clusters
	// instead of just the current cluster.
	LoadAllCAs bool
}

Config is a client config

func MakeDefaultConfig

func MakeDefaultConfig() *Config

MakeDefaultConfig returns default client config

func (*Config) DatabaseProxyHostPort

func (c *Config) DatabaseProxyHostPort(db tlsca.RouteToDatabase) (string, int)

DatabaseProxyHostPort returns proxy connection endpoint for the database.

func (*Config) DefaultResourceFilter

func (c *Config) DefaultResourceFilter() *proto.ListResourcesRequest

DefaultResourceFilter returns the default list resource request.

func (*Config) KubeClusterAddr

func (c *Config) KubeClusterAddr() string

KubeClusterAddr returns a public HTTPS address of the proxy for use by Kubernetes client.

func (*Config) KubeProxyHostPort

func (c *Config) KubeProxyHostPort() (string, int)

KubeProxyHostPort returns the host and port of the Kubernetes proxy.

func (*Config) LoadProfile

func (c *Config) LoadProfile(profileDir string, proxyName string) error

LoadProfile populates Config with the values stored in the given profiles directory. If profileDir is an empty string, the default profile directory ~/.tsh is used.

func (*Config) MongoProxyHostPort

func (c *Config) MongoProxyHostPort() (string, int)

MongoProxyHostPort returns the host and port of Mongo proxy.

func (*Config) MySQLProxyHostPort

func (c *Config) MySQLProxyHostPort() (string, int)

MySQLProxyHostPort returns the host and port of MySQL proxy.

func (*Config) ParseProxyHost

func (c *Config) ParseProxyHost(proxyHost string) error

ParseProxyHost parses the proxyHost string and updates the config.

Format of proxyHost string:

proxy_web_addr:<proxy_web_port>,<proxy_ssh_port>

func (*Config) PostgresProxyHostPort

func (c *Config) PostgresProxyHostPort() (string, int)

PostgresProxyHostPort returns the host and port of Postgres proxy.

func (*Config) ProxySpecified

func (c *Config) ProxySpecified() bool

ProxySpecified returns true if proxy has been specified.

func (*Config) SSHProxyHostPort

func (c *Config) SSHProxyHostPort() (string, int)

SSHProxyHostPort returns the host and port of the SSH proxy.

func (*Config) SaveProfile

func (c *Config) SaveProfile(dir string, makeCurrent bool) error

SaveProfile updates the given profiles directory with the current configuration If profileDir is an empty string, the default ~/.tsh is used

func (*Config) WebProxyHost

func (c *Config) WebProxyHost() string

WebProxyHost returns the web proxy host without the port number.

func (*Config) WebProxyHostPort

func (c *Config) WebProxyHostPort() (string, int)

WebProxyHostPort returns the host and port of the web proxy.

func (*Config) WebProxyPort

func (c *Config) WebProxyPort() int

WebProxyPort returns the port of the web proxy.

type CreateSSHCertReq

type CreateSSHCertReq struct {
	// User is a teleport username
	User string `json:"user"`
	// Password is user's pass
	Password string `json:"password"`
	// OTPToken is second factor token
	OTPToken string `json:"otp_token"`
	// PubKey is a public key user wishes to sign
	PubKey []byte `json:"pub_key"`
	// TTL is a desired TTL for the cert (max is still capped by server,
	// however user can shorten the time)
	TTL time.Duration `json:"ttl"`
	// Compatibility specifies OpenSSH compatibility flags.
	Compatibility string `json:"compatibility,omitempty"`
	// RouteToCluster is an optional cluster name to route the response
	// credentials to.
	RouteToCluster string
	// KubernetesCluster is an optional k8s cluster name to route the response
	// credentials to.
	KubernetesCluster string
	// AttestationStatement is an attestation statement associated with the given public key.
	AttestationStatement *keys.AttestationStatement `json:"attestation_statement,omitempty"`
}

CreateSSHCertReq are passed by web client to authenticate against teleport server and receive a temporary cert signed by auth server authority

type DBCertChecker

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

DBCertChecker is a middleware that ensures that the local proxy has valid TLS database certs.

func (*DBCertChecker) OnNewConnection

func (c *DBCertChecker) OnNewConnection(ctx context.Context, lp *alpnproxy.LocalProxy, conn net.Conn) error

OnNewConnection is a callback triggered when a new downstream connection is accepted by the local proxy.

func (*DBCertChecker) OnStart

func (c *DBCertChecker) OnStart(ctx context.Context, lp *alpnproxy.LocalProxy) error

OnStart is a callback triggered when the local proxy starts.

type DynamicForwardedPort

type DynamicForwardedPort struct {
	// SrcIP is the IP address to listen on locally.
	SrcIP string

	// SrcPort is the port to listen on locally.
	SrcPort int
}

DynamicForwardedPort local port for dynamic application-level port forwarding. Whenever a connection is made to this port, SOCKS5 protocol is used to determine the address of the remote host. More or less equivalent to OpenSSH's -D flag.

func (*DynamicForwardedPort) ToString

func (p *DynamicForwardedPort) ToString() string

ToString returns a string representation of a dynamic port spec, compatible with OpenSSH's -D flag, i.e. "src_host:src_port".

type DynamicForwardedPorts

type DynamicForwardedPorts []DynamicForwardedPort

DynamicForwardedPorts is a slice of locally forwarded dynamic ports (SOCKS5).

func ParseDynamicPortForwardSpec

func ParseDynamicPortForwardSpec(spec []string) (DynamicForwardedPorts, error)

ParseDynamicPortForwardSpec parses the dynamic port forwarding spec passed in the -D flag. The format of the dynamic port forwarding spec is [bind_address:]port.

func (DynamicForwardedPorts) String

func (fp DynamicForwardedPorts) String() (retval []string)

String returns the same string spec which can be parsed by ParseDynamicPortForwardSpec.

type FSLocalKeyStore

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

FSLocalKeyStore implements LocalKeyStore interface using the filesystem.

The FS store uses the file layout outlined in `api/utils/keypaths.go`.

func NewFSLocalKeyStore

func NewFSLocalKeyStore(dirPath string) (s *FSLocalKeyStore, err error)

NewFSLocalKeyStore creates a new filesystem-based local keystore object and initializes it.

If dirPath is empty, sets it to ~/.tsh.

func (*FSLocalKeyStore) AddKey

func (fs *FSLocalKeyStore) AddKey(key *Key) error

AddKey adds the given key to the store.

func (*FSLocalKeyStore) AddKnownHostKeys

func (fs *FSLocalKeyStore) AddKnownHostKeys(hostname, proxyHost string, hostKeys []ssh.PublicKey) (retErr error)

AddKnownHostKeys adds a new entry to `known_hosts` file.

func (*FSLocalKeyStore) DeleteKey

func (fs *FSLocalKeyStore) DeleteKey(idx KeyIndex) error

DeleteKey deletes the user's key with all its certs.

func (*FSLocalKeyStore) DeleteKeys

func (fs *FSLocalKeyStore) DeleteKeys() error

DeleteKeys removes all session keys.

func (*FSLocalKeyStore) DeleteUserCerts

func (fs *FSLocalKeyStore) DeleteUserCerts(idx KeyIndex, opts ...CertOption) error

DeleteUserCerts deletes only the specified certs of the user's key, keeping the private key intact. Empty clusterName indicates to delete the certs for all clusters.

Useful when needing to log out of a specific service, like a particular database proxy.

func (*FSLocalKeyStore) GetKey

func (fs *FSLocalKeyStore) GetKey(idx KeyIndex, opts ...CertOption) (*Key, error)

GetKey returns the user's key including the specified certs. If the key is not found, returns trace.NotFound error.

func (*FSLocalKeyStore) GetKnownHostKeys

func (fs *FSLocalKeyStore) GetKnownHostKeys(hostname string) (keys []ssh.PublicKey, retErr error)

GetKnownHostKeys returns all known public keys from `known_hosts`.

func (*FSLocalKeyStore) GetSSHCertificates

func (fs *FSLocalKeyStore) GetSSHCertificates(proxyHost, username string) ([]*ssh.Certificate, error)

GetSSHCertificates gets all certificates signed for the given user and proxy.

func (*FSLocalKeyStore) GetTrustedCertsPEM

func (fs *FSLocalKeyStore) GetTrustedCertsPEM(proxyHost string) ([][]byte, error)

GetTrustedCertsPEM returns trusted TLS certificates of certificate authorities PEM blocks.

func (*FSLocalKeyStore) SaveTrustedCerts

func (fs *FSLocalKeyStore) SaveTrustedCerts(proxyHost string, cas []auth.TrustedCerts) (retErr error)

SaveTrustedCerts saves trusted TLS certificates of certificate authorities.

type ForwardedPort

type ForwardedPort struct {
	SrcIP    string
	SrcPort  int
	DestPort int
	DestHost string
}

ForwardedPort specifies local tunnel to remote destination managed by the client, is equivalent of ssh -L src:host:dst command

func (*ForwardedPort) ToString

func (p *ForwardedPort) ToString() string

ToString returns a string representation of a forwarded port spec, compatible with OpenSSH's -L flag, i.e. "src_host:src_port:dest_host:dest_port".

type ForwardedPorts

type ForwardedPorts []ForwardedPort

ForwardedPorts contains an array of forwarded port structs

func ParsePortForwardSpec

func ParsePortForwardSpec(spec []string) (ports ForwardedPorts, err error)

ParsePortForwardSpec parses parameter to -L flag, i.e. strings like "[ip]:80:remote.host:3000" The opposite of this function (spec generation) is ForwardedPorts.String()

func (ForwardedPorts) String

func (fp ForwardedPorts) String() (retval []string)

String returns the same string spec which can be parsed by ParsePortForwardSpec.

type HostKeyCallback

type HostKeyCallback func(host string, ip net.Addr, key ssh.PublicKey) error

HostKeyCallback is called by SSH client when it needs to check remote host key or certificate validity

type Key

type Key struct {
	KeyIndex

	// PrivateKey is a private key used for cryptographical operations.
	*keys.PrivateKey

	// Cert is an SSH client certificate
	Cert []byte `json:"Cert,omitempty"`
	// TLSCert is a PEM encoded client TLS x509 certificate.
	// It's used to authenticate to the Teleport APIs.
	TLSCert []byte `json:"TLSCert,omitempty"`
	// KubeTLSCerts are TLS certificates (PEM-encoded) for individual
	// kubernetes clusters. Map key is a kubernetes cluster name.
	KubeTLSCerts map[string][]byte `json:"KubeCerts,omitempty"`
	// DBTLSCerts are PEM-encoded TLS certificates for database access.
	// Map key is the database service name.
	DBTLSCerts map[string][]byte `json:"DBCerts,omitempty"`
	// AppTLSCerts are TLS certificates for application access.
	// Map key is the application name.
	AppTLSCerts map[string][]byte `json:"AppCerts,omitempty"`
	// WindowsDesktopCerts are TLS certificates for Windows Desktop access.
	// Map key is the desktop server name.
	WindowsDesktopCerts map[string][]byte `json:"WindowsDesktopCerts,omitempty"`
	// TrustedCA is a list of trusted certificate authorities
	TrustedCA []auth.TrustedCerts
}

Key describes a complete (signed) client key

func GenerateRSAKey

func GenerateRSAKey() (*Key, error)

GenerateRSAKey generates a new unsigned key.

func KeyFromIdentityFile

func KeyFromIdentityFile(path string) (*Key, error)

KeyFromIdentityFile loads the private key + certificate from an identity file into a Key.

func NewKey

func NewKey(priv *keys.PrivateKey) *Key

NewKey creates a new Key for the given private key.

func (*Key) ActiveRequests

func (k *Key) ActiveRequests() (services.RequestIDs, error)

ActiveRequests gets the active requests associated with this key.

func (*Key) AppTLSCertificates

func (k *Key) AppTLSCertificates() (certs []x509.Certificate, err error)

AppTLSCertificates returns all parsed x509 app access certificates.

func (*Key) AsAgentKey

func (k *Key) AsAgentKey() (agent.AddedKey, error)

AsAgentKeys converts client.Key struct to a []*agent.AddedKey. All elements of the []*agent.AddedKey slice need to be loaded into the agent!

func (*Key) AsAuthMethod

func (k *Key) AsAuthMethod() (ssh.AuthMethod, error)

AsAuthMethod returns an "auth method" interface, a common abstraction used by Golang SSH library. This is how you actually use a Key to feed it into the SSH lib.

func (*Key) CertPrincipals

func (k *Key) CertPrincipals() ([]string, error)

CertPrincipals returns the principals listed on the SSH certificate.

func (*Key) CertRoles

func (k *Key) CertRoles() ([]string, error)

func (*Key) CertUsername

func (k *Key) CertUsername() (string, error)

CertUsername returns the name of the Teleport user encoded in the SSH certificate.

func (*Key) CertValidBefore

func (k *Key) CertValidBefore() (t time.Time, err error)

CertValidBefore returns the time of the cert expiration

func (*Key) CheckCert

func (k *Key) CheckCert() error

CheckCert makes sure the key's SSH certificate is valid.

func (*Key) DBTLSCertificates

func (k *Key) DBTLSCertificates() (certs []x509.Certificate, err error)

DBTLSCertificates returns all parsed x509 database access certificates.

func (*Key) EqualPrivateKey

func (k *Key) EqualPrivateKey(other *Key) bool

EqualPrivateKey returns whether this key and the given key have the same PrivateKey.

func (*Key) GetClusterNames

func (k *Key) GetClusterNames() ([]string, error)

GetClusterNames gets the names of clusters this key has CAs for.

func (*Key) HostKeyCallback

func (k *Key) HostKeyCallback(withHostKeyFallback bool) (ssh.HostKeyCallback, error)

HostKeyCallback returns an ssh.HostKeyCallback that validates host keys/certs against SSH CAs in the Key.

If not CAs are present in the Key, the returned ssh.HostKeyCallback is nil. This causes golang.org/x/crypto/ssh to prompt the user to verify host key fingerprint (same as OpenSSH does for an unknown host).

func (*Key) HostKeyCallbackForClusters

func (k *Key) HostKeyCallbackForClusters(withHostKeyFallback bool, clusters []string) (ssh.HostKeyCallback, error)

HostKeyCallbackForClusters returns an ssh.HostKeyCallback that validates host keys/certs against SSH clusters CAs.

If not CAs are present in the Key, the returned ssh.HostKeyCallback is nil. This causes golang.org/x/crypto/ssh to prompt the user to verify host key fingerprint (same as OpenSSH does for an unknown host).

func (*Key) KubeClientTLSConfig

func (k *Key) KubeClientTLSConfig(cipherSuites []uint16, kubeClusterName string) (*tls.Config, error)

func (*Key) KubeTLSCertificate

func (k *Key) KubeTLSCertificate(kubeClusterName string) (*x509.Certificate, error)

KubeTLSCertificate returns the parsed x509 certificate for authentication against a named kubernetes cluster.

func (*Key) ProxyClientSSHConfig

func (k *Key) ProxyClientSSHConfig(keyStore sshKnowHostGetter, host string) (*ssh.ClientConfig, error)

ProxyClientSSHConfig returns an ssh.ClientConfig with SSH credentials from this Key and HostKeyCallback matching SSH CAs in the Key.

The config is set up to authenticate to proxy with the first available principal and ( if keyStore != nil ) trust local SSH CAs without asking for public keys.

func (*Key) RootClusterCAs

func (k *Key) RootClusterCAs() ([][]byte, error)

RootClusterCAs returns root cluster CAs.

func (*Key) RootClusterName

func (k *Key) RootClusterName() (string, error)

RootClusterName extracts the root cluster name from the issuer of the Teleport TLS certificate.

func (*Key) SSHCAs

func (k *Key) SSHCAs() (result [][]byte)

SSHCAs returns all SSH CA certificates from this key

func (*Key) SSHCAsForClusters

func (k *Key) SSHCAsForClusters(clusters []string) (result [][]byte, err error)

SSHCAsForClusters returns SSH CA for particular clusters.

func (*Key) SSHCert

func (k *Key) SSHCert() (*ssh.Certificate, error)

SSHCert returns parsed SSH certificate

func (*Key) SSHSigner

func (k *Key) SSHSigner() (ssh.Signer, error)

SSHSigner returns an ssh.Signer using the SSH certificate in this key.

func (*Key) TLSCAs

func (k *Key) TLSCAs() (result [][]byte)

TLSCAs returns all TLS CA certificates from this key

func (*Key) TeleportClientTLSConfig

func (k *Key) TeleportClientTLSConfig(cipherSuites []uint16, clusters []string) (*tls.Config, error)

TeleportClientTLSConfig returns client TLS configuration used to authenticate against API servers.

func (*Key) TeleportTLSCertValidBefore

func (k *Key) TeleportTLSCertValidBefore() (t time.Time, err error)

TeleportTLSCertValidBefore returns the time of the TLS cert expiration

func (*Key) TeleportTLSCertificate

func (k *Key) TeleportTLSCertificate() (*x509.Certificate, error)

TeleportTLSCertificate returns the parsed x509 certificate for authentication against Teleport APIs.

type KeyIndex

type KeyIndex struct {
	// ProxyHost is the root proxy hostname that a key is associated with.
	ProxyHost string
	// Username is the username that a key is associated with.
	Username string
	// ClusterName is the cluster name that a key is associated with.
	ClusterName string
}

KeyIndex helps to identify a key in the store.

func (KeyIndex) Check

func (idx KeyIndex) Check() error

Check verifies the KeyIndex is fully specified.

type KubeSession

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

KubeSession a joined kubernetes session from the client side.

func NewKubeSession

func NewKubeSession(ctx context.Context, tc *TeleportClient, meta types.SessionTracker, kubeAddr string, tlsServer string, mode types.SessionParticipantMode, tlsConfig *tls.Config) (*KubeSession, error)

NewKubeSession joins a live kubernetes session.

func (*KubeSession) Close

func (s *KubeSession) Close() error

Close sends a close request to the other end and waits it to gracefully terminate the connection.

func (*KubeSession) Detach

func (s *KubeSession) Detach() error

Detach detaches the terminal from the session. Must be called if Close is not called.

func (*KubeSession) Wait

func (s *KubeSession) Wait()

Wait waits for the session to finish.

type LocalAgentConfig

type LocalAgentConfig struct {
	Keystore   LocalKeyStore
	Agent      agent.ExtendedAgent
	ProxyHost  string
	Username   string
	KeysOption string
	Insecure   bool
	Site       string
	LoadAllCAs bool
}

LocalAgentConfig contains parameters for creating the local keys agent.

type LocalKeyAgent

type LocalKeyAgent struct {

	// ExtendedAgent is the teleport agent
	agent.ExtendedAgent
	// contains filtered or unexported fields
}

LocalKeyAgent holds Teleport certificates for a user connected to a cluster.

func NewLocalAgent

func NewLocalAgent(conf LocalAgentConfig) (a *LocalKeyAgent, err error)

NewLocalAgent reads all available credentials from the provided LocalKeyStore and loads them into the local and system agent

func (*LocalKeyAgent) AddDatabaseKey

func (a *LocalKeyAgent) AddDatabaseKey(key *Key) error

AddDatabaseKey activates a new signed database key by adding it into the keystore. key must contain at least one db cert. ssh cert is not required.

func (*LocalKeyAgent) AddHostSignersToCache

func (a *LocalKeyAgent) AddHostSignersToCache(certAuthorities []auth.TrustedCerts) error

AddHostSignersToCache takes a list of CAs whom we trust. This list is added to a database of "seen" CAs.

Every time we connect to a new host, we'll request its certificate to be signed by one of these trusted CAs.

Why do we trust these CAs? Because we received them from a trusted Teleport Proxy. Why do we trust the proxy? Because we've connected to it via HTTPS + username + Password + OTP.

func (*LocalKeyAgent) AddKey

func (a *LocalKeyAgent) AddKey(key *Key) error

AddKey activates a new signed session key by adding it into the keystore and also by loading it into the SSH agent.

func (*LocalKeyAgent) CheckHostSignature

func (a *LocalKeyAgent) CheckHostSignature(addr string, remote net.Addr, hostKey ssh.PublicKey) error

CheckHostSignature checks if the given host key was signed by a Teleport certificate authority (CA) or a host certificate the user has seen before.

func (*LocalKeyAgent) ClientCertPool

func (a *LocalKeyAgent) ClientCertPool(cluster string) (*x509.CertPool, error)

ClientCertPool returns x509.CertPool containing trusted CA.

func (*LocalKeyAgent) DeleteKey

func (a *LocalKeyAgent) DeleteKey() error

DeleteKey removes the key with all its certs from the key store and unloads the key from the agent.

func (*LocalKeyAgent) DeleteKeys

func (a *LocalKeyAgent) DeleteKeys() error

DeleteKeys removes all keys from the keystore as well as unloads keys from the agent.

func (*LocalKeyAgent) DeleteUserCerts

func (a *LocalKeyAgent) DeleteUserCerts(clusterName string, opts ...CertOption) error

DeleteUserCerts deletes only the specified certs of the user's key, keeping the private key intact.

func (*LocalKeyAgent) GetClusterNames

func (a *LocalKeyAgent) GetClusterNames() ([]string, error)

GetClusterNames gets the names of the Teleport clusters this key agent knows about.

func (*LocalKeyAgent) GetCoreKey

func (a *LocalKeyAgent) GetCoreKey() (*Key, error)

GetCoreKey returns the key without any cluster-dependent certificates, i.e. including only the private key and the Teleport TLS certificate.

func (*LocalKeyAgent) GetKey

func (a *LocalKeyAgent) GetKey(clusterName string, opts ...CertOption) (*Key, error)

GetKey returns the key for the given cluster of the proxy from the backing keystore.

func (*LocalKeyAgent) GetTrustedCertsPEM

func (a *LocalKeyAgent) GetTrustedCertsPEM() ([][]byte, error)

GetTrustedCertsPEM returns trusted TLS certificates of certificate authorities PEM blocks.

func (*LocalKeyAgent) LoadKey

func (a *LocalKeyAgent) LoadKey(key Key) error

LoadKey adds a key into the Teleport ssh agent as well as the system ssh agent.

func (*LocalKeyAgent) LoadKeyForCluster

func (a *LocalKeyAgent) LoadKeyForCluster(clusterName string) error

LoadKeyForCluster fetches a cluster-specific SSH key and loads it into the SSH agent.

func (*LocalKeyAgent) SaveTrustedCerts

func (a *LocalKeyAgent) SaveTrustedCerts(certAuthorities []auth.TrustedCerts) error

SaveTrustedCerts saves trusted TLS certificates of certificate authorities.

func (*LocalKeyAgent) Signers

func (a *LocalKeyAgent) Signers() ([]ssh.Signer, error)

Signers returns a set of ssh.Signers using all certificates for the current proxy and user.

func (*LocalKeyAgent) UnloadKey

func (a *LocalKeyAgent) UnloadKey() error

UnloadKey will unload key for user from the teleport ssh agent as well as the system agent.

func (*LocalKeyAgent) UnloadKeys

func (a *LocalKeyAgent) UnloadKeys() error

UnloadKeys will unload all Teleport keys from the teleport agent as well as the system agent.

func (*LocalKeyAgent) UpdateCluster

func (a *LocalKeyAgent) UpdateCluster(cluster string)

UpdateCluster changes the cluster that the local agent operates on.

func (*LocalKeyAgent) UpdateLoadAllCAs

func (a *LocalKeyAgent) UpdateLoadAllCAs(loadAllCAs bool)

UpdateLoadAllCAs changes whether or not the local agent should load all host CAs.

func (*LocalKeyAgent) UpdateProxyHost

func (a *LocalKeyAgent) UpdateProxyHost(proxyHost string)

UpdateProxyHost changes the proxy host that the local agent operates on.

func (*LocalKeyAgent) UpdateUsername

func (a *LocalKeyAgent) UpdateUsername(username string)

UpdateUsername changes username that the local agent operates on.

func (*LocalKeyAgent) UserRefusedHosts

func (a *LocalKeyAgent) UserRefusedHosts() bool

UserRefusedHosts returns 'true' if a user refuses connecting to remote hosts when prompted during host authorization

type LocalKeyStore

type LocalKeyStore interface {
	// AddKey adds the given key to the store.
	AddKey(key *Key) error

	// GetKey returns the user's key including the specified certs.
	GetKey(idx KeyIndex, opts ...CertOption) (*Key, error)

	// DeleteKey deletes the user's key with all its certs.
	DeleteKey(idx KeyIndex) error

	// DeleteUserCerts deletes only the specified certs of the user's key,
	// keeping the private key intact.
	DeleteUserCerts(idx KeyIndex, opts ...CertOption) error

	// DeleteKeys removes all session keys.
	DeleteKeys() error

	// AddKnownHostKeys adds the public key to the list of known hosts for
	// a hostname.
	AddKnownHostKeys(hostname, proxyHost string, keys []ssh.PublicKey) error

	// GetKnownHostKeys returns all public keys for a hostname.
	GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error)

	// SaveTrustedCerts saves trusted TLS certificates of certificate authorities.
	SaveTrustedCerts(proxyHost string, cas []auth.TrustedCerts) error

	// GetTrustedCertsPEM gets trusted TLS certificates of certificate authorities.
	// Each returned byte slice contains an individual PEM block.
	GetTrustedCertsPEM(proxyHost string) ([][]byte, error)

	// GetSSHCertificates gets all certificates signed for the given user and proxy,
	// including certificates for trusted clusters.
	GetSSHCertificates(proxyHost, username string) ([]*ssh.Certificate, error)
}

LocalKeyStore interface allows for different storage backends for tsh to load/save its keys.

The _only_ filesystem-based implementation of LocalKeyStore is declared below (FSLocalKeyStore)

type MFAAuthenticateChallenge

type MFAAuthenticateChallenge struct {
	// WebauthnChallenge contains a WebAuthn credential assertion used for
	// login/authentication ceremonies.
	WebauthnChallenge *wanlib.CredentialAssertion `json:"webauthn_challenge"`
	// TOTPChallenge specifies whether TOTP is supported for this user.
	TOTPChallenge bool `json:"totp_challenge"`
}

MFAAuthenticateChallenge is an MFA authentication challenge sent on user login / authentication ceremonies.

func MakeAuthenticateChallenge

func MakeAuthenticateChallenge(protoChal *proto.MFAAuthenticateChallenge) *MFAAuthenticateChallenge

MakeAuthenticateChallenge converts proto to JSON format.

type MFAChallengeRequest

type MFAChallengeRequest struct {
	User string `json:"user"`
	Pass string `json:"pass"`
	// Passwordless explicitly requests a passwordless/usernameless challenge.
	Passwordless bool `json:"passwordless"`
}

MFAChallengeRequest is a request from the client for a MFA challenge from the server.

type MFARegisterChallenge

type MFARegisterChallenge struct {
	// Webauthn contains webauthn challenge.
	Webauthn *wanlib.CredentialCreation `json:"webauthn"`
	// TOTP contains TOTP challenge.
	TOTP *TOTPRegisterChallenge `json:"totp"`
}

MFARegisterChallenge is an MFA register challenge sent on new MFA register.

func MakeRegisterChallenge

func MakeRegisterChallenge(protoChal *proto.MFARegisterChallenge) *MFARegisterChallenge

MakeRegisterChallenge converts proto to JSON format.

type MemLocalKeyStore

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

MemLocalKeyStore is an in-memory session keystore implementation.

func NewMemLocalKeyStore

func NewMemLocalKeyStore(dirPath string) (*MemLocalKeyStore, error)

NewMemLocalKeyStore initializes a MemLocalKeyStore. The key directory here is only used for storing CA certificates and known host fingerprints.

func (*MemLocalKeyStore) AddKey

func (s *MemLocalKeyStore) AddKey(key *Key) error

AddKey writes a key to the underlying key store.

func (*MemLocalKeyStore) AddKnownHostKeys

func (fs *MemLocalKeyStore) AddKnownHostKeys(hostname, proxyHost string, hostKeys []ssh.PublicKey) (retErr error)

AddKnownHostKeys adds a new entry to `known_hosts` file.

func (*MemLocalKeyStore) DeleteKey

func (s *MemLocalKeyStore) DeleteKey(idx KeyIndex) error

DeleteKey deletes the user's key with all its certs.

func (*MemLocalKeyStore) DeleteKeys

func (s *MemLocalKeyStore) DeleteKeys() error

DeleteKeys removes all session keys.

func (*MemLocalKeyStore) DeleteUserCerts

func (s *MemLocalKeyStore) DeleteUserCerts(idx KeyIndex, opts ...CertOption) error

DeleteUserCerts deletes only the specified certs of the user's key, keeping the private key intact. Empty clusterName indicates to delete the certs for all clusters.

Useful when needing to log out of a specific service, like a particular database proxy.

func (*MemLocalKeyStore) GetKey

func (s *MemLocalKeyStore) GetKey(idx KeyIndex, opts ...CertOption) (*Key, error)

GetKey returns the user's key including the specified certs.

func (*MemLocalKeyStore) GetKnownHostKeys

func (fs *MemLocalKeyStore) GetKnownHostKeys(hostname string) (keys []ssh.PublicKey, retErr error)

GetKnownHostKeys returns all known public keys from `known_hosts`.

func (*MemLocalKeyStore) GetSSHCertificates

func (s *MemLocalKeyStore) GetSSHCertificates(proxyHost, username string) ([]*ssh.Certificate, error)

GetSSHCertificates gets all certificates signed for the given user and proxy.

func (*MemLocalKeyStore) GetTrustedCertsPEM

func (fs *MemLocalKeyStore) GetTrustedCertsPEM(proxyHost string) ([][]byte, error)

GetTrustedCertsPEM returns trusted TLS certificates of certificate authorities PEM blocks.

func (*MemLocalKeyStore) SaveTrustedCerts

func (fs *MemLocalKeyStore) SaveTrustedCerts(proxyHost string, cas []auth.TrustedCerts) (retErr error)

SaveTrustedCerts saves trusted TLS certificates of certificate authorities.

type NodeClient

type NodeClient struct {
	Namespace   string
	Tracer      oteltrace.Tracer
	Client      *tracessh.Client
	TC          *TeleportClient
	OnMFA       func()
	FIPSEnabled bool
}

NodeClient implements ssh client to a ssh node (teleport or any regular ssh node) NodeClient can run shell and commands or upload and download files.

func NewNodeClient

func NewNodeClient(ctx context.Context, sshConfig *ssh.ClientConfig, conn net.Conn, nodeAddress string, tc *TeleportClient, fipsEnabled bool) (*NodeClient, error)

NewNodeClient constructs a NodeClient that is connected to the node at nodeAddress

func (*NodeClient) Close

func (c *NodeClient) Close() error

Close closes client and it's operations

func (*NodeClient) ExecuteSCP

func (c *NodeClient) ExecuteSCP(ctx context.Context, cmd scp.Command) error

ExecuteSCP runs remote scp command(shellCmd) on the remote server and runs local scp handler using SCP Command

func (*NodeClient) GetRemoteTerminalSize

func (c *NodeClient) GetRemoteTerminalSize(ctx context.Context, sessionID string) (*term.Winsize, error)

GetRemoteTerminalSize fetches the terminal size of a given SSH session.

func (*NodeClient) RunInteractiveShell

func (c *NodeClient) RunInteractiveShell(ctx context.Context, mode types.SessionParticipantMode, sessToJoin types.SessionTracker) error

RunInteractiveShell creates an interactive shell on the node and copies stdin/stdout/stderr to and from the node and local shell. This will block until the interactive shell on the node is terminated.

func (*NodeClient) TransferFiles

func (c *NodeClient) TransferFiles(ctx context.Context, cfg *sftp.Config) error

TransferFiles transfers files over SFTP.

type NodeDetails

type NodeDetails struct {
	// Addr is an address to dial
	Addr string
	// Namespace is the node namespace
	Namespace string
	// Cluster is the name of the target cluster
	Cluster string

	// MFACheck is optional parameter passed if MFA check was already done.
	// It can be nil.
	MFACheck *proto.IsMFARequiredResponse
}

NodeDetails provides connection information for a node

func (*NodeDetails) ProxyFormat

func (n *NodeDetails) ProxyFormat() string

ProxyFormat returns the address in the format used by the proxy subsystem

func (NodeDetails) String

func (n NodeDetails) String() string

String returns a user-friendly name

type NodeSession

type NodeSession struct {
	ExitMsg string
	// contains filtered or unexported fields
}

func (*NodeSession) Close

func (ns *NodeSession) Close() error

func (*NodeSession) NodeClient

func (ns *NodeSession) NodeClient() *NodeClient

type ParsedProxyHost

type ParsedProxyHost struct {
	Host string

	// UsingDefaultWebProxyPort means that the port in WebProxyAddr was
	// supplied by ParseProxyHost function rather than ProxyHost string
	// itself.
	UsingDefaultWebProxyPort bool
	WebProxyAddr             string
	SSHProxyAddr             string
}

ParsedProxyHost holds the hostname and Web & SSH proxy addresses parsed out of a WebProxyAddress string.

func ParseProxyHost

func ParseProxyHost(proxyHost string) (*ParsedProxyHost, error)

ParseProxyHost parses a ProxyHost string of the format <hostname>:<proxy_web_port>,<proxy_ssh_port> and returns the parsed components.

There are several "default" ports that the Web Proxy service may use, and if the port is not specified in the supplied proxyHost string

If a definitive answer is not possible (e.g. no proxy port is specified in the supplied string), ParseProxyHost() will supply default versions and flag that a default value is being used in the returned `ParsedProxyHost`

type ProfileOptions

type ProfileOptions struct {
	ProfileName   string
	ProfileDir    string
	WebProxyAddr  string
	Username      string
	SiteName      string
	KubeProxyAddr string
	IsVirtual     bool
}

ProfileOptions contains fields needed to initialize a profile beyond those derived directly from a Key.

type ProfileStatus

type ProfileStatus struct {
	// Name is the profile name.
	Name string

	// Dir is the directory where profile is located.
	Dir string

	// ProxyURL is the URL the web client is accessible at.
	ProxyURL url.URL

	// Username is the Teleport username.
	Username string

	// Roles is a list of Teleport Roles this user has been assigned.
	Roles []string

	// Logins are the Linux accounts, also known as principals in OpenSSH terminology.
	Logins []string

	// KubeEnabled is true when this profile is configured to connect to a
	// kubernetes cluster.
	KubeEnabled bool

	// KubeUsers are the kubernetes users used by this profile.
	KubeUsers []string

	// KubeGroups are the kubernetes groups used by this profile.
	KubeGroups []string

	// Databases is a list of database services this profile is logged into.
	Databases []tlsca.RouteToDatabase

	// Apps is a list of apps this profile is logged into.
	Apps []tlsca.RouteToApp

	// ValidUntil is the time at which this SSH certificate will expire.
	ValidUntil time.Time

	// Extensions is a list of enabled SSH features for the certificate.
	Extensions []string

	// CriticalOptions is a map of SSH critical options for the certificate.
	CriticalOptions map[string]string

	// Cluster is a selected cluster
	Cluster string

	// Traits hold claim data used to populate a role at runtime.
	Traits wrappers.Traits

	// ActiveRequests tracks the privilege escalation requests applied
	// during certificate construction.
	ActiveRequests services.RequestIDs

	// AWSRoleARNs is a list of allowed AWS role ARNs user can assume.
	AWSRolesARNs []string

	// AllowedResourceIDs is a list of resources the user can access. An empty
	// list means there are no resource-specific restrictions.
	AllowedResourceIDs []types.ResourceID

	// IsVirtual is set when this profile does not actually exist on disk,
	// probably because it was constructed from an identity file. When set,
	// certain profile functions - particularly those that return paths to
	// files on disk - must be accompanied by fallback logic when those paths
	// do not exist.
	IsVirtual bool
}

ProfileStatus combines metadata from the logged in profile and associated SSH certificate.

func ReadProfileFromIdentity

func ReadProfileFromIdentity(key *Key, opts ProfileOptions) (*ProfileStatus, error)

ReadProfileFromIdentity creates a "fake" profile from only an identity file, allowing the various profile-using subcommands to use identity files as if they were profiles. It will set the `username` and `siteName` fields of the profileOptions to certificate-provided values if they are unset.

func ReadProfileStatus

func ReadProfileStatus(profileDir string, profileName string) (*ProfileStatus, error)

ReadProfileStatus reads in the profile as well as the associated certificate and returns a *ProfileStatus which can be used to print the status of the profile.

func StatusCurrent

func StatusCurrent(profileDir, proxyHost, identityFilePath string) (*ProfileStatus, error)

StatusCurrent returns the active profile status.

func StatusFor

func StatusFor(profileDir, proxyHost, username string) (*ProfileStatus, error)

StatusFor returns profile for the specified proxy/user.

func (*ProfileStatus) AppCertPath

func (p *ProfileStatus) AppCertPath(name string) string

AppCertPath returns path to the specified app access certificate for this profile.

It's kept in <profile-dir>/keys/<proxy>/<user>-app/<cluster>/<name>-x509.pem

func (*ProfileStatus) AppLocalCAPath

func (p *ProfileStatus) AppLocalCAPath(name string) string

AppLocalCAPath returns the specified app's self-signed localhost CA path for this profile.

It's kept in <profile-dir>/keys/<proxy>/<user>-app/<cluster>/<name>-localca.pem

func (*ProfileStatus) AppNames

func (p *ProfileStatus) AppNames() (result []string)

AppNames returns a list of app names this profile is logged into.

func (*ProfileStatus) CACertPathForCluster

func (p *ProfileStatus) CACertPathForCluster(cluster string) string

CACertPathForCluster returns path to the cluster CA certificate for this profile.

It's stored in <profile-dir>/keys/<proxy>/cas/<cluster>.pem by default.

func (*ProfileStatus) DatabaseCertPathForCluster

func (p *ProfileStatus) DatabaseCertPathForCluster(clusterName string, databaseName string) string

DatabaseCertPathForCluster returns path to the specified database access certificate for this profile, for the specified cluster.

It's kept in <profile-dir>/keys/<proxy>/<user>-db/<cluster>/<name>-x509.pem

If the input cluster name is an empty string, the selected cluster in the profile will be used.

func (*ProfileStatus) DatabaseServices

func (p *ProfileStatus) DatabaseServices() (result []string)

DatabaseServices returns a list of database service names for this profile.

func (*ProfileStatus) DatabasesForCluster

func (p *ProfileStatus) DatabasesForCluster(clusterName string) ([]tlsca.RouteToDatabase, error)

DatabasesForCluster returns a list of databases for this profile, for the specified cluster name.

func (*ProfileStatus) IsExpired

func (p *ProfileStatus) IsExpired(clock clockwork.Clock) bool

IsExpired returns true if profile is not expired yet

func (*ProfileStatus) KeyPath

func (p *ProfileStatus) KeyPath() string

KeyPath returns path to the private key for this profile.

It's kept in <profile-dir>/keys/<proxy>/<user>.

func (*ProfileStatus) KubeConfigPath

func (p *ProfileStatus) KubeConfigPath(name string) string

KubeConfigPath returns path to the specified kubeconfig for this profile.

It's kept in <profile-dir>/keys/<proxy>/<user>-kube/<cluster>/<name>-kubeconfig

type PromptMFAChallengeHandler

type PromptMFAChallengeHandler func(ctx context.Context, proxyAddr string, c *proto.MFAAuthenticateChallenge) (*proto.MFAAuthenticateResponse, error)

PromptMFAChallengeHandler is a handler for MFA challenges.

The challenge c from proxyAddr should be presented to the user, asking to use one of their registered MFA devices. User's response should be returned, or an error if anything goes wrong.

type PromptMFAChallengeOpts

type PromptMFAChallengeOpts struct {
	// HintBeforePrompt is an optional hint message to print before an MFA prompt.
	// It is used to provide context about why the user is being prompted where it may
	// not be obvious.
	HintBeforePrompt string
	// PromptDevicePrefix is an optional prefix printed before "security key" or
	// "device". It is used to emphasize between different kinds of devices, like
	// registered vs new.
	PromptDevicePrefix string
	// Quiet suppresses users prompts.
	Quiet bool
	// AllowStdinHijack allows stdin hijack during MFA prompts.
	// Stdin hijack provides a better login UX, but it can be difficult to reason
	// about and is often a source of bugs.
	// Do not set this options unless you deeply understand what you are doing.
	// If false then only the strongest auth method is prompted.
	AllowStdinHijack bool
	// AuthenticatorAttachment specifies the desired authenticator attachment.
	AuthenticatorAttachment wancli.AuthenticatorAttachment
	// PreferOTP favors OTP challenges, if applicable.
	// Takes precedence over AuthenticatorAttachment settings.
	PreferOTP bool
}

PromptMFAChallengeOpts groups optional settings for PromptMFAChallenge.

type ProxyClient

type ProxyClient struct {
	Client *tracessh.Client
	Tracer oteltrace.Tracer
	// contains filtered or unexported fields
}

ProxyClient implements ssh client to a teleport proxy It can provide list of nodes or connect to nodes

func (*ProxyClient) Close

func (proxy *ProxyClient) Close() error

Close closes the proxy and auth clients

func (*ProxyClient) ClusterName

func (proxy *ProxyClient) ClusterName() string

ClusterName returns the name of the cluster the proxy is a member of.

func (*ProxyClient) ConnectToAuthServiceThroughALPNSNIProxy

func (proxy *ProxyClient) ConnectToAuthServiceThroughALPNSNIProxy(ctx context.Context, clusterName, proxyAddr string) (auth.ClientI, error)

ConnectToAuthServiceThroughALPNSNIProxy uses ALPN proxy service to connect to remote/local auth service and returns auth client. For routing purposes, TLS ServerName is set to destination auth service cluster name with ALPN values set to teleport-auth protocol.

func (*ProxyClient) ConnectToCluster

func (proxy *ProxyClient) ConnectToCluster(ctx context.Context, clusterName string) (auth.ClientI, error)

ConnectToCluster connects to the auth server of the given cluster via proxy. It returns connected and authenticated auth server client

func (*ProxyClient) ConnectToNode

func (proxy *ProxyClient) ConnectToNode(ctx context.Context, nodeAddress NodeDetails, user string, details sshutils.ClusterDetails, authMethods []ssh.AuthMethod) (*NodeClient, error)

ConnectToNode connects to the ssh server via Proxy. It returns connected and authenticated NodeClient

func (*ProxyClient) ConnectToRootCluster

func (proxy *ProxyClient) ConnectToRootCluster(ctx context.Context) (auth.ClientI, error)

ConnectToRootCluster connects to the auth server of the root cluster via proxy. It returns connected and authenticated auth server client

func (*ProxyClient) CreateAccessRequest

func (proxy *ProxyClient) CreateAccessRequest(ctx context.Context, req types.AccessRequest) error

CreateAccessRequest registers a new access request with the auth server.

func (*ProxyClient) CreateAppSession

func (proxy *ProxyClient) CreateAppSession(ctx context.Context, req types.CreateAppSessionRequest) (types.WebSession, error)

CreateAppSession creates a new application access session.

func (*ProxyClient) CurrentCluster

func (proxy *ProxyClient) CurrentCluster() auth.ClientI

CurrentCluster returns an authenticated auth server client for the local cluster.

func (*ProxyClient) DeleteAppSession

func (proxy *ProxyClient) DeleteAppSession(ctx context.Context, sessionID string) error

DeleteAppSession removes the specified application access session.

func (*ProxyClient) DeleteUserAppSessions

func (proxy *ProxyClient) DeleteUserAppSessions(ctx context.Context, req *proto.DeleteUserAppSessionsRequest) error

DeleteUserAppSessions removes user's all application web sessions.

func (*ProxyClient) FindAppServersByFilters

func (proxy *ProxyClient) FindAppServersByFilters(ctx context.Context, req proto.ListResourcesRequest) ([]types.AppServer, error)

FindAppServersByFilters returns a list of application servers in the current cluster which have filters matched.

func (*ProxyClient) FindAppServersByFiltersForCluster

func (proxy *ProxyClient) FindAppServersByFiltersForCluster(ctx context.Context, req proto.ListResourcesRequest, cluster string) ([]types.AppServer, error)

FindAppServersByFiltersForCluster returns a list of application servers for a given cluster which have filters matched.

func (*ProxyClient) FindDatabaseServersByFilters

func (proxy *ProxyClient) FindDatabaseServersByFilters(ctx context.Context, req proto.ListResourcesRequest) ([]types.DatabaseServer, error)

FindDatabaseServersByFilters returns registered database proxy servers that match the provided filter.

func (*ProxyClient) FindDatabaseServersByFiltersForCluster

func (proxy *ProxyClient) FindDatabaseServersByFiltersForCluster(ctx context.Context, req proto.ListResourcesRequest, cluster string) ([]types.DatabaseServer, error)

FindDatabaseServersByFiltersForCluster returns all registered database proxy servers in the provided cluster.

func (*ProxyClient) FindDatabasesByFilters

func (proxy *ProxyClient) FindDatabasesByFilters(ctx context.Context, req proto.ListResourcesRequest) ([]types.Database, error)

FindDatabasesByFilters returns registered databases that match the provided filter in the current cluster.

func (*ProxyClient) FindDatabasesByFiltersForCluster

func (proxy *ProxyClient) FindDatabasesByFiltersForCluster(ctx context.Context, req proto.ListResourcesRequest, cluster string) ([]types.Database, error)

FindDatabasesByFiltersForCluster returns registered databases that match the provided filter in the provided cluster.

func (*ProxyClient) FindNodesByFilters

func (proxy *ProxyClient) FindNodesByFilters(ctx context.Context, req proto.ListResourcesRequest) ([]types.Server, error)

FindNodesByFilters returns list of the nodes which have filters matched.

func (*ProxyClient) FindNodesByFiltersForCluster

func (proxy *ProxyClient) FindNodesByFiltersForCluster(ctx context.Context, req proto.ListResourcesRequest, cluster string) ([]types.Server, error)

FindNodesByFiltersForCluster returns list of the nodes in a specified cluster which have filters matched.

func (*ProxyClient) GetAccessRequests

func (proxy *ProxyClient) GetAccessRequests(ctx context.Context, filter types.AccessRequestFilter) ([]types.AccessRequest, error)

GetAccessRequests loads all access requests matching the supplied filter.

func (*ProxyClient) GetClusterAlerts

func (proxy *ProxyClient) GetClusterAlerts(ctx context.Context, req types.GetClusterAlertsRequest) ([]types.ClusterAlert, error)

func (*ProxyClient) GetLeafClusters

func (proxy *ProxyClient) GetLeafClusters(ctx context.Context) ([]types.RemoteCluster, error)

GetLeafClusters returns the leaf/remote clusters.

func (*ProxyClient) GetRole

func (proxy *ProxyClient) GetRole(ctx context.Context, name string) (types.Role, error)

GetRole loads a role resource by name.

func (*ProxyClient) GetSites

func (proxy *ProxyClient) GetSites(ctx context.Context) ([]types.Site, error)

GetSites returns list of the "sites" (AKA teleport clusters) connected to the proxy Each site is returned as an instance of its auth server

func (*ProxyClient) IssueUserCertsWithMFA

func (proxy *ProxyClient) IssueUserCertsWithMFA(ctx context.Context, params ReissueParams, promptMFAChallenge PromptMFAChallengeHandler) (*Key, error)

IssueUserCertsWithMFA generates a single-use certificate for the user.

func (*ProxyClient) ListResources

func (proxy *ProxyClient) ListResources(ctx context.Context, namespace, resource, startKey string, limit int) ([]types.ResourceWithLabels, string, error)

ListResources returns a paginated list of resources.

func (*ProxyClient) NewTracingClient

func (proxy *ProxyClient) NewTracingClient(ctx context.Context, clusterName string) (*tracing.Client, error)

NewTracingClient connects to the auth server of the given cluster via proxy. It returns a connected and authenticated tracing.Client that will export spans to the auth server, where they will be forwarded onto the configured exporter.

func (*ProxyClient) NewWatcher

func (proxy *ProxyClient) NewWatcher(ctx context.Context, watch types.Watch) (types.Watcher, error)

NewWatcher sets up a new event watcher.

func (*ProxyClient) PortForwardToNode

func (proxy *ProxyClient) PortForwardToNode(ctx context.Context, nodeAddress NodeDetails, user string, details sshutils.ClusterDetails, authMethods []ssh.AuthMethod) (*NodeClient, error)

PortForwardToNode connects to the ssh server via Proxy It returns connected and authenticated NodeClient

func (*ProxyClient) ReissueUserCerts

func (proxy *ProxyClient) ReissueUserCerts(ctx context.Context, cachePolicy CertCachePolicy, params ReissueParams) error

ReissueUserCerts generates certificates for the user that have a metadata instructing server to route the requests to the cluster

func (*ProxyClient) RootClusterName

func (proxy *ProxyClient) RootClusterName(ctx context.Context) (string, error)

RootClusterName returns name of the current cluster

type Redirector

type Redirector struct {
	// SSHLoginSSO contains SSH login parameters
	SSHLoginSSO

	// RedirectorConfig allows customization of Redirector
	RedirectorConfig
	// contains filtered or unexported fields
}

Redirector handles SSH redirect flow with the Teleport server

func NewRedirector

func NewRedirector(ctx context.Context, login SSHLoginSSO, config *RedirectorConfig) (*Redirector, error)

NewRedirector returns new local web server redirector

func (*Redirector) ClickableURL

func (rd *Redirector) ClickableURL() string

ClickableURL returns a short clickable redirect URL

func (*Redirector) Close

func (rd *Redirector) Close() error

Close closes redirector and releases all resources

func (*Redirector) Done

func (rd *Redirector) Done() <-chan struct{}

Done is called when redirector is closed or parent context is closed

func (*Redirector) ErrorC

func (rd *Redirector) ErrorC() <-chan error

ErrorC returns a channel with error

func (*Redirector) ResponseC

func (rd *Redirector) ResponseC() <-chan *auth.SSHLoginResponse

ResponseC returns a channel with response

func (*Redirector) Start

func (rd *Redirector) Start() error

Start launches local http server on the machine, initiates SSO login request sequence with the Teleport Proxy

type RedirectorConfig

type RedirectorConfig struct {
	// SSOLoginConsoleRequestFn allows customizing issuance of SSOLoginConsoleReq. Optional.
	SSOLoginConsoleRequestFn func(req SSOLoginConsoleReq) (*SSOLoginConsoleResponse, error)
}

RedirectorConfig allows customization of Redirector

type ReissueParams

type ReissueParams struct {
	RouteToCluster        string
	NodeName              string
	KubernetesCluster     string
	AccessRequests        []string
	DropAccessRequests    []string
	RouteToDatabase       proto.RouteToDatabase
	RouteToApp            proto.RouteToApp
	RouteToWindowsDesktop proto.RouteToWindowsDesktop

	// ExistingCreds is a gross hack for lib/web/terminal.go to pass in
	// existing user credentials. The TeleportClient in lib/web/terminal.go
	// doesn't have a real LocalKeystore and keeps all certs in memory.
	// Normally, existing credentials are loaded from
	// TeleportClient.localAgent.
	//
	// TODO(awly): refactor lib/web to use a Keystore implementation that
	// mimics LocalKeystore and remove this.
	ExistingCreds *Key

	// MFACheck is optional parameter passed if MFA check was already done.
	// It can be nil.
	MFACheck *proto.IsMFARequiredResponse
	// AuthClient is the client used for the MFACheck that can be reused
	AuthClient auth.ClientI
}

ReissueParams encodes optional parameters for user certificate reissue.

type SSHLogin

type SSHLogin struct {
	// ProxyAddr is the target proxy address
	ProxyAddr string
	// PubKey is SSH public key to sign
	PubKey []byte
	// TTL is requested TTL of the client certificates
	TTL time.Duration
	// Insecure turns off verification for x509 target proxy
	Insecure bool
	// Pool is x509 cert pool to use for server certifcate verification
	Pool *x509.CertPool
	// Compatibility sets compatibility mode for SSH certificates
	Compatibility string
	// RouteToCluster is an optional cluster name to route the response
	// credentials to.
	RouteToCluster string
	// KubernetesCluster is an optional k8s cluster name to route the response
	// credentials to.
	KubernetesCluster string
	// AttestationStatement is an attestation statement.
	AttestationStatement *keys.AttestationStatement
}

SSHLogin contains common SSH login parameters.

type SSHLoginDirect

type SSHLoginDirect struct {
	SSHLogin
	// User is the login username.
	User string
	// User is the login password.
	Password string
	// User is the optional OTP token for the login.
	OTPToken string
}

SSHLoginDirect contains SSH login parameters for direct (user/pass/OTP) login.

type SSHLoginFunc

type SSHLoginFunc func(context.Context, *keys.PrivateKey) (*auth.SSHLoginResponse, error)

SSHLoginFunc is a function which carries out authn with an auth server and returns an auth response.

type SSHLoginMFA

type SSHLoginMFA struct {
	SSHLogin
	// User is the login username.
	User string
	// Password is the login password.
	Password string

	// AllowStdinHijack allows stdin hijack during MFA prompts.
	// Do not set this options unless you deeply understand what you are doing.
	AllowStdinHijack bool
	// AuthenticatorAttachment is the authenticator attachment for MFA prompts.
	AuthenticatorAttachment wancli.AuthenticatorAttachment
	// PreferOTP prefers OTP in favor of other MFA methods.
	PreferOTP bool
}

SSHLoginMFA contains SSH login parameters for MFA login.

type SSHLoginPasswordless

type SSHLoginPasswordless struct {
	SSHLogin

	// StderrOverride will override the default os.Stderr if provided.
	StderrOverride io.Writer

	// User is the login username.
	User string

	// AuthenticatorAttachment is the authenticator attachment for passwordless prompts.
	AuthenticatorAttachment wancli.AuthenticatorAttachment

	// CustomPrompt defines a custom webauthn login prompt.
	// It's an optional field that when nil, it will use the wancli.DefaultPrompt.
	CustomPrompt wancli.LoginPrompt
}

SSHLoginPasswordless contains SSH login parameters for passwordless login.

type SSHLoginSSO

type SSHLoginSSO struct {
	SSHLogin
	// ConnectorID is the OIDC or SAML connector ID to use
	ConnectorID string
	// Protocol is an optional protocol selection
	Protocol string
	// BindAddr is an optional host:port address to bind
	// to for SSO login flows
	BindAddr string
	// Browser can be used to pass the name of a browser to override the system
	// default (not currently implemented), or set to 'none' to suppress
	// browser opening entirely.
	Browser string
}

SSHLoginSSO contains SSH login parameters for SSO login.

type SSOLoginConsoleReq

type SSOLoginConsoleReq struct {
	RedirectURL   string        `json:"redirect_url"`
	PublicKey     []byte        `json:"public_key"`
	CertTTL       time.Duration `json:"cert_ttl"`
	ConnectorID   string        `json:"connector_id"`
	Compatibility string        `json:"compatibility,omitempty"`
	// RouteToCluster is an optional cluster name to route the response
	// credentials to.
	RouteToCluster string
	// KubernetesCluster is an optional k8s cluster name to route the response
	// credentials to.
	KubernetesCluster string
	// AttestationStatement is an attestation statement associated with the given public key.
	AttestationStatement *keys.AttestationStatement `json:"attestation_statement,omitempty"`
}

SSOLoginConsoleReq is used to SSO for tsh

func (*SSOLoginConsoleReq) CheckAndSetDefaults

func (r *SSOLoginConsoleReq) CheckAndSetDefaults() error

CheckAndSetDefaults makes sure that the request is valid

type SSOLoginConsoleResponse

type SSOLoginConsoleResponse struct {
	RedirectURL string `json:"redirect_url"`
}

SSOLoginConsoleResponse is a response to SSO console request

type SSOLoginFunc

type SSOLoginFunc func(ctx context.Context, connectorID string, priv *keys.PrivateKey, protocol string) (*auth.SSHLoginResponse, error)

SSOLoginFunc is a function used in tests to mock SSO logins.

type ShellCreatedCallback

type ShellCreatedCallback func(s *tracessh.Session, c *tracessh.Client, terminal io.ReadWriteCloser) (exit bool, err error)

ShellCreatedCallback can be supplied for every teleport client. It will be called right after the remote shell is created, but the session hasn't begun yet.

It allows clients to cancel SSH action

type TOTPRegisterChallenge

type TOTPRegisterChallenge struct {
	QRCode []byte `json:"qrCode"`
}

type TeleportClient

type TeleportClient struct {
	Config

	// OnShellCreated gets called when the shell is created. It's
	// safe to keep it nil.
	OnShellCreated ShellCreatedCallback
	// contains filtered or unexported fields
}

TeleportClient is a wrapper around SSH client with teleport specific workflow built in. TeleportClient is NOT safe for concurrent use.

func NewClient

func NewClient(c *Config) (tc *TeleportClient, err error)

NewClient creates a TeleportClient object and fully configures it

func (*TeleportClient) ActivateKey

func (tc *TeleportClient) ActivateKey(ctx context.Context, key *Key) error

ActivateKey saves the target session cert into the local keystore (and into the ssh-agent) for future use.

func (*TeleportClient) AddKey

func (tc *TeleportClient) AddKey(key *Key) error

AddKey adds a key to the client's local agent, used in tests.

func (*TeleportClient) AddTrustedCA

func (tc *TeleportClient) AddTrustedCA(ctx context.Context, ca types.CertAuthority) error

AddTrustedCA adds a new CA as trusted CA for this client, used in tests

func (*TeleportClient) AskOTP

func (tc *TeleportClient) AskOTP(ctx context.Context) (token string, err error)

AskOTP prompts the user to enter the OTP token.

func (*TeleportClient) AskPassword

func (tc *TeleportClient) AskPassword(ctx context.Context) (pwd string, err error)

AskPassword prompts the user to enter the password

func (*TeleportClient) ConnectToNode

func (tc *TeleportClient) ConnectToNode(ctx context.Context, proxyClient *ProxyClient, nodeDetails NodeDetails, user string) (*NodeClient, error)

ConnectToNode attempts to establish a connection to the node resolved to by the provided NodeDetails. If the connection fails due to an Access Denied error, Auth is queried to determine if per-session MFA is required for the node. If it is required then the MFA ceremony is performed and another connection is attempted with the freshly minted certificates. If it is not required, then the original Access Denied error from the node is returned.

func (*TeleportClient) ConnectToProxy

func (tc *TeleportClient) ConnectToProxy(ctx context.Context) (*ProxyClient, error)

ConnectToProxy will dial to the proxy server and return a ProxyClient when successful. If the passed in context is canceled, this function will return a trace.ConnectionProblem right away.

func (*TeleportClient) CreateAccessRequest

func (tc *TeleportClient) CreateAccessRequest(ctx context.Context, req types.AccessRequest) error

CreateAccessRequest registers a new access request with the auth server.

func (*TeleportClient) CreateAppSession

CreateAppSession creates a new application access session.

func (*TeleportClient) DeleteAppSession

func (tc *TeleportClient) DeleteAppSession(ctx context.Context, sessionID string) error

DeleteAppSession removes the specified application access session.

func (*TeleportClient) EventsChannel

func (tc *TeleportClient) EventsChannel() <-chan events.EventFields

EventsChannel returns a channel that can be used to listen for events that occur for this session.

func (*TeleportClient) ExecuteSCP

func (tc *TeleportClient) ExecuteSCP(ctx context.Context, cmd scp.Command) (err error)

ExecuteSCP executes SCP command. It executes scp.Command using lower-level API integrations that mimic SCP CLI command behavior

func (*TeleportClient) GetAccessRequests

func (tc *TeleportClient) GetAccessRequests(ctx context.Context, filter types.AccessRequestFilter) ([]types.AccessRequest, error)

GetAccessRequests loads all access requests matching the supplied filter.

func (*TeleportClient) GetClusterAlerts

func (tc *TeleportClient) GetClusterAlerts(ctx context.Context, req types.GetClusterAlertsRequest) ([]types.ClusterAlert, error)

GetClusterAlerts returns a list of matching alerts from the current cluster.

func (*TeleportClient) GetNewLoginKey

func (tc *TeleportClient) GetNewLoginKey(ctx context.Context, keyPolicy keys.PrivateKeyPolicy) (*keys.PrivateKey, error)

GetNewLoginKey gets a new private key for login.

func (*TeleportClient) GetRole

func (tc *TeleportClient) GetRole(ctx context.Context, name string) (types.Role, error)

GetRole loads a role resource by name.

func (*TeleportClient) GetSessionEvents

func (tc *TeleportClient) GetSessionEvents(ctx context.Context, namespace, sessionID string) ([]events.EventFields, error)

func (*TeleportClient) GetTrustedCA

func (tc *TeleportClient) GetTrustedCA(ctx context.Context, clusterName string) ([]types.CertAuthority, error)

GetTrustedCA returns a list of host certificate authorities trusted by the cluster client is authenticated with.

func (*TeleportClient) GetWebConfig

func (tc *TeleportClient) GetWebConfig(ctx context.Context) (*webclient.WebConfig, error)

GetWebConfig retrieves Teleport proxy web config

func (*TeleportClient) IssueUserCertsWithMFA

func (tc *TeleportClient) IssueUserCertsWithMFA(ctx context.Context, params ReissueParams, applyOpts func(opts *PromptMFAChallengeOpts)) (*Key, error)

IssueUserCertsWithMFA issues a single-use SSH or TLS certificate for connecting to a target (node/k8s/db/app) specified in params with an MFA check. A user has to be logged in, there should be a valid login cert available.

If access to this target does not require per-connection MFA checks (according to RBAC), IssueCertsWithMFA will: - for SSH certs, return the existing Key from the keystore. - for TLS certs, fall back to ReissueUserCerts.

func (*TeleportClient) Join

func (tc *TeleportClient) Join(ctx context.Context, mode types.SessionParticipantMode, namespace string, sessionID session.ID, input io.Reader) (err error)

Join connects to the existing/active SSH session

func (*TeleportClient) ListAllNodes

func (tc *TeleportClient) ListAllNodes(ctx context.Context) ([]types.Server, error)

ListAllNodes is the same as ListNodes except that it ignores labels.

func (*TeleportClient) ListAppServersWithFilters

func (tc *TeleportClient) ListAppServersWithFilters(ctx context.Context, customFilter *proto.ListResourcesRequest) ([]types.AppServer, error)

ListAppServersWithFilters returns a list of application servers.

func (*TeleportClient) ListApps

func (tc *TeleportClient) ListApps(ctx context.Context, customFilter *proto.ListResourcesRequest) ([]types.Application, error)

ListApps returns all registered applications.

func (*TeleportClient) ListAppsAllClusters

func (tc *TeleportClient) ListAppsAllClusters(ctx context.Context, customFilter *proto.ListResourcesRequest) (map[string][]types.Application, error)

ListAppsAllClusters returns all registered applications across all clusters.

func (*TeleportClient) ListDatabaseServersWithFilters

func (tc *TeleportClient) ListDatabaseServersWithFilters(ctx context.Context, customFilter *proto.ListResourcesRequest) ([]types.DatabaseServer, error)

ListDatabaseServersWithFilters returns all registered database proxy servers.

func (*TeleportClient) ListDatabases

func (tc *TeleportClient) ListDatabases(ctx context.Context, customFilter *proto.ListResourcesRequest) ([]types.Database, error)

ListDatabases returns all registered databases.

func (*TeleportClient) ListDatabasesAllClusters

func (tc *TeleportClient) ListDatabasesAllClusters(ctx context.Context, customFilter *proto.ListResourcesRequest) (map[string][]types.Database, error)

ListDatabasesAllClusters returns all registered databases across all clusters.

func (*TeleportClient) ListKubernetesClustersWithFiltersAllClusters

func (tc *TeleportClient) ListKubernetesClustersWithFiltersAllClusters(ctx context.Context, req proto.ListResourcesRequest) (map[string][]types.KubeCluster, error)

ListKubernetesClustersWithFiltersAllClusters returns a map of all kube clusters in all clusters connected to a proxy.

func (*TeleportClient) ListNodesWithFilters

func (tc *TeleportClient) ListNodesWithFilters(ctx context.Context) ([]types.Server, error)

ListNodesWithFilters returns a list of nodes connected to a proxy

func (*TeleportClient) ListNodesWithFiltersAllClusters

func (tc *TeleportClient) ListNodesWithFiltersAllClusters(ctx context.Context) (map[string][]types.Server, error)

ListNodesWithFiltersAllClusters returns a map of all nodes in all clusters connected to this proxy.

func (*TeleportClient) LoadKeyForCluster

func (tc *TeleportClient) LoadKeyForCluster(clusterName string) error

LoadKeyForCluster fetches a cluster-specific SSH key and loads it into the SSH agent.

func (*TeleportClient) LoadKeyForClusterWithReissue

func (tc *TeleportClient) LoadKeyForClusterWithReissue(ctx context.Context, clusterName string) error

LoadKeyForClusterWithReissue fetches a cluster-specific SSH key and loads it into the SSH agent. If the key is not found, it is requested to be reissued.

func (*TeleportClient) LocalAgent

func (tc *TeleportClient) LocalAgent() *LocalKeyAgent

LocalAgent is a getter function for the client's local agent

func (*TeleportClient) Login

func (tc *TeleportClient) Login(ctx context.Context) (*Key, error)

Login logs the user into a Teleport cluster by talking to a Teleport proxy.

The returned Key should typically be passed to ActivateKey in order to update local agent state.

If the initial login fails due to a private key policy not being met, Login will automatically retry login with a private key that meets the required policy. This will initiate the same login flow again, aka prompt for password/otp/sso/mfa.

func (*TeleportClient) Logout

func (tc *TeleportClient) Logout() error

Logout removes certificate and key for the currently logged in user from the filesystem and agent.

func (*TeleportClient) LogoutAll

func (tc *TeleportClient) LogoutAll() error

LogoutAll removes all certificates for all users from the filesystem and agent.

func (*TeleportClient) LogoutApp

func (tc *TeleportClient) LogoutApp(appName string) error

LogoutApp removes certificate for the specified app.

func (*TeleportClient) LogoutDatabase

func (tc *TeleportClient) LogoutDatabase(dbName string) error

LogoutDatabase removes certificate for a particular database.

func (*TeleportClient) NewTracingClient

func (tc *TeleportClient) NewTracingClient(ctx context.Context) (*apitracing.Client, error)

NewTracingClient provides a tracing client that will forward spans on to the current clusters auth server. The auth server will then forward along to the configured telemetry backend.

func (*TeleportClient) NewWatcher

func (tc *TeleportClient) NewWatcher(ctx context.Context, watch types.Watch) (types.Watcher, error)

NewWatcher sets up a new event watcher.

func (*TeleportClient) Ping

Ping makes a ping request to the proxy, and updates tc based on the response. The successful ping response is cached, multiple calls to Ping will return the original response and skip the round-trip.

Ping can be called for its side-effect of applying the proxy-provided settings (such as various listening addresses).

func (*TeleportClient) PingAndShowMOTD

func (tc *TeleportClient) PingAndShowMOTD(ctx context.Context) (*webclient.PingResponse, error)

PingAndShowMOTD pings the Teleport Proxy and displays the Message Of The Day if it's available.

func (*TeleportClient) Play

func (tc *TeleportClient) Play(ctx context.Context, namespace, sessionID string) (err error)

Play replays the recorded session

func (*TeleportClient) PromptMFAChallenge

func (tc *TeleportClient) PromptMFAChallenge(ctx context.Context, proxyAddr string, c *proto.MFAAuthenticateChallenge, applyOpts func(opts *PromptMFAChallengeOpts)) (*proto.MFAAuthenticateResponse, error)

PromptMFAChallenge prompts the user to complete MFA authentication challenges. If proxyAddr is empty, the TeleportClient.WebProxyAddr is used. See client.PromptMFAChallenge.

func (*TeleportClient) ReissueUserCerts

func (tc *TeleportClient) ReissueUserCerts(ctx context.Context, cachePolicy CertCachePolicy, params ReissueParams) error

ReissueUserCerts issues new user certs based on params and stores them in the local key agent (usually on disk in ~/.tsh).

func (*TeleportClient) RootClusterName

func (tc *TeleportClient) RootClusterName(ctx context.Context) (string, error)

RootClusterName returns root cluster name.

func (*TeleportClient) SFTP

func (tc *TeleportClient) SFTP(ctx context.Context, args []string, port int, opts sftp.Options, quiet bool) (err error)

SFTP securely copies files between Nodes or SSH servers using SFTP

func (*TeleportClient) SSH

func (tc *TeleportClient) SSH(ctx context.Context, command []string, runLocally bool) error

SSH connects to a node and, if 'command' is specified, executes the command on it, otherwise runs interactive shell

Returns nil if successful, or (possibly) *exec.ExitError

func (*TeleportClient) SSHLogin

func (tc *TeleportClient) SSHLogin(ctx context.Context, sshLoginFunc SSHLoginFunc) (*Key, error)

SSHLogin uses the given login function to login the client. This function handles private key logic and parsing the resulting auth response.

func (*TeleportClient) SearchSessionEvents

func (tc *TeleportClient) SearchSessionEvents(ctx context.Context, fromUTC, toUTC time.Time, pageSize int, order types.EventOrder, max int) ([]apievents.AuditEvent, error)

SearchSessionEvents allows searching for session events with a full pagination support.

func (*TeleportClient) SendEvent

func (tc *TeleportClient) SendEvent(ctx context.Context, e events.EventFields) error

SendEvent adds a events.EventFields to the channel.

func (*TeleportClient) ShowMOTD

func (tc *TeleportClient) ShowMOTD(ctx context.Context) error

ShowMOTD fetches the cluster MotD, displays it (if any) and waits for confirmation from the user.

func (*TeleportClient) SignersForClusterWithReissue

func (tc *TeleportClient) SignersForClusterWithReissue(ctx context.Context, clusterName string) ([]ssh.Signer, error)

SignersForClusterWithReissue fetches cluster-specific signers from stored certificates. If the cluster certificates are not found, it is requested to be reissued.

func (*TeleportClient) TransferFiles

func (tc *TeleportClient) TransferFiles(ctx context.Context, hostLogin, nodeAddr string, cfg *sftp.Config) error

TransferFiles copies files between the current machine and the specified Node using the supplied config

func (*TeleportClient) UpdateTrustedCA

func (tc *TeleportClient) UpdateTrustedCA(ctx context.Context, clusterName string) error

UpdateTrustedCA connects to the Auth Server and fetches all host certificates and updates ~/.tsh/keys/proxy/certs.pem and ~/.tsh/known_hosts.

func (*TeleportClient) WithRootClusterClient

func (tc *TeleportClient) WithRootClusterClient(ctx context.Context, do func(clt auth.ClientI) error) error

WithRootClusterClient provides a functional interface for making calls against the root cluster's auth server.

func (*TeleportClient) WithoutJumpHosts

func (tc *TeleportClient) WithoutJumpHosts(fn func(tcNoJump *TeleportClient) error) error

WithoutJumpHosts executes the given function with a Teleport client that has no JumpHosts set, i.e. presumably falling back to the proxy specified in the profile.

type VirtualPathKind

type VirtualPathKind string

VirtualPathKind is the suffix component for env vars denoting the type of file that will be loaded.

const (
	// VirtualPathEnvPrefix is the env var name prefix shared by all virtual
	// path vars.
	VirtualPathEnvPrefix = "TSH_VIRTUAL_PATH"

	VirtualPathKey        VirtualPathKind = "KEY"
	VirtualPathCA         VirtualPathKind = "CA"
	VirtualPathDatabase   VirtualPathKind = "DB"
	VirtualPathApp        VirtualPathKind = "APP"
	VirtualPathKubernetes VirtualPathKind = "KUBE"
)

type VirtualPathParams

type VirtualPathParams []string

VirtualPathParams are an ordered list of additional optional parameters for a virtual path. They can be used to specify a more exact resource name if multiple might be available. Simpler integrations can instead only specify the kind and it will apply wherever a more specific env var isn't found.

func VirtualPathAppParams

func VirtualPathAppParams(appName string) VirtualPathParams

VirtualPathAppParams returns parameters for selecting specific apps by name.

func VirtualPathCAParams

func VirtualPathCAParams(caType types.CertAuthType) VirtualPathParams

VirtualPathCAParams returns parameters for selecting CA certificates.

func VirtualPathDatabaseParams

func VirtualPathDatabaseParams(databaseName string) VirtualPathParams

VirtualPathDatabaseParams returns parameters for selecting specific database certificates.

func VirtualPathKubernetesParams

func VirtualPathKubernetesParams(k8sCluster string) VirtualPathParams

VirtualPathKubernetesParams returns parameters for selecting k8s clusters by name.

type WebClient

type WebClient struct {
	*roundtrip.Client
}

WebClient is a package local lightweight client used in tests and some functions to handle errors properly

func NewWebClient

func NewWebClient(url string, opts ...roundtrip.ClientParam) (*WebClient, error)

func (*WebClient) Delete

func (w *WebClient) Delete(ctx context.Context, endpoint string) (*roundtrip.Response, error)

func (*WebClient) DeleteWithParams

func (w *WebClient) DeleteWithParams(ctx context.Context, endpoint string, val url.Values) (*roundtrip.Response, error)

func (*WebClient) Get

func (w *WebClient) Get(ctx context.Context, endpoint string, val url.Values) (*roundtrip.Response, error)

func (*WebClient) PostJSON

func (w *WebClient) PostJSON(ctx context.Context, endpoint string, val interface{}) (*roundtrip.Response, error)

func (*WebClient) PostJSONWithFallback

func (w *WebClient) PostJSONWithFallback(ctx context.Context, endpoint string, val interface{}, allowHTTPFallback bool) (*roundtrip.Response, error)

PostJSONWithFallback serializes an object to JSON and attempts to execute a POST using HTTPS, and then fall back to plain HTTP under certain, very specific circumstances.

  • The caller must specifically allow it via the allowHTTPFallback parameter, and
  • The target host must resolve to the loopback address.

If these conditions are not met, then the plain-HTTP fallback is not allowed, and a the HTTPS failure will be considered final.

func (*WebClient) PutJSON

func (w *WebClient) PutJSON(ctx context.Context, endpoint string, val interface{}) (*roundtrip.Response, error)

type WithAppCerts

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

WithAppCerts is a CertOption for handling application access certificates.

type WithDBCerts

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

WithDBCerts is a CertOption for handling database access certificates.

type WithKubeCerts

type WithKubeCerts struct{}

WithKubeCerts is a CertOption for handling kubernetes certificates.

type WithSSHCerts

type WithSSHCerts struct{}

WithSSHCerts is a CertOption for handling SSH certificates.

Directories

Path Synopsis
db
Package db contains methods for working with database connection profiles that combine connection parameters for a particular database.
Package db contains methods for working with database connection profiles that combine connection parameters for a particular database.
Package escape implements client-side escape character logic.
Package escape implements client-side escape character logic.
Package identityfile handles formatting and parsing of identity files.
Package identityfile handles formatting and parsing of identity files.

Jump to

Keyboard shortcuts

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