ssh

package module
v0.0.0-...-cfe0618 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

DragonEye SSH

A high-level Go library for building SSH servers, inspired by the net/http API.

Quick Start

package main

import (
    "io"
    "log"

    "eye.dragonsecurity.io/ssh"
)

func main() {
    ssh.Handle(func(s ssh.Session) {
        io.WriteString(s, "Hello, "+s.User()+"!\n")
    })

    log.Fatal(ssh.ListenAndServe(":2222", nil,
        ssh.PasswordAuth(func(ctx ssh.Context, pass string) bool {
            return pass == "secret"
        }),
    ))
}

Authentication

At least one authentication method must be configured, or NoClientAuth must be explicitly set to true. Attempting to serve without authentication configuration returns ErrNoAuthConfigured.

Password Authentication
ssh.ListenAndServe(":2222", handler,
    ssh.PasswordAuth(func(ctx ssh.Context, password string) bool {
        return password == "secret"
    }),
)
Public Key Authentication
ssh.ListenAndServe(":2222", handler,
    ssh.PublicKeyAuth(func(ctx ssh.Context, key ssh.PublicKey) bool {
        data, _ := os.ReadFile("/path/to/authorized_keys")
        allowed, _, _, _, _ := ssh.ParseAuthorizedKey(data)
        return ssh.KeysEqual(key, allowed)
    }),
)
Keyboard-Interactive Authentication
ssh.ListenAndServe(":2222", handler,
    ssh.KeyboardInteractiveAuth(func(ctx ssh.Context, challenger gossh.KeyboardInteractiveChallenge) bool {
        // implement challenge-response
        return true
    }),
)
No Authentication (explicit opt-in)
srv := &ssh.Server{
    Addr:         ":2222",
    Handler:      handler,
    NoClientAuth: true, // required - will not silently default to open
}
log.Fatal(srv.ListenAndServe())

Host Keys

If no host key is provided, an Ed25519 key is generated automatically on each start. For production, specify a persistent host key:

// From file
ssh.ListenAndServe(":2222", handler, ssh.HostKeyFile("/etc/ssh/ssh_host_ed25519_key"))

// From PEM bytes
ssh.ListenAndServe(":2222", handler, ssh.HostKeyPEM(pemBytes))

// Programmatically
srv := &ssh.Server{Handler: handler}
srv.AddHostKey(signer)

Session Handling

The Session interface provides access to the SSH session:

func handler(s ssh.Session) {
    // Connection info
    user := s.User()
    addr := s.RemoteAddr()

    // Command execution
    rawCmd := s.RawCommand()   // exact command string
    args := s.Command()         // POSIX shell-parsed arguments
    // When Command() returns empty, the user requested a shell

    // Environment variables (set by client before exec/shell)
    env := s.Environ()

    // PTY support
    pty, winCh, isPty := s.Pty()
    if isPty {
        // pty.Term = terminal type (e.g. "xterm-256color")
        // pty.Window = initial window size
        // winCh receives window resize events
    }

    // Signals
    sigCh := make(chan ssh.Signal, 1)
    s.Signals(sigCh)

    // Read/Write (s embeds gossh.Channel)
    io.WriteString(s, "Hello!\n")
    io.Copy(s, s) // echo stdin back

    // Exit with status code
    s.Exit(0)
}

Subsystems

Register named subsystem handlers on the server:

srv := &ssh.Server{
    Handler: sessionHandler,
    SubsystemHandlers: map[string]ssh.SubsystemHandler{
        "sftp": sftpHandler,
    },
}

Port Forwarding

Local (direct-tcpip)
srv := &ssh.Server{
    Handler: handler,
    LocalPortForwardingCallback: func(ctx ssh.Context, host string, port uint32) bool {
        return host == "localhost" // only allow forwarding to localhost
    },
    ChannelHandlers: map[string]ssh.ChannelHandler{
        "session":      ssh.DefaultSessionHandler,
        "direct-tcpip": ssh.DirectTCPIPHandler,
    },
}
Reverse (tcpip-forward)
forwardHandler := &ssh.ForwardedTCPHandler{}
srv := &ssh.Server{
    Handler: handler,
    ReversePortForwardingCallback: func(ctx ssh.Context, host string, port uint32) bool {
        return port >= 1024 // only allow unprivileged ports
    },
    RequestHandlers: map[string]ssh.RequestHandler{
        "tcpip-forward":        forwardHandler.HandleSSHRequest,
        "cancel-tcpip-forward": forwardHandler.HandleSSHRequest,
    },
}

