sshserver

package
v0.0.0-...-ef38420 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package sshserver provides OpenSSH daemon configuration parsing and resolution. It reads sshd_config(5) files, applies Match blocks, command-line overrides (-o), and defaults to produce a resolved configuration that can be converted to golang.org/x/crypto/ssh.ServerConfig.

Optional features are surfaced through handler interfaces defined in handlers.go; a caller supplies only the handlers it cares about and the rest are ignored.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllSupportedCiphers

func AllSupportedCiphers() []string

AllSupportedCiphers returns both secure and insecure ciphers.

func AllSupportedHostKeyAlgorithms

func AllSupportedHostKeyAlgorithms() []string

AllSupportedHostKeyAlgorithms returns all host key signing algorithms.

func AllSupportedKexAlgorithms

func AllSupportedKexAlgorithms() []string

AllSupportedKexAlgorithms returns all key exchange algorithms.

func AllSupportedMACs

func AllSupportedMACs() []string

AllSupportedMACs returns all MAC algorithms.

func AllSupportedPublicKeyAlgorithms

func AllSupportedPublicKeyAlgorithms() []string

AllSupportedPublicKeyAlgorithms returns all public key auth algorithms.

func ParseConnectionSpec

func ParseConnectionSpec(specs []string) map[string]string

ParseConnectionSpec parses a single -C argument (comma-separated key=value pairs) into a MatchContext overlay. Used by -T/-G test modes to simulate a connection for Match block evaluation.

func ResolveCASignatureAlgorithms

func ResolveCASignatureAlgorithms(raw string) []string

ResolveCASignatureAlgorithms resolves the CASignatureAlgorithms option.

func ResolveCiphers

func ResolveCiphers(raw string) []string

ResolveCiphers resolves the Ciphers option.

func ResolveHostKeyAlgorithms

func ResolveHostKeyAlgorithms(raw string) []string

ResolveHostKeyAlgorithms resolves the HostKeyAlgorithms option.

func ResolveHostbasedAcceptedAlgorithms

func ResolveHostbasedAcceptedAlgorithms(raw string) []string

ResolveHostbasedAcceptedAlgorithms resolves the HostbasedAcceptedAlgorithms option.

func ResolveKexAlgorithms

func ResolveKexAlgorithms(raw string) []string

ResolveKexAlgorithms resolves the KexAlgorithms option.

func ResolveMACs

func ResolveMACs(raw string) []string

ResolveMACs resolves the MACs option.

func ResolvePubkeyAcceptedAlgorithms

func ResolvePubkeyAcceptedAlgorithms(raw string) []string

ResolvePubkeyAcceptedAlgorithms resolves the PubkeyAcceptedAlgorithms option.

func Serve

func Serve(listener net.Listener, opts *Options, handlers Handlers) error

Serve accepts connections on the given listener and hands each one to ServeConn in its own goroutine. Blocks until the listener errors or returns net.ErrClosed. The returned error is never nil; it is net.ErrClosed for a clean shutdown.

func ServeConn

func ServeConn(raw net.Conn, opts *Options, handlers Handlers) error

ServeConn performs the server-side SSH handshake on a single net.Conn, dispatches accepted channels to the session handler, and services global requests. The connection is closed before return. Returns nil on clean disconnect, or an error describing why the session failed.

Types

type AccessController

type AccessController interface {
	// CheckAccess is called after authentication but before the connection
	// is accepted. It may return an error to deny access.
	CheckAccess(meta ssh.ConnMetadata, perms *ssh.Permissions, opts *Options) error
}

AccessController enforces coarse-grained access policies before authentication is considered successful.

Relevant options:

  • AllowUsers, DenyUsers, AllowGroups, DenyGroups, RefuseConnection, MaxSessions

type AgentForwarder

type AgentForwarder interface {
	HandleAgentRequest(ctx SessionContext) error
}

AgentForwarder handles ssh-agent forwarding.

Relevant options:

  • AllowAgentForwarding, DisableForwarding

type AuthorizedKeysAuthenticator

type AuthorizedKeysAuthenticator struct{}

AuthorizedKeysAuthenticator is a minimal PublicKeyAuthenticator that reads keys from the target user's AuthorizedKeysFile paths and accepts any matching public key. It does NOT currently evaluate key options (from=, command=, etc.) — callers needing those semantics should wrap this implementation.

func (*AuthorizedKeysAuthenticator) AuthenticatePublicKey

func (a *AuthorizedKeysAuthenticator) AuthenticatePublicKey(meta ssh.ConnMetadata, key ssh.PublicKey, opts *Options) (*ssh.Permissions, error)

