ssh

package
v0.16.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 42 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// Bound both original and quoted payloads below SSH transport packet and
	// common per-argument limits; remote servers may impose smaller limits.
	MaxCommandBytes       = 64 << 10
	MaxCommandInputBytes  = 16 << 20
	DefaultCommandOutput  = 5 << 20
	MaxCommandOutput      = 64 << 20
	DefaultCommandTimeout = 5 * time.Minute
)
View Source
const (
	DefaultKeepAliveInterval = 15 * time.Second
	DefaultKeepAliveTimeout  = 10 * time.Second
)

心跳默认参数:接收空闲 15s 后探测;等待回复期间连续 10s 无接收进展才超时。 网络拥塞下的有效接收进展会推迟探测或刷新等待时间,网络黑洞仍有确定的退出路径。

View Source
const (
	MuxProtoVersion    uint32 = 4
	MuxProtocolVersion uint32 = 4
)

OpenSSH PROTOCOL.mux version 4.

View Source
const (
	MUX_MSG_HELLO        uint32 = 0x00000001
	MUX_C_NEW_SESSION    uint32 = 0x10000002
	MUX_C_ALIVE_CHECK    uint32 = 0x10000004
	MUX_C_TERMINATE      uint32 = 0x10000005
	MUX_C_OPEN_FWD       uint32 = 0x10000006
	MUX_C_CLOSE_FWD      uint32 = 0x10000007
	MUX_C_NEW_STDIO_FWD  uint32 = 0x10000008
	MUX_C_STOP_LISTENING uint32 = 0x10000009
	MUX_C_PROXY          uint32 = 0x1000000f
	MUX_C_EXT_INFO       uint32 = 0x20000001
)

Client -> Master request message types.

View Source
const (
	MUX_S_OK                uint32 = 0x80000001
	MUX_S_PERMISSION_DENIED uint32 = 0x80000002
	MUX_S_FAILURE           uint32 = 0x80000003
	MUX_S_EXIT_MESSAGE      uint32 = 0x80000004
	MUX_S_ALIVE             uint32 = 0x80000005
	MUX_S_SESSION_OPENED    uint32 = 0x80000006
	MUX_S_REMOTE_PORT       uint32 = 0x80000007
	MUX_S_TTY_ALLOC_FAIL    uint32 = 0x80000008
	MUX_S_PROXY             uint32 = 0x8000000f
	MUX_S_EXT_INFO          uint32 = 0x90000001
)

Master -> Client response message types.

View Source
const (
	MUX_FWD_LOCAL   uint32 = 1
	MUX_FWD_REMOTE  uint32 = 2
	MUX_FWD_DYNAMIC uint32 = 3
)

Forwarding types.

View Source
const (
	MaxMuxPacketLength = 256 * 1024 // 256 KB
	MaxMuxStringLength = 64 * 1024  // 64 KB
)

Packet limits to defend against resource exhaustion DOS.

View Source
const (
	OptionControlMaster                = "control_master"
	OptionControlPath                  = "control_path"
	OptionControlPersist               = "control_persist"
	OptionConnectTimeout               = "connect_timeout"
	OptionServerAliveInterval          = "server_alive_interval"
	OptionServerAliveCountMax          = "server_alive_count_max"
	OptionTCPKeepAlive                 = "tcp_keep_alive"
	OptionStrictHostKeyChecking        = "strict_host_key_checking"
	OptionUserKnownHostsFile           = "user_known_hosts_file"
	OptionPubkeyAuthentication         = "pubkey_authentication"
	OptionPasswordAuthentication       = "password_authentication"
	OptionKbdInteractiveAuthentication = "kbd_interactive_authentication"
	OptionIdentitiesOnly               = "identities_only"
	OptionPreferredAuthentications     = "preferred_authentications"
	OptionBatchMode                    = "batch_mode"
	OptionHostKeyAlgorithms            = "host_key_algorithms"
	OptionCiphers                      = "ciphers"
	OptionMACs                         = "macs"
	OptionKexAlgorithms                = "kex_algorithms"
)

Standard canonical snake_case option keys used for persistence in ssh_options.

View Source
const (
	StrictHostKeyCheckingYes       = "yes"
	StrictHostKeyCheckingNo        = "no"
	StrictHostKeyCheckingAsk       = "ask"
	StrictHostKeyCheckingAcceptNew = "accept-new"
)

StrictHostKeyCheckingMode defines OpenSSH StrictHostKeyChecking values.

View Source
const (
	// MaxCmdPayloadBytes is the maximum command line length accepted by cmd.exe (8191 characters).
	MaxCmdPayloadBytes = 8191

	// MaxPowerShellPayloadBytes is the maximum command line length accepted by CreateProcess (32767 characters).
	MaxPowerShellPayloadBytes = 32767
)
View Source
const (
	DefaultInteractionTimeout = 2 * time.Minute
)
View Source
const DefaultMuxHandshakeTimeout = 10 * time.Second

DefaultMuxHandshakeTimeout bounds control-socket handshakes and RPCs when the caller's context carries no deadline of its own.

View Source
const DefaultPasswordPromptPattern = `` /* 126-byte string literal not displayed */

DefaultPasswordPromptPattern 是内置的多语言密码提示正则,覆盖主流语言环境。 匹配规则:密码关键词后面可以跟其他单词(如 "for user"),之后出现冒号即触发。

View Source
const MUX_SPECIAL_PORT_UNIX uint32 = 0xfffffffe

MUX_SPECIAL_PORT_UNIX indicates a Unix domain socket path rather than a TCP port.

Variables

View Source
var (
	// ErrHostKeyMismatch 主机密钥不匹配或不受信任
	ErrHostKeyMismatch = errors.New("host key verification failed")
	// ErrPasswordRequired 需要密码但未提供
	ErrPasswordRequired = errors.New("password required but empty")
	// ErrKeyPathRequired 需要私钥路径但未提供
	ErrKeyPathRequired = errors.New("private key path required but empty")
	// ErrAgentNotAvailable SSH Agent 不可用
	ErrAgentNotAvailable = errors.New("ssh-agent socket not available")
	// ErrProxyCycle 代理跳转环路
	ErrProxyCycle = errors.New("proxy jump cycle detected")
)
View Source
var (
	// ErrMasterAlreadyExists indicates a master is already listening on the socket path.
	ErrMasterAlreadyExists = errors.New("mux master already exists on control path")
	// ErrServerClosed indicates the multiplex server has shut down.
	ErrServerClosed = errors.New("mux server closed")
	// ErrUnauthorizedPeer indicates the peer UID check failed.
	ErrUnauthorizedPeer = errors.New("unauthorized peer UID")
)
View Source
var ErrConnectorClosed = errors.New("ssh connector is closed")

ErrConnectorClosed 表示 Connector 已执行 CloseAll,不能再建立或返回连接。

View Source
var ErrControlProxyRejected = errors.New("control master rejected proxy mode")

ErrControlProxyRejected reports that the master refused a MUX_C_PROXY request.

View Source
var ErrControlTargetMismatch = errors.New("control socket target mismatch")

ErrControlTargetMismatch indicates that an active control socket belongs to a master connected to a different remote destination than the requested target.

View Source
var ErrExecutionProbe = errors.New("SSH execution probe failed")

ErrExecutionProbe identifies an inconclusive or failed execution probe.

View Source
var ErrExecutionValidation = errors.New("execution validation error")

ErrExecutionValidation indicates an invalid execution configuration.

View Source
var ErrHandshakeClosed = errors.New("handshake coordinator is closed")

ErrHandshakeClosed 表示握手协调器已关闭或已被 fail-closed 中断。

View Source
var ErrInteractionRequired = errors.New("ssh interaction required")

ErrInteractionRequired 表示需要交互式输入但在非交互模式下被拒绝。

View Source
var ErrSSHOptionsValidation = errors.New("ssh options validation error")

ErrSSHOptionsValidation indicates an invalid SSH option key or value.

View Source
var ErrSessionNotConfirmed = errors.New("connection sharing request was not approved")

ErrSessionNotConfirmed reports that a confirmation-mode master (ControlMaster ask/autoask) rejected a request because no approval was granted.

View Source
var ErrSnapshotMismatch = errors.New("connection snapshot mismatch")

ErrSnapshotMismatch 表示连接快照与当前配置版本或目标不匹配

Functions

func BindOutput

func BindOutput(ctx context.Context, target io.Writer) (writer io.Writer, closeFn func() error, cancelable bool, err error)

BindOutput prepares a non-PTY command output sink with cancellation-aware ownership. Supported terminal/pipe writes can be interrupted. Regular files check cancellation between writes; a kernel write already in progress must finish before return, with no hard cancellation deadline for a stalled filesystem.

ContextWriter implementations, finite memory sinks, io.Discard, the null device, local regular files, and native terminal/pipe adapters bind to ctx. Linux and macOS terminal adapters use owned nonblocking handles; macOS also accepts already nonblocking pipes. Windows synchronous/overlapped pipes use owned duplicate handles with thread/request-specific cancellation, and Windows consoles use an owned duplicate handle with a pipe-backed relay subprocess only when the host explicitly selects WithConsoleOutputRelay on ctx and owns its returned cleanup function through command completion. The caller's file is never closed and its flags or console modes are not modified. macOS blocking pipes remain unsupported. Unlike PTY output, no per-write idle limit is applied, so a slow consumer such as a pager is not treated as a failure; only ctx cancellation or its deadline interrupts a write.

Any other writer is returned unchanged with cancelable=false: arbitrary Write callbacks cannot be interrupted, and wrapping them in a goroutine would merely hide the leak. The caller owns that writer and must keep it non-blocking. closeFn must be called after all writes have finished and releases only resources created by BindOutput.

func ComputeConnectionHash added in v0.16.0

func ComputeConnectionHash(localHost, host, portStr, user, jumpHost string) string

ComputeConnectionHash computes the 40-character lowercase hexadecimal SHA-1 hash matching OpenSSH ssh_connection_hash(%l%h%p%r%j).

func ConnectionKey

func ConnectionKey(plan ConnectionPlan) (string, error)

ConnectionKey hashes the complete normalized plan, including source and trust versions. It is not a file-transfer destination lock or authorization.

func CshQuote added in v0.16.0

func CshQuote(value string) string

CshQuote quotes value as a single C-shell (csh/tcsh) token.

func DecodeMuxAlive added in v0.16.0

func DecodeMuxAlive(payload []byte) (requestID uint32, pid uint32, err error)

func DecodeMuxClientRequestID added in v0.16.0

func DecodeMuxClientRequestID(payload []byte) (clientRequestID uint32, err error)

func DecodeMuxError added in v0.16.0

func DecodeMuxError(payload []byte) (clientRequestID uint32, reason string, err error)

func DecodeMuxExitMessage added in v0.16.0

func DecodeMuxExitMessage(payload []byte) (sessionID uint32, exitValue uint32, err error)

func DecodeMuxExtInfo added in v0.16.0

func DecodeMuxExtInfo(payload []byte) (requestID uint32, name string, err error)

func DecodeMuxExtInfoResponse added in v0.16.0

func DecodeMuxExtInfoResponse(payload []byte) (clientRequestID uint32, status uint32, msg string, err error)

func DecodeMuxRemotePort added in v0.16.0

func DecodeMuxRemotePort(payload []byte) (clientRequestID uint32, allocatedPort uint32, err error)

func DecodeMuxRequestID added in v0.16.0

func DecodeMuxRequestID(payload []byte) (requestID uint32, err error)

func DecodeMuxSessionOpened added in v0.16.0

func DecodeMuxSessionOpened(payload []byte) (clientRequestID uint32, sessionID uint32, err error)

func DecodeMuxTTYAllocFail added in v0.16.0

func DecodeMuxTTYAllocFail(payload []byte) (sessionID uint32, err error)

func DialControlProxy added in v0.16.0

func DialControlProxy(ctx context.Context, socketPath string, target TargetContext, opts ...MuxClientOption) (*cryptoSSH.Client, *muxProxySSHConn, error)

DialControlProxy connects to an OpenSSH ControlMaster socket in proxy mode, wraps the resulting connection in muxProxySSHConn, and returns a standard *cryptoSSH.Client. The endpoint must belong to the effective local user (or root); see DialMuxClient.

func DialMuxProxyStream added in v0.16.0

func DialMuxProxyStream(ctx context.Context, socketPath string, opts ...MuxClientOption) (net.Conn, error)

DialMuxProxyStream connects to the control socket, verifies the endpoint's peer user, completes the HELLO handshake, and switches to MUX_C_PROXY transport mode. The returned connection carries raw SSH transport bytes and is owned by the caller. It is the caller-facing equivalent of DialControlProxy for cases that need the socket itself rather than a cryptoSSH.Client.

func EncodeMuxAlive added in v0.16.0

func EncodeMuxAlive(requestID uint32, pid uint32) []byte

3. MUX_S_ALIVE (0x80000005)

func EncodeMuxClientRequestID added in v0.16.0

