client

package
v0.0.0-...-5c79d48 Latest Latest
Warning

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

Go to latest
Published: Feb 15, 2024 License: AGPL-3.0 Imports: 119 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 ErrNoCredentials = trace.NotFound("no credentials")

ErrNoCredentials is returned by the client store when a specific key is not found. This error can be used to determine whether a client should retrieve new credentials, like how it is used with lib/client.RetryWithRelogin.

WithAllCerts lists all known CertOptions.

Functions

func CreatePROXYHeaderGetter

func CreatePROXYHeaderGetter(ctx context.Context, proxySigner multiplexer.PROXYHeaderSigner) client.PROXYHeaderGetter

CreatePROXYHeaderGetter returns PROXY headers signer with embedded client source/destination IP addresses, which are taken from the context.

func ExportAuthorities

func ExportAuthorities(ctx context.Context, client auth.ClientI, req ExportAuthoritiesRequest) (string, error)

ExportAuthorities returns the list of authorities in OpenSSH compatible formats as a string. If the ExportAuthoritiesRequest.AuthType is present only prints keys for CAs of this type, otherwise returns host and user SSH keys.

Exporting using "tls*", "database", "windows" AuthType: Returns the certificate authority public key to be used by systems that rely on TLS. The format can be PEM or DER depending on the target.

Exporting using "user" AuthType: Returns the certificate authority public key exported as a single line that can be placed in ~/.ssh/authorized_keys file. The format adheres to the man sshd (8) authorized_keys format, a space-separated list of: options, keytype, base64-encoded key, comment. For example: > cert-authority AAA... type=user&clustername=cluster-a URL encoding is used to pass the CA type and cluster name into the comment field.

Exporting using "host" AuthType: Returns the certificate authority public key exported as a single line that can be placed in ~/.ssh/known_hosts. The format adheres to the man sshd (8) known_hosts format, a space-separated list of: marker, hosts, key, and comment. For example: > @cert-authority *.cluster-a ssh-rsa AAA... type=host URL encoding is used to pass the CA type and allowed logins into the comment field.

func ExportAuthoritiesSecrets

func ExportAuthoritiesSecrets(ctx context.Context, client auth.ClientI, req ExportAuthoritiesRequest) (string, error)

ExportAuthoritiesSecrets exports the Authority Certificate secrets (private keys). See ExportAuthorities for more information.

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 GetSessionFromResponse

func GetSessionFromResponse(resp *roundtrip.Response) (types.WebSession, error)

GetSessionFromResponse creates a types.WebSession if a cookie named websession.CookieName is present in the provided roundtrip.Response.

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

IsErrorResolvableWithRelogin returns true if relogin is attempted on `err`.

func IsNoCredentialsError

func IsNoCredentialsError(err error) bool

IsNoCredentialsError returns whether the given error is an ErrNoCredentials error.

func LoadKeysToKubeFromStore

func LoadKeysToKubeFromStore(profile *profile.Profile, dirPath, teleportCluster, kubeCluster string) ([]byte, []byte, error)

LoadKeysToKubeFromStore loads the keys for a given teleport cluster and kube cluster from the store. It returns the certificate and private key to be used for the kube cluster. If the keys are not found, it returns an error. This function is used to speed up the credentials loading process since Teleport Store transverses the entire store to find the keys. This operation takes a long time when the store has a lot of keys and when we call the function multiple times in parallel. Although this function speeds up the process since it removes all transversals, it still has to read 2 different files: - $TSH_HOME/keys/$PROXY/$USER-kube/$TELEPORT_CLUSTER/$KUBE_CLUSTER-x509.pem - $TSH_HOME/keys/$PROXY/$USER

func MFARequiredUnknown

func MFARequiredUnknown(err error) error

MFARequiredUnknown creates a new MFARequiredUnknownErr that wraps the error encountered attempting to determine if the mfa ceremony should proceed.

func NewInsecureWebClient

func NewInsecureWebClient() *http.Client

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, filename, sid string, speed float64) error

PlayFile plays the recorded session from a file.

func ProfileNameFromProxyAddress

func ProfileNameFromProxyAddress(store ProfileStore, proxyAddr string) (string, error)

ProfileNameFromProxyAddress converts proxy address to profile name or returns the current profile if the proxyAddr is not set.

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, opts ...RetryWithReloginOption) error

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

func RunALPNAuthTunnel

func RunALPNAuthTunnel(ctx context.Context, cfg ALPNAuthTunnelConfig) error

RunALPNAuthTunnel runs a local authenticated ALPN proxy to another service. At least one Route (which defines the service) must be defined

func RunPresenceTask

func RunPresenceTask(ctx context.Context, term io.Writer, maintainer PresenceMaintainer, sessionID string, mfaPrompt mfa.Prompt, opts ...PresenceOption) error

RunPresenceTask periodically performs and MFA ceremony to detect that a user is still present and attentive.

func SSHAgentHeadlessLogin

func SSHAgentHeadlessLogin(ctx context.Context, login SSHLoginHeadless) (*auth.SSHLoginResponse, error)

SSHAgentHeadlessLogin begins the headless login ceremony, returning new user certificates if successful.

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 TrustedCertsFromCACerts

func TrustedCertsFromCACerts(tlsCACerts [][]byte, knownHosts []sshutils.KnownHost) ([]auth.TrustedCerts, error)

TrustedCertsFromCACerts converts the given TLS CA certificates and KnownHosts files into a list of Trusted Certs. If a proxyHost is specified, only known hosts with that proxy host as one of its hostnames are returned.

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.

func WithHostAddress

func WithHostAddress(addr string) func(*SSHOptions)

WithHostAddress returns a SSHOptions which overrides the target host address with the one provided.

Types

type ALPNAuthClient