AuthenticatePublicKey implements PublicKeyAuthenticator.

type CLIArgs

type CLIArgs struct {
	// -4 / -6: AddressFamily restriction
	IPv4Only bool
	IPv6Only bool

	// -C connection_spec (repeatable): simulation parameters for -T/-G
	ConnectionSpec []string

	// -c host_certificate_file (repeatable)
	HostCertFiles []string

	// -D: foreground mode (do not daemonize)
	Foreground bool

	// -d: debug mode, bumps log level and forces foreground
	DebugLevel int

	// -E log_file: append logs here
	LogFile string

	// -e: log to stderr
	LogStderr bool

	// -f config_file: config file path
	ConfigFile string

	// -g login_grace_time: LoginGraceTime override
	LoginGraceTime string

	// -h host_key_file (repeatable)
	HostKeyFiles []string

	// -i: inetd mode
	Inetd bool

	// -o option (repeatable): raw -o entries
	Options []string

	// -p port (repeatable): Port overrides
	Ports []int

	// -q: quiet mode
	Quiet bool

	// -T: extended test mode (validate config, print, exit)
	TestMode bool

	// -G: parse-and-print config mode
	PrintConfig bool

	// -t: validate config and keys, exit
	Validate bool

	// -u len: utmp hostname truncation size
	UtmpHostLen *int

	// -V: print version
	Version bool
	// contains filtered or unexported fields
}

CLIArgs holds parsed sshd command-line arguments matching the invocation documented in sshd(8).

func (*CLIArgs) Directives

func (a *CLIArgs) Directives() ([]sshconfig.Directive, error)

Directives returns the config directives derived from CLI flags, followed by raw -o options parsed as directives.

func (*CLIArgs) Parse

func (a *CLIArgs) Parse(args ...string) error

Parse parses sshd command-line arguments into the receiver. Fields set before calling Parse are preserved unless overridden.

type CommandExecutor

type CommandExecutor interface {
	// Execute runs cmd as the given user (empty user = current process user).
	// It returns stdout; caller is responsible for parsing it.
	ExecuteAs(user, cmd string, args []string) ([]byte, error)
}

CommandExecutor executes local commands for features such as AuthorizedKeysCommand, AuthorizedPrincipalsCommand, and ForceCommand.

type DefaultSessionHandler

type DefaultSessionHandler struct {
	// ProcessLauncher runs shell and exec requests. If nil, shell and exec
	// requests are rejected but subsystem dispatch still functions.
	ProcessLauncher ProcessLauncher
}

DefaultSessionHandler services "session" channels using a conventional shell/exec/subsystem dispatch. It is designed as a drop-in for common deployments: pty-req allocates a pseudo-terminal for the user's shell, exec requests run commands through the login shell, and subsystem requests are resolved via the Options.LookupSubsystem registry.

The handler recognizes the following channel requests:

  • pty-req : record PTY parameters (actual PTY allocation is delegated to the process launcher)
  • env : collect environment variables subject to AcceptEnv
  • shell / exec : run the command via ProcessLauncher.Run
  • subsystem : resolve the subsystem and dispatch; internal subsystems call Subsystem.Handler, external subsystems are executed as processes
  • window-change : forwarded to ProcessLauncher.Resize if supported
  • signal : forwarded to ProcessLauncher.Signal if supported

A nil ProcessLauncher disables shell/exec (they are rejected), but subsystems continue to work.

func (*DefaultSessionHandler) HandleSession

func (h *DefaultSessionHandler) HandleSession(ctx SessionContext) error

HandleSession implements SessionHandler.

type DefaultTcpForwarder

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

DefaultTcpForwarder provides a straightforward TCP forwarding implementation suitable for drop-in use. It proxies direct-tcpip channels by dialing the requested destination, and services tcpip-forward global requests by listening on the requested address and opening forwarded-tcpip channels for each accepted connection.

PermitOpen and PermitListen policies are enforced where applicable. The forwarder does NOT perform GSS-API or SOCKS specific handling — those concerns belong in higher-level code.

func (*DefaultTcpForwarder) HandleDirectTcpIP

func (f *DefaultTcpForwarder) HandleDirectTcpIP(nc ssh.NewChannel, meta ssh.ConnMetadata, opts *Options) error

HandleDirectTcpIP accepts a direct-tcpip channel, dials the requested host:port, and shuttles data both ways. PermitOpen is enforced before the dial; disallowed destinations are rejected with Prohibited.