func EncodeMuxClientRequestID(clientRequestID uint32) []byte

4. MUX_S_OK (0x80000001) & MUX_S_PROXY (0x8000000f)

func EncodeMuxError added in v0.16.0

func EncodeMuxError(clientRequestID uint32, reason string) []byte

5. MUX_S_FAILURE (0x80000003) & MUX_S_PERMISSION_DENIED (0x80000002)

func EncodeMuxExitMessage added in v0.16.0

func EncodeMuxExitMessage(sessionID uint32, exitValue uint32) []byte

10. MUX_S_EXIT_MESSAGE (0x80000004)

func EncodeMuxExtInfo added in v0.16.0

func EncodeMuxExtInfo(requestID uint32, name string) []byte

13. MUX_C_EXT_INFO (0x20000001)

func EncodeMuxExtInfoResponse added in v0.16.0

func EncodeMuxExtInfoResponse(clientRequestID uint32, status uint32, msg string) []byte

14. MUX_S_EXT_INFO (0x90000001)

func EncodeMuxFwdRequest added in v0.16.0

func EncodeMuxFwdRequest(req MuxFwdRequest) []byte

6. MUX_C_OPEN_FWD (0x10000006) & MUX_C_CLOSE_FWD (0x10000007)

func EncodeMuxHello added in v0.16.0

func EncodeMuxHello(version uint32, extensions []MuxExtension) []byte

1. MUX_MSG_HELLO (0x00000001)

func EncodeMuxNewSession added in v0.16.0

func EncodeMuxNewSession(req MuxNewSessionRequest) []byte

8. MUX_C_NEW_SESSION (0x10000002)

func EncodeMuxNewStdioFwd added in v0.16.0

func EncodeMuxNewStdioFwd(req MuxNewStdioFwdRequest) []byte

12. MUX_C_NEW_STDIO_FWD (0x10000008)

func EncodeMuxRemotePort added in v0.16.0

func EncodeMuxRemotePort(clientRequestID uint32, allocatedPort uint32) []byte

7. MUX_S_REMOTE_PORT (0x80000007)

func EncodeMuxRequestID added in v0.16.0

func EncodeMuxRequestID(requestID uint32) []byte

2. Simple Request ID requests (ALIVE_CHECK, TERMINATE, STOP_LISTENING, PROXY)

func EncodeMuxSessionOpened added in v0.16.0

func EncodeMuxSessionOpened(clientRequestID uint32, sessionID uint32) []byte

9. MUX_S_SESSION_OPENED (0x80000006)

func EncodeMuxTTYAllocFail added in v0.16.0

func EncodeMuxTTYAllocFail(sessionID uint32) []byte

11. MUX_S_TTY_ALLOC_FAIL (0x80000008)

func ExpandControlPath added in v0.16.0

func ExpandControlPath(rawPath string, env Environment, target TargetContext) (string, error)

ExpandControlPath expands tokens (%%, %h, %p, %r, %n, %u, %l, %L, %i, %d, %j, %C), tilde (~), and environment variables (${VAR}) in rawPath according to OpenSSH ssh_config(5) rules.

func FilterSupportedListValue added in v0.16.0

func FilterSupportedListValue(canonicalKey, raw string) string

FilterSupportedListValue filters a comma-separated option value (for algorithm lists or PreferredAuthentications) down to tokens supported by this implementation. Used when leniently parsing ~/.ssh/config so OpenSSH-only algorithms (such as sntrup761x25519-sha512@openssh.com or umac-128-etm@openssh.com) do not reject the remaining supported algorithms.

func FishQuote added in v0.16.0

func FishQuote(value string) string

FishQuote quotes value as a single fish token.

func FormatScriptPayload added in v0.16.0

func FormatScriptPayload(interp Interpreter, login bool, dialect LaunchDialect, args []string) (string, error)

FormatScriptPayload constructs the command string for executing a script from stdin.

func FormatTargetIdentity added in v0.16.0

func FormatTargetIdentity(identity string) string

FormatTargetIdentity formats a canonical target identity string for human-readable error messages.

func FormatWorkingDirCommand

func FormatWorkingDirCommand(cwd, command string, execution *ExecutionConfig) (string, error)

FormatWorkingDirCommand formats a command prepended with working directory change based on the execution configuration, or returns an error if cwd cannot be applied.

func MaxControlPathLength added in v0.16.0

func MaxControlPathLength() int

MaxControlPathLength returns the maximum socket path length allowed by the OS sockaddr_un buffer. Linux / Windows AF_UNIX: 108 bytes. Darwin (macOS) / BSD: 104 bytes.

func NeedsExecutionProbe

func NeedsExecutionProbe(execution *ExecutionConfig) bool

NeedsExecutionProbe identifies an unspecified interpreter and unknown outer dialect. Explicit interpreter choices, including server, are never replaced.

func NormalizeWindowsSFTPWorkingDir

func NormalizeWindowsSFTPWorkingDir(cwd string) string

NormalizeWindowsSFTPWorkingDir converts OpenSSH SFTP drive paths /C:/... to C:/... for cmd.exe and Windows PowerShell. Other paths stay untouched. Callers must establish Windows semantics before using it.

func ParseControlPersist added in v0.16.0

func ParseControlPersist(val string) (enabled bool, indefinite bool, timeout time.Duration, err error)

ParseControlPersist parses OpenSSH ControlPersist specifications: - "no" / "false" / "": disabled - "yes" / "true" / "0": enabled indefinitely (indefinite=true, timeout=0) - duration: time formats documented in sshd_config(5), e.g. "10m", "1h", "600s", "600", "1d", "1w", "1h30m"

func ParseStrictHostKeyChecking added in v0.16.0

func ParseStrictHostKeyChecking(raw string) (string, error)

ParseStrictHostKeyChecking validates and normalizes StrictHostKeyChecking values.

func ReadMuxPacket added in v0.16.0

func ReadMuxPacket(r io.Reader) (packetType uint32, payload []byte, err error)

ReadMuxPacket reads a single framed MUX packet from r. Wire format:

uint32 packet_length (big-endian: 4 bytes type + payload length)
uint32 packet_type   (big-endian opcode)
bytes  payload

func ResolveAlgorithmList added in v0.16.0

func ResolveAlgorithmList(spec string, defaults []string) ([]string, error)

ResolveAlgorithmList resolves an OpenSSH algorithm specification (explicit list, +append, -remove, or ^prepend) against the provided default list.

func StartKeepAlive

func StartKeepAlive(ctx context.Context, client *ssh.Client, interval, timeout time.Duration, fallback func(err error)) <-chan struct{}

StartKeepAlive 开启一个协程,定期向 SSH Server 发送心跳 ctx: 用于控制协程退出的上下文 client: 目标 SSH 客户端 interval: 接收空闲探测间隔 (建议 15s - 60s) timeout: 等待心跳回复期间允许连续无接收进展的时间 (建议 5s - 15s) fallback: 可选的回调函数,用于在心跳失败后执行,心跳失败时会关闭连接 返回的通道在心跳 goroutine 完全退出后关闭,调用方可据此等待资源回收。 client.Close 必须能解除本地 I/O 阻塞;嵌套 ProxyJump 使用 Connector.EnableKeepAlive 或 Client.Wait,由连接所有者提供最外层传输的中断路径。 接收进展由 Connector 创建的连接提供;外部构造的 client 保留固定探测超时。

func StaticRespond

func StaticRespond(s string) func() (string, error)

StaticRespond 返回一个固定字符串的 Respond 回调。

func ValidateControlPath added in v0.16.0

func ValidateControlPath(expandedPath string) error

ValidateControlPath validates that the expanded socket path is non-empty and fits within OS limits.

func ValidateControlPathSyntax added in v0.16.0

func ValidateControlPathSyntax(rawPath string) error

ValidateControlPathSyntax verifies raw ControlPath string token syntax without environment dependencies.

func WithConsoleOutputRelay added in v0.15.0

func WithConsoleOutputRelay(ctx context.Context, relay ConsoleOutputRelay) (context.Context, func() error)

WithConsoleOutputRelay opts a command into Windows console output and returns its cleanup function. The host MUST retain and call cleanup after command I/O finishes, including on failure. Cleanup cancels active writes, retries bindings that could not be reaped locally, and can itself be retried on error. It never closes borrowed console streams. Other platforms ignore the capability.

func WriteMuxPacket added in v0.16.0

func WriteMuxPacket(w io.Writer, packetType uint32, payload []byte) error

WriteMuxPacket writes a single framed MUX packet to w in a single atomic Write call.

Types

type AuthMaterial

type AuthMaterial struct {
	Password   []byte
	Passphrase []byte
}

AuthMaterial 包含单次 SSH 握手所需的敏感认证材料。

func (*AuthMaterial) Zero

func (a *AuthMaterial) Zero()

Zero 清零敏感字节切片并清空引用。

type AuthMethod

type AuthMethod interface {
	GetMethod() (ssh.AuthMethod, error)
}

AuthMethod 定义获取 SSH 认证方法的接口

type AuthenticatedConnectionConfirmer

type AuthenticatedConnectionConfirmer interface {
	ConfirmAuthenticatedConnection(context.Context, string, *Client) (*ExecutionConfig, error)
}

AuthenticatedConnectionConfirmer optionally inspects an authenticated client before enrollment and credential recording. It may run bounded read-only probes but must not retain/close the client or execute user commands. Implementations own confirmation and may return newly persisted execution defaults for this client; nil preserves its frozen defaults. ConnectionConfirmer is the fallback.

type AutoAuthOptions

type AutoAuthOptions struct {
	AgentSocket               string
	DefaultKeyPaths           []string
	ResolveKeyPath            func(string) string
	LifecycleCtx              context.Context
	NodeID                    string
	User                      string
	Host                      string
	Port                      int
	VersionToken              string
	Resolver                  SecretResolver
	Prompter                  SecretPrompter
	HandshakeTimeout          time.Duration
	InteractionTimeout        time.Duration
	FailClosed                func(error)
	RecoveryPrompter          SecretPrompter
	KeyPath                   string
	PasswordCallback          func(string)
	PassphraseCallback        func(keyPath, passphrase string)
	CandidateRejectedCallback func(protocol string)
	SSHOptions                *Options
	HostKeyChanged            *atomic.Bool
	Logger                    logger.DebugLogger
	Diagnostics               logger.DiagnosticObserver
}

AutoAuthOptions 封装 auto 认证的完整上下文选项。

type Client

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

func DialControlProxyClient added in v0.16.0

func DialControlProxyClient(
	ctx context.Context,
	socketPath string,
	target TargetContext,
	env Environment,
	cfg *ClientConfig,
	l logger.DebugLogger,
	opts ...MuxClientOption,
) (*Client, error)

DialControlProxyClient connects to an OpenSSH ControlMaster socket in MUX_C_PROXY mode, verifies target identity if target.Host is specified, and returns a wrapped *Client ready to execute SSH sessions over the multiplexed connection without falling back to direct TCP. The caller owns the returned *Client and must Close it when done.

func NewTestClient

func NewTestClient(connCfg ConnectionConfig) *Client

NewTestClient creates a Client for unit testing with the provided connection config.

func NewTestClientWithRaw

func NewTestClientWithRaw(rawClient *ssh.Client, connCfg ConnectionConfig) *Client

NewTestClientWithRaw creates a Client for unit testing with an underlying raw SSH client.

func (*Client) AuthMaterial

func (c *Client) AuthMaterial() *AuthMaterial

AuthMaterial returns authentication material held by the client. Connected and pooled clients retain no AuthMaterial, always returning nil.

func (*Client) CachedExecutionProbe

func (c *Client) CachedExecutionProbe() (*ProbeResult, bool)

CachedExecutionProbe returns an already completed diagnostic snapshot without starting or waiting for network work. A failed or running probe returns false.

func (*Client) Close

func (c *Client) Close() error

func (*Client) Config

func (c *Client) Config() *ClientConfig

Config returns a snapshot of the node configuration. Mutating the returned value never changes the live client configuration. The snapshot contains no plaintext secrets (Password, Passphrase, SuPwd are always empty).

func (*Client) ConnectionConfig

func (c *Client) ConnectionConfig() ConnectionConfig

ConnectionConfig returns a copy of the live connection configuration.

func (*Client) ExecuteCommand

func (c *Client) ExecuteCommand(ctx context.Context, plan CommandPlan) (result CommandResult)

ExecuteCommand sends a frozen command exactly once with finite stdin and internally bounded output. It does not accept external writers or request a PTY, perform privilege escalation, probe the server, or retry execution. All workers are joined; closing a stuck channel may interrupt the shared transport, including other operations using the same ProxyJump connection.

func (*Client) Execution

func (c *Client) Execution() *ExecutionConfig

Execution returns the configured execution configuration for this client, or nil.

func (*Client) Interrupt

func (c *Client) Interrupt() error

