sshclient

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: 20 Imported by: 0

Documentation

Overview

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

Package sshclient provides OpenSSH client configuration parsing and resolution, plus terminal user-interaction callbacks for SSH clients.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllSupportedCiphers

func AllSupportedCiphers() []string

AllSupportedCiphers returns both secure and insecure ciphers supported by x/crypto/ssh.

func AllSupportedHostKeyAlgorithms

func AllSupportedHostKeyAlgorithms() []string

AllSupportedHostKeyAlgorithms returns all host key 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 ParseOverrides

func ParseOverrides(opts []string) ([]sshconfig.Entry, error)

ParseOverrides parses command-line -o options into config entries. Each option should be in "Key=Value" or "Key Value" format. The returned entries have no conditions (always match, highest priority).

func ResolveCASignatureAlgorithms

func ResolveCASignatureAlgorithms(raw string) []string

ResolveCASignatureAlgorithms resolves the CASignatureAlgorithms option.

func ResolveCiphers

func ResolveCiphers(raw string) []string

ResolveCiphers resolves the Ciphers option to a list of supported cipher names.

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.

Types

type AgentForwarder

type AgentForwarder interface {
	ForwardAgent(client *ssh.Client, session *ssh.Session, opts *Options) error
}

AgentForwarder enables SSH agent forwarding on a session, allowing the remote host to use the local SSH agent for authentication.

Relevant options in Options:

  • ForwardAgent: "yes", "no", a socket path, or "$ENV_VAR"

type CLIArgs

type CLIArgs struct {
	// Connection
	Port        string // raw string, parsed later
	User        string // from -l
	ConfigFile  string
	Options     []string // -o (repeatable)
	PrintConfig bool     // -G
	QueryType   string
	Tag         string

	// Auth
	PKCS11 string

	// Forwarding
	StdioFwd string // -W host:port

	// Session
	TTYCount  int
	NoTTY     bool
	NoCommand bool // -N
	Subsystem bool

	// Debug
	Verbosity int
	Quiet     bool
	LogFile   string
	Version   bool
	Syslog    bool

	// Multiplex
	CtlCmd string

	// Positional
	Destination string
	Command     []string
	Rest        []string // unconsumed positional args (mode-dependent)
	// contains filtered or unexported fields
}

CLIArgs holds parsed SSH command-line arguments.

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. Explicit flags come first (highest priority), then user -o entries.

func (*CLIArgs) LookupPort

func (a *CLIArgs) LookupPort() (int, error)

LookupPort returns the explicitly requested port, if any, in numeric form.

func (*CLIArgs) LookupUser

func (a *CLIArgs) LookupUser() string

LookupUser returns the effective user for host lookup and connection setup. An explicit user in the destination takes precedence over -l.

func (*CLIArgs) Parse

func (a *CLIArgs) Parse(mode ParseMode, args ...string) error

Parse parses ssh command-line arguments into the receiver. Fields set before calling Parse are preserved unless overridden by the arguments. mode controls how positional (non-flag) arguments are interpreted.

func (*CLIArgs) RemoteCommand

func (a *CLIArgs) RemoteCommand() string

RemoteCommand joins positional command arguments into the exec payload used for config resolution and session setup.

func (*CLIArgs) SessionType

func (a *CLIArgs) SessionType() string

SessionType returns the session type implied by the parsed CLI flags.

type CommandExecutor

type CommandExecutor interface {
	// Execute runs a command and returns any error. Used for LocalCommand.
	Execute(command string) error

	// ExecuteWithOutput runs a command and returns its stdout. Used for
	// KnownHostsCommand and Match exec evaluation.
	ExecuteWithOutput(command string) ([]byte, error)
}

CommandExecutor executes local commands. It is used for:

  • LocalCommand (executed after successful connection when PermitLocalCommand is yes)
  • Match exec conditions during config resolution

Relevant options in Options:

  • LocalCommand: command to execute after connection
  • PermitLocalCommand: whether local command execution is allowed