func (*DefaultTcpForwarder) StartRemoteForward

func (f *DefaultTcpForwarder) StartRemoteForward(bindAddr string, bindPort uint32, conn *ssh.ServerConn, opts *Options) (uint32, error)

StartRemoteForward begins listening on bindAddr:bindPort and forwards each accepted connection over a forwarded-tcpip channel on conn.

func (*DefaultTcpForwarder) StopRemoteForward

func (f *DefaultTcpForwarder) StopRemoteForward(bindAddr string, bindPort uint32, conn *ssh.ServerConn) error

StopRemoteForward cancels a previously-started remote forward.

type DenyPasswordAuthenticator

type DenyPasswordAuthenticator struct{}

DenyPasswordAuthenticator is a PasswordAuthenticator that rejects every attempt. It is a safe default for deployments that rely solely on public-key authentication.

func (DenyPasswordAuthenticator) AuthenticatePassword

func (DenyPasswordAuthenticator) AuthenticatePassword(_ ssh.ConnMetadata, _ []byte, _ *Options) (*ssh.Permissions, error)

AuthenticatePassword always returns an error.

type ExecProcessLauncher

type ExecProcessLauncher struct {
	// Shell is the default login shell for the authenticated user.
	// For "shell" requests, the launcher runs Shell with no arguments.
	// For "exec" requests it runs Shell -c <command>.
	// If empty, "/bin/sh" is used.
	Shell string
}

ExecProcessLauncher is a minimal ProcessLauncher that runs commands via os/exec in the current process's user context. It does NOT switch uids, allocate PTYs, or enforce ChrootDirectory — it exists as a reference implementation for test deployments and as a starting point for more capable launchers.

func (*ExecProcessLauncher) Resize

func (l *ExecProcessLauncher) Resize(_ WindowChange) error

Resize is a no-op for the reference launcher.

func (*ExecProcessLauncher) Run

func (l *ExecProcessLauncher) Run(req ProcessRequest, reporter ExitReporter) error

Run implements ProcessLauncher.

func (*ExecProcessLauncher) Signal

func (l *ExecProcessLauncher) Signal(_ string) error

Signal is a no-op for the reference launcher.

type ExitReporter

type ExitReporter interface {
	// Exit reports a normal process exit.
	Exit(status uint32) error
	// ExitSignal reports that the process was terminated by a signal.
	ExitSignal(sig string, core bool, errMsg string) error
}

ExitReporter lets ProcessLauncher report the command's exit code back to the SSH client via an "exit-status" channel request.

type Handlers

type Handlers struct {

	// PasswordAuth validates a password. If nil, password authentication
	// is unavailable regardless of PasswordAuthentication in the config.
	PasswordAuth PasswordAuthenticator

	// PublicKeyAuth validates a client public key against the target
	// user's authorized keys, certificate principals, etc.
	PublicKeyAuth PublicKeyAuthenticator

	// KeyboardInteractiveAuth drives a keyboard-interactive exchange.
	KeyboardInteractiveAuth KeyboardInteractiveAuthenticator

	// HostbasedAuth validates hostbased authentication.
	HostbasedAuth HostbasedAuthenticator

	// GSSAPIServer provides the server-side GSSAPI implementation.
	GSSAPIServer ssh.GSSAPIServer

	// AccessController enforces AllowUsers/DenyUsers/AllowGroups/DenyGroups
	// and related policies. It is invoked before authentication succeeds.
	AccessController AccessController

	// HostKeyProvider returns the signers used as host keys. When non-nil
	// it overrides the file-based HostKey resolution. This is useful for
	// agent-backed host keys (HostKeyAgent) or for callers that manage
	// host keys themselves.
	HostKeyProvider HostKeyProvider

	// SessionHandler handles accepted "session" channels. It must service
	// channel requests ("pty-req", "shell", "exec", "subsystem", ...) and
	// read/write channel data. A nil SessionHandler causes session channels
	// to be rejected.
	SessionHandler SessionHandler

	// TcpForwarder handles "direct-tcpip" channel requests (local→remote
	// forwarding initiated by the client) and global "tcpip-forward"
	// requests (remote→local forwarding). A nil TcpForwarder rejects all
	// TCP forwarding regardless of AllowTcpForwarding.
	TcpForwarder TcpForwarder

	// StreamLocalForwarder handles Unix-domain socket forwarding
	// (direct-streamlocal and streamlocal-forward).
	StreamLocalForwarder StreamLocalForwarder

	// AgentForwarder handles "auth-agent-req@openssh.com" requests.
	AgentForwarder AgentForwarder

	// X11Forwarder handles "x11-req" requests.
	X11Forwarder X11Forwarder

	// TunnelForwarder handles "tun@openssh.com" requests.
	TunnelForwarder TunnelForwarder

	// CommandExecutor runs local commands such as AuthorizedKeysCommand
	// or AuthorizedPrincipalsCommand.
	CommandExecutor CommandExecutor

	// Logger receives diagnostic log messages.
	Logger Logger
}