Agent Forwarding

Agent forwarding is denied by default. Enable it with a callback:

srv := &ssh.Server{
    Handler: handler,
    AgentForwardingCallback: func(ctx ssh.Context) bool {
        return true // allow agent forwarding
    },
}

Then in your session handler:

func handler(s ssh.Session) {
    if ssh.AgentRequested(s) {
        l, err := ssh.NewAgentListener()
        if err != nil {
            log.Fatal(err)
        }
        defer l.Close()
        go ssh.ForwardAgentConnections(l, s)
        // l.Addr().String() can be set as SSH_AUTH_SOCK
    }
}

Connection Timeouts

srv := &ssh.Server{
    Handler:          handler,
    HandshakeTimeout: 10 * time.Second,  // max time to complete SSH handshake
    IdleTimeout:      5 * time.Minute,   // disconnect after inactivity
    MaxTimeout:       1 * time.Hour,     // absolute max connection lifetime
}

Server Lifecycle

srv := &ssh.Server{...}

// Graceful shutdown
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
srv.Shutdown(ctx)

// Immediate close
srv.Close()

Functional Options

Configure servers using the functional option pattern:

Option Description
PasswordAuth(fn) Set password authentication handler
PublicKeyAuth(fn) Set public key authentication handler
KeyboardInteractiveAuth(fn) Set keyboard-interactive handler
HostKeyFile(path) Load host key from PEM file
HostKeyPEM(bytes) Load host key from PEM bytes
NoPty() Deny all PTY requests
WrapConn(fn) Wrap net.Conn before handling

Context

The ssh.Context interface extends context.Context with SSH-specific metadata:

ctx.User()           // username
ctx.SessionID()      // hex-encoded session hash
ctx.ClientVersion()  // client version string
ctx.ServerVersion()  // server version string
ctx.RemoteAddr()     // client address
ctx.LocalAddr()      // server address
ctx.Permissions()    // auth permissions
ctx.SetValue(k, v)   // store custom values

Breaking Changes

If upgrading from an earlier version, be aware of the following:

  • Authentication is now required: Servers no longer silently fall back to NoClientAuth. Set NoClientAuth: true explicitly, or configure an auth handler.
  • Agent forwarding is denied by default: Previously accepted unconditionally. Set AgentForwardingCallback to allow it.
  • Context no longer embeds sync.Locker: The Lock()/Unlock() methods are no longer exposed on the Context interface. Use SetValue() for connection-scoped state.
  • ErrPermissionDenied: Auth callbacks now return the sentinel ErrPermissionDenied instead of fmt.Errorf("permission denied").

Security Notes

  • Ed25519 host keys are generated by default (not RSA)
  • Authentication is required unless NoClientAuth is explicitly set
  • Agent forwarding is denied unless AgentForwardingCallback is configured
  • Port forwarding callbacks deny by default when nil
  • KeysEqual uses constant-time comparison to prevent timing attacks
  • Signal names are validated against RFC 4254 POSIX signals
  • Environment variable accumulation is capped at 256 entries (32KB each)
  • Port forwarding error messages are sanitized to prevent information leakage

License

Apache License 2.0

Documentation

Overview

Package ssh wraps the crypto/ssh package with a higher-level API for building SSH servers. The goal of the API was to make it as simple as using net/http, so the API is very similar.

You should be able to build any SSH server using only this package, which wraps relevant types and some functions from crypto/ssh. However, you still need to use crypto/ssh for building SSH clients.

ListenAndServe starts an SSH server with a given address, handler, and options. The handler is usually nil, which means to use DefaultHandler. Handle sets DefaultHandler:

ssh.Handle(func(s ssh.Session) {
    io.WriteString(s, "Hello world\n")
})

log.Fatal(ssh.ListenAndServe(":2222", nil,
    ssh.PasswordAuth(func(ctx ssh.Context, pass string) bool {
        return pass == "secret"
    }),
))