Interrupt closes the underlying transport forcefully and synchronously. Closing the physical connection unblocks I/O without relying on a peer reply or manufacturing deadline errors in the SSH transport. For ProxyJump this closes the outermost transport and all clients sharing it.

func (*Client) LocalForward

func (c *Client) LocalForward(ctx context.Context, localAddr, remoteAddr string, opts ...ForwardOption) (*Forward, error)

LocalForward starts local port forwarding. Listens on localAddr, forwards connections to remoteAddr via SSH.

func (*Client) OpenSFTPStream added in v0.16.0

func (c *Client) OpenSFTPStream(ctx context.Context, sudo bool) (*SFTPStream, error)

OpenSFTPStream opens a binary SFTP stdio stream. When sudo is false, it requests the standard "sftp" subsystem. When sudo is true, it detects privilege escalation, executes an elevated sftp-server binary on the remote host (or uses the standard subsystem if the remote user is root), and performs a clean binary stream handoff.

func (*Client) ProbeControlledExecution

func (c *Client) ProbeControlledExecution(ctx context.Context, execution *ExecutionConfig) (*ExecutionConfig, error)

ProbeControlledExecution resolves a missing adapter for a restricted operation. Call only before script/ensure/cwd validation, never after a user command has started. Results share the Client's bounded probe cache; neither live command defaults nor disk configuration are changed. Consumers must still validate whether their operation supports the detected adapter.

func (*Client) ProbeExecutionConfig

func (c *Client) ProbeExecutionConfig(ctx context.Context) (*ProbeResult, error)

ProbeExecutionConfig performs a read-only, bounded two-stage probe. Successful results and non-context failures are shared for the authenticated connection's lifetime, including pooled wrappers. Concurrent callers share one attempt; each waiter can cancel independently. Non-context failures are cached, preventing repeated probes of restricted servers. A canceled or expired attempt can be retried by a later caller; its original waiters still receive its own result. This method neither changes Execution() nor writes configuration or retries user commands. A new connection is required to retry non-context failures.

func (*Client) RemoteForward

func (c *Client) RemoteForward(ctx context.Context, remoteAddr, localAddr string, opts ...ForwardOption) (*Forward, error)

RemoteForward starts remote port forwarding. Asks SSH server to listen on remoteAddr, forwards connections to localAddr. Startup and listener shutdown have independent, bounded request lifetimes. Canceling startup or timing out a request interrupts the shared SSH transport.

func (*Client) ResolvePrivilegeExecution added in v0.16.0

func (c *Client) ResolvePrivilegeExecution(ctx context.Context) (*ExecutionConfig, error)

ResolvePrivilegeExecution probes and returns the effective ExecutionConfig for privilege escalation. In non-interactive environments, it validates that required credentials are present before probing. If probing fails without context cancellation, it gracefully falls back to legacy defaults.

func (*Client) ResolveWorkingDirectoryExecution

func (c *Client) ResolveWorkingDirectoryExecution(ctx context.Context, execution *ExecutionConfig) (*ExecutionConfig, error)

ResolveWorkingDirectoryExecution selects an adapter for one cwd-aware command. A known server/cmd configuration has native CMD semantics, so CMD can apply the directory without changing command language. Keep this derived adapter session-local; unspecified configurations still use the bounded probe.

func (*Client) Run

func (c *Client) Run(ctx context.Context, cmd string, opts ...RunOption) (string, error)

func (*Client) RunCommandPlanWithIO

func (c *Client) RunCommandPlanWithIO(ctx context.Context, plan CommandPlan, stdin io.Reader, stdout, stderr io.Writer) (retErr error)

RunCommandPlanWithIO executes a frozen command plan with streaming stdin, stdout and stderr, without a PTY, privilege escalation, or replay.

stdin is borrowed and follows the RunCommandWithIO ownership contract (nil, an *os.File, or a finite in-memory reader); EOF closes only the sending direction. The plan must not carry finite input of its own: runtime stdin and plan input are never concatenated. stdout and stderr must be non-nil and cancelable as described by BindOutput; arbitrary writers are rejected before the command is sent. The plan's total timeout applies. A confirmed non-zero exit, signal or missing status is returned as an *ssh.ExitError or *ssh.ExitMissingError wrapped with context. Output is not retained.

func (*Client) RunCommandWithIO

func (c *Client) RunCommandWithIO(ctx context.Context, command string, sudo bool, stdin io.Reader, stdout, stderr io.Writer) (retErr error)

RunCommandWithIO executes a command (or interactive bash when command is empty) using caller-provided I/O streams. If sudo is true, it escalates privileges according to the target node's SudoMode. stdin is borrowed from the caller and will never be closed by this method. To guarantee cancellation without leaking a goroutine, stdin must be nil, an *os.File, or a finite in-memory *bytes.Buffer, *bytes.Reader, or *strings.Reader. Use RunCommandWithInput for arbitrary finite input bytes.

func (*Client) RunCommandWithInput

func (c *Client) RunCommandWithInput(ctx context.Context, command string, input []byte, stdout, stderr io.Writer) error

RunCommandWithInput executes a command (or interactive bash when command is empty) using finite byte input.

func (*Client) RunInteractive

func (c *Client) RunInteractive(ctx context.Context, cmd string) error

RunInteractive runs one command in a PTY using an SSH exec request. A non-interactive login bash loads the login environment without starting a prompt or writing the command through the terminal's echoed input stream.

func (*Client) RunInteractiveCmd

func (c *Client) RunInteractiveCmd(ctx context.Context, cmd string) error

RunInteractiveCmd 在 PTY 环境下直接执行命令(通过 SSH exec 通道,不启动交互式 shell), 不会产生登录信息或命令回显,适合在已有 shell 环境内调用 vim/top 等程序。

func (*Client) RunInteractiveCmdWithIO

func (c *Client) RunInteractiveCmdWithIO(ctx context.Context, cmd string, streams InteractiveIO) error

RunInteractiveCmdWithIO runs one PTY-backed command using caller-provided streams.

func (*Client) RunInteractivePlan

func (c *Client) RunInteractivePlan(ctx context.Context, plan CommandPlan) error

RunInteractivePlan executes a validated command plan in a PTY with the environment's terminal streams. stdin belongs to the terminal, not the plan.

func (*Client) RunInteractivePlanWithIO

func (c *Client) RunInteractivePlanWithIO(ctx context.Context, plan CommandPlan, streams InteractiveIO) (retErr error)

RunInteractivePlanWithIO requires local terminal input and finite, context-aware, or regular-file output. Regular files are borrowed and check cancellation between writes; a kernel write in progress must finish before return, so file-output cleanup has no hard time bound. Native terminal/pipe support follows the platform adapters; macOS blocking pipes remain unsupported.

func (*Client) RunInteractiveWithOptions

func (c *Client) RunInteractiveWithOptions(ctx context.Context, command string, opts ...RunOption) error

RunInteractiveWithOptions preserves the legacy login default while honoring an explicit WithLoginShell override. Terminal I/O is supplied by Environment.

func (*Client) RunInteractiveWithSudo

func (c *Client) RunInteractiveWithSudo(ctx context.Context, command string) error

RunInteractiveWithSudo 在 PTY 环境下以提权方式执行单条交互式命令

func (*Client) RunInteractiveWithSudoExecution added in v0.15.0

func (c *Client) RunInteractiveWithSudoExecution(ctx context.Context, command string, execution *ExecutionConfig) error

RunInteractiveWithSudoExecution applies a per-operation execution configuration without mutating the shared client's defaults. Terminal streams are borrowed from the host environment; the existing privilege lifecycle owns their binding.

func (*Client) RunInteractiveWithSudoExecutionIO added in v0.16.0

func (c *Client) RunInteractiveWithSudoExecutionIO(ctx context.Context, command string, execution *ExecutionConfig, streams InteractiveIO) (retErr error)

RunInteractiveWithSudoExecutionIO applies a per-operation execution configuration using caller-provided streams without mutating the shared client's defaults.

func (*Client) RunInteractiveWithSudoIO

func (c *Client) RunInteractiveWithSudoIO(ctx context.Context, command string, streams InteractiveIO) (retErr error)

RunInteractiveWithSudoIO uses an authenticated terminal handoff before consuming caller input. The injected streams avoid process-global I/O changes.

func (*Client) RunScript

func (c *Client) RunScript(ctx context.Context, scriptContent string, opts ...RunOption) (output string, retErr error)

RunScript 执行 Shell 脚本内容

func (*Client) RunScriptWithExecution

func (c *Client) RunScriptWithExecution(ctx context.Context, content string, execution *ExecutionConfig, extraOpts ...RunOption) (string, error)

RunScriptWithExecution applies the resolved execution configuration to RunScript.

func (*Client) RunScriptWithSudo

func (c *Client) RunScriptWithSudo(ctx context.Context, scriptContent string, opts ...RunOption) (string, error)

RunScriptWithSudo 提权执行脚本

func (*Client) RunScriptWithSudoExecution

func (c *Client) RunScriptWithSudoExecution(ctx context.Context, content string, execution *ExecutionConfig, extraOpts ...RunOption) (string, error)

RunScriptWithSudoExecution applies the same target/login capability checks to a script whose interpreter has already been resolved by the caller.

func (*Client) RunShellWithIO

func (c *Client) RunShellWithIO(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer) (retErr error)

RunShellWithIO sends an SSH shell request without a PTY using caller-provided I/O streams. Unlike RunShellWithoutPTY, which enforces strict output cancelability, RunShellWithIO allows uncancelable outputs on platforms where native cancelable output is unavailable.

func (*Client) RunShellWithoutPTY

func (c *Client) RunShellWithoutPTY(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer) (retErr error)

RunShellWithoutPTY sends an SSH shell request without a PTY and forwards streaming stdin. It is for non-terminal input to a server shell: no interpreter is inserted, no empty exec request is sent, and unlike a full login terminal session the remote exit status is retained. Input, output and cancellation follow RunCommandPlanWithIO. Duration is controlled by ctx.

func (*Client) RunStream

func (c *Client) RunStream(ctx context.Context, cmd string) (io.ReadCloser, error)

RunStream 执行命令并返回流式输出

func (*Client) RunWithSudo

func (c *Client) RunWithSudo(ctx context.Context, command string, opts ...RunOption) (string, error)

func (*Client) RunWithSudoExecution

func (c *Client) RunWithSudoExecution(ctx context.Context, command string, execution *ExecutionConfig, extraOpts ...RunOption) (string, error)

RunWithSudoExecution honors a frozen execution configuration or rejects an unvalidated escalation adapter. Nil configuration preserves legacy behavior.

func (*Client) RunWithoutLogin

func (c *Client) RunWithoutLogin(ctx context.Context, cmd string) (string, error)

RunWithoutLogin 执行命令并在非登录 Shell 中运行,避免加载 profile 脚本产生干扰输出

func (*Client) SSHClient

func (c *Client) SSHClient() *ssh.Client

func (*Client) Shell

func (c *Client) Shell(ctx context.Context) error

func (*Client) ShellWithIO

func (c *Client) ShellWithIO(ctx context.Context, streams InteractiveIO) error

ShellWithIO starts an interactive remote shell using caller-provided streams.

func (*Client) ShellWithSudo

func (c *Client) ShellWithSudo(ctx context.Context) error

ShellWithSudo opens an interactive privileged shell using the default streams.

func (*Client) ShellWithSudoIO

func (c *Client) ShellWithSudoIO(ctx context.Context, streams InteractiveIO) (retErr error)

ShellWithSudoIO authenticates before switching the local terminal to raw mode.

func (*Client) Socks5Forward

func (c *Client) Socks5Forward(ctx context.Context, listenAddr string, opts ...ForwardOption) (*Forward, error)

Socks5Forward starts a SOCKS5 proxy server on listenAddr, forwarding traffic via SSH.

func (*Client) Wait

func (c *Client) Wait(ctx context.Context) error

Wait monitors the SSH transport, probing idle connections to detect network loss. It closes the client before returning and joins its transport waiter. Caller cancellation returns only cleanup errors; transport loss is an error. Receive progress postpones idle probes and extends pending probe timeouts. Cancellation or a failed probe aborts the entire shared ProxyJump transport.

type ClientConfig

type ClientConfig struct {
	KeyRef       string
	TrustVersion string
	NodeID       string // 逻辑标识
	Address      string
	Port         int
	User         string
	AuthType     string // "password", "key", "agent", "auto"
	Password     string
	KeyPath      string
	Passphrase   string
	// AuthUpdateToken conditionally authorizes persistence of discovered
	// authentication values. An empty token makes discovery session-local.
	AuthUpdateToken string
	SudoMode        SudoMode // "root", "sudo", "sudoer", "su", "none", "auto"
	SuPwd           string
	// SudoUpdateToken conditionally authorizes persistence of discovered sudo
	// values. An empty token makes discovery session-local.
	SudoUpdateToken      string
	ProxyJump            string // 跳板机的 NodeID
	OriginalProxyJump    string // 来自 Provider 的原始 ProxyJump 配置(用于目标一致性变更检查)
	HasOriginalProxyJump bool   // 是否显式保留了配置态 ProxyJump 快照(区分显式空字符串与未设置)
	// PasswordPromptPattern 自定义密码提示正则(节点级,可选)。
	// 为空时回落到 Connector 的全局配置,再为空则使用内置的多语言默认模式。
	PasswordPromptPattern string
	Execution             *ExecutionConfig
	Options               *Options
}