type ALPNAuthClient interface {
	// GetClusterCACert returns the PEM-encoded TLS certs for the local cluster.
	// If the cluster has multiple TLS certs, they will all be concatenated.
	GetClusterCACert(ctx context.Context) (*proto.GetClusterCACertResponse, error)

	// GetCurrentUser returns current user as seen by the server.
	// Useful especially in the context of remote clusters which perform role and trait mapping.
	GetCurrentUser(ctx context.Context) (types.User, error)

	// GenerateUserCerts takes the public key in the OpenSSH `authorized_keys` plain
	// text format, signs it using User Certificate Authority signing key and
	// returns the resulting certificates.
	GenerateUserCerts(ctx context.Context, req proto.UserCertsRequest) (*proto.Certs, error)
}

ALPNAuthClient contains the required auth.ClientI methods to create a local ALPN proxy.

type ALPNAuthTunnelConfig

type ALPNAuthTunnelConfig struct {
	// MFAAuthenticateResponse is a response to MFAAuthenticateChallenge using one
	// of the MFA devices registered for a user.
	MFAResponse *proto.MFAAuthenticateResponse

	// AuthClient is the client that's used to interact with the cluster and obtain Certificates.
	AuthClient ALPNAuthClient

	// Listener to be used to accept connections that will go trough the tunnel.
	Listener net.Listener

	// InsecureSkipTLSVerify turns off verification for x509 upstream ALPN proxy service certificate.
	InsecureSkipVerify bool

	// Expires is a desired time of the expiry of the certificate.
	Expires time.Time

	// Protocol name.
	Protocol alpn.Protocol

	// PublicProxyAddr is public address of the proxy
	PublicProxyAddr string

	// ConnectionDiagnosticID contains the ID to be used to store Connection Diagnostic checks.
	// Can be empty.
	ConnectionDiagnosticID string

	// RouteToDatabase contains the destination server that must receive the connection.
	// Specific for database proxying.
	RouteToDatabase proto.RouteToDatabase
}

ALPNAuthTunnelConfig contains the required fields used to create an authed ALPN Proxy

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 *wantypes.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 *wantypes.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 ClusterClient

type ClusterClient struct {
	ProxyClient *proxyclient.Client
	AuthClient  auth.ClientI
	Tracer      oteltrace.Tracer
	// contains filtered or unexported fields
}

ClusterClient facilitates communicating with both the Auth and Proxy services of a cluster.

func (*ClusterClient) Close

func (c *ClusterClient) Close() error

Close terminates the connections to Auth and Proxy.

func (*ClusterClient) ClusterName

func (c *ClusterClient) ClusterName() string

ClusterName returns the name of the cluster that the client is connected to.

func (*ClusterClient) ConnectToCluster

func (c *ClusterClient) 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 (*ClusterClient) ConnectToRootCluster

func (c *ClusterClient) 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 (*ClusterClient) CurrentCluster

func (c *ClusterClient) CurrentCluster() auth.ClientI

CurrentCluster returns an authenticated auth server client for the local cluster. The returned auth server client does not need to be closed, it will be closed when the ClusterClient is closed.

func (*ClusterClient) DialHostWithResumption

func (c *ClusterClient) DialHostWithResumption(ctx context.Context, target, cluster string, keyring agent.ExtendedAgent) (net.Conn, proxyclient.ClusterDetails, error)

DialHostWithResumption is proxyclient.DialHost called on the underlying *proxyclient.Client of the ClusterClient, but with additional logic that attempts to resume the connection if it's supported by the remote server and if it's not been disabled in the TeleportClient (with a command-line flag, typically).

func (*ClusterClient) SessionSSHConfig

func (c *ClusterClient) SessionSSHConfig(ctx context.Context, user string, target NodeDetails) (*ssh.ClientConfig, error)

SessionSSHConfig returns the ssh.ClientConfig that should be used to connected to the provided target for the provided user. If per session MFA is required to establish the connection, then the MFA ceremony will be performed.

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

	// UseSearchAsRoles modifies the behavior of resource loading to
	// use search as roles feature.
	UseSearchAsRoles bool

	// 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

	// NonInteractive tells the client not to trigger interactive features for non-interactive commands,
	// such as prompting user to re-login on credential errors. This is used by external programs linking
	// against Teleport client and obtaining credentials from elsewhere. e.g. from an identity file.
	NonInteractive bool

	// Agent is an SSH agent to use for local Agent procedures. Defaults to in-memory agent keyring.
	Agent agent.ExtendedAgent

	ClientStore *Store

	// 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 the client store.
	AuthMethods []ssh.AuthMethod

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

	// ProxySSHPrincipal determines the SSH username (principal) the client should be using
	// when connecting to auth/proxy servers. By default, the SSH username is pulled from
	// the user's certificate, but the web-based terminal provides this username explicitly.
	ProxySSHPrincipal 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

	// SessionID is a session ID to use when opening a new session.
	SessionID string

	// InteractiveCommand tells tsh to launch a remote exec command in interactive mode,
	// i.e. attaching the terminal to it.
	InteractiveCommand 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
	// CallbackAddr is the optional base URL to give to the user when performing
	// SSO redirect flows.
	CallbackAddr 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

	// MockHeadlessLogin is used in tests for mocking the Headless login response.
	MockHeadlessLogin SSHLoginFunc

	// OverrideMySQLOptionFilePath overrides the MySQL option file path to use.
	// Useful in parallel tests so they don't all use the default path in the
	// user home dir.
	OverrideMySQLOptionFilePath string

	// OverridePostgresServiceFilePath overrides the Postgres service file path.
	// Useful in parallel tests so they don't all use the default path in the
	// user home dir.
	OverridePostgresServiceFilePath string

	// 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

	// TLSRoutingConnUpgradeRequired indicates that ALPN connection upgrades
	// are required for making TLS routing requests.
	//
	// Note that this is applicable to the Proxy's Web port regardless of
	// whether the Proxy is in single-port or multi-port configuration.
	TLSRoutingConnUpgradeRequired 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

	// PIVSlot specifies a specific PIV slot to use with hardware key support.
	PIVSlot keys.PIVSlot

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

	// AllowHeadless determines whether headless login can be used. Currently, only
	// the ssh, scp, and ls commands can use headless login. Other commands will ignore
	// headless auth connector and default to local instead.
	AllowHeadless bool

	// DialOpts used by the api.client.proxy.Client when establishing a connection to
	// the proxy server. Used by tests.
	DialOpts []grpc.DialOption

	// PROXYSigner is used to sign PROXY headers for securely propagating client IP address
	PROXYSigner multiplexer.PROXYHeaderSigner

	// DTAuthnRunCeremony allows tests to override the default device
	// authentication function.
	// Defaults to "dtauthn.NewCeremony().Run()".
	DTAuthnRunCeremony DTAuthnRunCeremonyFunc

	// WebauthnLogin allows tests to override the Webauthn Login func.
	// Defaults to [wancli.Login].
	WebauthnLogin WebauthnLoginFunc

	// SSHLogDir is the directory to log the output of multiple SSH commands to.
	// If not set, no logs will be created.
	SSHLogDir string

	// MFAPromptConstructor is a custom MFA prompt constructor to use when prompting for MFA.
	MFAPromptConstructor func(cfg *libmfa.PromptConfig) mfa.Prompt

	// DisableSSHResumption disables transparent SSH connection resumption.
	DisableSSHResumption bool
	// contains filtered or unexported fields
}

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) DoesDatabaseUseWebProxyHostPort