At least one authentication handler must be configured, or NoClientAuth must be explicitly set to true on the Server. Without this, Serve returns ErrNoAuthConfigured.

If you don't specify a host key, it will generate an Ed25519 key every time. This is convenient except you'll have to deal with clients being confused that the host key is different. It's a better idea to generate or point to an existing key on your system:

log.Fatal(ssh.ListenAndServe(":2222", nil,
    ssh.HostKeyFile("/Users/progrium/.ssh/id_ed25519"),
    ssh.PasswordAuth(authHandler),
))

Although all options have functional option helpers, another way to control the server's behavior is by creating a custom Server:

s := &ssh.Server{
    Addr:             ":2222",
    Handler:          sessionHandler,
    PublicKeyHandler: authHandler,
}
s.AddHostKey(hostKeySigner)

log.Fatal(s.ListenAndServe())

This package automatically handles basic SSH requests like setting environment variables, requesting PTY, and changing window size. These requests are processed, responded to, and any relevant state is updated. This state is then exposed to you via the Session interface.

The Session abstraction supports basic signal forwarding via the Signals method. Terminal modes are not yet supported.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ContextKeyUser is a context key for use with Contexts in this package.
	// The associated value will be of type string.
	ContextKeyUser = &contextKey{"user"}

	// ContextKeySessionID is a context key for use with Contexts in this package.
	// The associated value will be of type string.
	ContextKeySessionID = &contextKey{"session-id"}

	// ContextKeyPermissions is a context key for use with Contexts in this package.
	// The associated value will be of type *Permissions.
	ContextKeyPermissions = &contextKey{"permissions"}

	// ContextKeyClientVersion is a context key for use with Contexts in this package.
	// The associated value will be of type string.
	ContextKeyClientVersion = &contextKey{"client-version"}

	// ContextKeyServerVersion is a context key for use with Contexts in this package.
	// The associated value will be of type string.
	ContextKeyServerVersion = &contextKey{"server-version"}

	// ContextKeyLocalAddr is a context key for use with Contexts in this package.
	// The associated value will be of type net.Addr.
	ContextKeyLocalAddr = &contextKey{"local-addr"}

	// ContextKeyRemoteAddr is a context key for use with Contexts in this package.
	// The associated value will be of type net.Addr.
	ContextKeyRemoteAddr = &contextKey{"remote-addr"}

	// ContextKeyServer is a context key for use with Contexts in this package.
	// The associated value will be of type *Server.
	ContextKeyServer = &contextKey{"ssh-server"}

	// ContextKeyConn is a context key for use with Contexts in this package.
	// The associated value will be of type gossh.ServerConn.
	ContextKeyConn = &contextKey{"ssh-conn"}

	// ContextKeyPublicKey is a context key for use with Contexts in this package.
	// The associated value will be of type PublicKey.
	ContextKeyPublicKey = &contextKey{"public-key"}
)
View Source
var (
	// ErrServerClosed is returned by the Server's Serve, ListenAndServe,
	// and ListenAndServeTLS methods after a call to Shutdown or Close.
	ErrServerClosed = errors.New("ssh: Server closed")

	// ErrNoAuthConfigured is returned when no authentication handlers are set
	// and NoClientAuth is not explicitly enabled.
	ErrNoAuthConfigured = errors.New("ssh: no authentication configured; set an auth handler or explicitly enable NoClientAuth")

	// ErrPermissionDenied is returned by authentication callbacks when access is denied.
	ErrPermissionDenied = errors.New("ssh: permission denied")
)
View Source
var DefaultChannelHandlers = map[string]ChannelHandler{
	"session": DefaultSessionHandler,
}
View Source
var DefaultRequestHandlers = map[string]RequestHandler{}
View Source
var DefaultSubsystemHandlers = map[string]SubsystemHandler{}

Functions

func AgentRequested

func AgentRequested(sess Session) bool

AgentRequested returns true if the client requested agent forwarding.

func DefaultSessionHandler

func DefaultSessionHandler(srv *Server, conn *gossh.ServerConn, newChan gossh.NewChannel, ctx Context)

DefaultSessionHandler is the default channel handler for "session" channels.

func DirectTCPIPHandler

func DirectTCPIPHandler(srv *Server, conn *gossh.ServerConn, newChan gossh.NewChannel, ctx Context)