ClientConfig 定义建立 SSH 连接所需的各种参数,代替原有的 models.Node/Host/Identity。

func (*ClientConfig) ToConnectionConfig

func (c *ClientConfig) ToConnectionConfig() ConnectionConfig

ToConnectionConfig 将 ClientConfig 转换为仅含网络与连接参数的 ConnectionConfig,剥离所有明文密码。

type CommandExitError

type CommandExitError struct {
	ExitCode *uint32
	Signal   string
}

CommandExitError reports a confirmed unsuccessful remote termination.

func (*CommandExitError) Error

func (e *CommandExitError) Error() string

type CommandOptions

type CommandOptions struct {
	Interpreter   Interpreter
	LaunchDialect LaunchDialect
	Login         LoginMode
	Stdin         []byte
	Timeout       time.Duration
	OutputLimit   int
}

CommandOptions is copied into an immutable CommandPlan. Stdin is finite user data, never a second command or an interpreter-selection probe. Timeout zero and OutputLimit zero select bounded defaults; negative values are invalid.

type CommandPlan

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

CommandPlan is immutable and safe to share across execution attempts. The zero value is invalid. Accessors return values, never mutable internal state. Digest binds command semantics and input but is not an authorization permit.

func PlanCommand

func PlanCommand(command string, options CommandOptions) (CommandPlan, error)

PlanCommand validates and freezes one ordinary command without network I/O. It never performs OS detection or fallback. Unix adapters require a known POSIX or fish outer shell; server preserves command bytes and accepts only inherited login mode.

func (CommandPlan) Command

func (p CommandPlan) Command() string

func (CommandPlan) Digest

func (p CommandPlan) Digest() string

func (CommandPlan) Interpreter

func (p CommandPlan) Interpreter() Interpreter

func (CommandPlan) LaunchDialect

func (p CommandPlan) LaunchDialect() LaunchDialect

func (CommandPlan) LoginMode

func (p CommandPlan) LoginMode() LoginMode

func (CommandPlan) Payload

func (p CommandPlan) Payload() string

type CommandResult

type CommandResult struct {
	PlanDigest   string
	Phase        string
	Outcome      ExecutionOutcome
	ExitCode     *uint32
	Signal       string
	Output       string
	Truncated    bool
	ExecutionErr error
	IOErr        error
	CleanupErr   error
}

CommandResult retains remote termination independently of local I/O/cleanup failures. ExitCode is nil if no exit-status was received, including signals.

func (CommandResult) Err

func (r CommandResult) Err() error

type ConfigStore

type ConfigStore interface {
	ConnectionProvider
	CredentialRecorder
}

ConfigStore 聚合 ConnectionProvider 和 CredentialRecorder 接口。 Deprecated: 请优先使用拆分后的小接口 ConnectionProvider, SecretResolver, CredentialRecorder。

type ConnectionConfig

type ConnectionConfig struct {
	KeyRef                string
	TrustVersion          string
	NodeID                string
	Address               string
	Port                  int
	User                  string
	AuthType              string
	KeyPath               string
	AuthUpdateToken       string
	SudoMode              SudoMode
	SudoUpdateToken       string
	ProxyJump             string
	OriginalProxyJump     string
	HasOriginalProxyJump  bool
	PasswordPromptPattern string
	Execution             *ExecutionConfig
	Options               *Options
}

ConnectionConfig 包含建立连接所需的目标与网络参数,不包含登录或提权明文机密。

func (ConnectionConfig) Clone added in v0.16.0

Clone returns a deep copy of ConnectionConfig, isolating mutable Execution and Options pointers.

type ConnectionConfirmer

type ConnectionConfirmer interface {
	ConfirmConnection(context.Context, string) error
}

ConnectionConfirmer is an optional provider capability invoked immediately after SSH authentication, before recording credentials or dispatching user work.

type ConnectionError

type ConnectionError struct {
	NodeID   string
	Address  string
	Port     int
	AuthType string
	Err      error
}

ConnectionError 携带节点连接相关的结构化上下文

func (*ConnectionError) Error

func (e *ConnectionError) Error() string

func (*ConnectionError) Unwrap

func (e *ConnectionError) Unwrap() error

type ConnectionPlan

type ConnectionPlan struct {
	Scope string
	Hops  []ConnectionConfig
}

ConnectionPlan is an immutable connection snapshot. Hops are ordered from the first directly reachable jump to the final target, without plaintext secrets. Scope separates consumers that share node names or credentials.

func CapturePlan

func CapturePlan(ctx context.Context, provider ConnectionProvider, nodeID, scope string) (_ ConnectionPlan, retErr error)

CapturePlan resolves a complete snapshot from a host-supplied immutable in-memory provider. It never dials or retains that provider after returning.

type ConnectionProvider

type ConnectionProvider interface {
	// GetConfig 获取指定 nodeID 的连接配置
	GetConfig(nodeID string) (*ClientConfig, error)
}

ConnectionProvider 提供指定节点的底层连接配置。

type Connector

type Connector struct {

	// 自动接受新的主机密钥
	AcceptNewHostKey atomic.Bool
	// PasswordPromptPattern 全局级自定义密码提示正则(可选)。
	// 当节点的 ClientConfig.PasswordPromptPattern 为空时,使用此值;
	// su 在两者均为空时使用 DefaultPasswordPromptPattern;sudo 回退仅接受有效显式配置。
	PasswordPromptPattern string
	// contains filtered or unexported fields
}

Connector 负责创建 SSH 连接

func NewConnector

func NewConnector(provider ConnectionProvider, opts ...Option) *Connector

NewConnector 创建一个新的 Connector,支持 Functional Options。 支持接收 ConnectionProvider 或兼容的 ConfigStore。

func (*Connector) AcquireMaster added in v0.16.0

func (c *Connector) AcquireMaster(server *MuxServer) bool

AcquireMaster restores this connector's active-session reference on a master it owns after a handoff reservation was rolled back.

func (*Connector) CloseAll

func (c *Connector) CloseAll() error

CloseAll 关闭所有缓存的连接并等待在途建连与心跳 goroutine 退出。 调用后 Connector 进入永久关闭状态,后续 Connect 返回 ErrConnectorClosed。

func (*Connector) Connect

func (c *Connector) Connect(ctx context.Context, nodeName string) (*Client, error)

Connect 根据节点名称建立 SSH 连接。 ProxyJump 链会先完整解析并检测环,再从最底层跳板机开始逐层建立连接。

func (*Connector) ConnectPlan

func (c *Connector) ConnectPlan(ctx context.Context, plan ConnectionPlan) (*PlanConnection, error)

ConnectPlan never reads the connector's mutable ConnectionProvider. The source references and complete jump chain are copied into a generation-owned provider; legacy credential recording is disabled for these snapshots.

func (*Connector) EnableKeepAlive

func (c *Connector) EnableKeepAlive(ctx context.Context, interval, timeout time.Duration)

EnableKeepAlive 启用连接池周期心跳(opt-in,幂等)。 启用后所有新入池的连接(含 ProxyJump 跳板机连接)会挂载周期性 keepalive 探测: 接收数据会推迟空闲探测;等待回复期间持续接收数据会刷新超时。 探测失败或持续无接收进展直到超时才关闭连接并从池中驱逐,下次 Connect 自动重建。 interval/timeout 传非正值时回退到 DefaultKeepAliveInterval/DefaultKeepAliveTimeout。 Connect 的缓存复检以 timeout 为总时限,不随接收进展延长。 生命周期同时绑定 ctx 与 CloseAll:任一方取消都会终止全部心跳 goroutine 并清理配置; ctx 取消完成清理后允许再次启用,CloseAll 之后则不会恢复。 仅对启用后入池的连接生效,存量连接不补挂。 适用于 MCP server 等长驻进程;CLI 短生命周期命令无需启用(Connect 的缓存探测已兜底)。

func (*Connector) HasMasterSession added in v0.16.0

func (c *Connector) HasMasterSession(server *MuxServer) bool

HasMasterSession reports whether this connector still holds its initial active-session reference on server.

func (*Connector) Masters added in v0.16.0

func (c *Connector) Masters() []*MuxServer

Masters returns a snapshot of the multiplexing masters this connector started in deterministic creation order (outermost jump master to innermost target).

func (*Connector) OwnsMaster added in v0.16.0

func (c *Connector) OwnsMaster(server *MuxServer) bool

OwnsMaster reports whether server was started by this connector.

func (*Connector) ReleaseMaster added in v0.16.0

func (c *Connector) ReleaseMaster(server *MuxServer) bool

ReleaseMaster drops this connector's active-session reference to a master it started, without stopping the master. A ControlPersist handoff needs exactly that: the connector keeps its transport counted so the idle timer cannot kill a live session, but the detached daemon that inherits the socket must be able to take the master over. It reports whether this connector owned server; the master stays owned, so CloseAll still stops it if no handoff happens.

func (*Connector) RetirePlan

func (c *Connector) RetirePlan(plan ConnectionPlan) error

RetirePlan stops new reuse of this cached generation and drains its existing leases. This is cache invalidation, not authorization/revocation: callers must check current operation bindings before requesting any plan again.

type ConsoleOutputRelay added in v0.15.0

type ConsoleOutputRelay struct {
	Executable string
	Args       []string
	Env        []string
}

ConsoleOutputRelay describes a host-owned Windows helper entry point. The executable must dispatch Args followed by a private handle specification to ServeConsoleOutputRelay before normal application startup. Env is an explicit snapshot; core never discovers or dispatches the host executable.

type ContextWriter

type ContextWriter interface {
	WriteContext(context.Context, []byte) (int, error)
}

ContextWriter is an explicit output capability. Implementations must return when ctx is canceled, perform no writes after returning, and not retain data. Ordinary io.Writer callbacks cannot provide that guarantee automatically. The built-in regular-file adapter has a weaker contract: cancellation is checked between writes, and an in-flight kernel write must finish before return.

type ControlConfig added in v0.16.0

type ControlConfig struct {
	Master  ControlMasterMode `json:"master,omitempty" yaml:"master,omitempty"`
	Path    string            `json:"path,omitempty" yaml:"path,omitempty"`
	Persist string            `json:"persist,omitempty" yaml:"persist,omitempty"`
	// ImplicitTier4 is true when multiplexing was resolved solely from ~/.ssh/config
	// (Tier 4) without any CLI flag or xops node/global configuration.
	ImplicitTier4 bool `json:"-" yaml:"-"`
}

ControlConfig specifies the connection multiplexing parameters for an SSH connection. Matches the contract defined in PROJECT.md and Schema V2.

func EffectiveControl added in v0.16.0

func EffectiveControl(layers ...*ControlConfig) (*ControlConfig, error)

EffectiveControl resolves a hierarchy of multiplexing configs from highest priority to lowest priority (e.g. session CLI overrides, node, global, openssh).

func ResolveControl added in v0.16.0

func ResolveControl(child, parent *ControlConfig) (*ControlConfig, error)

ResolveControl merges a child (higher priority) multiplexing config with a parent (lower priority) config according to inheritance rules: - Master inherits from parent unless child explicitly sets it. - Path inherits from parent unless child explicitly sets it. - Persist inherits from parent unless child explicitly sets it. - If child sets Path="none", multiplexing is disabled for the child.

func (*ControlConfig) Clone added in v0.16.0

func (c *ControlConfig) Clone() *ControlConfig

Clone returns a deep copy of ControlConfig.

func (*ControlConfig) Equal added in v0.16.0

func (c *ControlConfig) Equal(other *ControlConfig) bool

Equal reports whether two ControlConfig values are equal.

func (*ControlConfig) IsEnabled added in v0.16.0

func (c *ControlConfig) IsEnabled() bool

IsEnabled returns true if multiplexing is enabled (either master or reuse).

type ControlMasterMode added in v0.16.0

type ControlMasterMode string

ControlMasterMode specifies connection sharing master behavior. Compatible with OpenSSH ssh_config(5) ControlMaster options.

const (
	// ControlMasterNo disables listening on the control socket.
	// If a control socket exists and is active, client will reuse it; otherwise connects normally.
	ControlMasterNo ControlMasterMode = "no"

	// ControlMasterYes listens on the control socket as master.
	ControlMasterYes ControlMasterMode = "yes"

	// ControlMasterAsk listens as master, prompting confirmation before opening new sessions.
	ControlMasterAsk ControlMasterMode = "ask"

	// ControlMasterAuto opportunistically attempts client reuse on ControlPath;
	// if none exists or the socket is stale, it establishes master listening on ControlPath.
	ControlMasterAuto ControlMasterMode = "auto"

	// ControlMasterAutoAsk opportunistic reuse like auto, but prompting confirmation like ask.
	ControlMasterAutoAsk ControlMasterMode = "autoask"
)

