ssh

package
v0.0.0-...-9bd0860 Latest Latest
Warning

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

Go to latest
Published: Oct 18, 2026 License: BSD-3-Clause Imports: 23 Imported by: 0

Documentation

Overview

Package ssh provides an enterprise-grade SSH tunneling, command execution, and file transfer client.

Index

Constants

View Source
const (
	// DefaultWindowSize specifies the default initial SSH channel window size (16MB).
	DefaultWindowSize uint32 = 16 * 1024 * 1024

	// DefaultMaxPacketSize specifies the default maximum SSH packet size (64KB).
	DefaultMaxPacketSize uint32 = 64 * 1024
)

Variables

View Source
var (
	// ErrSSHDialFailed is returned when connecting or authenticating with an SSH server fails.
	ErrSSHDialFailed = errors.New("aoni/ssh/client: connection or authentication failed")

	// ErrSSHClosed is returned when attempting an operation on an inactive SSH client.
	ErrSSHClosed = errors.New("aoni/ssh/client: session is closed")

	// ErrInvalidPrivateKey is returned when parsing an invalid or encrypted PEM private key fails.
	ErrInvalidPrivateKey = errors.New("aoni/ssh/client: invalid or encrypted private key")

	// ErrInvalidCertificate is returned when parsing or validating an OpenSSH certificate fails.
	ErrInvalidCertificate = errors.New("aoni/ssh/client: invalid or corrupted ssh certificate")

	// ErrHostKeyMismatch is returned when a host key does not match the entry in known_hosts.
	ErrHostKeyMismatch = errors.New("aoni/ssh/client: host key mismatch detected")

	// ErrHostNotFound is returned when a host key is missing from the known_hosts file.
	ErrHostNotFound = errors.New("aoni/ssh/client: host not found in known_hosts")

	// ErrCommandInitFailed is returned when environment variables or session options fail to apply.
	ErrCommandInitFailed = errors.New("aoni/ssh/client: command initialization failed")

	// ErrProxyAndJumpConflict is returned when attempting to set both a SOCKS5 proxy and an SSH jump host on the same client.
	ErrProxyAndJumpConflict = errors.New("aoni/ssh/client: cannot combine proxy and jump host on the same client level")

	// ErrFingerprintMismatch is returned when the remote host key fingerprint does not match the expected SHA256 pin.
	ErrFingerprintMismatch = errors.New("aoni/ssh/client: host key fingerprint mismatch")

	// ErrPtyRequestFailed is returned when the server rejects a pseudo-terminal (PTY) allocation request.
	ErrPtyRequestFailed = errors.New("aoni/ssh/client: failed to request pseudo-terminal")
)

Functions

func AddKnownHost

func AddKnownHost(host string, remote net.Addr, key ssh.PublicKey, knownFile string) error

AddKnownHost appends a host key entry to knownFile and invalidates the internal callback cache.

func CheckKnownHost

func CheckKnownHost(host string, remote net.Addr, key ssh.PublicKey, knownFile string) (bool, error)

CheckKnownHost verifies if host exists in knownFile using cached host key callbacks. Returns (true, nil) if matched, (true, ErrHostKeyMismatch) on key mismatch, or (false, ErrHostNotFound) if absent.

func DefaultKnownHosts

func DefaultKnownHosts() (ssh.HostKeyCallback, error)

DefaultKnownHosts returns a host key callback using the default user known_hosts file path.

func DefaultKnownHostsPath

func DefaultKnownHostsPath() (string, error)

DefaultKnownHostsPath returns the standard ~/.ssh/known_hosts path.

func Dial

func Dial(ctx context.Context, c *Client, config *ssh.ClientConfig) error

Dial connects client to the remote target host using configured options, proxies, or jump hosts.

func EnsureKnownHosts

func EnsureKnownHosts(file string) (ssh.HostKeyCallback, error)

EnsureKnownHosts returns a host key callback, creating the file and parent directory if missing.

func KnownHosts

func KnownHosts(file string) (ssh.HostKeyCallback, error)

KnownHosts returns a thread-safe, cached host key callback targeting an existing known_hosts file path. Debounces os.Stat calls using a 1-second interval to eliminate disk I/O syscall overhead.

func ParseCertKey

func ParseCertKey(certBytes, keyBytes []byte, passphrase string) (ssh.Signer, error)

ParseCertKey parses a private key and an OpenSSH certificate payload, returning a cert-backed ssh.Signer ready for SSH client authentication.

