client

package
v0.0.0-...-8d1852a Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2022 License: Apache-2.0 Imports: 41 Imported by: 0

Documentation

Index

Constants

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 (
	// Directory location where tsh profiles (and session keys) are stored
	ProfileDir = ".tsh"
)
View Source
const (
	ProfileMakeCurrent = 1 << iota
)

Variables

This section is empty.

Functions

func FullProfilePath

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 LogoutFromEverywhere

func LogoutFromEverywhere(username string) error

LogoutFromEverywhere looks at the list of proxy servers tsh is currently logged into by examining ~/.tsh and logs him out of them all

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 UnlinkCurrentProfile

func UnlinkCurrentProfile() error

If there's a current profile symlink, remove it

func Username

func Username() string

Username returns the current user's username

Types

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.

type ClientProfile

type ClientProfile struct {
	//
	// proxy configuration
	//
	ProxyHost    string `yaml:"proxy_host,omitempty"`
	ProxySSHPort int    `yaml:"proxy_port,omitempty"`
	ProxyWebPort int    `yaml:"proxy_web_port,omitempty"`

	//
	// auth/identity
	//
	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"`

	//
	// other stuff
	//
	ForwardedPorts []string `yaml:"forward_ports,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

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

ProfileFromDir reads the user profile from a given directory. It works by looking for a "profile" symlink in that directory pointing to the profile's YAML file.

func ProfileFromFile

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

ProfileFromFile loads the profile from a YAML file

func (*ClientProfile) SaveTo

func (cp *ClientProfile) SaveTo(filePath string, opts ProfileOptions) error

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

type Config

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

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

	// HostPort is a remote host port to connect to
	HostPort int

	// ProxyHostPort is a host or IP of the proxy (with optional ":ssh_port,https_port").
	// The value is taken from the --proxy flag and can look like --proxy=host:5025,5080
	ProxyHostPort 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 will not try to connect to local SSH agent
	// or use any local certs, and not use interactive logins
	SkipLocalAuth bool

	// AuthMethods to use to login into cluster. If left empty, teleport will
	// use its own session store,
	AuthMethods []ssh.AuthMethod

	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

	// Locally forwarded ports (parameters to -L ssh flag)
	LocalForwardPorts ForwardedPorts

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

	// ConnectorID is used to authenticate user via OpenID Connect
	// registered connector
	ConnectorID string

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

Config is a client config

func MakeDefaultConfig

func MakeDefaultConfig() *Config

func (*Config) LoadProfile

func (c *Config) LoadProfile(profileDir 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) NodeHostPort

func (c *Config) NodeHostPort() string

NodeHostPort returns host:port string based on user supplied data either if user has set host:port in the connection string, or supplied the -p flag. If user has set both, -p flag data is ignored

func (*Config) ProxyHost

func (c *Config) ProxyHost() string

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

func (*Config) ProxySSHHostPort

func (c *Config) ProxySSHHostPort() string

func (*Config) ProxySSHPort

func (c *Config) ProxySSHPort() (retval int)

ProxySSHPort returns the port number of teleport SSH proxy stored in the config usually 3023 by default.

func (*Config) ProxySpecified

func (c *Config) ProxySpecified() bool

ProxySpecified returns true if proxy has been specified

func (*Config) ProxyWebHostPort

func (c *Config) ProxyWebHostPort() string

func (*Config) ProxyWebPort

func (c *Config) ProxyWebPort() (retval int)

ProxyWebPort returns the port number of teleport HTTP proxy stored in the config usually 3080 by default.

func (*Config) SaveProfile

func (c *Config) SaveProfile(profileDir string) error

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

func (*Config) SetProxy

func (c *Config) SetProxy(host string, webPort, sshPort int)

type FSLocalKeyStore

type FSLocalKeyStore struct {
	LocalKeyStore

	// KeyDir is the directory where all keys are stored
	KeyDir string
}

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 └── sessions --> server-signed session keys

└── host-a
|   ├── cert
|   ├── key
|   └── pub
└── host-b
    ├── cert
    ├── key
    └── pub

func NewFSLocalKeyStore

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

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

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

func (*FSLocalKeyStore) AddKey

func (fs *FSLocalKeyStore) AddKey(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

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

AddKnownHostKeys adds a new entry to 'known_hosts' file

func (*FSLocalKeyStore) DeleteKey

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

DeleteKey deletes a key from the local store

func (*FSLocalKeyStore) GetKey

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

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

func (*FSLocalKeyStore) GetKeys

func (fs *FSLocalKeyStore) GetKeys(username string) (keys []Key, err error)

GetKeys returns all user session keys stored in the store

func (*FSLocalKeyStore) GetKnownHostKeys

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

GetKnownHostKeys returns all known public keys from 'known_hosts'

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

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.ToString()

func (ForwardedPorts) ToStringSpec

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

ToString() returns the same string spec which can be parsed by ParsePortForwardSpec

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

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

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

type Key

type Key struct {
	Priv []byte `json:"Priv,omitempty"`
	Pub  []byte `json:"Pub,omitempty"`
	Cert []byte `json:"Cert,omitempty"`

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

Key describes a complete (signed) client key

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!

This is done because OpenSSH clients older than OpenSSH 7.3/7.3p1 (2016-08-01) have a bug in how they use certificates that have been loaded in an agent. Specifically when you add a certificate to an agent, you can't just embed the private key within the certificate, you have to add the certificate and private key to the agent separately. Teleport works around this behavior to ensure OpenSSH interoperability.

For more details see the following: https://bugzilla.mindrot.org/show_bug.cgi?id=2550

func (*Key) CertValidBefore

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

CertValidBefore returns the time of the cert expiration

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

type LocalKeyAgent

type LocalKeyAgent struct {
	agent.Agent // Agent is the teleport agent
	// contains filtered or unexported fields
}

func NewLocalAgent

func NewLocalAgent(keyDir, 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 NewPocketLocalAgent

func NewPocketLocalAgent(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

func (a *LocalKeyAgent) AddHostSignersToCache(hostSigners []services.CertAuthority) 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

func (a *LocalKeyAgent) AddKey(host string, username string, key *Key) (*CertAuthMethod, error)

AddKey stores a new signed session key for future use.

It returns an implementation of ssh.Authmethod which can be passed to ssh.Config to make new SSH connections authenticated by this key.

func (*LocalKeyAgent) AuthMethods

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

AuthMethods returns the list of differnt 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

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

CheckHostSignature checks if the given host key was signed by one of the trusted certificaate authorities (CAs)

func (*LocalKeyAgent) DeleteKey

func (a *LocalKeyAgent) DeleteKey(proxyHost string, username string) error

DeleteKey removes the key from the key store as well as unloading the key from the agent.

func (*LocalKeyAgent) GetKeys

func (a *LocalKeyAgent) GetKeys(username string) ([]Key, error)

GetKeys returns a slice of keys that it has read in from the local keystore (~/.tsh)

func (*LocalKeyAgent) LoadKey

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

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

func (*LocalKeyAgent) UnloadKey

func (a *LocalKeyAgent) UnloadKey(username string) error

UnloadKey will unload a key 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.

type LocalKeyStore

type LocalKeyStore interface {
	// client key management
	GetKeys(username string) ([]Key, error)
	AddKey(host string, username string, key *Key) error
	GetKey(host string, username string) (*Key, error)
	DeleteKey(host string, username string) error

	// interface to known_hosts file:
	AddKnownHostKeys(hostname string, keys []ssh.PublicKey) error
	GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error)
}

LocalKeyStore interface allows for different storage back-ends for TSH to load/save its keys

type MEMLocalKeyStore

type MEMLocalKeyStore struct {
	LocalKeyStore
	// contains filtered or unexported fields
}

func NewMemLocalKeyStore

func NewMemLocalKeyStore() (*MEMLocalKeyStore, error)

func (*MEMLocalKeyStore) AddKey

func (ms *MEMLocalKeyStore) AddKey(host string, username string, key *Key) error

func (*MEMLocalKeyStore) AddKnownHostKeys

func (ms *MEMLocalKeyStore) AddKnownHostKeys(hostname string, hostKeys []ssh.PublicKey) error

interface to known_hosts file:

func (*MEMLocalKeyStore) DeleteKey

func (ms *MEMLocalKeyStore) DeleteKey(host string, username string) error

func (*MEMLocalKeyStore) GetKey

func (ms *MEMLocalKeyStore) GetKey(host string, username string) (*Key, error)

func (*MEMLocalKeyStore) GetKeys

func (ms *MEMLocalKeyStore) GetKeys(username string) ([]Key, error)

GetKeys returns all user session keys stored in the store

func (*MEMLocalKeyStore) GetKnownHostKeys

func (ms *MEMLocalKeyStore) GetKnownHostKeys(hostname string) ([]ssh.PublicKey, error)

type NodeClient

type NodeClient struct {
	Client *ssh.Client
	Proxy  *ProxyClient
}

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

func (*NodeClient) Download

func (client *NodeClient) Download(remoteSourcePath, localDestinationPath string, recursive bool, stderr, progressWriter io.Writer) error

Download downloads file or dir from the remote server

func (*NodeClient) Upload

func (client *NodeClient) Upload(srcPath, rDestPath string, recursive bool, stderr, progressWriter io.Writer) error

Upload uploads local file(s) or to the remote server's destination path

type NodeSession

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

type ProfileOptions

type ProfileOptions int

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

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

ConnectToSite connects to the auth server of the given site 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) FindServersByLabels

func (proxy *ProxyClient) FindServersByLabels(ctx context.Context, 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

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 ShellCreatedCallback

type ShellCreatedCallback func(shell 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

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 MakeNewClient

func MakeNewClient(cfg *service.PocketConfig, login, targetHost string) (tc *TeleportClient, err error)

makeClient takes the command-line configuration and constructs & returns a fully configured TeleportClient object

func NewClient

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

NewClient creates a TeleportClient object and fully configures it

func NewPocketClient

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

NewPocketClient creates a TeleportClient object and fully configures it

func (*TeleportClient) APISCP

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

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

func (*TeleportClient) APISSH

func (tc *TeleportClient) APISSH(ctx context.Context, command []string, password 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) AddKey

func (tc *TeleportClient) AddKey(host string, key *Key) (*CertAuthMethod, error)

func (*TeleportClient) AddTrustedCA

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

Adds a new CA as trusted CA for this client

func (*TeleportClient) AskPasswordAndHOTP

func (tc *TeleportClient) AskPasswordAndHOTP() (pwd string, token string, err error)

AskPasswordAndHOTP prompts the user to enter the password + HTOP 2nd factor

func (*TeleportClient) ConnectToProxy

func (tc *TeleportClient) ConnectToProxy() (*ProxyClient, error)

ConnectToProxy dials the proxy server and returns ProxyClient if successful

func (*TeleportClient) Join

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

Join connects to the existing/active SSH session

func (*TeleportClient) ListNodes

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

ListNodes returns a list of nodes connected to a proxy

func (*TeleportClient) LocalAgent

func (tc *TeleportClient) LocalAgent() *LocalKeyAgent

func (*TeleportClient) Login

func (tc *TeleportClient) Login() (*CertAuthMethod, error)

Login logs the user into a Teleport cluster by talking to a Teleport proxy. If successful, saves the received session keys into the local keystore for future use.

func (*TeleportClient) Logout

func (tc *TeleportClient) Logout() error

Logout locates a certificate stored for a given proxy and deletes it

func (*TeleportClient) MakeKey

func (tc *TeleportClient) MakeKey() (key *Key, err error)

MakeKey generates a new unsigned key. It's useless by itself until a trusted CA signs it

func (*TeleportClient) Play

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

Play replays the recorded session

func (*TeleportClient) SCP

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

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

Jump to

Keyboard shortcuts

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