DirectTCPIPHandler can be enabled by adding it to the server's ChannelHandlers under direct-tcpip.

func ForwardAgentConnections

func ForwardAgentConnections(l net.Listener, s Session)

ForwardAgentConnections takes connections from a listener to proxy into the session on the OpenSSH channel for agent connections. It blocks and services connections until the listener stops accepting.

func Handle

func Handle(handler Handler)

Handle registers the handler as the DefaultHandler.

func KeysEqual

func KeysEqual(ak, bk PublicKey) bool

KeysEqual is constant time compare of the keys to avoid timing attacks.

func ListenAndServe

func ListenAndServe(addr string, handler Handler, options ...Option) error

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle sessions on incoming connections. Handler is typically nil, in which case the DefaultHandler is used.

Example
package main

import (
	"io"

	"eye.dragonsecurity.io/ssh"
)

func main() {
	ssh.ListenAndServe(":2222", func(s ssh.Session) {
		io.WriteString(s, "Hello world\n")
	},
		ssh.PasswordAuth(func(ctx ssh.Context, pass string) bool {
			return pass == "secret"
		}),
	)
}

func NewAgentListener

func NewAgentListener() (net.Listener, error)

NewAgentListener sets up a temporary Unix socket that can be communicated to the session environment and used for forwarding connections. The returned listener cleans up its temporary directory when closed.

func Serve

func Serve(l net.Listener, handler Handler, options ...Option) error

Serve accepts incoming SSH connections on the listener l, creating a new connection goroutine for each. The connection goroutines read requests and then calls handler to handle sessions. Handler is typically nil, in which case the DefaultHandler is used.

func SetAgentRequested

func SetAgentRequested(ctx Context)

SetAgentRequested sets up the session context so that AgentRequested returns true.

Types

type AgentForwardingCallback

type AgentForwardingCallback func(ctx Context) bool

AgentForwardingCallback is a hook for allowing agent forwarding. If nil, agent forwarding is denied.

type BannerHandler

type BannerHandler func(ctx Context) string

BannerHandler is a callback for displaying the server banner.

type ChannelHandler

type ChannelHandler func(srv *Server, conn *gossh.ServerConn, newChan gossh.NewChannel, ctx Context)

ChannelHandler is a callback for handling SSH channel opens.

type ConnCallback

type ConnCallback func(ctx Context, conn net.Conn) net.Conn

ConnCallback is a hook for new connections before handling. It allows wrapping for timeouts and limiting by returning the net.Conn that will be used as the underlying connection.

type ConnectionFailedCallback

type ConnectionFailedCallback func(conn net.Conn, err error)

ConnectionFailedCallback is a hook for reporting failed connections Please note: the net.Conn is likely to be closed at this point

type Context

type Context interface {
	context.Context

	// User returns the username used when establishing the SSH connection.
	User() string

	// SessionID returns the session hash.
	SessionID() string

	// ClientVersion returns the version reported by the client.
	ClientVersion() string

	// ServerVersion returns the version reported by the server.
	ServerVersion() string

	// RemoteAddr returns the remote address for this connection.
	RemoteAddr() net.Addr

	// LocalAddr returns the local address for this connection.
	LocalAddr() net.Addr

	// Permissions returns the Permissions object used for this connection.
	Permissions() *Permissions

	// SetValue allows you to easily write new values into the underlying context.
	SetValue(key, value any)
}

Context is a package specific context interface. It exposes connection metadata and allows new values to be easily written to it. It's used in authentication handlers and callbacks, and its underlying context.Context is exposed on Session in the session Handler.

type ForwardedTCPHandler

type ForwardedTCPHandler struct {
	sync.Mutex
	// contains filtered or unexported fields
}

ForwardedTCPHandler can be enabled by creating a ForwardedTCPHandler and adding the HandleSSHRequest callback to the server's RequestHandlers under tcpip-forward and cancel-tcpip-forward.

func (*ForwardedTCPHandler) HandleSSHRequest

func (h *ForwardedTCPHandler) HandleSSHRequest(ctx Context, srv *Server, req *gossh.Request) (bool, []byte)

type Handler

type Handler func(Session)

Handler is a callback for handling established SSH sessions.