type DialConfig

type DialConfig = dialer.DialConfig

DialConfig exposes the resolved outbound dial settings that a wrapper may need when replacing or decorating the transport.

type Dialer

type Dialer = dialer.Dialer

Dialer establishes network connections for SSH.

type DialerWrapper

type DialerWrapper = dialer.Wrapper

DialerWrapper wraps a config-derived SSH dialer. Implementations can replace or decorate the transport while still receiving the full set of resolved dialer inputs from DialConfig.

Relevant fields in DialConfig:

  • ProxyCommand: external command whose stdio becomes the connection
  • ProxyJump: chain of SSH jump hosts
  • ProxyUseFdpass: whether ProxyCommand passes an fd instead of using stdio
  • BindAddress: local address to bind the outgoing connection to
  • BindInterface: local interface to bind to
  • IPQoS: DSCP values for the connection

type DialerWrapperFunc

type DialerWrapperFunc = dialer.WrapperFunc

DialerWrapperFunc adapts a function to DialerWrapper.

type Forward

type Forward struct {
	// BindAddress is the optional bind address (empty = loopback).
	BindAddress string
	// BindPort is the local/remote port, or a Unix socket path.
	BindPort string
	// Host is the destination host (for LocalForward/RemoteForward).
	Host string
	// HostPort is the destination port, or a Unix socket path.
	HostPort string
}

Forward represents a port forwarding specification.

type ForwardHandler

type ForwardHandler interface {
	SetupForwarding(client *ssh.Client, opts *Options) error
}

ForwardHandler sets up port forwarding on an established SSH connection.

Relevant options in Options:

  • LocalForward: local-to-remote port forwarding rules
  • RemoteForward: remote-to-local port forwarding rules
  • DynamicForward: SOCKS proxy forwarding ports
  • GatewayPorts: whether to bind forwarding ports on all interfaces
  • PermitRemoteOpen: allowed destinations for remote forwarding
  • StreamLocalBindMask: umask for Unix domain socket forwarding
  • StreamLocalBindUnlink: whether to unlink existing sockets
  • ExitOnForwardFailure: whether to abort if forwarding setup fails
  • ClearAllForwardings: whether all forwarding was cleared

type GSSAPIClient

type GSSAPIClient = ssh.GSSAPIClient

GSSAPIClient is an alias for ssh.GSSAPIClient, re-exported for convenience. Callers must provide an implementation of this interface to enable GSSAPI/Kerberos authentication. The interface requires:

  • InitSecContext: Initialize or continue a security context exchange
  • GetMIC: Generate a MIC (Message Integrity Code) for verification
  • DeleteSecContext: Clean up the security context

Two ready-made implementations are provided in the github.com/jamesits/sshconf/pkg/gssapi package:

  • [gssapi.Krb5Client]: Pure Go implementation using gokrb5/v8. No CGO required.
  • [gssapi.CGOClient]: System GSSAPI library via CGO. Only available when CGO is enabled.

Example:

// Pure Go (always available):
krb5, err := gssapi.NewKrb5ClientFromCCache("", gssapi.Krb5Config{})
handlers.GSSAPIClient = krb5

// CGO (requires CGO_ENABLED=1 and libgssapi_krb5):
handlers.GSSAPIClient = gssapi.NewCGOClient()

type GSSAPIConfig

type GSSAPIConfig struct {
	// Enabled is true when GSSAPIAuthentication is "yes".
	Enabled bool

	// DelegateCredentials is true when GSSAPIDelegateCredentials is "yes".
	DelegateCredentials bool

	// Target is the GSSAPI service principal name, typically "host@<hostname>".
	// Constructed from the resolved Hostname.
	Target string
}

GSSAPIConfig holds configuration for GSSAPI authentication derived from ssh_config options.

type Handlers