Handlers holds optional interface implementations for SSH daemon features that cannot be derived solely from the config file. Each handler covers a functional group of options. A nil handler means the corresponding feature is unavailable (or uses a built-in fallback where applicable).

Zero-value Handlers (all nil) yields a minimal server that still performs protocol handshake, auth via embedded callbacks, and session dispatch — but cannot authenticate users, run commands, or forward anything.

type HostKeyProvider

type HostKeyProvider interface {
	HostKeys(opts *Options) ([]ssh.Signer, error)
}

HostKeyProvider returns the signers to use as host keys. When non-nil, it overrides the file-based HostKey directive resolution.

Relevant options:

  • HostKey, HostKeyAgent, HostCertificate

type HostbasedAuthenticator

type HostbasedAuthenticator interface {
	AuthenticateHostbased(meta ssh.ConnMetadata, key ssh.PublicKey, clientHost, clientUser string, opts *Options) (*ssh.Permissions, error)
}

HostbasedAuthenticator validates hostbased authentication.

Relevant options:

  • HostbasedAuthentication, HostbasedAcceptedAlgorithms, HostbasedUsesNameFromPacketOnly, IgnoreRhosts, IgnoreUserKnownHosts

type KeyboardInteractiveAuthenticator

type KeyboardInteractiveAuthenticator interface {
	AuthenticateKeyboardInteractive(meta ssh.ConnMetadata, client ssh.KeyboardInteractiveChallenge, opts *Options) (*ssh.Permissions, error)
}

KeyboardInteractiveAuthenticator drives a keyboard-interactive exchange.

Relevant options:

  • KbdInteractiveAuthentication, UsePAM, PAMServiceName

type Logger

type Logger interface {
	Log(level, msg string)
}

Logger receives diagnostic messages from the SSH daemon.

Relevant options:

  • LogLevel, LogVerbose, SyslogFacility

type Lookup

type Lookup struct {
	// ConfigFile is the path to sshd_config.
	// Empty means /etc/ssh/sshd_config.
	ConfigFile string

	// CommandLineDirectives are pre-parsed directives from CLI flags,
	// highest priority. Applied before CommandLineOptions.
	CommandLineDirectives []sshconfig.Directive

	// CommandLineOptions are raw -o "Key=Value" strings from the -o flag.
	CommandLineOptions []string

	// User is the authenticating user (empty during boot).
	User string
	// Groups are the user's groups.
	Groups []string
	// Host is the DNS-resolved client hostname (empty if UseDNS=no).
	Host string
	// RemoteAddr is the client address in "ip:port" or bare IP form.
	RemoteAddr string
	// LocalAddr is the server address the client connected to.
	LocalAddr string
	// LocalPort is the server port.
	LocalPort int
	// RDomain is the routing domain.
	RDomain string
	// InvalidUser indicates an unknown account.
	InvalidUser bool

	// Version is the server version string (for Match version).
	Version string

	// ExecFunc evaluates "Match exec" commands. If nil, exec conditions
	// always evaluate to false.
	ExecFunc func(cmd string) bool
}

Lookup specifies the inputs for SSH daemon configuration resolution. At boot time many fields are zero; per-connection re-resolution fills in the RemoteAddr / LocalAddr / User fields to allow Match blocks to fire.

func (*Lookup) Resolve

func (l *Lookup) Resolve() (*Options, error)

Resolve applies the sshd configuration resolution algorithm:

  1. Command-line directives (-f/-o flags)
  2. Config file
  3. Defaults

For each matching block, first-value-wins for scalar options. Multi-value options (HostKey, ListenAddress, etc.) are accumulated.

type Options