var DefaultHandler Handler

DefaultHandler is the default Handler used by Serve.

type KeyboardInteractiveHandler

type KeyboardInteractiveHandler func(ctx Context, challenger gossh.KeyboardInteractiveChallenge) bool

KeyboardInteractiveHandler is a callback for performing keyboard-interactive authentication.

type LocalPortForwardingCallback

type LocalPortForwardingCallback func(ctx Context, destinationHost string, destinationPort uint32) bool

LocalPortForwardingCallback is a hook for allowing port forwarding

type Option

type Option func(*Server) error

Option is a functional option handler for Server.

func HostKeyFile

func HostKeyFile(filepath string) Option

HostKeyFile returns a functional option that adds HostSigners to the server from a PEM file at filepath.

Example
package main

import (
	"eye.dragonsecurity.io/ssh"
)

func main() {
	ssh.ListenAndServe(":2222", nil,
		ssh.HostKeyFile("/path/to/host/key"),
		ssh.PasswordAuth(func(ctx ssh.Context, pass string) bool {
			return pass == "secret"
		}),
	)
}

func HostKeyPEM

func HostKeyPEM(bytes []byte) Option

HostKeyPEM returns a functional option that adds HostSigners to the server from a PEM file as bytes.

func KeyboardInteractiveAuth

func KeyboardInteractiveAuth(fn KeyboardInteractiveHandler) Option

func NoPty

func NoPty() Option

NoPty returns a functional option that sets PtyCallback to return false, denying PTY requests.

Example
package main

import (
	"eye.dragonsecurity.io/ssh"
)

func main() {
	ssh.ListenAndServe(":2222", nil,
		ssh.NoPty(),
		ssh.PasswordAuth(func(ctx ssh.Context, pass string) bool {
			return pass == "secret"
		}),
	)
}

func PasswordAuth

func PasswordAuth(fn PasswordHandler) Option

PasswordAuth returns a functional option that sets PasswordHandler on the server.

Example
package main

import (
	"eye.dragonsecurity.io/ssh"
)

func main() {
	ssh.ListenAndServe(":2222", nil,
		ssh.PasswordAuth(func(ctx ssh.Context, pass string) bool {
			return pass == "secret"
		}),
	)
}

func PublicKeyAuth

func PublicKeyAuth(fn PublicKeyHandler) Option

PublicKeyAuth returns a functional option that sets PublicKeyHandler on the server.

Example
package main

import (
	"os"

	"eye.dragonsecurity.io/ssh"
)

func main() {
	ssh.ListenAndServe(":2222", nil,
		ssh.PublicKeyAuth(func(ctx ssh.Context, key ssh.PublicKey) bool {
			data, _ := os.ReadFile("/path/to/allowed/key.pub")
			allowed, _, _, _, _ := ssh.ParseAuthorizedKey(data)
			return ssh.KeysEqual(key, allowed)
		}),
	)
}

func WrapConn

func WrapConn(fn ConnCallback) Option

WrapConn returns a functional option that sets ConnCallback on the server.

type PasswordHandler

type PasswordHandler func(ctx Context, password string) bool

PasswordHandler is a callback for performing password authentication.

type Permissions

type Permissions struct {
	*gossh.Permissions
}

The Permissions type holds fine-grained permissions that are specific to a user or a specific authentication method for a user. Permissions, except for "source-address", must be enforced in the server application layer, after successful authentication.

type Pty

type Pty struct {
	Term   string
	Window Window
}

Pty represents a PTY request and configuration.

type PtyCallback

type PtyCallback func(ctx Context, pty Pty) bool

PtyCallback is a hook for allowing PTY sessions.

type PublicKey

type PublicKey interface {
	gossh.PublicKey
}

PublicKey is an abstraction of different types of public keys.

func ParseAuthorizedKey

func ParseAuthorizedKey(in []byte) (out PublicKey, comment string, options []string, rest []byte, err error)

ParseAuthorizedKey parses a public key from an authorized_keys file used in OpenSSH according to the sshd(8) manual page.

func ParsePublicKey

func ParsePublicKey(in []byte) (out PublicKey, err error)

ParsePublicKey parses an SSH public key formatted for use in the SSH wire protocol according to RFC 4253, section 6.6.