func ParseCertKeyFile

func ParseCertKeyFile(certFile, keyFile, passphrase string) (ssh.Signer, error)

ParseCertKeyFile loads and parses a cert-backed ssh.Signer from file paths.

func ParseKey

func ParseKey(privateKey []byte, passphrase string) (ssh.Signer, error)

ParseKey parses an ssh.Signer from raw PEM encoded private key bytes.

func ParseKeyFile

func ParseKeyFile(prvFile, passphrase string) (ssh.Signer, error)

ParseKeyFile loads and parses an ssh.Signer from a private key file path.

Types

type Client

type Client struct {
	*ssh.Client

	User          string
	Addr          string
	Port          uint
	ProxyURL      string
	Jump          *Client
	Dialer        ContextDialer
	RequestPty    bool
	PtyTerm       string
	PtyWidth      int
	PtyHeight     int
	WindowSize    uint32
	MaxPacketSize uint32
	// contains filtered or unexported fields
}

Client represents an SSH client session routed through aoni's L4 network transport pipeline.

func New

func New(ctx context.Context, user, targetAddr string, opts ...Option) (*Client, error)

New establishes an SSH connection wrapped in aoni's transport pipeline.

func NewClientFromConfig

func NewClientFromConfig(ctx context.Context, alias string, opts ...Option) (*Client, error)

NewClientFromConfig creates an SSH Client loading options automatically from ~/.ssh/config for alias.

func (*Client) Close

func (c *Client) Close() error

Close terminates the keep-alive worker, active SFTP client, and underlying SSH connection.

func (*Client) Command

func (c *Client) Command(ctx context.Context, name string, args ...string) (*Cmd, error)

Command instantiates a new Cmd targeting name with optional arguments.

func (*Client) DialContext

func (c *Client) DialContext(ctx context.Context, network, targetAddr string) (net.Conn, error)

DialContext establishes a routed TCP connection through the remote SSH tunnel.

func (*Client) DialUnix

func (c *Client) DialUnix(ctx context.Context, remoteSocketPath string) (net.Conn, error)

DialUnix establishes a streamlocal UNIX domain socket connection on the remote host via SSH.

func (*Client) Download

func (c *Client) Download(remotePath, localPath string) error

Download transfers a remote file to localPath via SFTP.

func (*Client) DownloadParallel

func (c *Client) DownloadParallel(
	ctx context.Context,
	remotePath, localPath string,
	workers int,
	chunkSize int64,
) error

DownloadParallel downloads a remote file to localPath over SFTP using multiple worker threads.

func (*Client) GetSftp

func (c *Client) GetSftp(opts ...pkgsftp.ClientOption) (*pkgsftp.Client, error)

GetSftp returns a thread-safe, cached SFTP client instance, initializing it lazily on first access.

func (*Client) ListenSOCKS5

func (c *Client) ListenSOCKS5(ctx context.Context, localAddr string) (net.Listener, error)

ListenSOCKS5 starts a local SOCKS5 proxy server on localAddr (e.g. "127.0.0.1:1080"), routing all inbound connections through the remote SSH tunnel (equivalent to `ssh -D 1080`).

func (*Client) NewSftp

func (c *Client) NewSftp(opts ...pkgsftp.ClientOption) (*pkgsftp.Client, error)

NewSftp initializes a new SFTP client over the active SSH session.

func (*Client) Run

func (c *Client) Run(ctx context.Context, cmdStr string) ([]byte, error)

Run executes command on the remote host and returns its combined stdout and stderr.

func (*Client) Scp

func (c *Client) Scp(ctx context.Context, localFilePath, remoteFilePath string) error

Scp uploads localFilePath to remoteFilePath using SCP protocol.

func (*Client) Script

func (c *Client) Script(ctx context.Context, r io.Reader, opts ...CmdOption) (*Cmd, error)

Script executes a script from r on the remote host using an interpreter.

func (*Client) ScriptFile

func (c *Client) ScriptFile(ctx context.Context, localPath string, opts ...CmdOption) (*Cmd, error)

ScriptFile reads localPath into memory and executes it as a script on the remote host.

func (*Client) Stream

func (c *Client) Stream(
	ctx context.Context,
	command string,
	timeout time.Duration,
) (<-chan string, <-chan string, <-chan bool, <-chan error, error)

