sshserver

package module
v0.9.18 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2021 License: MIT Imports: 25 Imported by: 15

README

ContainerSSH - Launch Containers on Demand

ContainerSSH SSH Server Library

Go Report Card LGTM Alerts

This library provides an overlay for the built-in go SSH server library that makes it easier to handle.

⚠⚠⚠ Warning: This is a developer documentation. ⚠⚠⚠
The user documentation for ContainerSSH is located at containerssh.io.

Using this library

This library provides a friendlier way to handle SSH requests than with the built-in SSH library. the primary method of using this library is via the Lifecycle objects from the service library:

// Create the server. See the description below for parameters.
server, err := sshserver.New(
    cfg,
    handler,
    logger,
)
if err != nil {
    // Handle configuration errors
    log.Fatalf("%v", err)
}
lifecycle := service.NewLifecycle(server)

defer func() {
    // The Run method will run the server and return when the server is shut down.
    // We are running this in a goroutine so the shutdown below can proceed after a minute.
    if err := lifecycle.Run(); err != nil {
        // Handle errors while running the server
    }
}()

time.Sleep(60 * time.Second)

// Shut down the server. Pass a context to indicate how long the server should wait
// for existing connections to finish. This function will return when the server
// has stopped. 
lifecycle.Stop(
    context.WithTimeout(
        context.Background(),
        30 * time.Second,
    ),
)

The cfg variable will be a Config structure as described in config.go.

The handler variable must be an implementation of the Handler interface described in handler.go.

The logger variable needs to be an instance of the Logger interface from github.com/containerssh/log.

Implementing a handler

The handler interface consists of multiple parts:

  • The Handler is the main handler for the application providing several hooks for events. On new connections the OnNetworkConnection method is called, which must return a NetworkConnectionHandler
  • The NetworkConnectionHandler is a handler for network connections before the SSH handshake is complete. It is called to perform authentication and return an SSHConnectionHandler when the authentication is successful.
  • The SSHConnectionHandler is responsible for handling an individual SSH connection. Most importantly, it is responsible for providing a SessionChannelHandler when a new session channel is requested by the client.
  • The SessionChannelHandler is responsible for an individual session channel (single program execution). It provides several hooks for setting up and running the program. Once the program execution is complete the channel is closed. You must, however, keep handling requests (e.g. window size change) during program execution.

A sample implementation can be found in the test code at the bottom of the file.

About the connectionID

The connectionID parameter in the OnNetworkConnection() is a hexadecimal string uniquely identifying a connection. This ID can be used to track connection-related information across multiple subsystems (e.g. logs, audit logs, authentication and configuration requests, etc.)

Testing a backend

This library contains a testing toolkit for running Linux commands against a backend. The primary resource for these tests will be the conformance tests. To use these you must implement a set of factories that fulfill the following signature: func(logger log.Logger) (sshserver.NetworkConnectionHandler, error).

These factories can then be used as follows:

func TestConformance(t *testing.T) {
		var factories = map[string]func() (
            sshserver.NetworkConnectionHandler,
            error,
        ) {
    		"some-method": func(
                logger log.Logger,
            ) (sshserver.NetworkConnectionHandler, error) {
    			
    		},
    		"some-other-method": func(
                logger log.Logger,
            ) (sshserver.NetworkConnectionHandler, error) {
    			
    		},
    	}
    
    	sshserver.RunConformanceTests(t, factories)
}

The conformance tests will then attempt to execute a series of Linux interactions against the network connection handler and report features that have failed.

Alternatively, you can also use the components that make up the conformance tests separately.

Creating a test user

The first step of using the test utilities is creating a test user. This can be done using the following calls:

user := sshserver.NewTestUser(
    "test",
)

This use can then be configured with a random password using RandomPassword(), or set credentials using SetPassword() or GenerateKey(). These test users can then be passed to the test server or test client.

Creating a test client

The test SSH client offers functionality over the Golang SSH client that helps with testing. The test client can be created as follows:

sshclient := NewTestClient(
    serverIPAndPort,
    serverHostPrivateKey,
    user *TestUser,
    logger log.Logger,
)

Note that you must pass the servers private key in PEM format which will be used to extract the the public key for validation. This makes the client unsuitable for purposes other than testing.

The test client can then be used to interact with the server. The client is described in test_client.go and functions can be discovered using code completion in the IDE.

Creating a test server

We also provide a simplified test server that you can plug in any backend:

srv := NewTestServer(
    handler,
    logger,
)

You can then start the server in the background and subsequently stop it:

srv.Start()
defer srv.Stop(10 * time.Second)

Creating a simple authenticating handler

We also provide an authentication handler that can be used to authenticate using the test users:

handler := NewTestAuthenticationHandler(
    handler,
    user1,
    user2,
    user3,
)

Documentation

Index

Constants