func ParseControlMasterMode added in v0.16.0

func ParseControlMasterMode(val string) (ControlMasterMode, error)

ParseControlMasterMode normalizes string inputs into a valid ControlMasterMode. Supports OpenSSH keywords ("no", "yes", "ask", "auto", "autoask") and boolean aliases ("true", "false").

type ControlProvider added in v0.16.0

type ControlProvider interface {
	GetControlConfig(nodeID string) (*ControlConfig, error)
}

ControlProvider provides multiplexing configuration for a node.

type CredentialFailureReporter

type CredentialFailureReporter interface {
	CredentialRecoveryAllowed() bool
	ReportCredentialFailure(context.Context, string) error
}

CredentialFailureReporter opts an interactive composition root into temporary credential recovery. Reports contain operation names only, never backend errors, which may contain secrets. Returning an error aborts recovery.

type CredentialRecorder

type CredentialRecorder interface {
	// UpdateAuth 在探测到可用密码或私钥 passphrase 时,写回持久化存储并返回本次提交后的新认证令牌
	UpdateAuth(ctx context.Context, nodeID, authUpdateToken, password, keyPath, passphrase string) (string, error)

	// UpdateSudo 在探测到可用提权模式或接收到 su 密码时,写回持久化存储并返回本次提交后的新提权令牌
	UpdateSudo(ctx context.Context, nodeID, sudoUpdateToken string, mode SudoMode, suPwd string) (string, error)
}

CredentialRecorder 负责将探测或交互获得的新凭据写回持久化存储。

type Dialer

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

Dialer 定义网络连接行为的接口 用于统一 "直连" 和 "通过 SSH 跳板机连接" 的行为

type Environment

type Environment struct {
	InitializationError error
	KnownHostsFile      string
	AgentSocket         string
	DefaultKeyPaths     []string
	ResolveKeyPath      func(string) string
	InteractiveIO       InteractiveIO
	InputBridge         InputBridge

	// Multiplexing and path expansion parameters injected by host
	HomeDir   string
	LocalUser string
	LocalHost string
	LocalUID  string
	LookupEnv func(string) (string, bool)
}

Environment supplies explicitly selected local resources. The core never discovers a home directory, SSH_AUTH_SOCK, or process standard streams. Slices are copied by WithEnvironment; callbacks must be concurrency-safe.

type ExecutionConfig

type ExecutionConfig struct {
	Interpreter   Interpreter   `yaml:"interpreter,omitempty" json:"interpreter,omitempty"`
	LaunchDialect LaunchDialect `yaml:"launch_dialect,omitempty" json:"launchDialect,omitempty"`
	Login         *bool         `yaml:"login,omitempty" json:"login,omitempty"`
}

ExecutionConfig specifies the execution environment for commands. It can be configured at global, node, playbook settings, or step levels.

func DeriveWorkingDirectoryExecution added in v0.16.0

func DeriveWorkingDirectoryExecution(execution *ExecutionConfig) (*ExecutionConfig, bool)

DeriveWorkingDirectoryExecution returns a derived ExecutionConfig when an explicit server interpreter has a known launch dialect that can safely execute cd.

func EffectiveExecution

func EffectiveExecution(layers ...*ExecutionConfig) (*ExecutionConfig, error)

EffectiveExecution resolves a hierarchy of execution configs from highest priority to lowest priority (e.g. step, settings, node, global).

func ResolveExecution

func ResolveExecution(child, parent *ExecutionConfig) (*ExecutionConfig, error)

ResolveExecution merges a child (higher priority) execution config with a parent (lower priority) execution config according to the inheritance rules:

  • launch_dialect inherits from parent unless explicitly overridden by child.
  • If child overrides interpreter to a different non-empty interpreter, parent's login option is NOT inherited (child's login applies, or nil).
  • If child does not override interpreter, parent's interpreter is inherited, and login inherits from parent unless child explicitly sets it.
  • Explicit incompatible combinations fail validation.

func ResolveScriptExecution

func ResolveScriptExecution(step, settings, node, global *ExecutionConfig, scriptBytes []byte) (*ExecutionConfig, error)

ResolveScriptExecution resolves the execution configuration for a script following the precedence order:

  1. Explicit Playbook step execution (step)
  2. Playbook settings execution (settings)
  3. Supported shebang declaration in script bytes
  4. Node execution (non-server only)
  5. Global execution (non-server only)

Explicitly selecting the server interpreter in step or settings returns an error. If the script declares an unsupported shebang without an explicit step or settings override, an error is returned. In Phase P3, scripts use the unified model by default and fail before execution if no reliable interpreter is available. If execution config is present or defaulted but no valid non-server script interpreter can be determined, an error is returned.

func (*ExecutionConfig) Clone

func (e *ExecutionConfig) Clone() *ExecutionConfig

Clone returns a deep copy of ExecutionConfig.

func (*ExecutionConfig) CommandOptions

func (e *ExecutionConfig) CommandOptions() CommandOptions

CommandOptions applies caller defaults, then converts execution config. In Phase P3, absence or unspecified interpreter defaults to InterpreterServer with LaunchUnknown and LoginInherit. An explicit interpreter uses its adapter defaults; server never inherits a POSIX launch assumption.

func (*ExecutionConfig) EffectiveInterpreter

func (e *ExecutionConfig) EffectiveInterpreter() Interpreter

EffectiveInterpreter returns the configured interpreter, or the default InterpreterServer if unspecified.

func (*ExecutionConfig) LoginMode

func (e *ExecutionConfig) LoginMode() LoginMode

LoginMode returns the effective LoginMode represented by the configuration.

func (ExecutionConfig) MarshalJSON

func (e ExecutionConfig) MarshalJSON() ([]byte, error)

MarshalJSON serializes ExecutionConfig using camelCase launchDialect.

func (*ExecutionConfig) SudoRunOptions

func (e *ExecutionConfig) SudoRunOptions(command string) ([]RunOption, error)

SudoRunOptions rejects unsupported escalation semantics before dispatch and maps the validated Bash, sh, zsh, fish, csh or tcsh mode to the sudo adapter explicitly. A nil config preserves the legacy POSIX Bash+login environment.

func (*ExecutionConfig) UnmarshalJSON

func (e *ExecutionConfig) UnmarshalJSON(data []byte) error

UnmarshalJSON strictly unmarshals and validates an ExecutionConfig from JSON, supporting both launchDialect and launch_dialect, and login as bool or string.

func (*ExecutionConfig) UnmarshalYAML

func (e *ExecutionConfig) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML strictly unmarshals and validates an ExecutionConfig from YAML, rejecting unknown fields.

func (*ExecutionConfig) Validate

func (e *ExecutionConfig) Validate() error

Validate validates that the execution configuration contains supported values and mutually compatible settings.

type ExecutionOutcome

type ExecutionOutcome string

ExecutionOutcome describes what is known about remote execution, not whether it succeeded. Unknown results must never be automatically replayed.

const (
	ExecutionNotStarted ExecutionOutcome = "not_started"
	ExecutionCompleted  ExecutionOutcome = "completed"
	ExecutionUnknown    ExecutionOutcome = "unknown"
)

type Expect

type Expect struct {
	Target io.Writer // 匹配过程中和完成后的透传目标(用于交互式 Shell 实时显示)
	// contains filtered or unexported fields
}

Expect 是一个被动的 io.Writer,拦截并分析 SSH 输出流,匹配多阶段交互。 通过实现 io.Writer,它消除了主动 Read 导致的 goroutine 泄露和数据竞争问题。

func NewExpect

func NewExpect(writer io.Writer, rules ...ExpectRule) *Expect

NewExpect 创建一个 Expect 实例。 writer 是自动响应的目标(例如 SSH 会话的 stdin)。 该构造器保留原有的可变参数 API;需要注入可选依赖时使用 NewExpectWithOptions。

func NewExpectWithOptions

func NewExpectWithOptions(writer io.Writer, rules []ExpectRule, opts ...ExpectOption) *Expect

NewExpectWithOptions 创建一个支持显式依赖注入的 Expect 实例。

func (*Expect) CleanOutput

func (e *Expect) CleanOutput(promptPattern *regexp.Regexp) string

CleanOutput 返回清理后的输出:剔除匹配 promptPattern 的密码输入行。

func (*Expect) Output

func (e *Expect) Output() string

Output 返回内部缓冲区累积的所有输出。

func (*Expect) SetAccumulate

func (e *Expect) SetAccumulate(acc bool)

SetAccumulate 设置是否在匹配结束后继续累积输出。 用于短生命周期的命令(如 runWithSu),以便执行完毕后获取完整输出。

func (*Expect) SetTarget

func (e *Expect) SetTarget(target io.Writer)

SetTarget 设置透传目标,所有 Write 进来的数据都会原样写入 target。

func (*Expect) Stop

func (e *Expect) Stop()

Stop 停止匹配逻辑,释放资源,不再缓冲多余数据(除非 accumulateAll=true)。

func (*Expect) Wait

func (e *Expect) Wait(ctx context.Context, timeout time.Duration) error

Wait 等待所有规则匹配完成、超时或 ctx 取消。 超时发生时,它会自动调用 Stop,后续不再进行任何正则匹配。

func (*Expect) Write

func (e *Expect) Write(p []byte) (n int, err error)

Write 实现了 io.Writer 接口,由 SSH 客户端底层主动调用,消除了竞态。

type ExpectOption

type ExpectOption func(*Expect)

ExpectOption 用于配置 Expect

func WithExpectLogger

func WithExpectLogger(l logger.DebugLogger) ExpectOption

WithExpectLogger 为 Expect 注入 DebugLogger(必须支持并发调用)

type ExpectRule

type ExpectRule struct {
	// Pattern 是用于匹配 PTY 输出的正则表达式。
	Pattern *regexp.Regexp

	// Respond 在 Pattern 命中后被调用,返回需要写入 stdin 的内容(不含换行符)。
	Respond func() (string, error)
}

ExpectRule 定义单条匹配规则:等待输出匹配 Pattern,然后调用 Respond 生成响应。

type Forward

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

Forward represents one running SSH port forward. Callers must either wait for it or cancel the context passed to its constructor.

func (*Forward) Addr

func (f *Forward) Addr() net.Addr

Addr returns the listener address, including a server-allocated port. For remote forwarding, the SSH server's GatewayPorts policy controls exposure; the returned host is not proof of the server's effective bind interfaces.

func (*Forward) Done

func (f *Forward) Done() <-chan struct{}

Done closes after the listener and all accepted connections have stopped.

func (*Forward) Wait

func (f *Forward) Wait() error

Wait blocks until the forwarding listener and all connection handlers exit. It is safe to call Wait more than once; every call returns the same result.

type ForwardOption

type ForwardOption func(*forwardOptions)

ForwardOption configures how a forwarding listener reports connection-level failures. These failures never stop the listener.

func WithForwardConnectionLimit

func WithForwardConnectionLimit(limit int) ForwardOption

WithForwardConnectionLimit bounds concurrent accepted connections. Excess connections are closed immediately. Nonpositive values leave the default unlimited behavior unchanged.

func WithForwardErrorHandler

func WithForwardErrorHandler(handler func(error)) ForwardOption

WithForwardErrorHandler receives errors isolated to one accepted connection. The callback must be safe for concurrent calls and return promptly.

type ForwardRequest added in v0.16.0

type ForwardRequest struct {
	Type        ForwardType
	ListenHost  string
	ListenPort  uint32
	ConnectHost string
	ConnectPort uint32
}

ForwardRequest represents a dynamic, local, or remote forwarding request.

type ForwardType added in v0.16.0

type ForwardType uint32

ForwardType defines the port forwarding direction in OpenSSH PROTOCOL.mux.

type HandshakeError

type HandshakeError struct {
	NodeID string
	Err    error
}

HandshakeError 封装 SSH 协议握手失败的错误

func (*HandshakeError) Error

func (e *HandshakeError) Error() string

func (*HandshakeError) Unwrap

func (e *HandshakeError) Unwrap() error

type HostKeyAlgorithmSource

type HostKeyAlgorithmSource interface {
	HostKeyAlgorithms(context.Context, HostKeyRequest) ([]string, error)
}

HostKeyAlgorithmSource is an optional HostKeyVerifier capability. It selects host key algorithms before the handshake using the same target/trust version as Verify. Hostname and Remote are not available at this stage. Implementations must honor ctx; errors, empty lists and unsupported algorithms fail closed. Selection does not replace Verify or authorize a different key of that type.

type HostKeyConfirmation

type HostKeyConfirmation struct {
	Hostname      string
	RemoteAddress string
	Algorithm     string
	Fingerprint   string
}

HostKeyConfirmation 描述主机密钥指纹确认请求

type HostKeyConfirmer