func (c *Config) DoesDatabaseUseWebProxyHostPort(db tlsca.RouteToDatabase) bool

DoesDatabaseUseWebProxyHostPort returns true if database is using web port.

This is useful for deciding whether local proxy is required when web port is behind a load balancer.

func (*Config) GetProfile

func (c *Config) GetProfile(ps ProfileStore, proxyAddr string) (*profile.Profile, error)

GetProfile gets the profile for the specified proxy address, or the current profile if no proxy is specified.

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(ps ProfileStore, proxyAddr 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) Profile

func (c *Config) Profile() *profile.Profile

Profile converts Config to *profile.Profile.

func (*Config) ProxySpecified

func (c *Config) ProxySpecified() bool

ProxySpecified returns true if proxy has been specified.

func (*Config) ResourceFilter

func (c *Config) ResourceFilter(kind string) *proto.ListResourcesRequest

ResourceFilter returns the default list resource request for the provided resource kind.

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(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"`
	// HeadlessAuthenticationID is a headless authentication resource id.
	HeadlessAuthenticationID string `json:"headless_id"`
	// 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 CreateWebSessionReq

type CreateWebSessionReq struct {
	// User is the Teleport username.
	User string `json:"user"`
	// Pass is the password.
	Pass string `json:"pass"`
	// SecondFactorToken is the OTP.
	SecondFactorToken string `json:"second_factor_token"`
}

CreateWebSessionReq is a request for the web api to initiate a new web session.

type CreateWebSessionResponse

type CreateWebSessionResponse struct {
	// TokenType is token type (bearer)
	TokenType string `json:"type"`
	// Token value
	Token string `json:"token"`
	// TokenExpiresIn sets seconds before this token is not valid
	TokenExpiresIn int `json:"expires_in"`
	// SessionExpires is when this session expires.
	SessionExpires time.Time `json:"sessionExpires,omitempty"`
	// SessionInactiveTimeoutMS specifies how long in milliseconds
	// a user WebUI session can be left idle before being logged out
	// by the server. A zero value means there is no idle timeout set.
	SessionInactiveTimeoutMS int `json:"sessionInactiveTimeout"`
}

CreateWebSessionResponse is a response from the web api to a CreateWebSessionReq request.

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 NewDBCertChecker

func NewDBCertChecker(tc *TeleportClient, dbRoute tlsca.RouteToDatabase, clock clockwork.Clock) *DBCertChecker

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 DTAuthnRunCeremonyFunc

DTAuthnRunCeremonyFunc matches the signature of dtauthn.Ceremony.Run.

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 ExportAuthoritiesRequest

type ExportAuthoritiesRequest struct {
	AuthType                   string
	ExportAuthorityFingerprint string
	UseCompatVersion           bool
}

ExportAuthoritiesRequest has the required fields to create an export authorities request.

An empty AuthType exports all types.

When exporting private keys, you can set ExportAuthorityFingerprint to filter the authority. Fingerprint must be the SHA256 of the Authority's public key.

You can export using the old 1.0 format where host and user certificate authorities were exported in the known_hosts format. To do so, set UseCompatVersion to true.

type FSKeyStore

type FSKeyStore struct {

	// KeyDir is the directory where all keys are stored.
	KeyDir string
	// contains filtered or unexported fields
}

FSKeyStore is an on-disk implementation of the KeyStore interface.

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

func NewFSKeyStore

func NewFSKeyStore(dirPath string) *FSKeyStore

NewFSKeyStore initializes a new FSClientStore.

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

func (*FSKeyStore) AddKey

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

AddKey adds the given key to the store.

func (*FSKeyStore) DeleteKey

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

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

func (*FSKeyStore) DeleteKeys

func (fs *FSKeyStore) DeleteKeys() error

DeleteKeys removes all session keys.

func (*FSKeyStore) DeleteUserCerts

func (fs *FSKeyStore) 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 (*FSKeyStore) GetKey

func (fs *FSKeyStore) 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 (*FSKeyStore) GetSSHCertificates

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

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

type FSProfileStore

type FSProfileStore struct {

	// Dir is the directory where all keys are stored.
	Dir string
	// contains filtered or unexported fields
}

FSProfileStore is an on-disk implementation of the ProfileStore interface.

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

func NewFSProfileStore

func NewFSProfileStore(dirPath string) *FSProfileStore

NewFSProfileStore creates a new instance of FSProfileStore.

func (*FSProfileStore) CurrentProfile

func (fs *FSProfileStore) CurrentProfile() (string, error)

CurrentProfile returns the current profile.

func (*FSProfileStore) GetProfile

func (fs *FSProfileStore) GetProfile(profileName string) (*profile.Profile, error)

GetProfile returns the requested profile.

func (*FSProfileStore) ListProfiles

func (fs *FSProfileStore) ListProfiles() ([]string, error)

ListProfiles returns a list of all profiles.

func (*FSProfileStore) SaveProfile

func (fs *FSProfileStore) SaveProfile(profile *profile.Profile, makeCurrent bool) error

SaveProfile saves the given profile. If makeCurrent is true, it makes this profile current.

type FSTrustedCertsStore

type FSTrustedCertsStore struct {

	// Dir is the directory where all keys are stored.
	Dir string
	// contains filtered or unexported fields
}

FSTrustedCertsStore is an on-disk implementation of the TrustedCAStore interface.

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

func NewFSTrustedCertsStore

func NewFSTrustedCertsStore(dirPath string) *FSTrustedCertsStore

NewFSTrustedCertsStore creates a new instance of FSTrustedCertsStore.

func (*FSTrustedCertsStore) GetTrustedCerts

func (fs *FSTrustedCertsStore) GetTrustedCerts(proxyHost string) ([]auth.TrustedCerts, error)

GetTrustedCerts gets the trusted CA TLS certificates and SSH host keys for the given proxyHost.

func (*FSTrustedCertsStore) GetTrustedCertsPEM

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

GetTrustedCertsPEM returns trusted TLS certificates of certificate authorities PEM blocks.

func (*FSTrustedCertsStore) GetTrustedHostKeys

func (fs *FSTrustedCertsStore) GetTrustedHostKeys(hostnames ...string) (keys []ssh.PublicKey, retErr error)

GetTrustedHostKeys returns all trusted public host keys. If hostnames are provided, only matching host keys will be returned. Host names should be a proxy host or cluster name.

func (*FSTrustedCertsStore) SaveTrustedCerts

func (fs *FSTrustedCertsStore) 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 HeadlessRequest

type HeadlessRequest struct {
	// Actions can be either accept or deny.
	Action string `json:"action"`
	// WebauthnAssertionResponse is a signed WebAuthn credential assertion.
	WebauthnAssertionResponse *wantypes.CredentialAssertionResponse `json:"webauthnAssertionResponse,omitempty"`
}

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 IssueUserCertsOpt

type IssueUserCertsOpt func(*issueUserCertsOpts)

IssueUserCertsOpt is an option func for issuing user certs.

func WithMFARequired

func WithMFARequired(mfaRequired *bool) IssueUserCertsOpt

WithMFARequired is an IssueUserCertsOpt that sets the MFA required check result in provided bool ptr.

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"`
	// TrustedCerts is a list of trusted certificate authorities
	TrustedCerts []auth.TrustedCerts
}