View Source
const (
	MConnected                = "SSH_CONNECTED"
	MDisconnected             = "SSH_DISCONNECTED"
	EHandshakeFailed          = "SSH_HANDSHAKE_FAILED"
	MHandshakeSuccessful      = "SSH_HANDSHAKE_SUCCESSFUL"
	EUnsupportedGlobalRequest = "SSH_UNSUPPORTED_GLOBAL_REQUEST"
	EReplyFailed              = "SSH_REPLY_SEND_FAILED"
	EUnsupportedChannelType   = "SSH_UNSUPPORTED_CHANNEL_TYPE"
	EAlreadyRunning           = "SSH_ALREADY_RUNNING"
	EStartFailed              = "SSH_START_FAILED"
	EListenCloseFailed        = "SSH_LISTEN_CLOSE_FAILED"
	MNewChannel               = "SSH_NEW_CHANNEL"
	MNewChannelRejected       = "SSH_NEW_CHANNEL_REJECTED"
	MServiceAvailable         = "SSH_AVAILABLE"
	EAuthUnavailable          = "SSH_AUTH_UNAVAILABLE"
	EAuthFailed               = "SSH_AUTH_FAILED"
	EAuthSuccessful           = "SSH_AUTH_SUCCESSFUL"
	EExitCodeFailed           = "SSH_EXIT_CODE_FAILED"
	EDecodeFailed             = "SSH_DECODE_FAILED"
	MExit                     = "SSH_EXIT"
	MExitSignal               = "SSH_EXIT_SIGNAL"
	MChannelRequest           = "SSH_CHANNEL_REQUEST"
	MChannelRequestFailed     = "SSH_CHANNEL_REQUEST_FAILED"
	MChannelRequestSuccessful = "SSH_CHANNEL_REQUEST_SUCCESSFUL"
)

Variables

View Source
var ErrAuthenticationFailed = errors.New("authentication failed")

ErrAuthenticationFailed is the error that is returned from TestClient.Connect when the authentication failed.

Functions

func GenerateConnectionID added in v0.9.9

func GenerateConnectionID() string

GenerateConnectionID generates a globally unique connection ID consisting of hexadecimal characters.

func RunConformanceTests added in v0.9.15

func RunConformanceTests(t *testing.T, backendFactories map[string]ConformanceTestBackendFactory)

RunConformanceTests runs a suite of conformance tests against the provided backends supporting a standard Linux shell.

Types

type AbstractHandler added in v0.9.15

type AbstractHandler struct {
}

AbstractHandler is the abstract implementation of the Handler interface that can be embedded to get a partial implementation.

func (*AbstractHandler) OnNetworkConnection added in v0.9.15

func (a *AbstractHandler) OnNetworkConnection(_ net.TCPAddr, _ string) (NetworkConnectionHandler, error)

OnNetworkConnection is called when a new network connection is opened. It must either return a NetworkConnectionHandler object or an error. In case of an error the network connection is closed.

The ip parameter provides the IP address of the connecting user. The connectionID parameter provides an opaque binary identifier for the connection that can be used to track the connection across multiple subsystems.

func (*AbstractHandler) OnReady added in v0.9.15

func (a *AbstractHandler) OnReady() error

OnReady is called when the server is ready to receive connections. It has an opportunity to return an error to

abort the startup.

func (*AbstractHandler) OnShutdown added in v0.9.15

func (a *AbstractHandler) OnShutdown(_ context.Context)

OnShutdown is called when a shutdown of the SSH server is desired. The shutdownContext is passed as a deadline

for the shutdown, after which the server should abort all running connections and return as fast as
possible.

type AbstractNetworkConnectionHandler added in v0.9.15

type AbstractNetworkConnectionHandler struct {
}

AbstractNetworkConnectionHandler is an empty implementation for the NetworkConnectionHandler interface.

func (*AbstractNetworkConnectionHandler) OnAuthKeyboardInteractive added in v0.9.16

func (a *AbstractNetworkConnectionHandler) OnAuthKeyboardInteractive(
	_ string,
	_ func(
		instruction string,
		questions KeyboardInteractiveQuestions,
	) (answers KeyboardInteractiveAnswers, err error),
) (response AuthResponse, reason error)

OnAuthKeyboardInteractive is a callback for interactive authentication. The implementer will be passed a callback function that can be used to issue challenges to the user. These challenges can, but do not have to contain questions.

func (*AbstractNetworkConnectionHandler) OnAuthPassword added in v0.9.15

func (a *AbstractNetworkConnectionHandler) OnAuthPassword(_ string, _ []byte) (response AuthResponse, reason error)

OnAuthPassword is called when a user attempts a password authentication. The implementation must always supply

AuthResponse and may supply error as a reason description.

func (*AbstractNetworkConnectionHandler) OnAuthPubKey added in v0.9.15

func (a *AbstractNetworkConnectionHandler) OnAuthPubKey(_ string, _ string) (response AuthResponse, reason error)

OnAuthPassword is called when a user attempts a pubkey authentication. The implementation must always supply

 AuthResponse and may supply error as a reason description. The pubKey parameter is an SSH key in
the form of "ssh-rsa KEY HERE".

func (*AbstractNetworkConnectionHandler) OnDisconnect added in v0.9.15

func (a *AbstractNetworkConnectionHandler) OnDisconnect()

OnDisconnect is called when the network connection is closed.

func (*AbstractNetworkConnectionHandler) OnHandshakeFailed added in v0.9.15

func (a *AbstractNetworkConnectionHandler) OnHandshakeFailed(_ error)

OnHandshakeFailed is called when the SSH handshake failed. This method is also called after an authentication

failure. After this method is the connection will be closed and the OnDisconnect method will be
called.

func (*AbstractNetworkConnectionHandler) OnHandshakeSuccess added in v0.9.15