type HostKeyConfirmer interface {
	ConfirmHostKey(ctx context.Context, request HostKeyConfirmation) (bool, error)
}

HostKeyConfirmer 负责提示用户确认未知的主机密钥

type HostKeyRequest

type HostKeyRequest struct {
	NodeID       string
	Host         string
	Port         int
	User         string
	VersionToken string
	Hostname     string
	Remote       net.Addr
}

HostKeyRequest binds trust verification to the connection being established.

type HostKeyVerifier

type HostKeyVerifier interface {
	Verify(context.Context, HostKeyRequest, cryptoSSH.PublicKey) error
}

HostKeyVerifier implementations must honor the handshake context and must not trust an unknown host implicitly.

type InputBridge

type InputBridge interface {
	Start(context.Context, InteractiveIO, io.Writer) (InputCopy, error)
}

InputBridge owns only duplicated input and cancellation handles. The caller owns the supplied terminal streams and the remote writer.

type InputCopy

type InputCopy interface {
	Close() error
	Wait(context.Context) error
}

InputCopy.Close interrupts reading; Wait joins the copy within its context. Closing a copy must not close any borrowed process standard stream.

func NewInputCopy

func NewInputCopy(ctx context.Context, cancel func() error, done <-chan error) (InputCopy, error)

NewInputCopy adapts a cancellable input pump. The pump must send exactly one completion result and exit when interrupted; cancellation must be bounded. The returned copy owns cancellation and joins the completion collector.

type InteractionHandler

type InteractionHandler interface {
	SecretPrompter
	HostKeyConfirmer
}

InteractionHandler 组合了机密提示与主机密钥确认接口

type InteractiveIO

type InteractiveIO struct {
	Stdin  *os.File
	Stdout io.Writer
	Stderr io.Writer
}

InteractiveIO supplies the terminal streams used by an interactive SSH operation. The caller owns these streams and their lifecycle.

type Interpreter

type Interpreter string

Interpreter selects how a command is executed, independently of the server's launch dialect. Only validated command adapters are exposed here.

const (
	InterpreterServer     Interpreter = "server"
	InterpreterBash       Interpreter = "bash"
	InterpreterSh         Interpreter = "sh"
	InterpreterFish       Interpreter = "fish"
	InterpreterZsh        Interpreter = "zsh"
	InterpreterCsh        Interpreter = "csh"
	InterpreterTcsh       Interpreter = "tcsh"
	InterpreterPowerShell Interpreter = "powershell"
	InterpreterPwsh       Interpreter = "pwsh"
	InterpreterCmd        Interpreter = "cmd"
)

type KeyAuth

type KeyAuth struct {
	Path       string
	Passphrase string
}

KeyAuth 实现私钥认证

func (*KeyAuth) GetMethod

func (k *KeyAuth) GetMethod() (ssh.AuthMethod, error)

type KeyLease

type KeyLease interface {
	Signer() cryptoSSH.Signer
	Close() error
}

KeyLease is owned by the handshake and released on every success/error path. Implementations honor the OpenKey context and keep Close bounded.

type KeyRequest

type KeyRequest struct {
	NodeID       string
	Host         string
	Port         int
	User         string
	Reference    string
	Path         string
	VersionToken string
}

KeyRequest binds a signer to a target and version. Reference is opaque to SSH and never interpreted as a local path; Path is an explicit file hint.

type KeySource

type KeySource interface {
	OpenKey(context.Context, KeyRequest) (KeyLease, error)
}

type KeyboardInteractiveOptions added in v0.16.0

type KeyboardInteractiveOptions struct {
	MaxQueries int
}

KeyboardInteractiveOptions allows customizing keyboard-interactive behavior.

type LaunchDialect

type LaunchDialect string

LaunchDialect describes the server shell parsing the SSH exec payload.

const (
	LaunchUnknown    LaunchDialect = "unknown"
	LaunchPOSIX      LaunchDialect = "posix"
	LaunchFish       LaunchDialect = "fish"
	LaunchCsh        LaunchDialect = "csh"
	LaunchPowerShell LaunchDialect = "powershell"
	LaunchCmd        LaunchDialect = "cmd"
)

type LockedWriter

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

LockedWriter 是一个并发安全的 io.Writer 包装器。 用于多个 goroutine 向同一目标(如 os.Stdout)写入时,保证写操作的原子性。

func NewLockedWriter

func NewLockedWriter(mu *sync.Mutex, w io.Writer) *LockedWriter

NewLockedWriter 创建一个并发安全的 Writer 包装器。

func (*LockedWriter) Write

func (lw *LockedWriter) Write(p []byte) (n int, err error)

type LoginMode

type LoginMode string

LoginMode preserves the distinction between omission and an explicit false.

const (
	LoginInherit  LoginMode = "inherit"
	LoginEnabled  LoginMode = "enabled"
	LoginDisabled LoginMode = "disabled"
)

type MuxClient added in v0.16.0

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

MuxClient manages communication with an OpenSSH multiplexing master process.

func DialMuxClient added in v0.16.0

func DialMuxClient(ctx context.Context, socketPath string, opts ...MuxClientOption) (*MuxClient, error)

DialMuxClient connects to the control socket and exchanges MUX_MSG_HELLO. The endpoint must belong to the effective local user (or root); a socket planted by another user in a shared directory is rejected before any request is sent.

func (*MuxClient) AliveCheck added in v0.16.0

func (m *MuxClient) AliveCheck(ctx context.Context) (uint32, error)

AliveCheck queries the master process alive status and returns the server PID.

func (*MuxClient) Close added in v0.16.0

func (m *MuxClient) Close() error

Close closes the underlying socket connection.

func (*MuxClient) CloseForward added in v0.16.0

func (m *MuxClient) CloseForward(ctx context.Context, req ForwardRequest) error

CloseForward cancels an active port forwarding on the master.

func (*MuxClient) Extension added in v0.16.0

func (m *MuxClient) Extension(name string) (string, bool)

Extension returns the value of an extension advertised by the master in MUX_MSG_HELLO.

func (*MuxClient) HasExtension added in v0.16.0

func (m *MuxClient) HasExtension(name string) bool

HasExtension returns true if the master server advertised the specified extension.

func (*MuxClient) OpenForward added in v0.16.0

func (m *MuxClient) OpenForward(ctx context.Context, req ForwardRequest) (uint32, error)

OpenForward requests port forwarding on the master. Returns dynamically allocated remote port if requested.

func (*MuxClient) Proxy added in v0.16.0

func (m *MuxClient) Proxy(ctx context.Context, target TargetContext) (*cryptoSSH.Client, *muxProxySSHConn, error)

Proxy switches the multiplexed connection into SSH transport proxy mode, returning an authenticated *cryptoSSH.Client wrapping muxProxySSHConn.

func (*MuxClient) RequestInfo added in v0.16.0

func (m *MuxClient) RequestInfo(ctx context.Context, name string) (string, error)

RequestInfo sends a MUX_C_EXT_INFO query to the master process ("connection" or "channels").

func (*MuxClient) StopListening added in v0.16.0

func (m *MuxClient) StopListening(ctx context.Context) error

StopListening requests the master to unlink the control socket and stop accepting new clients.

func (*MuxClient) Terminate added in v0.16.0

func (m *MuxClient) Terminate(ctx context.Context) error

Terminate requests the master process to terminate and disconnect the session.

type MuxClientOption added in v0.16.0

type MuxClientOption func(*muxClientOptions)

MuxClientOption configures a control-socket client connection.

func WithExpectedPeerUID added in v0.16.0

func WithExpectedPeerUID(uid uint32) MuxClientOption

WithExpectedPeerUID overrides the local user identity that the master endpoint must run as. Zero means "expect root" on platforms that expose peer credentials; it never disables the check, because a client running as root would otherwise accept a socket planted by any other local user. Platforms without peer credentials already treat the check as a no-op.

func WithMuxConnectionProvider added in v0.16.0

func WithMuxConnectionProvider(provider ConnectionProvider) MuxClientOption

WithMuxConnectionProvider configures the connection provider used by a control-proxy client to inspect node configuration without persisting edits.

func WithMuxPasswordPromptPattern added in v0.16.0

func WithMuxPasswordPromptPattern(pattern string) MuxClientOption

WithMuxPasswordPromptPattern configures the fallback password prompt regex used by a control-proxy client when node configuration does not specify one.

func WithMuxSecretPrompter added in v0.16.0

func WithMuxSecretPrompter(prompter SecretPrompter) MuxClientOption

WithMuxSecretPrompter configures the interactive secret prompter used by a control-proxy client when privilege elevation requires user input.

func WithMuxSecretResolver added in v0.16.0

func WithMuxSecretResolver(resolver SecretResolver) MuxClientOption

WithMuxSecretResolver configures the secret resolver used by a control-proxy client for privilege elevation over the multiplexed connection.

type MuxExtension added in v0.16.0

type MuxExtension struct {
	Name  string
	Value string
}

MuxExtension represents an extension name/value pair in MUX_MSG_HELLO.

func DecodeMuxHello added in v0.16.0

func DecodeMuxHello(payload []byte) (version uint32, extensions []MuxExtension, err error)

type MuxFwdRequest added in v0.16.0

type MuxFwdRequest struct {
	RequestID   uint32
	FwdType     uint32
	ListenHost  string
	ListenPort  uint32
	ConnectHost string
	ConnectPort uint32
}

MuxFwdRequest represents port forwarding parameters for OPEN_FWD and CLOSE_FWD.

func DecodeMuxFwdRequest added in v0.16.0

func DecodeMuxFwdRequest(payload []byte) (req MuxFwdRequest, err error)

type MuxMasterOptions added in v0.16.0

type MuxMasterOptions struct {
	Path        string
	Target      TargetContext
	Environment Environment
	RootConn    net.Conn
	// InitialActiveSessions is the number of sessions the caller already holds
	// on the new master. A connector passes 1 for its own transport: the master
	// exists to serve it, so an idle timer must not tear it down while the
	// caller keeps using it.
	InitialActiveSessions int32
	// ConfirmSession authorizes proxy sessions, passenger sessions, and
	// forwarding requests on an ask/autoask master. Nil rejects them.
	ConfirmSession func(action string) bool
}

MuxMasterOptions carries the master configuration a Connector applies for one resolved control path.

type MuxNewSessionRequest added in v0.16.0

type MuxNewSessionRequest struct {
	RequestID  uint32
	Reserved   string
	WantTTY    bool
	WantX11    bool
	WantAgent  bool
	Subsystem  bool
	EscapeChar uint32
	TermType   string
	Command    string
	Env        []string
}

MuxNewSessionRequest represents passenger session creation parameters.

func DecodeMuxNewSession added in v0.16.0

func DecodeMuxNewSession(payload []byte) (req MuxNewSessionRequest, err error)

type MuxNewStdioFwdRequest added in v0.16.0

type MuxNewStdioFwdRequest struct {
	RequestID   uint32
	Reserved    string
	ConnectHost string
	ConnectPort uint32
}

MuxNewStdioFwdRequest represents stdio forwarding parameters.

func DecodeMuxNewStdioFwd added in v0.16.0

func DecodeMuxNewStdioFwd(payload []byte) (req MuxNewStdioFwdRequest, err error)

type MuxServer added in v0.16.0

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

MuxServer implements the OpenSSH PROTOCOL.mux v4 server engine.

func GetActiveMuxServer added in v0.16.0

func GetActiveMuxServer(controlPath string) *MuxServer

GetActiveMuxServer returns the active MuxServer listening on the given control path, if any.

func NewMuxServer added in v0.16.0

func NewMuxServer(opts MuxServerOptions) (*MuxServer, error)

NewMuxServer creates and binds a new OpenSSH multiplex master server.

func StartMuxServer added in v0.16.0

func StartMuxServer(ctx context.Context, sshClient *cryptoSSH.Client, opts MuxMasterOptions) (*MuxServer, error)

StartMuxServer starts the master for opts.Path and returns it. The caller owns the returned server and must shut it down; nothing else releases the control socket or the SSH transport it references.

func (*MuxServer) ActiveSessions added in v0.16.0

func (s *MuxServer) ActiveSessions() int32

ActiveSessions returns the current number of active multiplex sessions.

func (*MuxServer) AddForegroundSession added in v0.16.0

func (s *MuxServer) AddForegroundSession() bool

AddForegroundSession adds an active in-process foreground session to prevent idle timeout.

func (*MuxServer) CancelHandoff added in v0.16.0

func (s *MuxServer) CancelHandoff()

CancelHandoff releases a reservation made by PrepareHandoff when a multi-hop handoff could not reserve every master in the chain.

func (*MuxServer) ControlPath added in v0.16.0

func (s *MuxServer) ControlPath() string

ControlPath returns the active control socket path.

func (*MuxServer) PersistEnabled added in v0.16.0

func (s *MuxServer) PersistEnabled() bool

PersistEnabled reports whether this master survives the end of the foreground session (`ControlPersist` other than "no").

