client

package
v4.0.0-rc.1+incompatible Latest Latest
Warning

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

Go to latest
Published: May 21, 2019 License: Apache-2.0 Imports: 57 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ProfileCreateNew creates new profile, but does not update current profile
	ProfileCreateNew = 0
	// ProfileMakeCurrent creates a new profile and makes it current
	ProfileMakeCurrent = 1 << iota
)
View Source
const (
	// HTTPS is https prefix
	HTTPS = "https"
	// WSS is secure web sockets prefix
	WSS = "wss"
)
View Source
const CurrentProfileSymlink = "profile"

CurrentProfileSymlink is a filename which is a symlink to the current profile, usually something like this:

~/.tsh/profile -> ~/.tsh/staging.yaml

View Source
const (
	// ProfileDir is a directory location where tsh profiles (and session keys) are stored
	ProfileDir = ".tsh"
)

Variables

This section is empty.

Functions

func FullProfilePath added in v1.2.6

func FullProfilePath(pDir string) string

FullProfilePath returns the full path to the user profile directory. If the parameter is empty, it returns expanded "~/.tsh", otherwise returns its unmodified parameter

func GetTokenFromHOTPMockFile

func GetTokenFromHOTPMockFile(path string) (token string, e error)

GetTokenFromHOTPMockFile opens HOTPMock from file, gets token value, increases hotp and saves it to the file. Returns hotp token value.

func HostCredentials