Key describes a complete (signed) client key

func GenerateRSAKey

func GenerateRSAKey() (*Key, error)

GenerateRSAKey generates a new unsigned key.

func NewKey

func NewKey(priv *keys.PrivateKey) *Key

NewKey creates a new Key for the given private key.

func PerformMFACeremony

func PerformMFACeremony(ctx context.Context, params PerformMFACeremonyParams) (*Key, *proto.Certs, error)

PerformMFACeremony issues single-use certificates via GenerateUserCerts, following its recommended RPC flow.

It is a lower-level, less opinionated variant of ProxyClient.IssueUserCertsWithMFA.

It does the following:

  1. if !params.MFAAgainstRoot: Call CurrentAuthClient.IsMFARequired, abort if MFA is not required.
  2. Call RootAuthClient.CreateAuthenticateChallenge, abort if MFA is not required
  3. Call params.PromptMFA to solve the authn challenge
  4. Call RootAuthClient.GenerateUserCerts

Returns the modified params.Key and the GenerateUserCertsResponse, or an error.

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)

AsAgentKey converts client.Key struct to an agent.AddedKey. Any agent.AddedKey can be added to a local agent (keyring), nut non-standard keys cannot be added to an SSH system agent through the ssh agent protocol. Check canAddToSystemAgent before adding this key to an SSH system 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) Copy

func (k *Key) Copy() *Key

Copy returns a shallow copy of k, or nil if k is nil.

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) HostKeyCallback

func (k *Key) HostKeyCallback(hostnames ...string) (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) KubeClientTLSConfig

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

func (*Key) KubeTLSCert

func (k *Key) KubeTLSCert(kubeClusterName string) (tls.Certificate, error)

KubeTLSCert returns the tls.Certificate for authentication against a named kubernetes cluster.

func (*Key) KubeX509Cert

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

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

func (*Key) ProxyClientSSHConfig

func (k *Key) ProxyClientSSHConfig(hostname 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) 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.

func (KeyIndex) Match

func (idx KeyIndex) Match(matchKey KeyIndex) bool

Match compares this key index to the given matchKey index. It will be considered a match if all non-zero elements of the matchKey are matched by this key index.

type KeyStore

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

	// GetKey returns the user's key including the specified certs. The key's
	// TrustedCerts will be nil and should be filled in using a TrustedCertsStore.
	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

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

KeyStore is a storage interface for client session keys and certificates.

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 {
	ClientStore *Store
	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) 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) AddKubeKey

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

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

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) HostKeyCallback

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

HostKeyCallback 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) LoadKey

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

LoadKey adds a key into the local agent as well as the system agent. Some agent keys are only supported by the local agent, such as those for a YubiKeyPrivateKey. Any failures to add the key will be aggregated into the returned error to be handled by the caller if necessary.

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 and host keys of certificate authorities. SaveTrustedCerts adds the given trusted CA TLS certificates and SSH host keys to the store. Existing TLS certificates for the given trusted certs will be overwritten, while host keys will be appended to existing entries.

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(key KeyIndex) error