Stream executes command and streams stdout and stderr line-by-line over channels in real-time.

func (*Client) Upload

func (c *Client) Upload(localPath, remotePath string) error

Upload transfers a local file to remotePath on the remote server via SFTP.

func (*Client) UploadParallel

func (c *Client) UploadParallel(ctx context.Context, localPath, remotePath string, workers int, chunkSize int64) error

UploadParallel uploads a local file to remotePath over SFTP using multiple worker threads.

func (*Client) WriteFile

func (c *Client) WriteFile(ctx context.Context, r io.Reader, size int64, remoteFilePath string) error

WriteFile streams size bytes from r into remoteFilePath using SCP protocol.

type Cmd

type Cmd struct {
	*ssh.Session

	Path string
	Args []string
	Env  []string

	Cancel func() error
	// contains filtered or unexported fields
}

Cmd represents an SSH command runner with context cancellation, signal control, and environment injection.

func (*Cmd) CombinedOutput

func (c *Cmd) CombinedOutput() ([]byte, error)

CombinedOutput runs the command remotely and returns its combined stdout and stderr.

func (*Cmd) Output

func (c *Cmd) Output() ([]byte, error)

Output runs the command remotely and returns its stdout.

func (*Cmd) Run

func (c *Cmd) Run() error

Run executes the command remotely and waits for completion.

func (*Cmd) Start

func (c *Cmd) Start() error

Start begins command execution on the remote host without waiting for completion.

func (*Cmd) String

func (c *Cmd) String() string

String formats the command line path and arguments without shell escaping.

type CmdOption

type CmdOption func(*Cmd)

CmdOption configures an SSH Cmd instance prior to execution.

func WithEnv

func WithEnv(env []string) CmdOption

WithEnv sets environment variables for the remote command session.

func WithPath

func WithPath(path string) CmdOption

WithPath sets the command executable path for Cmd.

func WithStderr

func WithStderr(w io.Writer) CmdOption

WithStderr assigns a writer for remote command stderr.

func WithStdin

func WithStdin(r io.Reader) CmdOption

WithStdin assigns a reader for remote command stdin.

func WithStdout

func WithStdout(w io.Writer) CmdOption

WithStdout assigns a writer for remote command stdout.

type ContextDialer

type ContextDialer interface {
	DialContext(ctx context.Context, network, addr string) (net.Conn, error)
}

ContextDialer is a generic dialer capable of establishing network connections with a context.

type HostConfig

type HostConfig struct {
	Host                  string
	HostName              string
	User                  string
	Port                  uint
	IdentityFiles         []string
	ProxyJump             string
	ProxyCommand          string
	StrictHostKeyChecking string
	UserKnownHostsFile    string
}

HostConfig holds options parsed from an OpenSSH config file for a specific host alias.

type Option

type Option func(*Client, *ssh.ClientConfig) error

Option configures an SSH Client and its underlying ssh.ClientConfig.

func WithAgent

func WithAgent(conn net.Conn) Option

WithAgent configures SSH agent authentication over a connected net.Conn.

func WithAgentSocket

func WithAgentSocket(socket string) Option

WithAgentSocket configures SSH agent authentication over a Unix socket path.

func WithAuth

func WithAuth(method ssh.AuthMethod) Option

WithAuth appends a custom ssh.AuthMethod to authentication options.

func WithBannerCallback

func WithBannerCallback(cb ssh.BannerCallback) Option

WithBannerCallback sets a banner message callback function.

func WithCert

func WithCert(certBytes, keyBytes []byte, passphrase string) Option

WithCert configures public key authentication using raw OpenSSH certificate and private key PEM bytes.

func WithCertFile

func WithCertFile(certFile, keyFile, passphrase string) Option

WithCertFile configures public key authentication using an OpenSSH certificate and private key file.

func WithCertSigner

func WithCertSigner(signer ssh.Signer) Option

WithCertSigner appends authentication using an existing certificate-backed ssh.Signer.

func WithCiphers

func WithCiphers(ciphers []string) Option

WithCiphers overrides or appends accepted SSH ciphers.

func WithConfig

func WithConfig(fn func(*ssh.ClientConfig) error) Option

WithConfig applies a custom modification callback to the underlying ssh.ClientConfig.

func WithDefaultAgent

func WithDefaultAgent() Option

WithDefaultAgent configures SSH agent authentication using SSH_AUTH_SOCK.

func WithDialer

func WithDialer(dialer ContextDialer) Option