type Options struct {
	// --- Listening ---
	AddressFamily  *string  // "any", "inet", "inet6"
	ListenAddress  []string // multi-value, accumulated (raw strings)
	Ports          []int    // multi-value, accumulated (accumulated; 'Port' directive)
	BindInterface  *string  // (not standard sshd_config; reserved for symmetry)
	RDomain        *string  // %D substitution target
	LoginGraceTime *int     // seconds; 0 = none

	// --- Host Keys ---
	HostKey           []string // multi-value; paths to private host keys
	HostKeyAgent      *string  // agent socket path or "SSH_AUTH_SOCK"
	HostCertificate   []string // multi-value; paths to host cert files
	TrustedUserCAKeys *string  // path to CA file
	RevokedKeys       *string  // path to revoked keys file

	// --- Crypto ---
	Ciphers                     *string // raw, may have +/-/^ prefix
	KexAlgorithms               *string // raw, may have +/-/^ prefix
	MACs                        *string // raw, may have +/-/^ prefix
	HostKeyAlgorithms           *string // raw, may have +/-/^ prefix
	CASignatureAlgorithms       *string // raw, may have +/-/^ prefix
	PubkeyAcceptedAlgorithms    *string // raw
	HostbasedAcceptedAlgorithms *string // raw
	RekeyLimit                  *string // "bytes [time]"
	RequiredRSASize             *int    // bits
	FingerprintHash             *string // "md5", "sha256"

	// --- Authentication ---
	AuthenticationMethods           *string // whitespace-separated lists
	PermitRootLogin                 *string // "yes", "prohibit-password", "forced-commands-only", "no"
	PasswordAuthentication          *bool
	PermitEmptyPasswords            *bool
	KbdInteractiveAuthentication    *bool
	PubkeyAuthentication            *bool
	PubkeyAuthOptions               *string // "none", "touch-required", "verify-required", ...
	HostbasedAuthentication         *bool
	HostbasedUsesNameFromPacketOnly *bool
	IgnoreRhosts                    *string // "yes", "no", "shosts-only"
	IgnoreUserKnownHosts            *bool
	GSSAPIAuthentication            *bool
	GSSAPICleanupCredentials        *bool
	GSSAPIStrictAcceptorCheck       *bool
	KerberosAuthentication          *bool
	KerberosGetAFSToken             *bool
	KerberosOrLocalPasswd           *bool
	KerberosTicketCleanup           *bool
	UsePAM                          *bool
	PAMServiceName                  *string
	MaxAuthTries                    *int
	LoginMaxRetries                 *int
	StrictModes                     *bool
	ExposeAuthInfo                  *bool
	PermitUserEnvironment           *string // "yes", "no", or pattern list
	PermitUserRC                    *bool

	// --- Access Control ---
	AllowUsers       []string // multi-value; user patterns
	DenyUsers        []string
	AllowGroups      []string
	DenyGroups       []string
	RefuseConnection *string // unconditional termination reason

	// --- Authorized Keys ---
	AuthorizedKeysFile              []string // default: ".ssh/authorized_keys .ssh/authorized_keys2"
	AuthorizedKeysCommand           *string
	AuthorizedKeysCommandUser       *string
	AuthorizedPrincipalsFile        *string
	AuthorizedPrincipalsCommand     *string
	AuthorizedPrincipalsCommandUser *string

	// --- Session / Forwarding ---
	AllowAgentForwarding       *bool
	AllowTcpForwarding         *string // "yes", "no", "local", "remote", "all"
	AllowStreamLocalForwarding *string // "yes", "no", "local", "remote", "all"
	DisableForwarding          *bool
	GatewayPorts               *string // "yes", "no", "clientspecified"
	PermitOpen                 []string
	PermitListen               []string
	PermitTTY                  *bool
	PermitTunnel               *string // "yes", "no", "point-to-point", "ethernet"
	X11Forwarding              *bool
	X11DisplayOffset           *int
	X11UseLocalhost            *bool
	XAuthLocation              *string
	StreamLocalBindMask        *string // octal
	StreamLocalBindUnlink      *bool
	ChrootDirectory            *string
	ForceCommand               *string
	Banner                     *string // path to file
	PrintLastLog               *bool
	PrintMotd                  *bool

	// --- Session Env ---
	AcceptEnv []string // multi-value
	SetEnv    []string // multi-value

	// --- Connection Lifetime ---
	TCPKeepAlive               *bool
	ClientAliveInterval        *int
	ClientAliveCountMax        *int
	UnusedConnectionTimeout    *string // "none" or time spec
	MaxSessions                *int
	MaxStartups                *string // "start:rate:full"
	PerSourceMaxStartups       *string
	PerSourceNetBlockSize      *string
	PerSourcePenalties         *string
	PerSourcePenaltyExemptList *string
	IPQoS                      *string
	ChannelTimeout             []string // multi-value; "type=interval"

	// --- Logging ---
	LogLevel       *string
	LogVerbose     []string
	SyslogFacility *string

	// --- Protocol ---
	Compression     *string // "yes", "delayed", "no"
	VersionAddendum *string
	ModuliFile      *string
	UseDNS          *bool

	// --- Subsystems ---
	// Subsystem maps a subsystem name (e.g. "sftp") to its definition.
	// An internal subsystem registered via a handler does not need to
	// appear here.
	Subsystems map[string]Subsystem

	// --- Daemon ---
	PidFile             *string
	SecurityKeyProvider *string
	SshdAuthPath        *string
	SshdSessionPath     *string

	// --- Misc ---
	IgnoreUnknown *string // pattern list

	// DialerConfig is populated during Resolve and can be adjusted by callers
	// before any server-initiated outbound connection is started.
	DialerConfig dialer.DialConfig
	// contains filtered or unexported fields
}