UnloadKey will unload keys matching the given KeyIndex from the teleport ssh agent and 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 MFAAuthenticateChallenge

type MFAAuthenticateChallenge struct {
	// WebauthnChallenge contains a WebAuthn credential assertion used for
	// login/authentication ceremonies.
	WebauthnChallenge *wantypes.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.

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 MFAChallengeResponse

type MFAChallengeResponse struct {
	// TOTPCode is a code for a otp device.
	TOTPCode string `json:"totp_code,omitempty"`
	// WebauthnResponse is a response from a webauthn device.
	WebauthnResponse *wantypes.CredentialAssertionResponse `json:"webauthn_response,omitempty"`
}

MFAChallengeResponse holds the response to a MFA challenge.

func (*MFAChallengeResponse) GetOptionalMFAResponseProtoReq

func (r *MFAChallengeResponse) GetOptionalMFAResponseProtoReq() (*proto.MFAAuthenticateResponse, error)

GetOptionalMFAResponseProtoReq converts response to a type proto.MFAAuthenticateResponse, if there were any responses set. Otherwise returns nil.

type MFARegisterChallenge

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

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

type MFARequiredUnknownErr

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

MFARequiredUnknownErr indicates that connections to an instance failed due to being unable to determine if mfa is required

func (MFARequiredUnknownErr) Error

func (m MFARequiredUnknownErr) Error() string

Error returns the error string of the wrapped error if one exists.

func (MFARequiredUnknownErr) Is

func (m MFARequiredUnknownErr) Is(err error) bool

Is determines if the provided error is an MFARequiredUnknownErr.

func (MFARequiredUnknownErr) Unwrap

func (m MFARequiredUnknownErr) Unwrap() error

Unwrap returns the underlying error from checking if an mfa ceremony should have been performed.

type MemKeyStore

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

func NewMemKeyStore

func NewMemKeyStore() *MemKeyStore

func (*MemKeyStore) AddKey

func (ms *MemKeyStore) AddKey(key *Key) error

AddKey writes a key to the underlying key store.

func (*MemKeyStore) DeleteKey

func (ms *MemKeyStore) DeleteKey(idx KeyIndex) error

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

func (*MemKeyStore) DeleteKeys

func (ms *MemKeyStore) DeleteKeys() error

DeleteKeys removes all session keys.

func (*MemKeyStore) DeleteUserCerts

func (ms *MemKeyStore) 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 (*MemKeyStore) GetKey

func (ms *MemKeyStore) GetKey(idx KeyIndex, opts ...CertOption) (*Key, error)

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

func (*MemKeyStore) GetSSHCertificates

func (ms *MemKeyStore) GetSSHCertificates(proxyHost, username string) ([]*ssh.Certificate, error)

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

type MemProfileStore

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

MemProfileStore is an in-memory implementation of ProfileStore.

func NewMemProfileStore

func NewMemProfileStore() *MemProfileStore

NewMemProfileStore creates a new instance of MemProfileStore.

func (*MemProfileStore) CurrentProfile

func (ms *MemProfileStore) CurrentProfile() (string, error)

CurrentProfile returns the current profile.

func (*MemProfileStore) GetProfile

func (ms *MemProfileStore) GetProfile(profileName string) (*profile.Profile, error)

GetProfile returns the requested profile.

func (*MemProfileStore) ListProfiles

func (ms *MemProfileStore) ListProfiles() ([]string, error)

ListProfiles returns a list of all profiles.

func (*MemProfileStore) SaveProfile

func (ms *MemProfileStore) SaveProfile(profile *profile.Profile, makecurrent bool) error

SaveProfile saves the given profile. If makeCurrent is true, it makes this profile current.

type MemTrustedCertsStore

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

MemTrustedCertsStore is an in-memory implementation of TrustedCertsStore.

func NewMemTrustedCertsStore

func NewMemTrustedCertsStore() *MemTrustedCertsStore

NewMemTrustedCertsStore creates a new instance of MemTrustedCertsStore.

func (*MemTrustedCertsStore) GetTrustedCerts

func (ms *MemTrustedCertsStore) GetTrustedCerts(proxyHost string) ([]auth.TrustedCerts, error)

GetTrustedCerts gets the trusted CA TLS certificates and SSH host keys for the given proxyHost.

func (*MemTrustedCertsStore) GetTrustedCertsPEM

func (ms *MemTrustedCertsStore) GetTrustedCertsPEM(proxyHost string) ([][]byte, error)

GetTrustedCertsPEM gets trusted TLS certificates of certificate authorities. Each returned byte slice contains an individual PEM block.

func (*MemTrustedCertsStore) GetTrustedHostKeys

func (ms *MemTrustedCertsStore) GetTrustedHostKeys(hostnames ...string) ([]ssh.PublicKey, error)

GetTrustedHostKeys returns all trusted public host keys. If hostnames are provided, only matching host keys will be returned. Host names should be a proxy host or cluster name.

func (*MemTrustedCertsStore) SaveTrustedCerts

func (ms *MemTrustedCertsStore) SaveTrustedCerts(proxyHost string, cas []auth.TrustedCerts) 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

	// ProxyPublicAddr is the web proxy public addr, as opposed to the local proxy
	// addr set in TC.WebProxyAddr. This is needed to report the correct address
	// to SSH_TELEPORT_WEBPROXY_ADDR used by some features like "teleport status".
	ProxyPublicAddr string
	// contains filtered or unexported fields
}

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, nodeName string, tc *TeleportClient, fipsEnabled bool, opts ...NodeClientOption) (*NodeClient, error)

NewNodeClient constructs a NodeClient that is connected to the node at nodeAddress. The nodeName field is optional and is used only to present better error messages.

func (*NodeClient) AddCancel

func (c *NodeClient) AddCancel(cancel context.CancelFunc)

AddCancel adds a context.CancelFunc that will be canceled when the client is closed.