type PublicKeyHandler

type PublicKeyHandler func(ctx Context, key PublicKey) bool

PublicKeyHandler is a callback for performing public key authentication.

type RequestHandler

type RequestHandler func(ctx Context, srv *Server, req *gossh.Request) (ok bool, payload []byte)

RequestHandler is a callback for handling server-level SSH requests.

type ReversePortForwardingCallback

type ReversePortForwardingCallback func(ctx Context, bindHost string, bindPort uint32) bool

ReversePortForwardingCallback is a hook for allowing reverse port forwarding

type Server

type Server struct {
	Addr        string   // TCP address to listen on, ":22" if empty
	Handler     Handler  // handler to invoke, ssh.DefaultHandler if nil
	HostSigners []Signer // private keys for the host key, must have at least one
	Version     string   // server version to be sent before the initial handshake
	Banner      string   // server banner

	NoClientAuth                  bool                          // explicitly allow connections without authentication
	BannerHandler                 BannerHandler                 // server banner handler, overrides Banner
	KeyboardInteractiveHandler    KeyboardInteractiveHandler    // keyboard-interactive authentication handler
	PasswordHandler               PasswordHandler               // password authentication handler
	PublicKeyHandler              PublicKeyHandler              // public key authentication handler
	PtyCallback                   PtyCallback                   // callback for allowing PTY sessions, allows all if nil
	ConnCallback                  ConnCallback                  // optional callback for wrapping net.Conn before handling
	LocalPortForwardingCallback   LocalPortForwardingCallback   // callback for allowing local port forwarding, denies all if nil
	ReversePortForwardingCallback ReversePortForwardingCallback // callback for allowing reverse port forwarding, denies all if nil
	ServerConfigCallback          ServerConfigCallback          // callback for configuring detailed SSH options
	SessionRequestCallback        SessionRequestCallback        // callback for allowing or denying SSH sessions
	AgentForwardingCallback       AgentForwardingCallback       // callback for allowing agent forwarding, denies all if nil

	ConnectionFailedCallback ConnectionFailedCallback // callback to report connection failures

	HandshakeTimeout time.Duration // connection timeout until successful handshake, none if empty
	IdleTimeout      time.Duration // connection timeout when no activity, none if empty
	MaxTimeout       time.Duration // absolute connection timeout, none if empty

	// ChannelHandlers allow overriding the built-in session handlers or provide
	// extensions to the protocol, such as tcpip forwarding. By default only the
	// "session" handler is enabled.
	ChannelHandlers map[string]ChannelHandler

	// RequestHandlers allow overriding the server-level request handlers or
	// provide extensions to the protocol, such as tcpip forwarding. By default
	// no handlers are enabled.
	RequestHandlers map[string]RequestHandler

	// SubsystemHandlers are handlers which are similar to the usual SSH command
	// handlers, but handle named subsystems.
	SubsystemHandlers map[string]SubsystemHandler
	// contains filtered or unexported fields
}

Server defines parameters for running an SSH server. The zero value for Server is a valid configuration. When no authentication handler is set, NoClientAuth must be explicitly set to true, otherwise Serve returns ErrNoAuthConfigured.

func (*Server) AddHostKey

func (srv *Server) AddHostKey(key Signer)

AddHostKey adds a private key as a host key. If an existing host key exists with the same algorithm, it is overwritten. Each server config must have at least one host key.

func (*Server) Close

func (srv *Server) Close() error

Close immediately closes all active listeners and all active connections.

Close returns any error returned from closing the Server's underlying Listener(s).

func (*Server) Handle

func (srv *Server) Handle(fn Handler)

Handle sets the Handler for the server.

func (*Server) HandleConn

func (srv *Server) HandleConn(newConn net.Conn)

func (*Server) ListenAndServe

func (srv *Server) ListenAndServe() error

ListenAndServe listens on the TCP network address srv.Addr and then calls Serve to handle incoming connections. If srv.Addr is blank, ":22" is used. ListenAndServe always returns a non-nil error.

func (*Server) Serve

func (srv *Server) Serve(l net.Listener) error

Serve accepts incoming connections on the Listener l, creating a new connection goroutine for each. The connection goroutines read requests and then calls srv.Handler to handle sessions.