func (a *AbstractNetworkConnectionHandler) OnHandshakeSuccess(_ string) (
	connection SSHConnectionHandler, failureReason error,
)

OnHandshakeSuccess is called when the SSH handshake was successful. It returns connection to process

requests, or failureReason to indicate that a backend error has happened. In this case, the
connection will be closed and OnDisconnect will be called.

func (*AbstractNetworkConnectionHandler) OnShutdown added in v0.9.15

OnShutdown is called when a shutdown of the SSH server is desired. The shutdownContext is passed as a deadline

for the shutdown, after which the server should abort all running connections and return as fast as
possible.

type AbstractSSHConnectionHandler added in v0.9.15

type AbstractSSHConnectionHandler struct {
}

AbstractSSHConnectionHandler is an empty implementation of the SSHConnectionHandler providing default methods.

func (*AbstractSSHConnectionHandler) OnSessionChannel added in v0.9.15

func (a *AbstractSSHConnectionHandler) OnSessionChannel(_ uint64, _ []byte, _ SessionChannel) (
	channel SessionChannelHandler, failureReason ChannelRejection,
)

OnSessionChannel is called when a channel of the session type is requested. The implementer must either return

the channel result if the channel was successful, or failureReason to state why the channel
should be rejected.

func (*AbstractSSHConnectionHandler) OnShutdown added in v0.9.15

func (a *AbstractSSHConnectionHandler) OnShutdown(_ context.Context)

OnShutdown is called when a shutdown of the SSH server is desired. The shutdownContext is passed as a deadline

for the shutdown, after which the server should abort all running connections and return as fast as
possible.

func (*AbstractSSHConnectionHandler) OnUnsupportedChannel added in v0.9.15

func (a *AbstractSSHConnectionHandler) OnUnsupportedChannel(_ uint64, _ string, _ []byte)

OnUnsupportedChannel is called when a new channel is requested of an unsupported type. This gives the implementer

the ability to log unsupported channel requests.

channelID is an ID uniquely identifying the channel within the connection. channelType is the type of channel requested by the client. We only support the "session" channel type extraData contains the binary extra data submitted by the client. This is usually empty.

func (*AbstractSSHConnectionHandler) OnUnsupportedGlobalRequest added in v0.9.15

func (a *AbstractSSHConnectionHandler) OnUnsupportedGlobalRequest(_ uint64, _ string, _ []byte)

OnUnsupportedGlobalRequest captures all global SSH requests and gives the implementation an opportunity to log

the request.

requestID is an ID uniquely identifying the request within the scope connection. The same ID may appear within

a channel.

type AbstractSessionChannelHandler added in v0.9.15

type AbstractSessionChannelHandler struct {
}

AbstractSessionChannelHandler is an abstract implementation of SessionChannelHandler providing default implementations.

func (*AbstractSessionChannelHandler) OnClose added in v0.9.15

func (a *AbstractSessionChannelHandler) OnClose()

OnClose is called when the channel is closed.

func (*AbstractSessionChannelHandler) OnEnvRequest added in v0.9.15

func (a *AbstractSessionChannelHandler) OnEnvRequest(
	_ uint64,
	_ string,
	_ string,
) error

OnEnvRequest is called when the client requests an environment variable to be set. The implementation can return

an error to reject the request.

func (*AbstractSessionChannelHandler) OnExecRequest added in v0.9.15

func (a *AbstractSessionChannelHandler) OnExecRequest(
	_ uint64,
	_ string,
) error

OnExecRequest is called when the client request a program to be executed. The implementation can return an error

to reject the request. This method MUST NOT block beyond initializing the program.

func (*AbstractSessionChannelHandler) OnFailedDecodeChannelRequest added in v0.9.15

func (a *AbstractSessionChannelHandler) OnFailedDecodeChannelRequest(
	_ uint64,
	_ string,
	_ []byte,
	_ error,
)

OnFailedDecodeChannelRequest is called when a supported channel request was received, but the payload could not

be decoded.

requestID is an incrementing number uniquely identifying this request within the channel. requestType contains the SSH request type. payload is the binary payload. reason is the reason why the decoding failed.

func (*AbstractSessionChannelHandler) OnPtyRequest added in v0.9.15

func (a *AbstractSessionChannelHandler) OnPtyRequest(
	_ uint64,
	_ string,
	_ uint32,
	_ uint32,
	_ uint32,
	_ uint32,
	_ []byte,
) error

OnPtyRequest is called when the client requests an interactive terminal to be allocated. The implementation can

return an error to reject the request.

requestID is an incrementing number uniquely identifying this request within the channel. Term is the terminal Name. This is usually set in the TERM environment variable. Columns is the number of Columns in the terminal. Rows is the number of Rows in the terminal. Width is the Width of the terminal in pixels. Height is the Height of a terminal in pixels. ModeList are the encoded terminal modes the client desires. See RFC4254 section 8 and RFC8160 for details.

func (*AbstractSessionChannelHandler) OnShell added in v0.9.15

func (a *AbstractSessionChannelHandler) OnShell(
	_ uint64,
) error

OnShell is called when the client requests a shell to be started. The implementation can return an error to

reject the request. The implementation should send the IO handling into background. It should also
respect the shutdown context on the Handler. This method MUST NOT block beyond initializing the shell.