func (*NodeClient) AddCloser

func (c *NodeClient) AddCloser(closer io.Closer)

AddCloser adds an io.Closer that will be closed when the client is closed.

func (*NodeClient) AddEnv

func (c *NodeClient) AddEnv(key, value string)

AddEnv add environment variable to SSH session. This method needs to be called before the session is created.

func (*NodeClient) Close

func (c *NodeClient) Close() error

Close closes client and it's operations

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) RunCommand

func (c *NodeClient) RunCommand(ctx context.Context, command []string, opts ...RunCommandOption) error

RunCommand executes a given bash command on the node.

func (*NodeClient) RunInteractiveShell

func (c *NodeClient) RunInteractiveShell(ctx context.Context, mode types.SessionParticipantMode, sessToJoin types.SessionTracker, beforeStart func(io.Writer)) 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 NodeClientOption

type NodeClientOption func(nc *NodeClient)

NodeClientOption is a functional argument for NewNodeClient.

func WithNodeHostname

func WithNodeHostname(hostname string) NodeClientOption

WithNodeHostname sets the hostname to display for the connected node.

func WithSSHLogDir

func WithSSHLogDir(logDir string) NodeClientOption

WithSSHLogDir sets the directory to write command output to when running commands on multiple nodes.

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
	// contains filtered or unexported fields
}

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 PerformMFACeremonyParams

type PerformMFACeremonyParams struct {
	// CurrentAuthClient is the Auth client for the target cluster.
	// Unused if MFAAgainstRoot is true.
	CurrentAuthClient PerformMFACurrentClient
	// RootAuthClient is the Auth client for the root cluster.
	// This is the client used to acquire the authn challenge and issue the user
	// certificates.
	RootAuthClient PerformMFARootClient
	// MFAPrompt is used to prompt the user for an MFA solution.
	MFAPrompt mfa.Prompt

	// MFAAgainstRoot tells whether to run the MFA required check against root or
	// current cluster.
	MFAAgainstRoot bool
	// MFARequiredReq is the request for the MFA verification check.
	MFARequiredReq *proto.IsMFARequiredRequest
	// ChallengeExtensions is used to provide additional extensions to apply to the
	// MFA challenge used in the ceremony. The scope extension must be supplied.
	ChallengeExtensions mfav1.ChallengeExtensions
	// CertsReq is the request for new certificates.
	CertsReq *proto.UserCertsRequest

	// Key is the client key to add the new certificates to.
	// Optional.
	Key *Key
}

PerformMFACeremonyParams are the input parameters for PerformMFACeremony.

type PerformMFACurrentClient

type PerformMFACurrentClient interface {
	IsMFARequired(ctx context.Context, req *proto.IsMFARequiredRequest) (*proto.IsMFARequiredResponse, error)
}

PerformMFACurrentClient is a subset of Auth methods required for MFA. Used by PerformMFACeremony.

type PerformMFARootClient

type PerformMFARootClient interface {
	CreateAuthenticateChallenge(ctx context.Context, req *proto.CreateAuthenticateChallengeRequest) (*proto.MFAAuthenticateChallenge, error)
	GenerateUserCerts(ctx context.Context, req proto.UserCertsRequest) (*proto.Certs, error)
}

PerformMFARootClient is a subset of Auth methods required for MFA. Used by PerformMFACeremony.

type PresenceMaintainer

type PresenceMaintainer interface {
	MaintainSessionPresence(ctx context.Context) (proto.AuthService_MaintainSessionPresenceClient, error)
}

PresenceMaintainer allows maintaining presence with the Auth service.

type PresenceOption

type PresenceOption func(p *presenceOptions)

PresenceOption a functional option for RunPresenceTask.

func WithPresenceClock

func WithPresenceClock(clock clockwork.Clock) PresenceOption

WithPresenceClock sets the clock to be used by RunPresenceTask.

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

	// AzureIdentities is a list of allowed Azure identities user can assume.
	AzureIdentities []string

	// GCPServiceAccounts is a list of allowed GCP service accounts user can assume.
	GCPServiceAccounts []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 (*ProfileStatus) AccessInfo

func (p *ProfileStatus) AccessInfo() *services.AccessInfo

AccessInfo returns the complete services.AccessInfo for this profile.

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) DatabaseLocalCAPath

func (p *ProfileStatus) DatabaseLocalCAPath() string

DatabaseLocalCAPath returns the specified db 's self-signed localhost CA path for this profile.

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

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) KubeCertPathForCluster

func (p *ProfileStatus) KubeCertPathForCluster(teleportCluster, kubeCluster string) string

KubeCertPathForCluster returns path to the specified kube access certificate for this profile, for the specified cluster name.

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

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

func (*ProfileStatus) OracleWalletDir

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

OracleWalletDir 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>/dbname-wallet/

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

type ProfileStore

type ProfileStore interface {
	// CurrentProfile returns the current profile.
	CurrentProfile() (string, error)

	// ListProfiles returns a list of all profiles.
	ListProfiles() ([]string, error)

	// GetProfile returns the requested profile.
	GetProfile(profileName string) (*profile.Profile, error)

	// SaveProfile saves the given profile. If makeCurrent
	// is true, it makes this profile current.
	SaveProfile(profile *profile.Profile, setCurrent bool) error
}

ProfileStore is a storage interface for client profile data.

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 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) (*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) CreateAccessRequestV2

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

CreateAccessRequestV2 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) 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) GetAppSession

func (proxy *ProxyClient) GetAppSession(ctx context.Context, req types.GetAppSessionRequest) (types.WebSession, error)

GetAppSession creates a new application access session.

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, mfaPrompt mfa.Prompt, applyOpts ...IssueUserCertsOpt) (*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
	// See [proto.UserCertsRequest.DropAccessRequests].
	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
	// RequesterName identifies who is sending the cert reissue request.
	RequesterName proto.UserCertsRequest_Requester
}