type Handlers struct {

	// UI provides caller-implemented methods for authentication
	// prompts and host key confirmation. A nil UI disables all
	// interactive prompts.
	UI UI

	// GSSAPIClient provides a GSSAPI client for Kerberos auth.
	// If nil, GSSAPI auth is unavailable even if configured.
	GSSAPIClient ssh.GSSAPIClient

	// HostKeyCallback overrides the built-in host key verification.
	// If nil, host key verification is built from config (known_hosts, etc.).
	HostKeyCallback ssh.HostKeyCallback

	// Dialer wraps the config-derived dialer used for the TCP connection to
	// the SSH server. Use this to add tracing, proxies, or other transport
	// behaviour without losing the resolved socket settings.
	Dialer DialerWrapper

	// KeyProvider supplies additional SSH signing keys from external
	// sources such as PKCS#11 tokens or FIDO/U2F security keys.
	KeyProvider KeyProvider

	// HostKeySource provides additional trusted host keys beyond those
	// found in known_hosts files (e.g., via KnownHostsCommand).
	HostKeySource HostKeySource

	// HostbasedAuth provides a client-side hostbased authentication method.
	HostbasedAuth HostbasedAuthProvider

	// Multiplexer manages SSH connection multiplexing (ControlMaster).
	Multiplexer Multiplexer

	// HostCanonicalizer performs custom hostname canonicalization.
	HostCanonicalizer HostCanonicalizer

	// Forwarding sets up port forwarding (local, remote, dynamic).
	Forwarding ForwardHandler

	// AgentForwarding enables SSH agent forwarding on a session.
	AgentForwarding AgentForwarder

	// X11Forwarding enables X11 display forwarding on a session.
	X11Forwarding X11Forwarder

	// Tunnel sets up TUN/TAP tunnel forwarding.
	Tunnel TunnelHandler

	// Session configures an SSH session (TTY, env, command, timeouts).
	Session SessionConfigurator

	// CommandExecutor runs local commands (LocalCommand, Match exec).
	CommandExecutor CommandExecutor

	// Terminal handles terminal-related features (escape chars, keystroke
	// timing, visual host key, process backgrounding, stdin nullification).
	Terminal TerminalHandler

	// Logger receives diagnostic log messages.
	Logger Logger
}

Handlers holds optional interface implementations for SSH config options that are parsed and stored but cannot be automatically applied to ssh.ClientConfig. Each handler covers a functional group of options. A nil handler means the corresponding options are ignored (the caller reads them from Options directly if needed).

Zero-value Handlers (all nil) preserves the existing behavior exactly.

type HostCanonicalizer

type HostCanonicalizer interface {
	Canonicalize(host string, opts *Options) (string, error)
}

HostCanonicalizer performs hostname canonicalization using custom logic. When provided, it replaces the built-in DNS-based canonicalization.

Relevant options in Options:

  • CanonicalizeHostname: whether canonicalization is enabled
  • CanonicalDomains: domain suffixes to search
  • CanonicalizeMaxDots: max dots before skipping canonicalization
  • CanonicalizePermittedCNAMEs: CNAME following rules
  • CanonicalizeFallbackLocal: whether to fall back to unqualified name

type HostKeySource

type HostKeySource interface {
	HostKeys(hostname string, opts *Options) ([]ssh.PublicKey, error)
}

HostKeySource provides additional trusted host keys beyond those found in UserKnownHostsFile and GlobalKnownHostsFile. The returned keys are accepted as trusted for the given hostname.

Relevant options in Options:

  • KnownHostsCommand: command to execute for host key lookup

type HostbasedAuthProvider

type HostbasedAuthProvider interface {
	AuthMethod(opts *Options) ssh.AuthMethod
}

HostbasedAuthProvider creates an ssh.AuthMethod for client-side hostbased authentication. The x/crypto/ssh library does not include a built-in implementation, so this must be provided externally.

Relevant options in Options:

  • HostbasedAuthentication: whether hostbased auth is enabled
  • HostbasedAcceptedAlgorithms: allowed signature algorithms
  • EnableSSHKeysign: whether to use the ssh-keysign helper

type KeyProvider

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