func HostCredentials(ctx context.Context, proxyAddr string, insecure bool, req auth.RegisterUsingTokenRequest) (*auth.PackedKeys, 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 MakeIdentityFile

func MakeIdentityFile(filePath string, key *Key, format IdentityFileFormat, certAuthorities []services.CertAuthority) (err error)

MakeIdentityFile takes a username + their credentials and saves them to disk in a specified format

func NewInsecureWebClient

func NewInsecureWebClient() *http.Client

func ParseLabelSpec added in v1.0.0

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 ProxyHost

func ProxyHost(proxyHost string) string

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

func RetryWithRelogin

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

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

func SSHAgentLogin

func SSHAgentLogin(ctx context.Context, proxyAddr string, user string, password string, otpToken string, pubKey []byte, ttl time.Duration, insecure bool, pool *x509.CertPool, compatibility string) (*auth.SSHLoginResponse, error)

SSHAgentLogin is used by tsh to fetch local user credentials.

func SSHAgentSSOLogin

func SSHAgentSSOLogin(login SSHLogin) (*auth.SSHLoginResponse, error)

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

func SSHAgentU2FLogin

func SSHAgentU2FLogin(ctx context.Context, proxyAddr, user, password string, pubKey []byte, ttl time.Duration, insecure bool, pool *x509.CertPool, compatibility string) (*auth.SSHLoginResponse, error)

SSHAgentU2FLogin requests a U2F sign request (authentication challenge) via the proxy. If the credentials are valid, the proxy wiil return a challenge. We then call the official u2f-host binary to perform the signing and pass the signature to the proxy. If the authentication succeeds, we will get a temporary certificate back.

func Status

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

Status returns the active profile as well as a list of available profiles.

func UnlinkCurrentProfile added in v1.3.0

func UnlinkCurrentProfile() error

If there's a current profile symlink, remove it

func Username added in v1.0.0

func Username() (string, error)

Username returns the current user's username

Types

type AuthenticationSettings

type AuthenticationSettings struct {
	// Type is the type of authentication, can be either local or oidc.
	Type string `json:"type"`
	// SecondFactor is the type of second factor to use in authentication.
	// Supported options are: off, otp, and u2f.
	SecondFactor string `json:"second_factor,omitempty"`
	// U2F contains the Universal Second Factor settings needed for authentication.
	U2F *U2FSettings `json:"u2f,omitempty"`
	// OIDC contains OIDC connector settings needed for authentication.
	OIDC *OIDCSettings `json:"oidc,omitempty"`
	// SAML contains SAML connector settings needed for authentication.
	SAML *SAMLSettings `json:"saml,omitempty"`
	// Github contains Github connector settings needed for authentication.
	Github *GithubSettings `json:"github,omitempty"`
}

PingResponse contains the form of authentication the auth server supports.

type Benchmark

type Benchmark struct {
	// Threads is amount of concurrent execution threads to run
	Threads int
	// Rate is requests per second origination rate
	Rate int
	// Duration is test duration
	Duration time.Duration
	// Command is a command to run
	Command []string
	// Interactive turns on interactive sessions
	Interactive bool
}

Benchmark specifies benchmark requests to run

type BenchmarkResult

type BenchmarkResult struct {
	// RequestsOriginated is amount of reuqests originated
	RequestsOriginated int
	// RequestsFailed is amount of requests failed
	RequestsFailed int
	// Histogram is a duration histogram
	Histogram *hdrhistogram.Histogram
	// LastError contains last recorded error
	LastError error
}

BenchmarkResult is a result of the benchmark

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 CertAuthMethod

type CertAuthMethod struct {
	ssh.AuthMethod
	Cert ssh.Signer
}

CertAuthMethod is a wrapper around ssh.Signer (certificate signer) object. CertAuthMethod then implements ssh.Authmethod interface around this one certificate signer.

We need this wrapper because Golang's SSH library's unfortunate API design. It uses callbacks with 'authMethod' interfaces and without this wrapper it is impossible to tell which certificate an 'authMethod' passed via a callback had succeeded authenticating with.

func NewAuthMethodForCert

func NewAuthMethodForCert(cert ssh.Signer) *CertAuthMethod

type ClientProfile added in v1.2.6

type ClientProfile struct {
	// WebProxyAddr is the host:port the web proxy can be accessed at.
	WebProxyAddr string `yaml:"web_proxy_addr,omitempty"`

	// SSHProxyAddr is the host:port the SSH proxy can be accessed at.
	SSHProxyAddr string `yaml:"ssh_proxy_addr,omitempty"`

	// KubeProxyAddr is the host:port the Kubernetes proxy can be accessed at.
	KubeProxyAddr string `yaml:"kube_proxy_addr,omitempty"`

	// Username is the Teleport username for the client.
	Username string `yaml:"user,omitempty"`

	// AuthType (like "google")
	AuthType string `yaml:"auth_type,omitempty"`

	// SiteName is equivalient to --cluster argument
	SiteName string `yaml:"cluster,omitempty"`

	// ForwardedPorts is the list of ports to forward to the target node.
	ForwardedPorts []string `yaml:"forward_ports,omitempty"`

	// DynamicForwardedPorts is a list of ports to use for dynamic port
	// forwarding (SOCKS5).
	DynamicForwardedPorts []string `yaml:"dynamic_forward_ports,omitempty"`

	// DELETE IN: 3.1.0
	// The following fields have been deprecated and replaced with
	// "proxy_web_addr" and "proxy_ssh_addr".
	ProxyHost    string `yaml:"proxy_host,omitempty"`
	ProxySSHPort int    `yaml:"proxy_port,omitempty"`
	ProxyWebPort int    `yaml:"proxy_web_port,omitempty"`
}

ClientProfile is a collection of most frequently used CLI flags for "tsh".

Profiles can be stored in a profile file, allowing TSH users to type fewer CLI args.

func ProfileFromDir added in v1.2.6

func ProfileFromDir(dirPath string, proxyName string) (*ClientProfile, error)

ProfileFromDir reads the user (yaml) profile from a given directory. The default is to use the ~/<dir-path>/profile symlink unless another profile is explicitly asked for. It works by looking for a "profile" symlink in that directory pointing to the profile's YAML file first.

func ProfileFromFile added in v1.2.6

func ProfileFromFile(filePath string) (*ClientProfile, error)

ProfileFromFile loads the profile from a YAML file

func (*ClientProfile) Name

func (c *ClientProfile) Name() string

Name returns the name of the profile.

func (*ClientProfile) SaveTo added in v1.2.6

func (cp *ClientProfile) SaveTo(loc ProfileLocation) error

SaveTo saves the profile into a given filename, optionally overwriting it.

type Config added in v1.0.0

type Config struct {
	// Username is the Teleport account username (for logging into Teleport proxies)
	Username string

	// Remote host to connect
	Host string

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

	// Namespace is nodes namespace
	Namespace string

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Config is a client config

func MakeDefaultConfig added in v1.2.6

func MakeDefaultConfig() *Config

MakeDefaultConfig returns default client config

func (*Config) KubeProxyHostPort

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

KubeProxyHostPort returns the host and port of the Kubernetes proxy.

func (*Config) LoadProfile added in v1.2.6

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

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

func (*Config) 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) ProxySpecified added in v1.0.0

func (c *Config) ProxySpecified() bool

ProxySpecified returns true if proxy has been specified.

func (*Config) SSHProxyHostPort

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

SSHProxyHostPort returns the host and port of the SSH proxy.

func (*Config) SaveProfile added in v1.2.6

func (c *Config) SaveProfile(profileAliasHost, profileDir string, profileOptions ...ProfileOptions) error

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

func (*Config) WebProxyHostPort

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

WebProxyHostPort returns the host and 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"`
	// HOTPToken is second factor token
	// Deprecated: HOTPToken is deprecated, use OTPToken.
	HOTPToken string `json:"hotp_token"`
	// OTPToken is second factor token
	OTPToken string `json:"otp_token"`
	// PubKey is a public key user wishes to sign
	PubKey []byte `json:"pub_key"`
	// TTL is a desired TTL for the cert (max is still capped by server,
	// however user can shorten the time)
	TTL time.Duration `json:"ttl"`
	// Compatibility specifies OpenSSH compatibility flags.
	Compatibility string `json:"compatibility,omitempty"`
}

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