ReissueParams encodes optional parameters for user certificate reissue.

type RetryWithReloginOption

type RetryWithReloginOption func(*retryWithReloginOptions)

RetryWithReloginOption is a functional option for configuring the RetryWithRelogin helper.

func WithBeforeLoginHook

func WithBeforeLoginHook(fn func() error) RetryWithReloginOption

WithBeforeLogin is a functional option for configuring a function that will be called before the login attempt.

type RunCommandOption

type RunCommandOption func(opts *RunCommandOptions)

RunCommandOption is a functional argument for NodeClient.RunCommand.

func WithLabeledOutput

func WithLabeledOutput() RunCommandOption

WithLabeledOutput labels each line of output from a command with the node's hostname.

type RunCommandOptions

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

RunCommandOptions is a set of options for NodeClient.RunCommand.

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 certificate 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
	// ExtraHeaders is a map of extra HTTP headers to be included in requests.
	ExtraHeaders map[string]string
}

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 SSHLoginHeadless

type SSHLoginHeadless struct {
	SSHLogin

	// User is the login username.
	User string

	// HeadlessAuthenticationID is a headless authentication request ID.
	HeadlessAuthenticationID string
}

type SSHLoginMFA

type SSHLoginMFA struct {
	SSHLogin
	// PromptMFA is a customizable MFA prompt function.
	// Defaults to [mfa.NewPrompt().Run]
	PromptMFA mfa.Prompt
	// User is the login username.
	User string
	// Password is the login password.
	Password string
}

SSHLoginMFA contains SSH login parameters for MFA login.

type SSHLoginPasswordless

type SSHLoginPasswordless struct {
	SSHLogin

	// WebauthnLogin is a customizable webauthn login function.
	// Defaults to [wancli.Login]
	WebauthnLogin WebauthnLoginFunc

	// 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
	// CallbackAddr is the optional base URL to give to the user when performing
	// SSO redirect flows.
	CallbackAddr 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 SSHOptions

type SSHOptions struct {
	// HostAddress is the address of the target host. If specified it
	// will be used instead of the target provided when `tsh ssh` was invoked.
	HostAddress string
}

SSHOptions allow overriding configuration used when connecting to a host via TeleportClient.SSH.

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 Store

type Store struct {
	KeyStore
	TrustedCertsStore
	ProfileStore
	// contains filtered or unexported fields
}

Store is a storage interface for client data. Store is made up of three partial data stores; KeyStore, TrustedCertsStore, and ProfileStore.

A Store can be made up of partial data stores with different backends. For example, when using `tsh --add-keys-to-agent=only`, Store will be made up of an in-memory key store and an FS (~/.tsh) profile and trusted certs store.

func NewFSClientStore

func NewFSClientStore(dirPath string) *Store

NewMemClientStore initializes an FS backed client store with the given base dir.

func NewMemClientStore

func NewMemClientStore() *Store

NewMemClientStore initializes a new in-memory client store.

func (*Store) AddKey

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

AddKey adds the given key to the key store. The key's trusted certificates are added to the trusted certs store.

func (*Store) AddTrustedHostKeys

func (s *Store) AddTrustedHostKeys(proxyHost string, clusterName string, hostKeys ...ssh.PublicKey) error

AddTrustedHostKeys is a helper function to add ssh host keys directly, rather than through SaveTrustedCerts.

func (*Store) FullProfileStatus

func (s *Store) FullProfileStatus() (*ProfileStatus, []*ProfileStatus, error)

FullProfileStatus returns the name of the current profile with a a list of all profile statuses.

func (*Store) GetKey

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

GetKey gets the requested key with trusted the requested certificates. The key's trusted certs will be retrieved from the trusted certs store. If the key is not found or is missing data (certificates, etc.), then an ErrNoCredentials error is returned.

func (*Store) ReadProfileStatus

func (s *Store) ReadProfileStatus(profileName string) (*ProfileStatus, error)

ReadProfileStatus returns the profile status for the given profile name. If no profile name is provided, return the current profile.

type TOTPRegisterChallenge

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

TOTPRegisterChallenge contains a TOTP challenge.

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) 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) AttemptDeviceLogin

func (tc *TeleportClient) AttemptDeviceLogin(ctx context.Context, key *Key, rootAuthClient auth.ClientI) error

AttemptDeviceLogin attempts device authentication for the current device. It expects to receive the latest activated key, as acquired via TeleportClient.Login, and augments the certificates within the key with device extensions.

If successful, the new device certificates are automatically activated.

A nil response from this method doesn't mean that device authentication was successful, as skipping the ceremony is valid for various reasons (Teleport cluster doesn't support device authn, device wasn't enrolled, etc). Use TeleportClient.DeviceLogin if you want more control over process.

func (*TeleportClient) ConnectToCluster

func (tc *TeleportClient) ConnectToCluster(ctx context.Context) (_ *ClusterClient, err error)

ConnectToCluster will dial the auth and proxy server and return a ClusterClient when successful.

func (*TeleportClient) ConnectToNode

func (tc *TeleportClient) ConnectToNode(ctx context.Context, clt *ClusterClient, nodeDetails NodeDetails, user string) (_ *NodeClient, err error)

ConnectToNode attempts to establish a connection to the node resolved to by the provided NodeDetails. Connecting is attempted both with the already provisioned certificates and if per session mfa is required, after completing the mfa ceremony. In the event that both fail the error from the connection attempt with the already provisioned certificates will be returned. The client from whichever attempt succeeds first will be 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) ConnectToRootCluster

func (tc *TeleportClient) ConnectToRootCluster(ctx context.Context, key *Key) (*ClusterClient, auth.ClientI, error)

ConnectToRootCluster activates the provided key and connects to the root cluster with its credentials.

func (*TeleportClient) CreateAccessRequestV2

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

CreateAccessRequestV2 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) DeviceLogin