WithDialer routes the underlying SSH connection through a custom ContextDialer transport.

func WithEnsureKnownHosts

func WithEnsureKnownHosts(path string) Option

WithEnsureKnownHosts configures host key verification using path, creating the file if missing.

func WithFingerprint

func WithFingerprint(fingerprint string) Option

WithFingerprint verifies host key against an explicit SHA256 fingerprint string without requiring known_hosts.

func WithHighPerformanceDefaults

func WithHighPerformanceDefaults() Option

WithHighPerformanceDefaults configures AEAD ciphers, fast KEX curves, and large channel window scaling.

func WithHostKeyAlgorithms

func WithHostKeyAlgorithms(algorithms []string) Option

WithHostKeyAlgorithms sets custom accepted host key algorithms.

func WithHostKeyCallback

func WithHostKeyCallback(cb ssh.HostKeyCallback) Option

WithHostKeyCallback sets a custom host key callback function.

func WithInsecureIgnoreHostKey

func WithInsecureIgnoreHostKey() Option

WithInsecureIgnoreHostKey disables host key verification.

func WithJump

func WithJump(jumpClient *Client) Option

WithJump configures a pre-connected jump client to tunnel through.

func WithKey

func WithKey(pemBytes []byte, passphrase string) Option

WithKey configures public key authentication from raw PEM encoded key bytes.

func WithKeyExchanges

func WithKeyExchanges(kex []string) Option

WithKeyExchanges overrides or appends accepted Key Exchange algorithms.

func WithKeyFile

func WithKeyFile(keyFile, passphrase string) Option

WithKeyFile configures public key authentication from a private key file path.

func WithKeyboardInteractive

func WithKeyboardInteractive(handler func(user, instruction, question string, echo bool) (string, error)) Option

WithKeyboardInteractive configures interactive prompt-response authentication.

func WithKnownHosts

func WithKnownHosts(path string) Option

WithKnownHosts configures host key verification using path.

func WithLegacyCiphers

func WithLegacyCiphers() Option

WithLegacyCiphers enables legacy ciphers and KEX algorithms.

func WithMaxPacketSize

func WithMaxPacketSize(size uint32) Option

WithMaxPacketSize sets the maximum SSH packet size in bytes.

func WithPassword

func WithPassword(password string) Option

WithPassword configures password authentication.

func WithPort

func WithPort(port uint) Option

WithPort sets the target SSH port.

func WithProxy

func WithProxy(socks5URL string) Option

WithProxy configures a SOCKS5 proxy URL for routing the SSH connection.

func WithPtyTerminal

func WithPtyTerminal(term string, width, height int) Option

WithPtyTerminal configures pseudo-terminal dimensions and terminal type.

func WithRequestPty

func WithRequestPty(enabled bool) Option

WithRequestPty enables pseudo-terminal (PTY) allocation on sessions created by this client.

func WithSigner

func WithSigner(signer ssh.Signer) Option

WithSigner appends public key authentication from an ssh.Signer.

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the SSH handshake connection timeout.

func WithWindowSize

func WithWindowSize(size uint32) Option

WithWindowSize sets the SSH channel initial window size in bytes.

type SSHConfig

type SSHConfig struct {
	Hosts map[string]*HostConfig
}

SSHConfig represents a parsed OpenSSH config file containing host entries.

func ParseSSHConfig

func ParseSSHConfig(r io.Reader) (*SSHConfig, error)

ParseSSHConfig parses OpenSSH config directives from reader.

func ParseSSHConfigFile

func ParseSSHConfigFile(path string) (*SSHConfig, error)

ParseSSHConfigFile loads and parses an OpenSSH config file from path. If path is empty, defaults to ~/.ssh/config.

func (*SSHConfig) GetHost

func (cfg *SSHConfig) GetHost(alias string) *HostConfig

GetHost retrieves the HostConfig matching alias, falling back to wildcard '*' settings.

Directories

Path Synopsis
Package agent provides SSH agent socket authentication utilities.
Package agent provides SSH agent socket authentication utilities.
Package reverse provides a reverse SSH tunnel client for exposing local services.
Package reverse provides a reverse SSH tunnel client for exposing local services.
Package sftp provides high-performance SFTP and SCP file transfer services over SSH sessions.
Package sftp provides high-performance SFTP and SCP file transfer services over SSH sessions.

Jump to

Keyboard shortcuts

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