Serve always returns a non-nil error.

func (*Server) SetOption

func (srv *Server) SetOption(option Option) error

SetOption runs a functional option against the server.

func (*Server) Shutdown

func (srv *Server) Shutdown(ctx context.Context) error

Shutdown gracefully shuts down the server without interrupting any active connections. Shutdown works by first closing all open listeners, and then waiting indefinitely for connections to close. If the provided context expires before the shutdown is complete, then the context's error is returned.

type ServerConfigCallback

type ServerConfigCallback func(ctx Context) *gossh.ServerConfig

ServerConfigCallback is a hook for creating custom default server configs

type Session

type Session interface {
	gossh.Channel

	// User returns the username used when establishing the SSH connection.
	User() string

	// RemoteAddr returns the net.Addr of the client side of the connection.
	RemoteAddr() net.Addr

	// LocalAddr returns the net.Addr of the server side of the connection.
	LocalAddr() net.Addr

	// Environ returns a copy of strings representing the environment set by the
	// user for this session, in the form "key=value".
	Environ() []string

	// Exit sends an exit status and then closes the session.
	Exit(code int) error

	// Command returns a shell parsed slice of arguments that were provided by the
	// user. Shell parsing splits the command string according to POSIX shell rules,
	// which considers quoting not just whitespace.
	Command() []string

	// RawCommand returns the exact command that was provided by the user.
	RawCommand() string

	// Subsystem returns the subsystem requested by the user.
	Subsystem() string

	// PublicKey returns the PublicKey used to authenticate. If a public key was not
	// used it will return nil.
	PublicKey() PublicKey

	// Context returns the connection's context. The returned context is always
	// non-nil and holds the same data as the Context passed into auth
	// handlers and callbacks.
	//
	// The context is canceled when the client's connection closes or I/O
	// operation fails.
	Context() Context

	// Permissions returns a copy of the Permissions object that was available for
	// setup in the auth handlers via the Context.
	Permissions() Permissions

	// Pty returns PTY information, a channel of window size changes, and a boolean
	// of whether or not a PTY was accepted for this session.
	Pty() (Pty, <-chan Window, bool)

	// Signals registers a channel to receive signals sent from the client. The
	// channel must handle signal sends or it will block the SSH request loop.
	// Registering nil will unregister the channel from signal sends. During the
	// time no channel is registered signals are buffered up to a reasonable amount.
	// If there are buffered signals when a channel is registered, they will be
	// sent in order on the channel immediately after registering.
	Signals(c chan<- Signal)

	// Break registers a channel to receive notifications of break requests sent
	// from the client. The channel must handle break requests, or it will block
	// the request handling loop. Registering nil will unregister the channel.
	// During the time that no channel is registered, breaks are ignored.
	Break(c chan<- bool)
}

Session provides access to information about an SSH session and methods to read and write to the SSH channel with an embedded Channel interface from crypto/ssh.

When Command() returns an empty slice, the user requested a shell. Otherwise the user is performing an exec with those command arguments.

type SessionRequestCallback

type SessionRequestCallback func(sess Session, requestType string) bool

SessionRequestCallback is a callback for allowing or denying SSH sessions.

type Signal

type Signal string
const (
	SIGABRT Signal = "ABRT"
	SIGALRM Signal = "ALRM"
	SIGFPE  Signal = "FPE"
	SIGHUP  Signal = "HUP"
	SIGILL  Signal = "ILL"
	SIGINT  Signal = "INT"
	SIGKILL Signal = "KILL"
	SIGPIPE Signal = "PIPE"
	SIGQUIT Signal = "QUIT"
	SIGSEGV Signal = "SEGV"
	SIGTERM Signal = "TERM"
	SIGUSR1 Signal = "USR1"
	SIGUSR2 Signal = "USR2"
)

POSIX signals as listed in RFC 4254 Section 6.10.

type Signer

type Signer interface {
	gossh.Signer
}

A Signer can create signatures that verify against a public key.

type SubsystemHandler

type SubsystemHandler func(s Session)

SubsystemHandler is a callback for handling named subsystems.

type Window

type Window struct {
	Width  int
	Height int
}

Window represents the size of a PTY window.

Jump to

Keyboard shortcuts

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