func (tc *TeleportClient) DeviceLogin(ctx context.Context, rootAuthClient auth.ClientI, certs *devicepb.UserCertificates) (*devicepb.UserCertificates, error)

DeviceLogin attempts to authenticate the current device with Teleport.

The device must be previously registered and enrolled for the authentication to succeed (see `tsh device enroll`). Alternatively, if the cluster supports auto-enrollment, then DeviceLogin will attempt to auto-enroll the device on certain failures and login again.

DeviceLogin may fail for a variety of reasons, some of them legitimate (non-Enterprise cluster, Device Trust is disabled, etc). Because of that, a failure in this method may not warrant failing a broader action (for example, `tsh login`).

Device Trust is a Teleport Enterprise feature.

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) 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) GetAppSession

GetAppSession returns an existing application access session.

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) (priv *keys.PrivateKey, err 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) 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) HeadlessApprove

func (tc *TeleportClient) HeadlessApprove(ctx context.Context, headlessAuthenticationID string, confirm bool) error

HeadlessApprove handles approval of a headless authentication request.

func (*TeleportClient) IsALPNConnUpgradeRequiredForWebProxy

func (tc *TeleportClient) IsALPNConnUpgradeRequiredForWebProxy(ctx context.Context, proxyAddr string) bool

IsALPNConnUpgradeRequiredForWebProxy returns true if connection upgrade is required for provided addr. The provided address must be a web proxy address.

func (*TeleportClient) IssueUserCertsWithMFA

func (tc *TeleportClient) IssueUserCertsWithMFA(ctx context.Context, params ReissueParams, mfaPromptOpts ...mfa.PromptOpt) (*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 all nodes that match the filters in the current cluster that the logged in user has access to.

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(ctx context.Context, 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) LoadTLSConfig

func (tc *TeleportClient) LoadTLSConfig() (*tls.Config, error)

LoadTLSConfig returns the user's TLS configuration, either from static configuration or from its key store.

func (*TeleportClient) LoadTLSConfigForClusters

func (tc *TeleportClient) LoadTLSConfigForClusters(clusters []string) (*tls.Config, error)

LoadTLSConfigForClusters returns the client's TLS configuration, either from static configuration or from its key store. If loaded from the key store, CA certs will be loaded for the given clusters only.

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 ConnectToRootCluster in order to

update the local agent state and create an initial connection to the cluster.

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) LoginWeb

func (tc *TeleportClient) LoginWeb(ctx context.Context) (*WebClient, types.WebSession, error)

LoginWeb logs the user in via the Teleport web api the same way that the web UI does.

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) NewKubernetesServiceClient

func (tc *TeleportClient) NewKubernetesServiceClient(ctx context.Context, clusterName string) (kubeproto.KubeServiceClient, error)

NewKubernetesServiceClient connects to the proxy and returns an authenticated gRPC client to the Kubernetes service.

func (*TeleportClient) NewMFAPrompt

func (tc *TeleportClient) NewMFAPrompt(opts ...mfa.PromptOpt) mfa.Prompt

NewMFAPrompt creates a new MFA prompt from client settings.

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, sessionID string, speed float64) error

Play replays the recorded session.

func (*TeleportClient) ProfileStatus

func (tc *TeleportClient) ProfileStatus() (*ProfileStatus, error)

func (*TeleportClient) PromptMFA

PromptMFA runs a standard MFA prompt from client settings.

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) RootClusterCACertPool

func (tc *TeleportClient) RootClusterCACertPool(ctx context.Context) (*x509.CertPool, error)

RootClusterCACertPool returns a *x509.CertPool with the root cluster CA.

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, opts ...func(*SSHOptions)) 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, getter services.AuthorityGetter) 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 TrustedCertsStore

type TrustedCertsStore interface {
	// SaveTrustedCerts adds the given trusted CA TLS certificates and SSH host keys to the store.
	// Existing TLS certificates for the given trusted certs will be overwritten, while host keys
	// will be appended to existing entries.
	SaveTrustedCerts(proxyHost string, cas []auth.TrustedCerts) error

	// GetTrustedCerts gets the trusted CA TLS certificates and SSH host keys for the given proxyHost.
	GetTrustedCerts(proxyHost string) ([]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)

	// GetTrustedHostKeys returns all trusted public host keys. If hostnames are provided, only
	// matching host keys will be returned. Host names should be a proxy host or cluster name.
	GetTrustedHostKeys(hostnames ...string) ([]ssh.PublicKey, error)
}

TrustedCertsStore is a storage interface for trusted CA certificates and public keys.

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 SSHAgentLoginWeb

func SSHAgentLoginWeb(ctx context.Context, login SSHLoginDirect) (*WebClient, types.WebSession, error)

SSHAgentLoginWeb is used by tsh to fetch local user credentials via the web api.

func SSHAgentMFAWebSessionLogin

func SSHAgentMFAWebSessionLogin(ctx context.Context, login SSHLoginMFA) (*WebClient, types.WebSession, error)

SSHAgentMFAWebSessionLogin requests a MFA challenge via the proxy web api. 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.

func SSHAgentPasswordlessLoginWeb

func SSHAgentPasswordlessLoginWeb(ctx context.Context, login SSHLoginPasswordless) (*WebClient, types.WebSession, error)

SSHAgentPasswordlessLoginWeb requests a passwordless MFA challenge via the proxy web api.

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 WebLoginFunc

type WebLoginFunc func(context.Context, *keys.PrivateKey) (*WebClient, types.WebSession, error)

WebLoginFunc is a function which carries out authn with the web server and returns a web session and cookies.

type WebauthnLoginFunc

type WebauthnLoginFunc func(ctx context.Context, origin string, assertion *wantypes.CredentialAssertion, prompt wancli.LoginPrompt, opts *wancli.LoginOpts) (*proto.MFAAuthenticateResponse, string, error)

WebauthnLoginFunc matches the signature of wancli.Login.

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