KeyProvider loads additional SSH signing keys from external sources. The returned signers are added to the public key authentication method alongside keys from IdentityFile and the SSH agent.

Relevant options in Options:

  • PKCS11Provider: path to PKCS#11 shared library
  • SecurityKeyProvider: path to FIDO/U2F authenticator library

type Logger

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

Logger receives diagnostic messages from the SSH client library. The level parameter corresponds to the LogLevel option values: "QUIET", "FATAL", "ERROR", "INFO", "VERBOSE", "DEBUG", "DEBUG1", "DEBUG2", "DEBUG3".

Relevant options in Options:

  • LogLevel: minimum log level
  • LogVerbose: per-file/function log overrides
  • SyslogFacility: syslog facility code

type Lookup

type Lookup struct {
	// Host is the target hostname (may be overridden by Hostname directive).
	Host string
	// User is the target username (from command line; may be overridden by User directive).
	User string
	// Port is the target port from command line. 0 means not specified.
	Port int

	// OriginalHost is the hostname exactly as given on the command line.
	// If empty, defaults to Host.
	OriginalHost string
	// LocalUser is the local username. If empty, detected from OS.
	LocalUser string
	// Command is the remote command (for Match command criteria).
	Command string
	// Tag is the initial tag (from -P flag).
	Tag string
	// SessionType is one of "shell", "exec", "subsystem", "none".
	// If empty, defaults to "default".
	SessionType string
	// Version is the client version string for Match version.
	// If empty, defaults to a reasonable value.
	Version string

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

	// CommandLineOptions are raw -o "Key=Value" strings, highest priority.
	CommandLineOptions []string

	// UserConfigFile is the path to the user config file.
	// Empty means ~/.ssh/config.
	UserConfigFile string
	// SystemConfigFile is the path to the system config file.
	// Empty means /etc/ssh/ssh_config.
	SystemConfigFile string

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

	// Handlers provide optional implementations for config options that
	// cannot be automatically applied. During resolution, the
	// HostCanonicalizer and CommandExecutor handlers are consulted if set.
	Handlers Handlers
}

Lookup specifies the inputs for SSH client configuration resolution.

func (*Lookup) Resolve

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

Resolve applies the SSH configuration resolution algorithm:

  1. Command-line -o overrides (highest priority)
  2. User config file (~/.ssh/config)
  3. System config file (/etc/ssh/ssh_config)
  4. Defaults (lowest priority)

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

type Multiplexer

type Multiplexer interface {
	// CheckExisting checks for an existing multiplexed connection.
	// Returns a connected client if one exists, nil otherwise.
	CheckExisting(opts *Options) (*ssh.Client, error)

	// Register registers a new connection for multiplexing so future
	// sessions can reuse it.
	Register(client *ssh.Client, opts *Options) error
}

Multiplexer manages SSH connection multiplexing, allowing multiple sessions to share a single network connection.

Relevant options in Options:

  • ControlMaster: whether to act as a multiplexing master
  • ControlPath: path to the Unix domain socket for multiplexing
  • ControlPersist: whether the master persists after the last client disconnects

type Options