Options holds all resolved SSH daemon configuration options. Pointer fields distinguish "not set" (nil) from the zero value. After Resolve(), all fields populated here will either hold a user-provided value, a default, or remain nil if no default applies.

func (*Options) ApplyDirective

func (opts *Options) ApplyDirective(dir sshconfig.Directive) error

ApplyDirective sets the appropriate field in opts based on the directive. For scalar (first-value-wins) options, the field is only set if currently nil. For multi-value options, the value is appended.

func (*Options) GetDialer

func (opts *Options) GetDialer() dialer.Dialer

GetDialer returns the server-side outbound dialer derived from the resolved configuration.

func (*Options) GetDialerConfig

func (opts *Options) GetDialerConfig() dialer.DialConfig

GetDialerConfig returns the stored dialer configuration. Resolve populates this field, and callers may adjust it before starting any action.

func (*Options) Listen

func (opts *Options) Listen() ([]net.Listener, error)

Listen starts TCP listeners for every address:port combination derived from ListenAddress and Port directives. It returns the collection of active listeners. The caller is responsible for calling Close on each.

func (*Options) LookupSubsystem

func (opts *Options) LookupSubsystem(name string) (Subsystem, bool)

LookupSubsystem returns the subsystem definition for the given name, preferring internal subsystems over external ones.

func (*Options) RefreshDialerConfig

func (opts *Options) RefreshDialerConfig()

RefreshDialerConfig rebuilds DialerConfig from the parsed server options.

func (*Options) RegisterInternalSubsystem

func (opts *Options) RegisterInternalSubsystem(name string, handler SubsystemHandler)

RegisterInternalSubsystem records an in-process subsystem handler. It is safe to call this on an Options value before or after Resolve. An internal subsystem overrides any external definition with the same name.

func (*Options) SSHServerConfig

func (opts *Options) SSHServerConfig(handlers Handlers) (*ssh.ServerConfig, error)

SSHServerConfig converts the resolved Options into an ssh.ServerConfig, wiring the supplied handlers into the appropriate callbacks and loading the host keys from HostKey files or the HostKeyProvider handler.

The returned config is suitable for immediate use with ssh.NewServerConn.

type PTYRequest

type PTYRequest struct {
	Term   string
	Width  uint32
	Height uint32
	Modes  []byte
}

PTYRequest carries the "pty-req" parameters.

type PasswordAuthenticator

type PasswordAuthenticator interface {
	AuthenticatePassword(meta ssh.ConnMetadata, password []byte, opts *Options) (*ssh.Permissions, error)
}

PasswordAuthenticator validates a password for a given user. Return a non-nil Permissions on success; return an error to deny.

Relevant options:

  • PasswordAuthentication, PermitEmptyPasswords, PermitRootLogin, UsePAM, PAMServiceName

type ProcessLauncher

type ProcessLauncher interface {
	// Run starts the process attached to the session channel. It returns
	// when the process exits. The exit status (if any) is written back to
	// the client through the provided ExitReporter.
	Run(req ProcessRequest, reporter ExitReporter) error

	// Resize forwards a window-change request. Return nil for no-op.
	Resize(req WindowChange) error

	// Signal forwards a signal request. Return nil for no-op.
	Signal(sig string) error
}

ProcessLauncher runs a user command for a "shell" or "exec" request. Implementations handle PTY allocation, env variable application, uid switching, chroot, and so on — the pkg/server code only forwards the session channel to the launcher.

type ProcessRequest

type ProcessRequest struct {
	// User is the authenticated remote user.
	User string

	// Command is the command to run. For "shell" requests, Command is empty.
	Command string

	// Env is the approved environment list (applied after AcceptEnv filtering).
	Env []string

	// PTY holds the pseudo-terminal request details, or nil for no PTY.
	PTY *PTYRequest

	// Stdin, Stdout, Stderr are the three streams of the session channel.
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
}