func (*MuxServer) PersistIndefinite added in v0.16.0

func (s *MuxServer) PersistIndefinite() bool

PersistIndefinite reports whether the master keeps running until an explicit stop (-O exit/stop) instead of an idle timeout.

func (*MuxServer) PrepareHandoff added in v0.16.0

func (s *MuxServer) PrepareHandoff() bool

PrepareHandoff reserves the master for a ControlPersist handoff. It succeeds only when no other session or forward depends on this process: shutting the master down would otherwise cut those users off. On success the server is marked as shutting down so no new session or forward is admitted before the caller releases it.

func (*MuxServer) ReleaseForegroundOnStop added in v0.16.0

func (s *MuxServer) ReleaseForegroundOnStop()

ReleaseForegroundOnStop marks the master's initial foreground session reference (held by a -N process) to be dropped when -O stop arrives, so the master retires once any remaining client sessions drain.

func (*MuxServer) RemoveForegroundSession added in v0.16.0

func (s *MuxServer) RemoveForegroundSession()

RemoveForegroundSession removes an in-process foreground session and arms the idle timer if sessions reach 0.

func (*MuxServer) Serve added in v0.16.0

func (s *MuxServer) Serve() error

Serve enters the client connection accept loop.

func (*MuxServer) Shutdown added in v0.16.0

func (s *MuxServer) Shutdown() error

Shutdown gracefully closes the server, listeners, active forwards, and SSH connections.

func (*MuxServer) StoppedListening added in v0.16.0

func (s *MuxServer) StoppedListening() bool

StoppedListening reports whether -O stop has unlinked the control socket.

func (*MuxServer) Target added in v0.16.0

func (s *MuxServer) Target() TargetContext

Target returns the resolved connection target metadata for this master.

func (*MuxServer) Wait added in v0.16.0

func (s *MuxServer) Wait() <-chan struct{}

Wait returns a channel that is closed when the server shuts down.

func (*MuxServer) WaitForDrain added in v0.16.0

func (s *MuxServer) WaitForDrain(ctx context.Context, maxSessions int32) error

WaitForDrain blocks until activeSessions <= maxSessions and no active forwards remain on the master, or until the master stops listening, shuts down, or ctx is canceled.

type MuxServerOptions added in v0.16.0

type MuxServerOptions struct {
	ControlPath       string
	ExpectedUID       uint32
	CheckPeerUID      bool
	PersistEnabled    bool
	PersistDuration   time.Duration
	PersistIndefinite bool
	// ConfirmSession authorizes a proxy session, passenger session, or forwarding
	// request on an ask/autoask master. Nil rejects every such request.
	ConfirmSession        func(action string) bool
	AskConfirmation       bool
	SSHClient             *cryptoSSH.Client
	RootConn              net.Conn      // Optional underlying conn to close on Shutdown
	InitialActiveSessions int32         // Initial active session count (e.g. 1 for foreground master)
	Target                TargetContext // Optional target identity advertised via target@xops hello extension
}

MuxServerOptions configures the multiplex master server.

type Option

type Option func(*Connector)

Option 用于配置 Connector

func WithConnectionProvider

func WithConnectionProvider(provider ConnectionProvider) Option

WithConnectionProvider 配置连接配置提供者

func WithControlProvider added in v0.16.0

func WithControlProvider(provider ControlProvider) Option

WithControlProvider configures the ControlProvider for multiplexing.

func WithCredentialRecorder

func WithCredentialRecorder(recorder CredentialRecorder) Option

WithCredentialRecorder 配置凭据写回记录器(传 nil 时回退到默认 nop recorder)

func WithDiagnostics added in v0.15.0

func WithDiagnostics(observer logger.DiagnosticObserver) Option

WithDiagnostics installs an optional caller-owned protocol lifecycle observer.

func WithDialer

func WithDialer(dialer Dialer) Option

WithDialer 配置底层直连所使用的自定义 Dialer

func WithEnvironment

func WithEnvironment(environment Environment) Option

func WithHandshakeTimeout

func WithHandshakeTimeout(timeout time.Duration) Option

WithHandshakeTimeout 配置底层 SSH 握手网络超时时间

func WithHostKeyConfirmer

func WithHostKeyConfirmer(confirmer HostKeyConfirmer) Option

WithHostKeyConfirmer 单独配置主机密钥确认器

func WithHostKeyVerifier

func WithHostKeyVerifier(verifier HostKeyVerifier) Option

func WithInteractionHandler

func WithInteractionHandler(handler InteractionHandler) Option

WithInteractionHandler 配置交互处理器(同时设置 SecretPrompter 和 HostKeyConfirmer)

func WithInteractionTimeout

func WithInteractionTimeout(timeout time.Duration) Option

WithInteractionTimeout 配置单次交互提示超时时间

func WithKeySource

func WithKeySource(source KeySource) Option

func WithLogger

func WithLogger(l logger.DebugLogger) Option

WithLogger 配置 Connector 使用的 DebugLogger(必须支持并发调用)

func WithPasswordPromptPattern

func WithPasswordPromptPattern(pattern string) Option

WithPasswordPromptPattern 配置密码匹配正则

func WithSecretPrompter

func WithSecretPrompter(prompter SecretPrompter) Option

WithSecretPrompter 单独配置机密提示器

func WithSecretResolver

func WithSecretResolver(resolver SecretResolver) Option

WithSecretResolver 配置机密解析器(传 nil 时回退到默认 fail-closed resolver)

func WithSessionConfirmer added in v0.16.0

func WithSessionConfirmer(confirmer SessionConfirmer) Option

WithSessionConfirmer injects the confirmation source used by ask/autoask masters. Without one, every request against such a master is rejected.

type OptionClass added in v0.16.0

type OptionClass string

OptionClass categorizes OpenSSH options by security and functional domain.

const (
	OptionClassMux       OptionClass = "mux"
	OptionClassTransport OptionClass = "transport"
	OptionClassAuth      OptionClass = "auth"
	OptionClassTrust     OptionClass = "trust"
)

type OptionSpec added in v0.16.0

type OptionSpec struct {
	CanonicalKey string      // Persistent snake_case key (e.g. "control_master")
	OpenSSHName  string      // Canonical OpenSSH name (e.g. "ControlMaster")
	Class        OptionClass // Functional/security category
	Aliases      []string    // Accepted aliases (e.g. "ChallengeResponseAuthentication")
	AllowList    bool        // Whether YAML sequence values are accepted and joined with ","
	Normalize    func(raw string) (string, error)
}

OptionSpec describes a supported OpenSSH client option in the registry.

func LookupOptionSpec added in v0.16.0

func LookupOptionSpec(key string) (OptionSpec, bool)

LookupOptionSpec resolves a key (in either snake_case or OpenSSH case-insensitive format) to its OptionSpec.

func RegisteredOptionSpecs added in v0.16.0

func RegisteredOptionSpecs() []OptionSpec

RegisteredOptionSpecs returns a copy of all registered OpenSSH option specs.

type Options added in v0.16.0

type Options struct {

	// ImplicitTier4 is true when multiplexing was resolved solely from ~/.ssh/config
	// without any CLI flag or xops node/global configuration.
	ImplicitTier4 bool `json:"-" yaml:"-"`
	// contains filtered or unexported fields
}

Options represents an extensible set of OpenSSH client options. On disk (YAML/JSON) it serializes using canonical snake_case keys, while accepting both snake_case and OpenSSH standard names on input.

func EffectiveOptions added in v0.16.0

func EffectiveOptions(layers ...*Options) (*Options, error)

EffectiveOptions resolves a hierarchy of Options from highest priority to lowest priority.

func MergeOptionLayers added in v0.16.0

func MergeOptionLayers(layers ...*Options) *Options

MergeOptionLayers merges a slice of Options from highest priority to lowest priority using first-match-wins per option key, without applying cross-field effective finalization.

func MustOptions added in v0.16.0

func MustOptions(kv ...string) *Options

MustOptions creates an Options instance from alternating key, value pairs and panics on error.

func NewOptions added in v0.16.0

func NewOptions(kv ...string) (*Options, error)

NewOptions creates an Options instance from alternating key, value pairs.

func OptionsFromControl added in v0.16.0

func OptionsFromControl(ctrl *ControlConfig) *Options

OptionsFromControl constructs an Options instance from a ControlConfig.

func ResolveOptions added in v0.16.0

func ResolveOptions(child, parent *Options) (*Options, error)

ResolveOptions merges a higher-priority child Options with a lower-priority parent Options. Every option is inherited orthogonally unless overridden by child. Special multiplexing rule: if the effective control_path is "none", multiplexing is disabled (control_master="no", control_persist="").

func (*Options) BatchMode added in v0.16.0

func (o *Options) BatchMode() bool

BatchMode reports whether BatchMode is set to "yes".

func (*Options) Ciphers added in v0.16.0

func (o *Options) Ciphers() string

Ciphers returns the raw Ciphers specification, or "" if unset.

func (*Options) Clone added in v0.16.0

func (o *Options) Clone() *Options

Clone returns a deep copy of Options.

func (*Options) ConnectTimeout added in v0.16.0

func (o *Options) ConnectTimeout() time.Duration

ConnectTimeout returns the configured ConnectTimeout duration, or 0 if unset/disabled.

func (*Options) ControlConfig added in v0.16.0

func (o *Options) ControlConfig() *ControlConfig

ControlConfig extracts the multiplexing ControlConfig view from o, or returns nil if no multiplexing options are present.

func (*Options) ControlMaster added in v0.16.0

func (o *Options) ControlMaster() ControlMasterMode

ControlMaster returns the configured ControlMasterMode, or "" if unset.

func (*Options) ControlPath added in v0.16.0

func (o *Options) ControlPath() string

ControlPath returns the configured ControlPath, or "" if unset.

func (*Options) ControlPersist added in v0.16.0

func (o *Options) ControlPersist() string

ControlPersist returns the configured ControlPersist, or "" if unset.

func (*Options) Delete added in v0.16.0

func (o *Options) Delete(key string)

Delete removes an option by key.

func (*Options) Equal added in v0.16.0

func (o *Options) Equal(other *Options) bool

Equal reports whether two Options contain identical key-value pairs.

func (*Options) FilterByClasses added in v0.16.0

func (o *Options) FilterByClasses(allowed ...OptionClass) *Options

FilterByClasses returns a new Options containing only keys matching the allowed OptionClasses. Returns nil if the filtered result is empty.

func (*Options) Get added in v0.16.0

func (o *Options) Get(key string) string

Get returns the normalized string value for key, or "" if unset.

func (*Options) Has added in v0.16.0

func (o *Options) Has(key string) bool

Has reports whether key is explicitly configured in o.

func (*Options) HostKeyAlgorithms added in v0.16.0

func (o *Options) HostKeyAlgorithms() string

HostKeyAlgorithms returns the raw HostKeyAlgorithms specification, or "" if unset.

func (*Options) IdentitiesOnly added in v0.16.0

func (o *Options) IdentitiesOnly() bool

IdentitiesOnly reports whether IdentitiesOnly is set to "yes".

func (*Options) IsEmpty added in v0.16.0

func (o *Options) IsEmpty() bool

IsEmpty reports whether no options are configured.

func (Options) IsZero added in v0.16.0

func (o Options) IsZero() bool

IsZero implements yaml.IsZeroer so empty non-nil Options are omitted with omitempty.

func (*Options) KbdInteractiveAuthentication added in v0.16.0

func (o *Options) KbdInteractiveAuthentication() (bool, bool)

KbdInteractiveAuthentication returns (enabled, true) if KbdInteractiveAuthentication is set, or (true, false) if unset.

func (*Options) KexAlgorithms added in v0.16.0

func (o *Options) KexAlgorithms() string

KexAlgorithms returns the raw KexAlgorithms specification, or "" if unset.

func (*Options) MACs added in v0.16.0

func (o *Options) MACs() string

MACs returns the raw MACs specification, or "" if unset.

func (*Options) Map added in v0.16.0

func (o *Options) Map() map[string]string

Map returns a defensive copy of the canonical snake_case key-value map.

func (Options) MarshalJSON added in v0.16.0

func (o Options) MarshalJSON() ([]byte, error)

MarshalJSON serializes Options as a JSON object with canonical snake_case keys in deterministic order.

func (Options) MarshalYAML added in v0.16.0

func (o Options) MarshalYAML() (any, error)

MarshalYAML serializes Options as a YAML mapping using canonical snake_case keys in registry order.

func (*Options) PasswordAuthentication added in v0.16.0

func (o *Options) PasswordAuthentication() (bool, bool)

PasswordAuthentication returns (enabled, true) if PasswordAuthentication is set, or (true, false) if unset.

func (*Options) PreferredAuthentications added in v0.16.0

func (o *Options) PreferredAuthentications() []string

PreferredAuthentications returns the configured list of preferred authentication methods, or nil if unset.

func (*Options) PubkeyAuthentication added in v0.16.0