func (*AbstractSessionChannelHandler) OnShutdown added in v0.9.15

OnShutdown is called when a shutdown of the SSH server is desired. The shutdownContext is passed as a deadline

for the shutdown, after which the server should abort all running connections and return as fast as
possible.

func (*AbstractSessionChannelHandler) OnSignal added in v0.9.15

func (a *AbstractSessionChannelHandler) OnSignal(
	_ uint64,
	_ string,
) error

OnSignal is called when the client requests a Signal to be sent to the running process. The implementation can

return an error to reject the request.

func (*AbstractSessionChannelHandler) OnSubsystem added in v0.9.15

func (a *AbstractSessionChannelHandler) OnSubsystem(
	_ uint64,
	_ string,
) error

OnSubsystem is called when the client calls a well-known Subsystem (e.g. sftp). The implementation can return an

error to reject the request. The implementation should send the IO handling into background. It
should also respect the shutdown context on the Handler. This method MUST NOT block beyond
initializing the subsystem.

func (*AbstractSessionChannelHandler) OnUnsupportedChannelRequest added in v0.9.15

func (a *AbstractSessionChannelHandler) OnUnsupportedChannelRequest(
	_ uint64,
	_ string,
	_ []byte,
)

OnUnsupportedChannelRequest captures channel requests of unsupported types.

requestID is an incrementing number uniquely identifying this request within the channel. requestType contains the SSH request type. payload is the binary payload.

func (*AbstractSessionChannelHandler) OnWindow added in v0.9.15

func (a *AbstractSessionChannelHandler) OnWindow(
	_ uint64,
	_ uint32,
	_ uint32,
	_ uint32,
	_ uint32,
) error

OnWindow is called when the client requests requests the window size to be changed. This method may be called

after a program is started. The implementation can return an error to reject the request.

requestID is an incrementing number uniquely identifying this request within the channel. Columns is the number of Columns in the terminal. Rows is the number of Rows in the terminal. Width is the Width of the terminal in pixels. Height is the Height of a terminal in pixels.

type AuthResponse

type AuthResponse uint8

AuthResponse indicates the various response states for the authentication process.

const (
	// AuthResponseSuccess indicates that the authentication was successful.
	AuthResponseSuccess AuthResponse = 1

	// AuthResponseFailure indicates that the authentication failed for invalid credentials.
	AuthResponseFailure AuthResponse = 2

	// AuthResponseUnavailable indicates that the authentication could not be performed because a backend system failed
	//                         to respond.
	AuthResponseUnavailable AuthResponse = 3
)

type ChannelRejection

type ChannelRejection interface {
	error

	// Message contains a message intended for the user.
	Message() string
	// Reason contains the SSH-specific reason for the rejection.
	Reason() ssh.RejectionReason
}

ChannelRejection is an error type that also contains a Message and a Reason

type Cipher

type Cipher string

Cipher is the SSH cipher

const (
	CipherChaCha20Poly1305 Cipher = "chacha20-poly1305@openssh.com"
	CipherAES256GCM        Cipher = "aes256-gcm@openssh.com"
	CipherAES128GCM        Cipher = "aes128-gcm@openssh.com"
	CipherAES256CTE        Cipher = "aes256-ctr"
	CipherAES192CTR        Cipher = "aes192-ctr"
	CipherAES128CTR        Cipher = "aes128-ctr"
	CipherAES128CBC        Cipher = "aes128-cbc"
	CipherArcFour256       Cipher = "arcfour256"
	CipherArcFour128       Cipher = "arcfour128"
	CipherArcFour          Cipher = "arcfour"
	CipherTripleDESCBCID   Cipher = "tripledescbcID"
)

Cipher is the SSH cipher

func (Cipher) String

func (c Cipher) String() string

String creates a string representation.

type Config

type Config struct {
	// Listen is the listen address for the SSH server
	Listen string `json:"listen" yaml:"listen" default:"0.0.0.0:2222"`
	// ServerVersion is the version sent to the client.
	//               Must be in the format of "SSH-protoversion-softwareversion SPACE comments".
	//               See https://tools.ietf.org/html/rfc4253#page-4 section 4.2. Protocol Version Exchange
	//               The trailing CR and LF characters should NOT be added to this string.
	ServerVersion string `json:"serverVersion" yaml:"serverVersion" default:"SSH-2.0-ContainerSSH"`
	// Ciphers are the ciphers offered to the client.
	Ciphers []Cipher `` /* 205-byte string literal not displayed */
	// KexAlgorithms are the key exchange algorithms offered to the client.
	KexAlgorithms []Kex `` /* 176-byte string literal not displayed */
	// MACs are the MAC algorithms offered to the client.
	MACs []MAC `json:"macs" yaml:"macs" default:"[\"hmac-sha2-256-etm@openssh.com\",\"hmac-sha2-256\"]" comment:"MAC algorithms to use"`
	// Banner is the banner sent to the client on connecting.
	Banner string `json:"banner" yaml:"banner" comment:"Host banner to show after the username" default:""`
	// HostKeys are the host keys either in PEM format, or filenames to load.
	HostKeys []string `json:"hostkeys" yaml:"hostkeys" comment:"Host keys in PEM format or files to load PEM host keys from."`
}

Config is the base configuration structure of the SSH server.

func DefaultConfig

func DefaultConfig() Config