ProcessRequest describes a session command to run.

type PublicKeyAuthenticator

type PublicKeyAuthenticator interface {
	AuthenticatePublicKey(meta ssh.ConnMetadata, key ssh.PublicKey, opts *Options) (*ssh.Permissions, error)
}

PublicKeyAuthenticator validates a client-offered public key. Return a non-nil Permissions on success; return an error to deny.

Relevant options:

  • PubkeyAuthentication, AuthorizedKeysFile, AuthorizedKeysCommand, AuthorizedKeysCommandUser, AuthorizedPrincipalsFile, AuthorizedPrincipalsCommand, TrustedUserCAKeys, RevokedKeys, PubkeyAcceptedAlgorithms, RequiredRSASize, PubkeyAuthOptions

type SessionContext

type SessionContext interface {
	// Channel returns the session data channel.
	Channel() ssh.Channel

	// Requests returns the channel request stream. The handler is
	// responsible for calling Reply on requests that set WantReply.
	Requests() <-chan *ssh.Request

	// ConnMetadata returns the underlying connection metadata.
	ConnMetadata() ssh.ConnMetadata

	// Permissions returns the permissions returned by the successful
	// authentication callback, or nil for pre-auth contexts.
	Permissions() *ssh.Permissions

	// Options returns the resolved config options. Options are matched
	// per-connection at accept time.
	Options() *Options

	// Handlers returns the global handler set (so the session handler can
	// dispatch to TcpForwarder, X11Forwarder, etc. for sub-requests).
	Handlers() Handlers

	// LookupSubsystem returns a subsystem definition by name. It consults
	// internal subsystems first, then sshd_config entries.
	LookupSubsystem(name string) (Subsystem, bool)
}

SessionContext is the per-session interface exposed to a SessionHandler. It bundles the channel, request stream, connection metadata, and the resolved options — a handler can read requests, write responses, launch commands, and dispatch subsystems without depending on the server's internal goroutine plumbing.

type SessionHandler

type SessionHandler interface {
	HandleSession(ctx SessionContext) error
}

SessionHandler handles accepted "session" channels. The handler is given the newly-accepted channel and its request stream and is responsible for servicing pty-req, shell/exec/subsystem, env, signal, window-change, and break requests.

Relevant options:

  • PermitTTY, ForceCommand, ChrootDirectory, AcceptEnv, SetEnv, PermitUserEnvironment, PermitUserRC, PrintLastLog, PrintMotd, Banner, ChannelTimeout, UnusedConnectionTimeout, Subsystem

type SimpleAccessController

type SimpleAccessController struct{}

SimpleAccessController enforces AllowUsers/DenyUsers against the authenticated username. It does not consult group membership — callers needing AllowGroups/DenyGroups should compose their own controller.

func (SimpleAccessController) CheckAccess

func (SimpleAccessController) CheckAccess(meta ssh.ConnMetadata, _ *ssh.Permissions, opts *Options) error

CheckAccess implements AccessController.

type StaticPasswordAuthenticator

type StaticPasswordAuthenticator struct {
	// Users maps usernames to their passwords.
	Users map[string]string
}

StaticPasswordAuthenticator authenticates by looking up the user/password in an in-memory map. It is intended for tests and simple deployments only — production should use PAM or a dedicated backend.

func (*StaticPasswordAuthenticator) AuthenticatePassword

func (s *StaticPasswordAuthenticator) AuthenticatePassword(meta ssh.ConnMetadata, password []byte, _ *Options) (*ssh.Permissions, error)

AuthenticatePassword implements PasswordAuthenticator.

type StreamLocalForwarder

type StreamLocalForwarder interface {
	HandleDirectStreamLocal(nc ssh.NewChannel, meta ssh.ConnMetadata, opts *Options) error
	StartRemoteStreamLocalForward(path string, conn *ssh.ServerConn, opts *Options) error
	StopRemoteStreamLocalForward(path string, conn *ssh.ServerConn) error
}

StreamLocalForwarder handles Unix-domain socket forwarding.

Relevant options:

  • AllowStreamLocalForwarding, DisableForwarding, PermitOpen, PermitListen, StreamLocalBindMask, StreamLocalBindUnlink

type Subsystem