type CreateSSHCertWithU2FReq

type CreateSSHCertWithU2FReq struct {
	// User is a teleport username
	User string `json:"user"`
	// We only issue U2F sign requests after checking the password, so there's no need to check again.
	// U2FSignResponse is the signature from the U2F device
	U2FSignResponse u2f.SignResponse `json:"u2f_sign_response"`
	// 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"`
}

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

type DynamicForwardedPort

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

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

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

func (*DynamicForwardedPort) ToString

func (p *DynamicForwardedPort) ToString() string

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

type DynamicForwardedPorts

type DynamicForwardedPorts []DynamicForwardedPort

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

func ParseDynamicPortForwardSpec

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

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

func (DynamicForwardedPorts) String

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

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

type FSLocalKeyStore added in v1.0.0

type FSLocalKeyStore struct {

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

FSLocalKeyStore implements LocalKeyStore interface using the filesystem. Here's the file layout for the FS store:

~/.tsh/ ├── known_hosts --> trusted certificate authorities (their keys) in a format similar to known_hosts └── keys    ├── one.example.com    │   ├── certs.pem    │   ├── foo --> RSA Private Key    │   ├── foo-cert.pub --> SSH certificate for proxies and nodes    │   ├── foo.pub --> Public Key    │   └── foo-x509.pem --> TLS client certificate for Auth Server    └── two.example.com    ├── certs.pem    ├── bar    ├── bar-cert.pub    ├── bar.pub    └── bar-x509.pem

func NewFSLocalKeyStore added in v1.0.0

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

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

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

func (*FSLocalKeyStore) AddKey added in v1.0.0

func (fs *FSLocalKeyStore) AddKey(host, username string, key *Key) error

AddKey adds a new key to the session store. If a key for the host is already stored, overwrites it.

func (*FSLocalKeyStore) AddKnownHostKeys added in v1.0.0

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

AddKnownHostKeys adds a new entry to 'known_hosts' file

func (*FSLocalKeyStore) DeleteKey added in v1.0.0

func (fs *FSLocalKeyStore) DeleteKey(host string, username string) error

DeleteKey deletes a key from the local store

func (*FSLocalKeyStore) DeleteKeys

func (fs *FSLocalKeyStore) DeleteKeys() error

DeleteKeys removes all session keys from disk.

func (*FSLocalKeyStore) GetCerts

func (fs *FSLocalKeyStore) GetCerts(proxy string) (*x509.CertPool, error)

GetCerts returns trusted TLS certificates of certificate authorities

func (*FSLocalKeyStore) GetCertsPEM

func (fs *FSLocalKeyStore) GetCertsPEM(proxy string) ([]byte, error)

GetCertsPEM returns trusted TLS certificates of certificate authorities PEM block

func (*FSLocalKeyStore) GetKey added in v1.0.0

func (fs *FSLocalKeyStore) GetKey(proxyHost string, username string) (*Key, error)

GetKey returns a key for a given host. If the key is not found, returns trace.NotFound error.

func (*FSLocalKeyStore) GetKnownHostKeys added in v1.0.0

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

GetKnownHostKeys returns all known public keys from 'known_hosts'

func (*FSLocalKeyStore) SaveCerts

func (fs *FSLocalKeyStore) SaveCerts(proxy string, cas []auth.TrustedCerts) error

SaveCerts saves trusted TLS certificates of certificate authorities

type ForwardedPort added in v1.0.0

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 added in v1.2.6

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 added in v1.2.6

type ForwardedPorts []ForwardedPort

func ParsePortForwardSpec added in v1.1.0

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 GithubSettings

type GithubSettings struct {
	// Name is the internal name of the connector
	Name string `json:"name"`
	// Display is the connector display name
	Display string `json:"display"`
}

GithubSettings contains the Name and Display string for Github connector.

type HOTPMock

type HOTPMock struct {
	*hotp.HOTP
}

HOTPMock is a HOTP that can be saved or load from file Using HOTPMock disables the hotp security level, don't use it in production

func CreateHOTPMock

func CreateHOTPMock(hotpURLString string) (*HOTPMock, error)

func LoadHOTPMockFromFile

func LoadHOTPMockFromFile(path string) (*HOTPMock, error)

func (*HOTPMock) SaveToFile

func (otp *HOTPMock) SaveToFile(path string) error

type HostKeyCallback added in v1.0.0

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 IdentityFileFormat

type IdentityFileFormat string

IdentityFileFormat describes possible file formats how a user identity can be sotred

const (
	// IdentityFormatFile is when a key + cert are stored concatenated into a single file
	IdentityFormatFile IdentityFileFormat = "file"

	// IdentityFormatOpenSSH is OpenSSH-compatible format, when a key and a cert are stored in
	// two different files (in the same directory)
	IdentityFormatOpenSSH IdentityFileFormat = "openssh"

	// DefaultIdentityFormat is what Teleport uses by default
	DefaultIdentityFormat = IdentityFormatFile
)

type Key

type Key struct {
	// Priv is a PEM encoded private key
	Priv []byte `json:"Priv,omitempty"`
	// Pub is a public key
	Pub []byte `json:"Pub,omitempty"`
	// Cert is an SSH client certificate
	Cert []byte `json:"Cert,omitempty"`
	// TLSCert is a PEM encoded client TLS x509 certificate
	TLSCert []byte `json:"TLSCert,omitempty"`

	// ProxyHost (optionally) contains the hostname of the proxy server
	// which issued this key
	ProxyHost string

	// TrustedCA is a list of trusted certificate authorities
	TrustedCA []auth.TrustedCerts

	// ClusterName is a cluster name this key is associated with
	ClusterName string
}

Key describes a complete (signed) client key

func NewKey

func NewKey() (key *Key, err error)

NewKey generates a new unsigned key. Such key must be signed by a Teleport CA (auth server) before it becomes useful.

func (*Key) AsAgentKeys

func (k *Key) AsAgentKeys() ([]*agent.AddedKey, error)

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

func (*Key) AsAuthMethod

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

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

func (*Key) CertPrincipals

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

CertPrincipals returns the principals listed on the SSH certificate.

func (*Key) CertUsername

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

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

func (*Key) CertValidBefore added in v1.0.0

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 SSH certificate is valid.

func (*Key) ClientTLSConfig

func (k *Key) ClientTLSConfig() (*tls.Config, error)

TLSConfig returns client TLS configuration used to authenticate against API servers

func (*Key) EqualsTo

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

EqualsTo returns true if this key is the same as the other. Primarily used in tests

func (*Key) TLSCertValidBefore

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

TLSCertValidBefore returns the time of the TLS cert expiration

type KubeProxySettings

type KubeProxySettings struct {
	// Enabled is true when kubernetes proxy is enabled
	Enabled bool `json:"enabled,omitempty"`
	// PublicAddr is a kubernetes proxy public address if set
	PublicAddr string `json:"public_addr,omitempty"`
}

KubeProxySettings is kubernetes proxy settings

type LocalKeyAgent added in v1.0.0

type LocalKeyAgent struct {

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

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

func NewLocalAgent added in v1.0.0

func NewLocalAgent(keyDir string, proxyHost string, username string) (a *LocalKeyAgent, err error)

NewLocalAgent reads all Teleport certificates from disk (using FSLocalKeyStore), creates a LocalKeyAgent, loads all certificates into it, and returns the agent.

func (*LocalKeyAgent) AddHostSignersToCache added in v1.0.0

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

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

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

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

func (*LocalKeyAgent) AddKey added in v1.0.0

func (a *LocalKeyAgent) AddKey(key *Key) (*agent.AddedKey, 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) AuthMethods

func (a *LocalKeyAgent) AuthMethods() (m []ssh.AuthMethod)

AuthMethods returns the list of different authentication methods this agent supports It returns two:

  1. First to try is the external SSH agent
  2. Itself (disk-based local agent)

func (*LocalKeyAgent) CheckHostSignature added in v1.0.0

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

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

func (*LocalKeyAgent) DeleteKey added in v1.0.0

func (a *LocalKeyAgent) DeleteKey() error

DeleteKey removes the key from the key store as well as unloading 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) GetCerts

func (a *LocalKeyAgent) GetCerts() (*x509.CertPool, error)

func (*LocalKeyAgent) GetCertsPEM

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

func (*LocalKeyAgent) GetKey

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

GetKey returns the key for this user in a proxy from the filesystem keystore at ~/.tsh.

func (*LocalKeyAgent) LoadKey

func (a *LocalKeyAgent) LoadKey(key Key) (*agent.AddedKey, error)

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

func (*LocalKeyAgent) SaveCerts

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

func (*LocalKeyAgent) UnloadKey

func (a *LocalKeyAgent) UnloadKey() error

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

func (*LocalKeyAgent) UnloadKeys

func (a *LocalKeyAgent) UnloadKeys() error

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

func (*LocalKeyAgent) UpdateProxyHost

func (a *LocalKeyAgent) UpdateProxyHost(proxyHost string)

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

func (*LocalKeyAgent) UserRefusedHosts

func (a *LocalKeyAgent) UserRefusedHosts() bool

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

type LocalKeyStore added in v1.0.0

type LocalKeyStore interface {
	// AddKey adds the given session key for the proxy and username to the
	// storage backend.
	AddKey(proxy string, username string, key *Key) error

	// GetKey returns the session key for the given username and proxy.
	GetKey(proxy string, username string) (*Key, error)

	// DeleteKey removes a specific session key from a proxy.
	DeleteKey(proxyHost string, username string) error

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

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

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

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

	// GetCerts gets trusted TLS certificates of certificate authorities.
	GetCerts(proxy string) (*x509.CertPool, error)

	// GetCertsPEM gets trusted TLS certificates of certificate authorities.
	GetCertsPEM(proxy string) ([]byte, error)
}

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

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

type NodeClient

type NodeClient struct {
	Namespace string
	Client    *ssh.Client
	Proxy     *ProxyClient
	TC        *TeleportClient
}

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 (*NodeClient) Close

func (client *NodeClient) Close() error

Close closes client and it's operations

func (*NodeClient) ExecuteSCP

func (client *NodeClient) ExecuteSCP(cmd scp.Command) error

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

type NodeSession added in v1.1.0

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 OIDCSettings

type OIDCSettings struct {
	// Name is the internal name of the connector.
	Name string `json:"name"`
	// Display is the display name for the connector.
	Display string `json:"display"`
}

OIDCSettings contains the Name and Display string for OIDC.

type PingResponse

type PingResponse struct {
	// Auth contains the forms of authentication the auth server supports.
	Auth AuthenticationSettings `json:"auth"`
	// Proxy contains the proxy settings.
	Proxy ProxySettings `json:"proxy"`
	// ServerVersion is the version of Teleport that is running.
	ServerVersion string `json:"server_version"`
	// MinClientVersion is the minimum client version required by the server.
	MinClientVersion string `json:"min_client_version"`
}

PingResponse contains data about the Teleport server like supported authentication types, server version, etc.

func Find

func Find(ctx context.Context, proxyAddr string, insecure bool, pool *x509.CertPool) (*PingResponse, error)

Find is like ping, but used by servers to only fetch discovery data, without auth connector data, it is designed for servers in IOT mode to fetch proxy public addresses on a large scale.

func Ping

func Ping(ctx context.Context, proxyAddr string, insecure bool, pool *x509.CertPool, connectorName string) (*PingResponse, error)

Ping serves two purposes. The first is to validate the HTTP endpoint of a Teleport proxy. This leads to better user experience: users get connection errors before being asked for passwords. The second is to return the form of authentication that the server supports. This also leads to better user experience: users only get prompted for the type of authentication the server supports.

type ProfileLocation

type ProfileLocation struct {
	// AliasPath is an optional alias
	AliasPath string
	// Path is a profile file path on disk
	Path string
	// Options is a set of profile options
	Options ProfileOptions
}

ProfileLocation specifies profile on -disk location and it's parameters on disk

type ProfileOptions added in v1.2.6

type ProfileOptions int

type ProfileStatus

type ProfileStatus struct {
	// 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

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

	// Cluster is a selected cluster
	Cluster string
}

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

func (*ProfileStatus) IsExpired

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

IsExpired returns true if profile is not expired yet

type ProxyClient

type ProxyClient struct {
	Client *ssh.Client
	// 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

func (*ProxyClient) ClusterAccessPoint

func (proxy *ProxyClient) ClusterAccessPoint(ctx context.Context, clusterName string, quiet bool) (auth.AccessPoint, error)

ClusterAccessPoint returns cluster access point used for discovery and could be cached based on the access policy

func (*ProxyClient) ConnectToCluster

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

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

if 'quiet' is set to true, no errors will be printed to stdout, otherwise any connection errors are visible to a user.

func (*ProxyClient) ConnectToCurrentCluster

func (proxy *ProxyClient) ConnectToCurrentCluster(ctx context.Context, quiet bool) (auth.ClientI, error)

ConnectToCurrentCluster connects to the auth server of the currently selected cluster via proxy. It returns connected and authenticated auth server client

if 'quiet' is set to true, no errors will be printed to stdout, otherwise any connection errors are visible to a user.

func (*ProxyClient) ConnectToNode

func (proxy *ProxyClient) ConnectToNode(ctx context.Context, nodeAddress string, user string, quiet bool) (*NodeClient, error)

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

func (*ProxyClient) CurrentClusterAccessPoint

func (proxy *ProxyClient) CurrentClusterAccessPoint(ctx context.Context, quiet bool) (auth.AccessPoint, error)

CurrentClusterAccessPoint returns cluster access point to the currently selected cluster and is used for discovery and could be cached based on the access policy

func (*ProxyClient) FindServersByLabels added in v1.0.0

func (proxy *ProxyClient) FindServersByLabels(ctx context.Context, namespace string, labels map[string]string) ([]services.Server, error)

FindServersByLabels returns list of the nodes which have labels exactly matching the given label set.

A server is matched when ALL labels match. If no labels are passed, ALL nodes are returned.

func (*ProxyClient) GetSites added in v1.0.0

func (proxy *ProxyClient) GetSites() ([]services.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

type ProxySettings

type ProxySettings struct {
	// Kube is a kubernetes specific proxy section
	Kube KubeProxySettings `json:"kube"`
	// SSH is SSH specific proxy settings
	SSH SSHProxySettings `json:"ssh"`
}

ProxySettings contains basic information about proxy settings

type Redirector

type Redirector struct {
	// SSHLogin contains SSH login parameters
	SSHLogin
	// contains filtered or unexported fields
}

Redirector handles SSH redirect flow with the Teleport server

func NewRedirector

func NewRedirector(login SSHLogin) (*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 SAMLSettings

type SAMLSettings struct {
	// Name is the internal name of the connector.
	Name string `json:"name"`
	// Display is the display name for the connector.
	Display string `json:"display"`
}

SAMLSettings contains the Name and Display string for SAML

type SSHLogin

type SSHLogin struct {
	// Context is an external context
	Context context.Context
	// ProxyAddr is the target proxy address
	ProxyAddr string
	// ConnectorID is the OIDC or SAML connector ID to use
	ConnectorID string
	// PubKey is SSH public key to sign
	PubKey []byte
	// TTL is requested TTL of the client certificates
	TTL time.Duration
	// Insecure turns off verification for x509 target proxy
	Insecure bool
	// Pool is x509 cert pool to use for server certifcate verification
	Pool *x509.CertPool
	// Protocol is an optional protocol selection
	Protocol string
	// Compatibility sets compatibility mode for SSH certificates
	Compatibility string
	// BindAddr is an optional host:port address to bind
	// to for SSO login flows
	BindAddr string
}

SSHLogin contains SSH login parameters

type SSHProxySettings

type SSHProxySettings struct {
	// ListenAddr is the address that the SSH proxy is listening for
	// connections on.
	ListenAddr string `json:"listen_addr,omitempty"`

	// TunnelListenAddr
	TunnelListenAddr string `json:"tunnel_listen_addr,omitempty"`

	// PublicAddr is the public address of the HTTP proxy.
	PublicAddr string `json:"public_addr,omitempty"`

	// SSHPublicAddr is the public address of the SSH proxy.
	SSHPublicAddr string `json:"ssh_public_addr,omitempty"`

	// TunnelPublicAddr is the public address of the SSH reverse tunnel.
	TunnelPublicAddr string `json:"ssh_tunnel_public_addr,omitempty"`
}

SSHProxySettings is SSH specific proxy settings.

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"`
}

SSOLoginConsoleReq is used to SSO for tsh

func (SSOLoginConsoleReq) Check

func (r SSOLoginConsoleReq) Check() error

Check 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 ShellCreatedCallback added in v1.1.0

type ShellCreatedCallback func(s *ssh.Session, c *ssh.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 TeleportClient added in v1.0.0

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

func NewClient added in v1.0.0

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

NewClient creates a TeleportClient object and fully configures it

func (*TeleportClient) AddKey added in v1.0.0

func (tc *TeleportClient) AddKey(host string, key *Key) (*agent.AddedKey, error)

func (*TeleportClient) AddTrustedCA added in v1.0.0

func (tc *TeleportClient) AddTrustedCA(ca services.CertAuthority) error

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

func (*TeleportClient) AskOTP

func (tc *TeleportClient) AskOTP() (token string, err error)

AskOTP prompts the user to enter the OTP token.

func (*TeleportClient) AskPassword added in v1.3.0

func (tc *TeleportClient) AskPassword() (pwd string, err error)

AskPassword prompts the user to enter the password

func (*TeleportClient) Benchmark

func (tc *TeleportClient) Benchmark(ctx context.Context, bench Benchmark) (*BenchmarkResult, error)

Benchmark connects to remote server and executes requests in parallel according to benchmark spec. It returns benchmark result when completed. This is a blocking function that can be cancelled via context argument.

func (*TeleportClient) ConnectToProxy added in v1.0.0

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

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

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

func (*TeleportClient) ExecuteSCP

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

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

func (*TeleportClient) GetTrustedCA

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

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

func (*TeleportClient) Join added in v1.0.0

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

Join connects to the existing/active SSH session

func (*TeleportClient) ListNodes added in v1.0.0

func (tc *TeleportClient) ListNodes(ctx context.Context) ([]services.Server, error)

ListNodes returns a list of nodes connected to a proxy

func (*TeleportClient) LocalAgent added in v1.0.0

func (tc *TeleportClient) LocalAgent() *LocalKeyAgent

func (*TeleportClient) Login added in v1.0.0

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

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

If 'activateKey' is true, saves the received session cert into the local keystore (and into the ssh-agent) for future use.

func (*TeleportClient) Logout added in v1.0.0

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) Play added in v1.0.0

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

Play replays the recorded session

func (*TeleportClient) SCP added in v1.0.0

func (tc *TeleportClient) SCP(ctx context.Context, args []string, port int, recursive bool, quiet bool) (err error)

SCP securely copies file(s) from one SSH server to another

func (*TeleportClient) SSH added in v1.0.0

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

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

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

func (*TeleportClient) SendEvent

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

SendEvent adds a events.EventFields to the channel.

func (*TeleportClient) UpdateTrustedCA

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

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

type U2FSettings

type U2FSettings struct {
	// AppID is the U2F AppID.
	AppID string `json:"app_id"`
}

U2FSettings contains the AppID for Universal Second Factor.

type U2fSignRequestReq

type U2fSignRequestReq struct {
	User string `json:"user"`
	Pass string `json:"pass"`
}

U2fSignRequestReq is a request from the client for a U2F sign request from the server

type WebClient

type WebClient struct {
	*roundtrip.Client
}

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

func NewWebClient

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

func (*WebClient) Delete

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

func (*WebClient) 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) PutJSON

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

Jump to

Keyboard shortcuts

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