func (*Config) GenerateHostKey

func (cfg *Config) GenerateHostKey() error

GenerateHostKey generates a random host key and adds it to Config

func (*Config) LoadHostKeys added in v0.9.9

func (cfg *Config) LoadHostKeys() ([]ssh.Signer, error)

func (Config) Validate

func (cfg Config) Validate() error

Validate validates the configuration and returns an error if invalid.

type ConformanceTestBackendFactory added in v0.9.15

type ConformanceTestBackendFactory = func(logger log.Logger) (NetworkConnectionHandler, error)

ConformanceTestBackendFactory is a method to creating a network connection handler for testing purposes.

type ExitStatus added in v0.9.2

type ExitStatus uint32

ExitStatus contains the status code with which the program exited. See RFC 4254 section 6.10: Returning Exit Status for details. ( https://tools.ietf.org/html/rfc4254#section-6.10 )

type Handler

type Handler interface {
	// OnReady is called when the server is ready to receive connections. It has an opportunity to return an error to
	//         abort the startup.
	OnReady() error

	// OnShutdown is called when a shutdown of the SSH server is desired. The shutdownContext is passed as a deadline
	//            for the shutdown, after which the server should abort all running connections and return as fast as
	//            possible.
	OnShutdown(shutdownContext context.Context)

	// OnNetworkConnection is called when a new network connection is opened. It must either return a
	// NetworkConnectionHandler object or an error. In case of an error the network connection is closed.
	//
	// The ip parameter provides the IP address of the connecting user. The connectionID parameter provides an opaque
	// binary identifier for the connection that can be used to track the connection across multiple subsystems.
	OnNetworkConnection(client net.TCPAddr, connectionID string) (NetworkConnectionHandler, error)
}

Handler is the basic handler for SSH connections. It contains several methods to handle startup and operations of the

server

func NewTestAuthenticationHandler added in v0.9.15

func NewTestAuthenticationHandler(
	backend Handler,
	users ...*TestUser,
) Handler

NewTestAuthenticationHandler creates a new backend that authenticates a user based on the users variable and passes all further calls to the backend.

func NewTestHandler added in v0.9.15

func NewTestHandler() Handler

NewTestHandler creates a handler that can be used for testing purposes. It does not authenticate, that can be done using the NewTestAuthenticationHandler

type HostKeyAlgo

type HostKeyAlgo string

HostKeyAlgo are supported host key algorithms.

const (
	HostKeyAlgoSSHRSACertv01            HostKeyAlgo = "ssh-rsa-cert-v01@openssh.com"
	HostKeyAlgoSSHDSSCertv01            HostKeyAlgo = "ssh-dss-cert-v01@openssh.com"
	HostKeyAlgoECDSASHA2NISTp256Certv01 HostKeyAlgo = "ecdsa-sha2-nistp256-cert-v01@openssh.com"
	HostKeyAlgoECDSASHA2NISTp384Certv01 HostKeyAlgo = "ecdsa-sha2-nistp384-cert-v01@openssh.com"
	HostKeyAlgoECDSASHA2NISTp521Certv01 HostKeyAlgo = "ecdsa-sha2-nistp521-cert-v01@openssh.com"
	HostKeyAlgoSSHED25519Certv01        HostKeyAlgo = "ssh-ed25519-cert-v01@openssh.com"
	HostKeyAlgoSSHRSA                   HostKeyAlgo = "ssh-rsa"
	HostKeyAlgoSSHDSS                   HostKeyAlgo = "ssh-dss"
	HostKeyAlgoSSHED25519               HostKeyAlgo = "ssh-ed25519"
)

HostKeyAlgo are supported host key algorithms.

func (HostKeyAlgo) String

func (h HostKeyAlgo) String() string

String creates a string representation.

type Kex

type Kex string

Kex are the SSH key exchange algorithms

const (
	KexCurve25519SHA256 Kex = "curve25519-sha256@libssh.org"
	KexECDHSHA2NISTp521 Kex = "ecdh-sha2-nistp521"
	KexECDHSHA2Nistp384 Kex = "ecdh-sha2-nistp384"
	KexECDHSHA2Nistp256 Kex = "ecdh-sha2-nistp256"
	KexDHGroup14SHA1    Kex = "diffie-hellman-group14-sha1"
	KexDHGroup1SHA1     Kex = "diffie-hellman-group1-sha1"
)

Kex are the SSH key exchange algorithms

func (Kex) String

func (k Kex) String() string

String creates a string representation.

type KeyboardInteractiveAnswers added in v0.9.16

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

KeyboardInteractiveAnswers is a set of answer to a keyboard-interactive challenge.

func (*KeyboardInteractiveAnswers) Get added in v0.9.16

Get returns the answer for a question, or an error if no answer is present.

func (*KeyboardInteractiveAnswers) GetByQuestionText added in v0.9.16

func (k *KeyboardInteractiveAnswers) GetByQuestionText(question string) (string, error)

GetByQuestionText returns the answer for a question text, or an error if no answer is present.

type KeyboardInteractiveQuestion added in v0.9.16

type KeyboardInteractiveQuestion struct {
	// ID is an optional opaque ID that can be used to identify a question in an answer. Can be left empty.
	ID string
	// Question is the question text sent to the user.
	Question string
	// EchoResponse should be set to true to show the typed response to the user.
	EchoResponse bool
}

KeyboardInteractiveQuestion contains a question issued to a user as part of the keyboard-interactive exchange.

type KeyboardInteractiveQuestions added in v0.9.16

type KeyboardInteractiveQuestions []KeyboardInteractiveQuestion

KeyboardInteractiveQuestions is a list of questions for keyboard-interactive authentication

func (*KeyboardInteractiveQuestions) Add added in v0.9.16

type MAC

type MAC string

MAC are the SSH mac algorithms.

const (
	MACHMACSHA2256ETM MAC = "hmac-sha2-256-etm@openssh.com"
	MACHMACSHA2256    MAC = "hmac-sha2-256"
	MACHMACSHA1       MAC = "hmac-sha1"
	MACHMACSHA196     MAC = "hmac-sha1-96"
)

MAC are the SSH mac algorithms.

func (MAC) String

func (m MAC) String() string

String creates a string representation.

type NetworkConnectionHandler

type NetworkConnectionHandler interface {
	// OnAuthPassword is called when a user attempts a password authentication. The implementation must always supply
	//                AuthResponse and may supply error as a reason description.
	OnAuthPassword(username string, password []byte) (response AuthResponse, reason error)

	// OnAuthPassword is called when a user attempts a pubkey authentication. The implementation must always supply
	//                AuthResponse and may supply error as a reason description. The pubKey parameter is an SSH key in
	//               the form of "ssh-rsa KEY HERE".
	OnAuthPubKey(username string, pubKey string) (response AuthResponse, reason error)

	// OnAuthKeyboardInteractive is a callback for interactive authentication. The implementer will be passed a callback
	// function that can be used to issue challenges to the user. These challenges can, but do not have to contain
	// questions.
	OnAuthKeyboardInteractive(
		user string,
		challenge func(
			instruction string,
			questions KeyboardInteractiveQuestions,
		) (answers KeyboardInteractiveAnswers, err error),
	) (response AuthResponse, reason error)

	// OnHandshakeFailed is called when the SSH handshake failed. This method is also called after an authentication
	//                   failure. After this method is the connection will be closed and the OnDisconnect method will be
	//                   called.
	OnHandshakeFailed(reason error)

	// OnHandshakeSuccess is called when the SSH handshake was successful. It returns connection to process
	//                    requests, or failureReason to indicate that a backend error has happened. In this case, the
	//                    connection will be closed and OnDisconnect will be called.
	OnHandshakeSuccess(username string) (connection SSHConnectionHandler, failureReason error)

	// OnDisconnect is called when the network connection is closed.
	OnDisconnect()

	// OnShutdown is called when a shutdown of the SSH server is desired. The shutdownContext is passed as a deadline
	//            for the shutdown, after which the server should abort all running connections and return as fast as
	//            possible.
	OnShutdown(shutdownContext context.Context)
}

NetworkConnectionHandler is an object that is used to represent the underlying network connection and the SSH handshake.

type SSHConnectionHandler

type SSHConnectionHandler interface {
	// OnUnsupportedGlobalRequest captures all global SSH requests and gives the implementation an opportunity to log
	//                            the request.
	//
	// requestID is an ID uniquely identifying the request within the scope connection. The same ID may appear within
	//           a channel.
	OnUnsupportedGlobalRequest(requestID uint64, requestType string, payload []byte)

	// OnUnsupportedChannel is called when a new channel is requested of an unsupported type. This gives the implementer
	//                      the ability to log unsupported channel requests.
	//
	// channelID is an ID uniquely identifying the channel within the connection.
	// channelType is the type of channel requested by the client. We only support the "session" channel type
	// extraData contains the binary extra data submitted by the client. This is usually empty.
	OnUnsupportedChannel(channelID uint64, channelType string, extraData []byte)

	// OnSessionChannel is called when a channel of the session type is requested. The implementer must either return
	//                  the channel result if the channel was successful, or failureReason to state why the channel
	//                  should be rejected.
	//
	// channelID is an ID uniquely identifying the channel within the connection.
	// extraData contains the binary extra data submitted by the client. This is usually empty.
	// session contains a set of calls that can be used to manipulate the SSH session.
	OnSessionChannel(
		channelID uint64,
		extraData []byte,
		session SessionChannel,
	) (channel SessionChannelHandler, failureReason ChannelRejection)

	// OnShutdown is called when a shutdown of the SSH server is desired. The shutdownContext is passed as a deadline
	//            for the shutdown, after which the server should abort all running connections and return as fast as
	//            possible.
	OnShutdown(shutdownContext context.Context)
}

SSHConnectionHandler represents an established SSH connection that is ready to receive requests.

type Server

type Server interface {
	service.Service
}

Server is the main SSH server interface, compatible with the Service library. It should always be used in conjunction with the Lifecycle interface from the service library.

func New

func New(cfg Config, handler Handler, logger log.Logger) (Server, error)

New creates a new SSH server ready to be run. It may return an error if the configuration is invalid.

type SessionChannel added in v0.9.15

type SessionChannel interface {
	// Stdin returns the reader for the standard input.
	Stdin() io.Reader
	// Stdout returns the writer for the standard output.
	Stdout() io.Writer
	// Stderr returns the writer for the standard error.
	Stderr() io.Writer
	// ExitStatus sends the program exit status to the client.
	ExitStatus(code uint32)
	// ExitSignal sends a message to the client indicating that the program exited violently.
	ExitSignal(signal string, coreDumped bool, errorMessage string, languageTag string)
	// CloseWrite sends an EOF to the client indicating that no more data will be sent on stdout or stderr.
	CloseWrite() error
	// Close closes the channel for reading and writing.
	Close() error
}

SessionChannel contains a set of calls to manipulate the session channel.

type SessionChannelHandler

type SessionChannelHandler interface {

	// OnUnsupportedChannelRequest captures channel requests of unsupported types.
	//
	// requestID is an incrementing number uniquely identifying this request within the channel.
	// requestType contains the SSH request type.
	// payload is the binary payload.
	OnUnsupportedChannelRequest(
		requestID uint64,
		requestType string,
		payload []byte,
	)

	// OnFailedDecodeChannelRequest is called when a supported channel request was received, but the payload could not
	//                              be decoded.
	//
	// requestID is an incrementing number uniquely identifying this request within the channel.
	// requestType contains the SSH request type.
	// payload is the binary payload.
	// reason is the reason why the decoding failed.
	OnFailedDecodeChannelRequest(
		requestID uint64,
		requestType string,
		payload []byte,
		reason error,
	)

	// OnEnvRequest is called when the client requests an environment variable to be set. The implementation can return
	//              an error to reject the request.
	OnEnvRequest(
		requestID uint64,
		name string,
		value string,
	) error

	// OnPtyRequest is called when the client requests an interactive terminal to be allocated. The implementation can
	//              return an error to reject the request.
	//
	// requestID is an incrementing number uniquely identifying this request within the channel.
	// Term is the terminal Name. This is usually set in the TERM environment variable.
	// Columns is the number of Columns in the terminal.
	// Rows is the number of Rows in the terminal.
	// Width is the Width of the terminal in pixels.
	// Height is the Height of a terminal in pixels.
	// ModeList are the encoded terminal modes the client desires. See RFC4254 section 8 and RFC8160 for details.
	OnPtyRequest(
		requestID uint64,
		term string,
		columns uint32,
		rows uint32,
		width uint32,
		height uint32,
		modeList []byte,
	) error

	// OnExecRequest is called when the client request a program to be executed. The implementation can return an error
	//               to reject the request. This method MUST NOT block beyond initializing the program.
	//
	// requestID is an incrementing number uniquely identifying this request within the channel.
	// program is the Name of the program to be executed.
	OnExecRequest(
		requestID uint64,
		program string,
	) error

	// OnShell is called when the client requests a shell to be started. The implementation can return an error to
	//         reject the request. The implementation should send the IO handling into background. It should also
	//         respect the shutdown context on the Handler. This method MUST NOT block beyond initializing the shell.
	//
	// requestID is an incrementing number uniquely identifying this request within the channel.
	// stdin is a reader for the shell or program to read the stdin.
	// stdout is a writer for the shell or program standard output.
	// stderr is a writer for the shell or program standard error.
	// writeClose closes the stdout and stderr for writing.
	// onExit is a callback to send the exit status back to the client.
	OnShell(
		requestID uint64,
	) error

	// OnSubsystem is called when the client calls a well-known Subsystem (e.g. sftp). The implementation can return an
	//             error to reject the request. The implementation should send the IO handling into background. It
	//             should also respect the shutdown context on the Handler. This method MUST NOT block beyond
	//             initializing the subsystem.
	//
	// requestID is an incrementing number uniquely identifying this request within the channel.
	// subsystem is the name of the subsystem to be launched (e.g. sftp)
	OnSubsystem(
		requestID uint64,
		subsystem string,
	) error

	// OnSignal is called when the client requests a Signal to be sent to the running process. The implementation can
	//          return an error to reject the request.
	OnSignal(
		requestID uint64,
		signal string,
	) error

	// OnWindow is called when the client requests requests the window size to be changed. This method may be called
	//          after a program is started. The implementation can return an error to reject the request.
	//
	// requestID is an incrementing number uniquely identifying this request within the channel.
	// Columns is the number of Columns in the terminal.
	// Rows is the number of Rows in the terminal.
	// Width is the Width of the terminal in pixels.
	// Height is the Height of a terminal in pixels.
	OnWindow(
		requestID uint64,
		columns uint32,
		rows uint32,
		width uint32,
		height uint32,
	) error

	// OnClose is called when the channel is closed.
	OnClose()

	// OnShutdown is called when a shutdown of the SSH server is desired. The shutdownContext is passed as a deadline
	//            for the shutdown, after which the server should abort all running connections and return as fast as
	//            possible.
	OnShutdown(shutdownContext context.Context)
}

SessionChannelHandler is a channel of the "session" type used for interactive and non-interactive sessions

type TestClient added in v0.9.15

type TestClient interface {
	// Connect establishes a connection to the server.
	Connect() (TestClientConnection, error)
	// MustConnect is identical to Connect, but panics it if it cannot connect.
	MustConnect() TestClientConnection
}

TestClient is an SSH client intended solely for testing purposes.

func NewTestClient added in v0.9.15

func NewTestClient(
	server string,
	hostPrivateKey string,
	user *TestUser,
	logger log.Logger,
) TestClient

NewTestClient creates a new TestClient instance with the specified parameters

- server is the host and IP pair of the server. - hostPrivateKey is the PEM-encoded private host key. The public key and fingerprint are automatically extracted. - username is the username. - password is the password used for authentication.

type TestClientConnection added in v0.9.15

type TestClientConnection interface {
	// Session establishes a new session channel
	Session() (TestClientSession, error)

	//MustSession is identical to Session but panics if a session cannot be requested.
	MustSession() TestClientSession

	// Close closes the connection and all sessions in it.
	Close() error
}

TestClientConnection is an individual established connection to the server

type TestClientSession added in v0.9.15

type TestClientSession interface {
	// SetEnv sets an environment variable or returns with an error.
	SetEnv(name string, value string) error

	// MustSetEnv is identical to SetEnv, but panics if an error happens.
	MustSetEnv(name string, value string)

	// Window requests the terminal window to be resized to a certain size.
	Window(cols int, rows int) error

	// MustWindow is identical to Window, but panics if an error happens.
	MustWindow(cols int, rows int)

	// RequestPTY requests the server to open a PTY/TTY for this channel. Returns an error if the request failed.
	RequestPTY(term string, cols int, rows int) error

	// MustRequestPTY is identical to RequestPTY but panics if an error happens.
	MustRequestPTY(term string, cols int, rows int)

	// Signal sends a signal to the process
	Signal(signal string) error

	// MustSignal is equal to Signal but panics if an error happens.
	MustSignal(signal string)

	// Shell requests a shell to be opened. After this call returns I/O interactions are possible.
	Shell() error

	// MustShell is identical to Shell but panics if an error happens.
	MustShell()

	// Exec requests a specific program to be executed. After this call returns I/O interactions are possible.
	Exec(program string) error

	// MustExec is identical to Exec but panics if an error happens.
	MustExec(program string)

	// Subsystem requests a specific subsystem to be executed. After this call returns I/O interactions are possible.
	Subsystem(name string) error

	// MustSubsystem is identical to Subsystem but panics if an error happens.
	MustSubsystem(name string)

	// Write writes to the stdin of the session.
	Write(data []byte) (int, error)

	// Type writes to the stdin slowly with 50 ms delays
	Type(data []byte) error

	// Read reads from the stdout of the session.
	Read(data []byte) (int, error)

	// ReadRemaining reads the remaining bytes from stdout until EOF.
	ReadRemaining()

	// ReadRemainingStderr reads the remaining bytes from stderr until EOF.
	ReadRemainingStderr()

	// WaitForStdout waits for a specific byte sequence to appear on the stdout.
	WaitForStdout(ctx context.Context, data []byte) error

	// Stderr returns the reader for the stdout.
	Stderr() io.Reader

	// Wait waits for the session to terminate.
	Wait() error

	// ExitCode returns the exit code received from the session, or -1 if not received.
	ExitCode() int

	// Close closes the session.
	Close() error
}

type TestServer added in v0.9.15

type TestServer interface {
	// GetHostKey returns the hosts private key in PEM format. This can be used to extract the public key.
	GetHostKey() string
	// Start starts the server in the background.
	Start()
	// Stop stops the server running in the background.
	Stop(timeout time.Duration)

	// GetListen returns the listen IP and port
	GetListen() string
}

TestServer describes

func NewTestServer added in v0.9.15

func NewTestServer(handler Handler, logger log.Logger) TestServer

NewTestServer is a simplified API to start and stop a test server. The test server always listens on 127.0.0.1:2222

type TestUser added in v0.9.15

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

TestUser is a container for a username, a password and public keys

func NewTestUser added in v0.9.15

func NewTestUser(username string) *TestUser

NewTestUser creates a user that can be used with NewTestHandler and NewTestClient.

func (*TestUser) AddKeyboardInteractiveChallengeResponse added in v0.9.16

func (u *TestUser) AddKeyboardInteractiveChallengeResponse(challenge string, expectedResponse string)

AddKeyboardInteractiveChallengeResponse adds a challenge with an expected response for keyboard-interactive authentication.

func (*TestUser) GenerateKey added in v0.9.15

func (u *TestUser) GenerateKey() (privateKeyPEM string, publicKeyAuthorizedKeys string)

GenerateKey generates a public and private key pair that can be used to authenticate with this user.

func (*TestUser) GetAuthorizedKeys added in v0.9.15

func (u *TestUser) GetAuthorizedKeys() []string

GetAuthorizedKeys returns a slice of the authorized keys of this user.

func (*TestUser) KeyboardInteractiveChallengeResponse added in v0.9.16

func (u *TestUser) KeyboardInteractiveChallengeResponse() (questions KeyboardInteractiveQuestions)

KeyboardInteractiveChallengeResponse returns a construct of KeyboardInteractiveQuestions

func (*TestUser) Password added in v0.9.15

func (u *TestUser) Password() string

Password returns the current password for this user.

func (*TestUser) RandomPassword added in v0.9.15

func (u *TestUser) RandomPassword()

RandomPassword generates a random password for this user.

func (*TestUser) SetPassword added in v0.9.15

func (u *TestUser) SetPassword(password string)

SetPassword sets a specific password for this user.

func (*TestUser) Username added in v0.9.15

func (u *TestUser) Username() string

Username returns the username of this user.

Jump to

Keyboard shortcuts

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