func (o *Options) PubkeyAuthentication() (bool, bool)

PubkeyAuthentication returns (enabled, true) if PubkeyAuthentication is set, or (true, false) if unset.

func (*Options) ServerAliveCountMax added in v0.16.0

func (o *Options) ServerAliveCountMax() int

ServerAliveCountMax returns the configured ServerAliveCountMax (defaulting to 3 if unset).

func (*Options) ServerAliveInterval added in v0.16.0

func (o *Options) ServerAliveInterval() time.Duration

ServerAliveInterval returns the configured ServerAliveInterval, or 0 if unset/disabled.

func (*Options) Set added in v0.16.0

func (o *Options) Set(key, rawValue string) error

Set validates and sets an option by either snake_case or OpenSSH key name. Passing an empty value removes the option.

func (*Options) SetControlMaster added in v0.16.0

func (o *Options) SetControlMaster(m ControlMasterMode)

SetControlMaster sets the ControlMasterMode directly.

func (*Options) SetControlPath added in v0.16.0

func (o *Options) SetControlPath(path string)

SetControlPath sets the ControlPath directly.

func (*Options) SetControlPersist added in v0.16.0

func (o *Options) SetControlPersist(persist string)

SetControlPersist sets the ControlPersist directly.

func (*Options) StrictHostKeyChecking added in v0.16.0

func (o *Options) StrictHostKeyChecking() string

StrictHostKeyChecking returns the normalized StrictHostKeyChecking mode ("yes", "no", "ask", "accept-new"), or "" if unset.

func (*Options) StripClasses added in v0.16.0

func (o *Options) StripClasses(classes ...OptionClass)

StripClasses removes all options belonging to any of the specified OptionClasses in place.

func (*Options) TCPKeepAlive added in v0.16.0

func (o *Options) TCPKeepAlive() (bool, bool)

TCPKeepAlive returns (enabled, true) if TCPKeepAlive is explicitly set, or (false, false) if unset.

func (*Options) UnmarshalJSON added in v0.16.0

func (o *Options) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes a JSON object into Options, accepting both snake_case and OpenSSH option names.

func (*Options) UnmarshalYAML added in v0.16.0

func (o *Options) UnmarshalYAML(value *yaml.Node) error

UnmarshalYAML decodes a YAML mapping into Options, accepting both canonical snake_case and OpenSSH standard option names while rejecting unknown or duplicate options.

func (*Options) UserKnownHostsFile added in v0.16.0

func (o *Options) UserKnownHostsFile() string

UserKnownHostsFile returns the configured UserKnownHostsFile path, or "" if unset.

func (*Options) Validate added in v0.16.0

func (o *Options) Validate() error

Validate validates all individual option values and standalone cross-field rules.

func (*Options) ValidateEffective added in v0.16.0

func (o *Options) ValidateEffective() error

ValidateEffective validates cross-field constraints on a resolved effective Options set.

type OutputError added in v0.15.0

type OutputError struct {
	Target io.Writer // Borrowed sink identity; never closed by the error owner.
	Err    error
}

OutputError marks a failed output write. Hosts must not report it back to the same possibly blocked sink. Unwrap preserves cancellation and I/O causes.

func (*OutputError) Error added in v0.15.0

func (e *OutputError) Error() string

func (*OutputError) TargetsFile added in v0.15.0

func (e *OutputError) TargetsFile(file *os.File) bool

TargetsFile matches the original file even when serialized by LockedWriter. It compares file objects, without probing handles or consulting global stdio.

func (*OutputError) Unwrap added in v0.15.0

func (e *OutputError) Unwrap() error

type OutputMode

type OutputMode int

OutputMode 定义远程命令输出的收集策略。 注意:零值 OutputModeString 保持全量内存收集,这是为了向后兼容原有行为。 对于可能产生巨大输出的命令,调用方应显式指定其他模式以避免 OOM。

const (
	OutputModeString     OutputMode = iota // 默认,全量收集到内存(向后兼容)
	OutputModeRingBuffer                   // 环形缓冲,仅保留最后 N 字节
	OutputModeStream                       // 流式即时输出,不在内存中累积
	OutputModeFile                         // 直接写入文件,绕过内存
)

type PasswordAuth

type PasswordAuth struct {
	Password string
}

PasswordAuth 实现密码认证

func (*PasswordAuth) GetMethod

func (p *PasswordAuth) GetMethod() (ssh.AuthMethod, error)

type PlanConnection

type PlanConnection struct {
	Client *Client
	// contains filtered or unexported fields
}

PlanConnection leases one connection generation. Close releases this lease; it does not close transports still leased by another operation. Client is borrowed from the lease and must not outlive it.

func (*PlanConnection) Close

func (c *PlanConnection) Close() error

type PooledClient

type PooledClient struct {
	SSHClient *ssh.Client
	RootConn  net.Conn
	// contains filtered or unexported fields
}

PooledClient retains the outermost transport, including for ProxyJump clients. Interrupting it also terminates other clients sharing that transport.

type PrivilegeMaterial

type PrivilegeMaterial struct {
	Password []byte
	// contains filtered or unexported fields
}

PrivilegeMaterial 包含单次提权 (sudo/su) 所需的敏感机密材料。

func (*PrivilegeMaterial) Zero

func (p *PrivilegeMaterial) Zero()

Zero 清零敏感字节切片并清空引用。

type ProbeResult

type ProbeResult struct {
	DetectedDialect        LaunchDialect   `json:"detectedDialect" yaml:"detected_dialect"`
	AvailableInterpreters  []Interpreter   `json:"availableInterpreters" yaml:"available_interpreters"`
	RecommendedInterpreter Interpreter     `json:"recommendedInterpreter" yaml:"recommended_interpreter"`
	SuggestedConfig        ExecutionConfig `json:"suggestedConfig" yaml:"suggested_config"`
	RemoteOS               string          `json:"remoteOS" yaml:"remote_os"`
	RemoteShellPath        string          `json:"remoteShellPath" yaml:"remote_shell_path"`
	ServerVersion          string          `json:"serverVersion" yaml:"server_version"`
	Duration               time.Duration   `json:"duration" yaml:"duration"`
	ProbedAt               time.Time       `json:"probedAt" yaml:"probed_at"`
}

ProbeResult is a diagnostic snapshot. SuggestedConfig is safe to persist only when ProbeExecutionConfig returns no error. Unknown results preserve server passthrough semantics. Banner and shell path are metadata, never commands.

type ProxyCycleError

type ProxyCycleError struct {
	NodeID string
	Path   []string
}

ProxyCycleError 封装代理跳板环路错误

func (*ProxyCycleError) Error

func (e *ProxyCycleError) Error() string

func (*ProxyCycleError) Is

func (e *ProxyCycleError) Is(target error) bool

Is 支持与 auth.ErrProxyCycle 及 ErrProxyCycle 匹配

type RunConfig

type RunConfig struct {
	Interpreter   Interpreter
	LaunchDialect LaunchDialect
	LoginShell    bool
	OutMode       OutputMode
	RingMaxBytes  int
	StreamPrefix  string
	StreamWriter  io.Writer
	OutFile       *os.File
	ScriptArgs    []string
	// contains filtered or unexported fields
}

func DefaultRunConfig

func DefaultRunConfig() *RunConfig

type RunOption

type RunOption func(*RunConfig)

func WithInterpreter

func WithInterpreter(interp Interpreter) RunOption

func WithLaunchDialect

func WithLaunchDialect(dialect LaunchDialect) RunOption

WithLaunchDialect carries the frozen outer shell through legacy run adapters.

func WithLoginShell

func WithLoginShell(login bool) RunOption

func WithOutFile

func WithOutFile(file *os.File) RunOption

func WithOutputMode

func WithOutputMode(mode OutputMode) RunOption

func WithRingBuffer

func WithRingBuffer(maxBytes int) RunOption

func WithScriptArgs added in v0.16.0

func WithScriptArgs(args ...string) RunOption

WithScriptArgs specifies the positional arguments to pass to the script when executing via RunScript.

func WithStream

func WithStream(writer io.Writer, prefix string) RunOption

type SFTPStream added in v0.16.0

type SFTPStream struct {
	Reader      io.Reader
	WriteCloser io.WriteCloser
	Stderr      io.Reader
	// contains filtered or unexported fields
}

SFTPStream represents an active binary stream connected to a remote SFTP subsystem or elevated sftp-server binary.

func (*SFTPStream) Close added in v0.16.0

func (s *SFTPStream) Close() error

func (*SFTPStream) Read added in v0.16.0

func (s *SFTPStream) Read(p []byte) (int, error)

func (*SFTPStream) Write added in v0.16.0

func (s *SFTPStream) Write(p []byte) (int, error)

type SSHProxyDialer

type SSHProxyDialer struct {
	Client *ssh.Client
	// RootConn is the outermost transport, shared by every hop in the chain.
	// Retaining it lets cancellation abort nested reads without a peer response.
	RootConn net.Conn
}

SSHProxyDialer 实现了 Dialer 接口,通过 SSH 隧道转发流量

func (*SSHProxyDialer) Dial

func (s *SSHProxyDialer) Dial(network, addr string) (net.Conn, error)

func (*SSHProxyDialer) DialContext

func (s *SSHProxyDialer) DialContext(ctx context.Context, network, addr string) (net.Conn, error)

type SecretKind

type SecretKind uint8

SecretKind 标识需要交互输入的机密类型

const (
	SecretKindUnknown SecretKind = iota
	SecretKindLoginPassword
	SecretKindPrivateKeyPassphrase
	SecretKindSuPassword
	SecretKindSudoPassword
	SecretKindOTP
	SecretKindKeyboardInteractive
)

type SecretPrompter

type SecretPrompter interface {
	PromptSecret(ctx context.Context, request SecretRequest) (string, error)
}

SecretPrompter 负责提示用户输入敏感凭据(如密码、私钥密码短语等)

type SecretRequest

type SecretRequest struct {
	Kind         SecretKind
	NodeID       string
	User         string
	Host         string
	Port         int
	KeyPath      string
	VersionToken string
	Instruction  string
	Prompt       string
	Echo         bool
	Attempt      int
	NumPrompts   int
}

SecretRequest 描述向解析器或用户请求机密的上下文信息(严禁携带已有密码)

type SecretResolver

type SecretResolver interface {
	// ResolveSecret 根据机密请求解析并返回机密字节
	ResolveSecret(ctx context.Context, req SecretRequest) ([]byte, error)
}

SecretResolver 解析指定节点认证或提权所需机密。

type SessionConfirmer added in v0.16.0

type SessionConfirmer interface {
	ConfirmSession(ctx context.Context, action string) (bool, error)
}

SessionConfirmer authorizes connection-sharing requests on an ask/autoask master. Implementations must honor ctx, return promptly, and fail closed.

type ShebangInfo

type ShebangInfo struct {
	HasShebang  bool
	HasBOM      bool
	Supported   bool
	Interpreter Interpreter
	Dialect     LaunchDialect
	RawLine     string
}

ShebangInfo describes the result of parsing a script's shebang line.

func ParseShebang

func ParseShebang(data []byte) ShebangInfo

ParseShebang inspects the first line of script data and validates it against the supported shebang allowlist (sh, bash, zsh and fish paths or /usr/bin/env sh|bash|zsh|fish without additional arguments). Trailing CR is ignored for metadata parsing.

type SudoMode

type SudoMode string

SudoMode 定义了 SSH 连接执行命令时的提权方式

const (
	SudoModeRoot   SudoMode = "root"
	SudoModeSudo   SudoMode = "sudo"
	SudoModeSudoer SudoMode = "sudoer"
	SudoModeSu     SudoMode = "su"
	SudoModeNone   SudoMode = "none"
	SudoModeAuto   SudoMode = "auto"
)

type TargetContext added in v0.16.0

type TargetContext struct {
	Host         string         // Target host or IP address (%h)
	Port         int            // Target port (%p), defaults to 22 if <= 0
	User         string         // Target remote username (%r)
	OriginalHost string         // Original command-line host or alias (%n), defaults to Host if empty
	JumpHost     string         // ProxyJump host if any (%j), used in %C connection hash calculation
	KeyPath      string         // Effective private key path for this target, if any
	Control      *ControlConfig // Multiplexing control configuration
}

TargetContext supplies destination, port, user, and routing context for ControlPath token expansion.

func (TargetContext) CanonicalTargetIdentity added in v0.16.0

func (t TargetContext) CanonicalTargetIdentity() string

CanonicalTargetIdentity returns a normalized "user@host:port[via jump]" descriptor used to verify that a static ControlPath is not accidentally reused across different destination hosts, ports, users, or jump hosts. Returns "" if Host is empty.

func (TargetContext) MatchesMasterTarget added in v0.16.0

func (t TargetContext) MatchesMasterTarget(masterIdentity string) bool

MatchesMasterTarget reports whether the requested target is compatible with the master target identity advertised via the "target@xops" hello extension.

Jump to

Keyboard shortcuts

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