type Subsystem struct {
	// Name is the subsystem name as negotiated by the client (e.g. "sftp").
	Name string

	// Command is the external command to run for this subsystem.
	// Empty for internal subsystems.
	Command string

	// Internal indicates an in-process subsystem. When true, Handler is
	// invoked by the server's session handler on a subsystem request.
	Internal bool

	// Handler is invoked for internal subsystems. It must consume the
	// channel I/O itself; the caller closes the channel after return.
	// Nil for external subsystems.
	Handler SubsystemHandler
}

Subsystem represents a subsystem definition from sshd_config. External subsystems have a non-empty Command that is executed when the subsystem is requested. Internal subsystems are registered in code via Options.RegisterInternalSubsystem and carry a Handler rather than a command.

type SubsystemContext

type SubsystemContext interface {
	// Name returns the requested subsystem name (e.g. "sftp").
	Name() string

	// Stdin returns the channel read side.
	Stdin() io.Reader

	// Stdout returns the channel write side (normal data).
	Stdout() io.Writer

	// Stderr returns the channel stderr side (extended data).
	Stderr() io.Writer

	// Channel returns the underlying channel for handlers that need
	// low-level access (e.g. sending requests).
	Channel() ssh.Channel

	// ConnMetadata returns the underlying connection metadata.
	ConnMetadata() ssh.ConnMetadata

	// Options returns the resolved options for this connection.
	Options() *Options
}

SubsystemContext provides everything a subsystem needs to service a single request.

func NewSubsystemContext

func NewSubsystemContext(name string, channel ssh.Channel, meta ssh.ConnMetadata, opts *Options) SubsystemContext

NewSubsystemContext wraps a session channel for delivery to an internal subsystem handler. SessionHandler implementations that do their own subsystem dispatch can call this to construct the context they pass to Subsystem.Handler.

type SubsystemHandler

type SubsystemHandler interface {
	HandleSubsystem(ctx SubsystemContext) error
}

SubsystemHandler services a single in-process subsystem invocation. The handler owns the channel I/O for its duration; the server closes the channel after the handler returns.

type SubsystemHandlerFunc

type SubsystemHandlerFunc func(ctx SubsystemContext) error

SubsystemHandlerFunc is an adapter to allow using ordinary functions as SubsystemHandlers.

func (SubsystemHandlerFunc) HandleSubsystem

func (f SubsystemHandlerFunc) HandleSubsystem(ctx SubsystemContext) error

HandleSubsystem calls f(ctx).

type TcpForwarder

type TcpForwarder interface {
	// HandleDirectTcpIP services a direct-tcpip channel request.
	HandleDirectTcpIP(nc ssh.NewChannel, meta ssh.ConnMetadata, opts *Options) error

	// StartRemoteForward begins listening on the given address in response
	// to a tcpip-forward global request. If bindPort is 0, the server must
	// choose a port and return it in boundPort.
	StartRemoteForward(bindAddr string, bindPort uint32, conn *ssh.ServerConn, opts *Options) (boundPort uint32, err error)

	// StopRemoteForward cancels a previously started remote forward.
	StopRemoteForward(bindAddr string, bindPort uint32, conn *ssh.ServerConn) error
}

TcpForwarder handles TCP forwarding requests.

Direct-tcpip (client→server "local forwarding"): the client opens a direct-tcpip channel and the server should dial the target and relay.

Remote forwarding (server→client "remote forwarding"): the client sends a global "tcpip-forward" request. The server should begin listening on the requested address:port and open forwarded-tcpip channels for each accepted connection.

Relevant options:

  • AllowTcpForwarding, DisableForwarding, GatewayPorts, PermitOpen, PermitListen

type TunnelForwarder

type TunnelForwarder interface {
	HandleTunnelRequest(nc ssh.NewChannel, meta ssh.ConnMetadata, opts *Options) error
}

TunnelForwarder handles TUN/TAP forwarding (tun@openssh.com).

Relevant options:

  • PermitTunnel

type WindowChange

type WindowChange struct {
	Width  uint32
	Height uint32
}

WindowChange carries the "window-change" parameters.

type X11Forwarder

type X11Forwarder interface {
	HandleX11Request(ctx SessionContext, req X11Request) error
}

X11Forwarder handles X11 display forwarding.

Relevant options:

  • X11Forwarding, X11DisplayOffset, X11UseLocalhost, XAuthLocation, DisableForwarding

type X11Request

type X11Request struct {
	SingleConnection bool
	AuthProtocol     string
	AuthCookie       string
	ScreenNumber     uint32
}

X11Request carries the parsed payload of an x11-req channel request.

Jump to

Keyboard shortcuts

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