type Options struct {
	// --- Connection ---
	AddressFamily       *string // "any", "inet", "inet6"
	BatchMode           *bool
	BindAddress         *string
	BindInterface       *string
	ConnectTimeout      *int // seconds; 0 = system default
	ConnectionAttempts  *int
	TCPKeepAlive        *bool
	ServerAliveInterval *int // seconds
	ServerAliveCountMax *int
	Compression         *bool

	// --- Host Resolution ---
	Hostname                    *string
	Port                        *int
	CanonicalDomains            []string
	CanonicalizeFallbackLocal   *bool
	CanonicalizeHostname        *string // "yes", "no", "always", "none"
	CanonicalizeMaxDots         *int
	CanonicalizePermittedCNAMEs []string // "source:target" rules

	// --- Authentication ---
	User                         *string
	IdentityFile                 []string // multi-value, accumulated
	IdentitiesOnly               *bool
	IdentityAgent                *string
	CertificateFile              []string // multi-value, accumulated
	PasswordAuthentication       *bool
	KbdInteractiveAuthentication *bool
	KbdInteractiveDevices        *string
	PubkeyAuthentication         *string // "yes", "no", "unbound", "host-bound"
	PubkeyAcceptedAlgorithms     *string // raw, may have +/-/^ prefix
	PreferredAuthentications     *string // comma-separated method list
	NumberOfPasswordPrompts      *int
	HostbasedAuthentication      *bool
	HostbasedAcceptedAlgorithms  *string // raw, may have +/-/^ prefix
	EnableSSHKeysign             *bool
	GSSAPIAuthentication         *bool
	GSSAPIDelegateCredentials    *bool
	AddKeysToAgent               *string // "yes", "no", "ask", "confirm", or time interval

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

	// --- Host Key Verification ---
	CheckHostIP                      *bool
	GlobalKnownHostsFile             *string // whitespace-separated paths
	UserKnownHostsFile               *string // whitespace-separated paths
	HashKnownHosts                   *bool
	StrictHostKeyChecking            *string // "yes", "no", "ask", "accept-new", "off"
	HostKeyAlias                     *string
	KnownHostsCommand                *string
	RevokedHostKeys                  *string // path
	UpdateHostKeys                   *string // "yes", "no", "ask"
	VerifyHostKeyDNS                 *string // "yes", "no", "ask"
	NoHostAuthenticationForLocalhost *bool

	// --- Proxy ---
	ProxyCommand   *string
	ProxyJump      *string
	ProxyUseFdpass *bool

	// --- Forwarding ---
	LocalForward          []Forward // multi-value, accumulated
	RemoteForward         []Forward // multi-value, accumulated
	DynamicForward        []string  // multi-value, accumulated
	ClearAllForwardings   *bool
	ExitOnForwardFailure  *bool
	GatewayPorts          *bool
	PermitRemoteOpen      []string // multi-value
	StreamLocalBindMask   *string  // octal
	StreamLocalBindUnlink *bool

	// --- Agent Forwarding ---
	ForwardAgent *string // "yes", "no", path, or "$ENVVAR"

	// --- X11 ---
	ForwardX11        *bool
	ForwardX11Timeout *int // seconds
	ForwardX11Trusted *bool
	XAuthLocation     *string

	// --- Tunnel ---
	Tunnel       *string // "yes", "no", "point-to-point", "ethernet"
	TunnelDevice *string // "local[:remote]"

	// --- Session ---
	RequestTTY     *string // "yes", "no", "force", "auto"
	SessionType    *string // "none", "subsystem", "default"
	RemoteCommand  *string
	SendEnv        []string // multi-value, accumulated; '-' prefix clears
	SetEnv         []string // multi-value, accumulated; "NAME=VALUE"
	EscapeChar     *string  // single char, "^X", or "none"
	IPQoS          *string  // one or two DSCP values
	LogLevel       *string
	LogVerbose     []string
	Tag            *string
	ChannelTimeout []string // multi-value; "type=interval"

	// --- Connection Sharing ---
	ControlMaster  *string // "yes", "no", "ask", "auto", "autoask"
	ControlPath    *string
	ControlPersist *string // "yes", "no", time in seconds

	// --- Misc ---
	PermitLocalCommand      *bool
	LocalCommand            *string
	VisualHostKey           *bool
	ForkAfterAuthentication *bool
	StdinNull               *bool
	EnableEscapeCommandline *bool
	ObscureKeystrokeTiming  *string // "yes", "no", "interval:NNN"
	VersionAddendum         *string
	PKCS11Provider          *string
	SecurityKeyProvider     *string
	IgnoreUnknown           *string // pattern list
	RefuseConnection        *string // message
	SyslogFacility          *string

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

Options holds all resolved SSH client configuration options. Pointer fields distinguish "not set" (nil) from the zero value. After Resolve(), all fields will be populated (defaults applied).

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

func (opts *Options) ConfigureSession(client *ssh.Client, session *ssh.Session, handlers Handlers) error

ConfigureSession applies session-related options to an SSH session by invoking the appropriate handlers.

It calls handlers in the following order:

  1. SessionConfigurator.ConfigureSession — TTY, env, command, timeouts
  2. AgentForwarder.ForwardAgent — if ForwardAgent is enabled
  3. X11Forwarder.ForwardX11 — if ForwardX11 is enabled
  4. TerminalHandler.SetupTerminal — escape char, keystroke timing, etc.

func (*Options) Dial

func (opts *Options) Dial() (net.Conn, error)

Dial remains as a convenience wrapper around GetDialer for callers that want the resolved target connection directly.

func (*Options) GetDialer

func (opts *Options) GetDialer() Dialer

GetDialer returns the outbound SSH dialer derived from the stored dialer configuration.

func (*Options) GetDialerConfig

func (opts *Options) GetDialerConfig() DialConfig

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

func (*Options) PostConnect

func (opts *Options) PostConnect(client *ssh.Client, handlers Handlers) error

PostConnect performs post-connection setup by invoking the appropriate handlers. Call this after successfully establishing an SSH connection.

It calls handlers in the following order:

  1. Multiplexer.Register — register connection for multiplexing
  2. ForwardHandler.SetupForwarding — local/remote/dynamic port forwarding
  3. TunnelHandler.SetupTunnel — TUN/TAP tunnel forwarding
  4. CommandExecutor.Execute — run LocalCommand if PermitLocalCommand is yes

func (*Options) RefreshDialerConfig

func (opts *Options) RefreshDialerConfig()

RefreshDialerConfig rebuilds DialerConfig from the parsed SSH options. Callers that change dialer-related fields after Resolve should call this to resync the derived dialer state.

func (*Options) SSHClientConfig

func (opts *Options) SSHClientConfig(handlers Handlers) (*ssh.ClientConfig, error)

SSHClientConfig converts the resolved Options into an ssh.ClientConfig ready for use with ssh.Dial or ssh.NewClientConn.

The handlers parameter provides optional implementations for config options that cannot be automatically applied (proxy, forwarding, authentication prompts, host key confirmation, etc.). A zero-value Handlers preserves existing behavior.

type ParseMode

type ParseMode int

ParseMode controls how positional (non-flag) arguments are interpreted.

const (
	// ModeOptionsOnly parses flags only. All positional arguments are
	// collected in Rest.
	ModeOptionsOnly ParseMode = iota
	// ModeOptionsHost parses flags and a destination. The first positional
	// argument becomes Destination; any remaining go to Rest.
	ModeOptionsHost
	// ModeOptionsHostCommand parses flags, a destination, and a remote
	// command. The first positional argument becomes Destination; everything
	// after it becomes Command.
	ModeOptionsHostCommand
)

type SessionConfigurator

type SessionConfigurator interface {
	ConfigureSession(session *ssh.Session, opts *Options) error
}

SessionConfigurator configures an SSH session based on resolved options. It is called after the session is created but before the command is started.

Relevant options in Options:

  • RequestTTY: whether to request a pseudo-terminal
  • SessionType: "shell", "exec", "subsystem", or "none"
  • RemoteCommand: command to execute on the remote host
  • SendEnv: environment variable patterns to forward
  • SetEnv: explicit environment variables to set
  • ChannelTimeout: idle timeout per channel type

type TUI

type TUI struct {
	stdio.TerminalStreams

	// Host and User identify the remote account and are used to render
	// the password prompt. Set these before PasswordCallback is invoked.
	Host string
	User string
}

TUI provides terminal-based user interaction for SSH client operations. Its methods are directly compatible with the corresponding fields of UI, so callers can assign them without wrapping closures.

func NewTUI

func NewTUI(streams stdio.TerminalStreams) *TUI

NewTUI returns a TUI wired to the supplied streams.

func (*TUI) BannerCallback

func (t *TUI) BannerCallback(message string) error

BannerCallback prints an SSH server banner.

func (*TUI) HostKeyConfirm

func (t *TUI) HostKeyConfirm(hostname string, remote net.Addr, key ssh.PublicKey) bool

HostKeyConfirm prompts the user to accept an unknown or changed host key.

func (*TUI) InteractiveCallback

func (t *TUI) InteractiveCallback(name, instruction string, questions []string, echos []bool) ([]string, error)

InteractiveCallback handles keyboard-interactive authentication challenges.

func (*TUI) PassphraseCallback

func (t *TUI) PassphraseCallback(keyFile string) ([]byte, error)

PassphraseCallback prompts for a private key passphrase.

func (*TUI) PasswordCallback

func (t *TUI) PasswordCallback() (string, error)

PasswordCallback prompts for a password. Its signature matches [UI.PasswordCallback], so it can be assigned directly. The prompt uses t.Host and t.User; set those before the callback fires.

func (*TUI) PrintConfig

func (t *TUI) PrintConfig(opts *Options, host, originalHost string)

PrintConfig writes the resolved configuration in ssh -G format to Stdout.

func (*TUI) RunQuery

func (t *TUI) RunQuery(queryType string) error

RunQuery prints the results of an ssh -Q query to Stdout.

func (*TUI) Usage

func (t *TUI) Usage(program string, mode ParseMode)

Usage writes a usage string for the given program name and parse mode to Stderr.

type TerminalHandler

type TerminalHandler interface {
	SetupTerminal(opts *Options) error
}

TerminalHandler manages terminal and process lifecycle features that require direct interaction with the controlling terminal or process.

Relevant options in Options:

  • EscapeChar: the escape character for interactive sessions
  • EnableEscapeCommandline: whether ~C escape command line is enabled
  • ObscureKeystrokeTiming: keystroke timing obfuscation settings
  • VisualHostKey: whether to display ASCII art host key fingerprints
  • ForkAfterAuthentication: whether to fork to background
  • StdinNull: whether to redirect stdin from /dev/null

type TunnelHandler

type TunnelHandler interface {
	SetupTunnel(client *ssh.Client, opts *Options) error
}

TunnelHandler sets up TUN/TAP layer 2/3 tunnel forwarding between the client and server.

Relevant options in Options:

  • Tunnel: "yes" (point-to-point), "point-to-point", "ethernet", or "no"
  • TunnelDevice: "local_tun[:remote_tun]" device specification

type UI

type UI interface {
	// PasswordCallback prompts for a password. Required for password auth.
	PasswordCallback() (string, error)

	// PassphraseCallback prompts for a private key passphrase.
	// The argument is the key file path.
	PassphraseCallback(keyFile string) ([]byte, error)

	// InteractiveCallback handles keyboard-interactive challenges.
	InteractiveCallback(name, instruction string, questions []string, echos []bool) ([]string, error)

	// BannerCallback handles SSH server banner messages.
	BannerCallback(message string) error

	// HostKeyConfirm is called when StrictHostKeyChecking is "ask" and
	// a new or changed host key is encountered. Return true to accept.
	HostKeyConfirm(hostname string, remote net.Addr, key ssh.PublicKey) bool
}

UI provides caller-implemented methods for SSH operations that require user interaction. Implementations handle password/passphrase prompts, keyboard-interactive challenges, banner display, and host key confirmation. A nil UI disables all interactive code paths.

type X11Forwarder

type X11Forwarder interface {
	ForwardX11(client *ssh.Client, session *ssh.Session, opts *Options) error
}

X11Forwarder enables X11 display forwarding on a session, allowing remote graphical applications to display on the local X server.

Relevant options in Options:

  • ForwardX11: whether X11 forwarding is enabled
  • ForwardX11Trusted: whether to use trusted X11 forwarding
  • ForwardX11Timeout: timeout for untrusted X11 forwarding
  • XAuthLocation: path to the xauth binary

Jump to

Keyboard shortcuts

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