Documentation
¶
Index ¶
- Constants
- Variables
- func BindOutput(ctx context.Context, target io.Writer) (writer io.Writer, closeFn func() error, cancelable bool, err error)
- func ComputeConnectionHash(localHost, host, portStr, user, jumpHost string) string
- func ConnectionKey(plan ConnectionPlan) (string, error)
- func CshQuote(value string) string
- func DecodeMuxAlive(payload []byte) (requestID uint32, pid uint32, err error)
- func DecodeMuxClientRequestID(payload []byte) (clientRequestID uint32, err error)
- func DecodeMuxError(payload []byte) (clientRequestID uint32, reason string, err error)
- func DecodeMuxExitMessage(payload []byte) (sessionID uint32, exitValue uint32, err error)
- func DecodeMuxExtInfo(payload []byte) (requestID uint32, name string, err error)
- func DecodeMuxExtInfoResponse(payload []byte) (clientRequestID uint32, status uint32, msg string, err error)
- func DecodeMuxRemotePort(payload []byte) (clientRequestID uint32, allocatedPort uint32, err error)
- func DecodeMuxRequestID(payload []byte) (requestID uint32, err error)
- func DecodeMuxSessionOpened(payload []byte) (clientRequestID uint32, sessionID uint32, err error)
- func DecodeMuxTTYAllocFail(payload []byte) (sessionID uint32, err error)
- func DialControlProxy(ctx context.Context, socketPath string, target TargetContext, ...) (*cryptoSSH.Client, *muxProxySSHConn, error)
- func DialMuxProxyStream(ctx context.Context, socketPath string, opts ...MuxClientOption) (net.Conn, error)
- func EncodeMuxAlive(requestID uint32, pid uint32) []byte
- func EncodeMuxClientRequestID(clientRequestID uint32) []byte
- func EncodeMuxError(clientRequestID uint32, reason string) []byte
- func EncodeMuxExitMessage(sessionID uint32, exitValue uint32) []byte
- func EncodeMuxExtInfo(requestID uint32, name string) []byte
- func EncodeMuxExtInfoResponse(clientRequestID uint32, status uint32, msg string) []byte
- func EncodeMuxFwdRequest(req MuxFwdRequest) []byte
- func EncodeMuxHello(version uint32, extensions []MuxExtension) []byte
- func EncodeMuxNewSession(req MuxNewSessionRequest) []byte
- func EncodeMuxNewStdioFwd(req MuxNewStdioFwdRequest) []byte
- func EncodeMuxRemotePort(clientRequestID uint32, allocatedPort uint32) []byte
- func EncodeMuxRequestID(requestID uint32) []byte
- func EncodeMuxSessionOpened(clientRequestID uint32, sessionID uint32) []byte
- func EncodeMuxTTYAllocFail(sessionID uint32) []byte
- func ExpandControlPath(rawPath string, env Environment, target TargetContext) (string, error)
- func FilterSupportedListValue(canonicalKey, raw string) string
- func FishQuote(value string) string
- func FormatScriptPayload(interp Interpreter, login bool, dialect LaunchDialect, args []string) (string, error)
- func FormatTargetIdentity(identity string) string
- func FormatWorkingDirCommand(cwd, command string, execution *ExecutionConfig) (string, error)
- func MaxControlPathLength() int
- func NeedsExecutionProbe(execution *ExecutionConfig) bool
- func NormalizeWindowsSFTPWorkingDir(cwd string) string
- func ParseControlPersist(val string) (enabled bool, indefinite bool, timeout time.Duration, err error)
- func ParseStrictHostKeyChecking(raw string) (string, error)
- func ReadMuxPacket(r io.Reader) (packetType uint32, payload []byte, err error)
- func ResolveAlgorithmList(spec string, defaults []string) ([]string, error)
- func StartKeepAlive(ctx context.Context, client *ssh.Client, interval, timeout time.Duration, ...) <-chan struct{}
- func StaticRespond(s string) func() (string, error)
- func ValidateControlPath(expandedPath string) error
- func ValidateControlPathSyntax(rawPath string) error
- func WithConsoleOutputRelay(ctx context.Context, relay ConsoleOutputRelay) (context.Context, func() error)
- func WriteMuxPacket(w io.Writer, packetType uint32, payload []byte) error
- type AuthMaterial
- type AuthMethod
- type AuthenticatedConnectionConfirmer
- type AutoAuthOptions
- type Client
- func (c *Client) AuthMaterial() *AuthMaterial
- func (c *Client) CachedExecutionProbe() (*ProbeResult, bool)
- func (c *Client) Close() error
- func (c *Client) Config() *ClientConfig
- func (c *Client) ConnectionConfig() ConnectionConfig
- func (c *Client) ExecuteCommand(ctx context.Context, plan CommandPlan) (result CommandResult)
- func (c *Client) Execution() *ExecutionConfig
- func (c *Client) Interrupt() error
- func (c *Client) LocalForward(ctx context.Context, localAddr, remoteAddr string, opts ...ForwardOption) (*Forward, error)
- func (c *Client) OpenSFTPStream(ctx context.Context, sudo bool) (*SFTPStream, error)
- func (c *Client) ProbeControlledExecution(ctx context.Context, execution *ExecutionConfig) (*ExecutionConfig, error)
- func (c *Client) ProbeExecutionConfig(ctx context.Context) (*ProbeResult, error)
- func (c *Client) RemoteForward(ctx context.Context, remoteAddr, localAddr string, opts ...ForwardOption) (*Forward, error)
- func (c *Client) ResolvePrivilegeExecution(ctx context.Context) (*ExecutionConfig, error)
- func (c *Client) ResolveWorkingDirectoryExecution(ctx context.Context, execution *ExecutionConfig) (*ExecutionConfig, error)
- func (c *Client) Run(ctx context.Context, cmd string, opts ...RunOption) (string, error)
- func (c *Client) RunCommandPlanWithIO(ctx context.Context, plan CommandPlan, stdin io.Reader, ...) (retErr error)
- func (c *Client) RunCommandWithIO(ctx context.Context, command string, sudo bool, stdin io.Reader, ...) (retErr error)
- func (c *Client) RunCommandWithInput(ctx context.Context, command string, input []byte, stdout, stderr io.Writer) error
- func (c *Client) RunInteractive(ctx context.Context, cmd string) error
- func (c *Client) RunInteractiveCmd(ctx context.Context, cmd string) error
- func (c *Client) RunInteractiveCmdWithIO(ctx context.Context, cmd string, streams InteractiveIO) error
- func (c *Client) RunInteractivePlan(ctx context.Context, plan CommandPlan) error
- func (c *Client) RunInteractivePlanWithIO(ctx context.Context, plan CommandPlan, streams InteractiveIO) (retErr error)
- func (c *Client) RunInteractiveWithOptions(ctx context.Context, command string, opts ...RunOption) error
- func (c *Client) RunInteractiveWithSudo(ctx context.Context, command string) error
- func (c *Client) RunInteractiveWithSudoExecution(ctx context.Context, command string, execution *ExecutionConfig) error
- func (c *Client) RunInteractiveWithSudoExecutionIO(ctx context.Context, command string, execution *ExecutionConfig, ...) (retErr error)
- func (c *Client) RunInteractiveWithSudoIO(ctx context.Context, command string, streams InteractiveIO) (retErr error)
- func (c *Client) RunScript(ctx context.Context, scriptContent string, opts ...RunOption) (output string, retErr error)
- func (c *Client) RunScriptWithExecution(ctx context.Context, content string, execution *ExecutionConfig, ...) (string, error)
- func (c *Client) RunScriptWithSudo(ctx context.Context, scriptContent string, opts ...RunOption) (string, error)
- func (c *Client) RunScriptWithSudoExecution(ctx context.Context, content string, execution *ExecutionConfig, ...) (string, error)
- func (c *Client) RunShellWithIO(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer) (retErr error)
- func (c *Client) RunShellWithoutPTY(ctx context.Context, stdin io.Reader, stdout, stderr io.Writer) (retErr error)
- func (c *Client) RunStream(ctx context.Context, cmd string) (io.ReadCloser, error)
- func (c *Client) RunWithSudo(ctx context.Context, command string, opts ...RunOption) (string, error)
- func (c *Client) RunWithSudoExecution(ctx context.Context, command string, execution *ExecutionConfig, ...) (string, error)
- func (c *Client) RunWithoutLogin(ctx context.Context, cmd string) (string, error)
- func (c *Client) SSHClient() *ssh.Client
- func (c *Client) Shell(ctx context.Context) error
- func (c *Client) ShellWithIO(ctx context.Context, streams InteractiveIO) error
- func (c *Client) ShellWithSudo(ctx context.Context) error
- func (c *Client) ShellWithSudoIO(ctx context.Context, streams InteractiveIO) (retErr error)
- func (c *Client) Socks5Forward(ctx context.Context, listenAddr string, opts ...ForwardOption) (*Forward, error)
- func (c *Client) Wait(ctx context.Context) error
- type ClientConfig
- type CommandExitError
- type CommandOptions
- type CommandPlan
- type CommandResult
- type ConfigStore
- type ConnectionConfig
- type ConnectionConfirmer
- type ConnectionError
- type ConnectionPlan
- type ConnectionProvider
- type Connector
- func (c *Connector) AcquireMaster(server *MuxServer) bool
- func (c *Connector) CloseAll() error
- func (c *Connector) Connect(ctx context.Context, nodeName string) (*Client, error)
- func (c *Connector) ConnectPlan(ctx context.Context, plan ConnectionPlan) (*PlanConnection, error)
- func (c *Connector) EnableKeepAlive(ctx context.Context, interval, timeout time.Duration)
- func (c *Connector) HasMasterSession(server *MuxServer) bool
- func (c *Connector) Masters() []*MuxServer
- func (c *Connector) OwnsMaster(server *MuxServer) bool
- func (c *Connector) ReleaseMaster(server *MuxServer) bool
- func (c *Connector) RetirePlan(plan ConnectionPlan) error
- type ConsoleOutputRelay
- type ContextWriter
- type ControlConfig
- type ControlMasterMode
- type ControlProvider
- type CredentialFailureReporter
- type CredentialRecorder
- type Dialer
- type Environment
- type ExecutionConfig
- func DeriveWorkingDirectoryExecution(execution *ExecutionConfig) (*ExecutionConfig, bool)
- func EffectiveExecution(layers ...*ExecutionConfig) (*ExecutionConfig, error)
- func ResolveExecution(child, parent *ExecutionConfig) (*ExecutionConfig, error)
- func ResolveScriptExecution(step, settings, node, global *ExecutionConfig, scriptBytes []byte) (*ExecutionConfig, error)
- func (e *ExecutionConfig) Clone() *ExecutionConfig
- func (e *ExecutionConfig) CommandOptions() CommandOptions
- func (e *ExecutionConfig) EffectiveInterpreter() Interpreter
- func (e *ExecutionConfig) LoginMode() LoginMode
- func (e ExecutionConfig) MarshalJSON() ([]byte, error)
- func (e *ExecutionConfig) SudoRunOptions(command string) ([]RunOption, error)
- func (e *ExecutionConfig) UnmarshalJSON(data []byte) error
- func (e *ExecutionConfig) UnmarshalYAML(value *yaml.Node) error
- func (e *ExecutionConfig) Validate() error
- type ExecutionOutcome
- type Expect
- func (e *Expect) CleanOutput(promptPattern *regexp.Regexp) string
- func (e *Expect) Output() string
- func (e *Expect) SetAccumulate(acc bool)
- func (e *Expect) SetTarget(target io.Writer)
- func (e *Expect) Stop()
- func (e *Expect) Wait(ctx context.Context, timeout time.Duration) error
- func (e *Expect) Write(p []byte) (n int, err error)
- type ExpectOption
- type ExpectRule
- type Forward
- type ForwardOption
- type ForwardRequest
- type ForwardType
- type HandshakeError
- type HostKeyAlgorithmSource
- type HostKeyConfirmation
- type HostKeyConfirmer
- type HostKeyRequest
- type HostKeyVerifier
- type InputBridge
- type InputCopy
- type InteractionHandler
- type InteractiveIO
- type Interpreter
- type KeyAuth
- type KeyLease
- type KeyRequest
- type KeySource
- type KeyboardInteractiveOptions
- type LaunchDialect
- type LockedWriter
- type LoginMode
- type MuxClient
- func (m *MuxClient) AliveCheck(ctx context.Context) (uint32, error)
- func (m *MuxClient) Close() error
- func (m *MuxClient) CloseForward(ctx context.Context, req ForwardRequest) error
- func (m *MuxClient) Extension(name string) (string, bool)
- func (m *MuxClient) HasExtension(name string) bool
- func (m *MuxClient) OpenForward(ctx context.Context, req ForwardRequest) (uint32, error)
- func (m *MuxClient) Proxy(ctx context.Context, target TargetContext) (*cryptoSSH.Client, *muxProxySSHConn, error)
- func (m *MuxClient) RequestInfo(ctx context.Context, name string) (string, error)
- func (m *MuxClient) StopListening(ctx context.Context) error
- func (m *MuxClient) Terminate(ctx context.Context) error
- type MuxClientOption
- func WithExpectedPeerUID(uid uint32) MuxClientOption
- func WithMuxConnectionProvider(provider ConnectionProvider) MuxClientOption
- func WithMuxPasswordPromptPattern(pattern string) MuxClientOption
- func WithMuxSecretPrompter(prompter SecretPrompter) MuxClientOption
- func WithMuxSecretResolver(resolver SecretResolver) MuxClientOption
- type MuxExtension
- type MuxFwdRequest
- type MuxMasterOptions
- type MuxNewSessionRequest
- type MuxNewStdioFwdRequest
- type MuxServer
- func (s *MuxServer) ActiveSessions() int32
- func (s *MuxServer) AddForegroundSession() bool
- func (s *MuxServer) CancelHandoff()
- func (s *MuxServer) ControlPath() string
- func (s *MuxServer) PersistEnabled() bool
- func (s *MuxServer) PersistIndefinite() bool
- func (s *MuxServer) PrepareHandoff() bool
- func (s *MuxServer) ReleaseForegroundOnStop()
- func (s *MuxServer) RemoveForegroundSession()
- func (s *MuxServer) Serve() error
- func (s *MuxServer) Shutdown() error
- func (s *MuxServer) StoppedListening() bool
- func (s *MuxServer) Target() TargetContext
- func (s *MuxServer) Wait() <-chan struct{}
- func (s *MuxServer) WaitForDrain(ctx context.Context, maxSessions int32) error
- type MuxServerOptions
- type Option
- func WithConnectionProvider(provider ConnectionProvider) Option
- func WithControlProvider(provider ControlProvider) Option
- func WithCredentialRecorder(recorder CredentialRecorder) Option
- func WithDiagnostics(observer logger.DiagnosticObserver) Option
- func WithDialer(dialer Dialer) Option
- func WithEnvironment(environment Environment) Option
- func WithHandshakeTimeout(timeout time.Duration) Option
- func WithHostKeyConfirmer(confirmer HostKeyConfirmer) Option
- func WithHostKeyVerifier(verifier HostKeyVerifier) Option
- func WithInteractionHandler(handler InteractionHandler) Option
- func WithInteractionTimeout(timeout time.Duration) Option
- func WithKeySource(source KeySource) Option
- func WithLogger(l logger.DebugLogger) Option
- func WithPasswordPromptPattern(pattern string) Option
- func WithSecretPrompter(prompter SecretPrompter) Option
- func WithSecretResolver(resolver SecretResolver) Option
- func WithSessionConfirmer(confirmer SessionConfirmer) Option
- type OptionClass
- type OptionSpec
- type Options
- func EffectiveOptions(layers ...*Options) (*Options, error)
- func MergeOptionLayers(layers ...*Options) *Options
- func MustOptions(kv ...string) *Options
- func NewOptions(kv ...string) (*Options, error)
- func OptionsFromControl(ctrl *ControlConfig) *Options
- func ResolveOptions(child, parent *Options) (*Options, error)
- func (o *Options) BatchMode() bool
- func (o *Options) Ciphers() string
- func (o *Options) Clone() *Options
- func (o *Options) ConnectTimeout() time.Duration
- func (o *Options) ControlConfig() *ControlConfig
- func (o *Options) ControlMaster() ControlMasterMode
- func (o *Options) ControlPath() string
- func (o *Options) ControlPersist() string
- func (o *Options) Delete(key string)
- func (o *Options) Equal(other *Options) bool
- func (o *Options) FilterByClasses(allowed ...OptionClass) *Options
- func (o *Options) Get(key string) string
- func (o *Options) Has(key string) bool
- func (o *Options) HostKeyAlgorithms() string
- func (o *Options) IdentitiesOnly() bool
- func (o *Options) IsEmpty() bool
- func (o Options) IsZero() bool
- func (o *Options) KbdInteractiveAuthentication() (bool, bool)
- func (o *Options) KexAlgorithms() string
- func (o *Options) MACs() string
- func (o *Options) Map() map[string]string
- func (o Options) MarshalJSON() ([]byte, error)
- func (o Options) MarshalYAML() (any, error)
- func (o *Options) PasswordAuthentication() (bool, bool)
- func (o *Options) PreferredAuthentications() []string
- func (o *Options) PubkeyAuthentication() (bool, bool)
- func (o *Options) ServerAliveCountMax() int
- func (o *Options) ServerAliveInterval() time.Duration
- func (o *Options) Set(key, rawValue string) error
- func (o *Options) SetControlMaster(m ControlMasterMode)
- func (o *Options) SetControlPath(path string)
- func (o *Options) SetControlPersist(persist string)
- func (o *Options) StrictHostKeyChecking() string
- func (o *Options) StripClasses(classes ...OptionClass)
- func (o *Options) TCPKeepAlive() (bool, bool)
- func (o *Options) UnmarshalJSON(data []byte) error
- func (o *Options) UnmarshalYAML(value *yaml.Node) error
- func (o *Options) UserKnownHostsFile() string
- func (o *Options) Validate() error
- func (o *Options) ValidateEffective() error
- type OutputError
- type OutputMode
- type PasswordAuth
- type PlanConnection
- type PooledClient
- type PrivilegeMaterial
- type ProbeResult
- type ProxyCycleError
- type RunConfig
- type RunOption
- func WithInterpreter(interp Interpreter) RunOption
- func WithLaunchDialect(dialect LaunchDialect) RunOption
- func WithLoginShell(login bool) RunOption
- func WithOutFile(file *os.File) RunOption
- func WithOutputMode(mode OutputMode) RunOption
- func WithRingBuffer(maxBytes int) RunOption
- func WithScriptArgs(args ...string) RunOption
- func WithStream(writer io.Writer, prefix string) RunOption
- type SFTPStream
- type SSHProxyDialer
- type SecretKind
- type SecretPrompter
- type SecretRequest
- type SecretResolver
- type SessionConfirmer
- type ShebangInfo
- type SudoMode
- type TargetContext
Constants ¶
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 )
const ( DefaultKeepAliveInterval = 15 * time.Second DefaultKeepAliveTimeout = 10 * time.Second )
心跳默认参数:接收空闲 15s 后探测;等待回复期间连续 10s 无接收进展才超时。 网络拥塞下的有效接收进展会推迟探测或刷新等待时间,网络黑洞仍有确定的退出路径。
const ( MuxProtoVersion uint32 = 4 MuxProtocolVersion uint32 = 4 )
OpenSSH PROTOCOL.mux version 4.
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.
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.
const ( MUX_FWD_LOCAL uint32 = 1 MUX_FWD_REMOTE uint32 = 2 MUX_FWD_DYNAMIC uint32 = 3 )
Forwarding types.
const ( MaxMuxPacketLength = 256 * 1024 // 256 KB MaxMuxStringLength = 64 * 1024 // 64 KB )
Packet limits to defend against resource exhaustion DOS.
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.
const ( StrictHostKeyCheckingYes = "yes" StrictHostKeyCheckingNo = "no" StrictHostKeyCheckingAsk = "ask" StrictHostKeyCheckingAcceptNew = "accept-new" )
StrictHostKeyCheckingMode defines OpenSSH StrictHostKeyChecking values.
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 )
const (
DefaultInteractionTimeout = 2 * time.Minute
)
const DefaultMuxHandshakeTimeout = 10 * time.Second
DefaultMuxHandshakeTimeout bounds control-socket handshakes and RPCs when the caller's context carries no deadline of its own.
const DefaultPasswordPromptPattern = `` /* 126-byte string literal not displayed */
DefaultPasswordPromptPattern 是内置的多语言密码提示正则,覆盖主流语言环境。 匹配规则:密码关键词后面可以跟其他单词(如 "for user"),之后出现冒号即触发。
const MUX_SPECIAL_PORT_UNIX uint32 = 0xfffffffe
MUX_SPECIAL_PORT_UNIX indicates a Unix domain socket path rather than a TCP port.
Variables ¶
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") )
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 = errors.New("unauthorized peer UID") )
var ErrConnectorClosed = errors.New("ssh connector is closed")
ErrConnectorClosed 表示 Connector 已执行 CloseAll,不能再建立或返回连接。
var ErrControlProxyRejected = errors.New("control master rejected proxy mode")
ErrControlProxyRejected reports that the master refused a MUX_C_PROXY request.
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.
var ErrExecutionProbe = errors.New("SSH execution probe failed")
ErrExecutionProbe identifies an inconclusive or failed execution probe.
var ErrExecutionValidation = errors.New("execution validation error")
ErrExecutionValidation indicates an invalid execution configuration.
var ErrHandshakeClosed = errors.New("handshake coordinator is closed")
ErrHandshakeClosed 表示握手协调器已关闭或已被 fail-closed 中断。
var ErrInteractionRequired = errors.New("ssh interaction required")
ErrInteractionRequired 表示需要交互式输入但在非交互模式下被拒绝。
var ErrSSHOptionsValidation = errors.New("ssh options validation error")
ErrSSHOptionsValidation indicates an invalid SSH option key or value.
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.
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
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 DecodeMuxAlive ¶ added in v0.16.0
func DecodeMuxClientRequestID ¶ added in v0.16.0
func DecodeMuxError ¶ added in v0.16.0
func DecodeMuxExitMessage ¶ added in v0.16.0
func DecodeMuxExtInfo ¶ added in v0.16.0
func DecodeMuxExtInfoResponse ¶ added in v0.16.0
func DecodeMuxRemotePort ¶ added in v0.16.0
func DecodeMuxRequestID ¶ added in v0.16.0
func DecodeMuxSessionOpened ¶ added in v0.16.0
func DecodeMuxTTYAllocFail ¶ added in v0.16.0
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
3. MUX_S_ALIVE (0x80000005)
func EncodeMuxClientRequestID ¶ added in v0.16.0
4. MUX_S_OK (0x80000001) & MUX_S_PROXY (0x8000000f)
func EncodeMuxError ¶ added in v0.16.0
5. MUX_S_FAILURE (0x80000003) & MUX_S_PERMISSION_DENIED (0x80000002)
func EncodeMuxExitMessage ¶ added in v0.16.0
10. MUX_S_EXIT_MESSAGE (0x80000004)
func EncodeMuxExtInfo ¶ added in v0.16.0
13. MUX_C_EXT_INFO (0x20000001)
func EncodeMuxExtInfoResponse ¶ added in v0.16.0
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
7. MUX_S_REMOTE_PORT (0x80000007)
func EncodeMuxRequestID ¶ added in v0.16.0
2. Simple Request ID requests (ALIVE_CHECK, TERMINATE, STOP_LISTENING, PROXY)
func EncodeMuxSessionOpened ¶ added in v0.16.0
9. MUX_S_SESSION_OPENED (0x80000006)
func EncodeMuxTTYAllocFail ¶ added in v0.16.0
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
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 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
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 ¶
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
ParseStrictHostKeyChecking validates and normalizes StrictHostKeyChecking values.
func ReadMuxPacket ¶ added in v0.16.0
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
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 ¶
StaticRespond 返回一个固定字符串的 Respond 回调。
func ValidateControlPath ¶ added in v0.16.0
ValidateControlPath validates that the expanded socket path is non-empty and fits within OS limits.
func ValidateControlPathSyntax ¶ added in v0.16.0
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.
Types ¶
type AuthMaterial ¶
AuthMaterial 包含单次 SSH 握手所需的敏感认证材料。
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) 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 ¶
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
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) 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 ¶
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 ¶
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 ¶
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) RunWithSudo ¶
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 ¶
RunWithoutLogin 执行命令并在非登录 Shell 中运行,避免加载 profile 脚本产生干扰输出
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 ¶
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 ¶
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 ¶
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
func (c ConnectionConfig) Clone() ConnectionConfig
Clone returns a deep copy of ConnectionConfig, isolating mutable Execution and Options pointers.
type ConnectionConfirmer ¶
ConnectionConfirmer is an optional provider capability invoked immediately after SSH authentication, before recording credentials or dispatching user work.
type ConnectionError ¶
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
AcquireMaster restores this connector's active-session reference on a master it owns after a handoff reservation was rolled back.
func (*Connector) CloseAll ¶
CloseAll 关闭所有缓存的连接并等待在途建连与心跳 goroutine 退出。 调用后 Connector 进入永久关闭状态,后续 Connect 返回 ErrConnectorClosed。
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 ¶
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
HasMasterSession reports whether this connector still holds its initial active-session reference on server.
func (*Connector) Masters ¶ added in v0.16.0
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
OwnsMaster reports whether server was started by this connector.
func (*Connector) ReleaseMaster ¶ added in v0.16.0
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
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 ¶
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:
- Explicit Playbook step execution (step)
- Playbook settings execution (settings)
- Supported shebang declaration in script bytes
- Node execution (non-server only)
- 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 ¶
CleanOutput 返回清理后的输出:剔除匹配 promptPattern 的密码输入行。
func (*Expect) SetAccumulate ¶
SetAccumulate 设置是否在匹配结束后继续累积输出。 用于短生命周期的命令(如 runWithSu),以便执行完毕后获取完整输出。
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 ¶
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.
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.
const ( ForwardLocal ForwardType = ForwardType(MUX_FWD_LOCAL) ForwardRemote ForwardType = ForwardType(MUX_FWD_REMOTE) ForwardDynamic ForwardType = ForwardType(MUX_FWD_DYNAMIC) )
type HandshakeError ¶
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 ¶
InputBridge owns only duplicated input and cancellation handles. The caller owns the supplied terminal streams and the remote writer.
type InputCopy ¶
InputCopy.Close interrupts reading; Wait joins the copy within its context. Closing a copy must not close any borrowed process standard stream.
func NewInputCopy ¶
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 ¶
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 KeyLease ¶
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 包装器。
type LoginMode ¶
type LoginMode string
LoginMode preserves the distinction between omission and an explicit false.
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
AliveCheck queries the master process alive status and returns the server PID.
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
Extension returns the value of an extension advertised by the master in MUX_MSG_HELLO.
func (*MuxClient) HasExtension ¶ added in v0.16.0
HasExtension returns true if the master server advertised the specified extension.
func (*MuxClient) OpenForward ¶ added in v0.16.0
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
RequestInfo sends a MUX_C_EXT_INFO query to the master process ("connection" or "channels").
func (*MuxClient) StopListening ¶ added in v0.16.0
StopListening requests the master to unlink the control socket and stop accepting new clients.
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
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
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
ActiveSessions returns the current number of active multiplex sessions.
func (*MuxServer) AddForegroundSession ¶ added in v0.16.0
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
ControlPath returns the active control socket path.
func (*MuxServer) PersistEnabled ¶ added in v0.16.0
PersistEnabled reports whether this master survives the end of the foreground session (`ControlPersist` other than "no").
func (*MuxServer) PersistIndefinite ¶ added in v0.16.0
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
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) Shutdown ¶ added in v0.16.0
Shutdown gracefully closes the server, listeners, active forwards, and SSH connections.
func (*MuxServer) StoppedListening ¶ added in v0.16.0
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.
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 WithEnvironment ¶
func WithEnvironment(environment Environment) Option
func WithHandshakeTimeout ¶
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 ¶
WithInteractionTimeout 配置单次交互提示超时时间
func WithKeySource ¶
func WithLogger ¶
func WithLogger(l logger.DebugLogger) Option
WithLogger 配置 Connector 使用的 DebugLogger(必须支持并发调用)
func WithPasswordPromptPattern ¶
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
EffectiveOptions resolves a hierarchy of Options from highest priority to lowest priority.
func MergeOptionLayers ¶ added in v0.16.0
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
MustOptions creates an Options instance from alternating key, value pairs and panics on error.
func NewOptions ¶ added in v0.16.0
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
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) Ciphers ¶ added in v0.16.0
Ciphers returns the raw Ciphers specification, or "" if unset.
func (*Options) ConnectTimeout ¶ added in v0.16.0
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
ControlPath returns the configured ControlPath, or "" if unset.
func (*Options) ControlPersist ¶ added in v0.16.0
ControlPersist returns the configured ControlPersist, or "" if unset.
func (*Options) Equal ¶ added in v0.16.0
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
Get returns the normalized string value for key, or "" if unset.
func (*Options) HostKeyAlgorithms ¶ added in v0.16.0
HostKeyAlgorithms returns the raw HostKeyAlgorithms specification, or "" if unset.
func (*Options) IdentitiesOnly ¶ added in v0.16.0
IdentitiesOnly reports whether IdentitiesOnly is set to "yes".
func (Options) IsZero ¶ added in v0.16.0
IsZero implements yaml.IsZeroer so empty non-nil Options are omitted with omitempty.
func (*Options) KbdInteractiveAuthentication ¶ added in v0.16.0
KbdInteractiveAuthentication returns (enabled, true) if KbdInteractiveAuthentication is set, or (true, false) if unset.
func (*Options) KexAlgorithms ¶ added in v0.16.0
KexAlgorithms returns the raw KexAlgorithms specification, or "" if unset.
func (*Options) Map ¶ added in v0.16.0
Map returns a defensive copy of the canonical snake_case key-value map.
func (Options) MarshalJSON ¶ added in v0.16.0
MarshalJSON serializes Options as a JSON object with canonical snake_case keys in deterministic order.
func (Options) MarshalYAML ¶ added in v0.16.0
MarshalYAML serializes Options as a YAML mapping using canonical snake_case keys in registry order.
func (*Options) PasswordAuthentication ¶ added in v0.16.0
PasswordAuthentication returns (enabled, true) if PasswordAuthentication is set, or (true, false) if unset.
func (*Options) PreferredAuthentications ¶ added in v0.16.0
PreferredAuthentications returns the configured list of preferred authentication methods, or nil if unset.
func (*Options) PubkeyAuthentication ¶ added in v0.16.0
PubkeyAuthentication returns (enabled, true) if PubkeyAuthentication is set, or (true, false) if unset.
func (*Options) ServerAliveCountMax ¶ added in v0.16.0
ServerAliveCountMax returns the configured ServerAliveCountMax (defaulting to 3 if unset).
func (*Options) ServerAliveInterval ¶ added in v0.16.0
ServerAliveInterval returns the configured ServerAliveInterval, or 0 if unset/disabled.
func (*Options) Set ¶ added in v0.16.0
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
SetControlPath sets the ControlPath directly.
func (*Options) SetControlPersist ¶ added in v0.16.0
SetControlPersist sets the ControlPersist directly.
func (*Options) StrictHostKeyChecking ¶ added in v0.16.0
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
TCPKeepAlive returns (enabled, true) if TCPKeepAlive is explicitly set, or (false, false) if unset.
func (*Options) UnmarshalJSON ¶ added in v0.16.0
UnmarshalJSON decodes a JSON object into Options, accepting both snake_case and OpenSSH option names.
func (*Options) UnmarshalYAML ¶ added in v0.16.0
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
UserKnownHostsFile returns the configured UserKnownHostsFile path, or "" if unset.
func (*Options) Validate ¶ added in v0.16.0
Validate validates all individual option values and standalone cross-field rules.
func (*Options) ValidateEffective ¶ added in v0.16.0
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) 所需的敏感机密材料。
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 ¶
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 WithOutFile ¶
func WithOutputMode ¶
func WithOutputMode(mode OutputMode) RunOption
func WithRingBuffer ¶
func WithScriptArgs ¶ added in v0.16.0
WithScriptArgs specifies the positional arguments to pass to the script when executing via RunScript.
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
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) DialContext ¶
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 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.
Source Files
¶
- activity.go
- auth.go
- auth_diagnostics.go
- client.go
- command_execution.go
- command_plan.go
- command_stream.go
- connector.go
- context_output.go
- context_output_deadline.go
- context_output_linux.go
- control_config.go
- copy_stdin_unix.go
- credential_recovery.go
- diagnostics.go
- environment.go
- errors.go
- exec_output.go
- execute.go
- execution_config.go
- expect.go
- handshake_coordinator.go
- host_algorithms.go
- input_bridge.go
- keepalive.go
- key_source.go
- keyboard_interactive.go
- mux_client.go
- mux_peer_linux.go
- mux_protocol.go
- mux_proxy_conn.go
- mux_rights_unix.go
- mux_server.go
- options.go
- output.go
- output_relay.go
- plan.go
- privilege_diagnostics.go
- privilege_exchange.go
- privilege_persistence.go
- privilege_prompt_context.go
- privilege_terminal.go
- probe.go
- probe_controlled.go
- proxy.go
- remote_forward.go
- resource.go
- session_lifecycle.go
- sftp_stream.go
- shebang.go
- socks5.go
- ssh_options.go
- sudo_prompt.go
- tunnel.go
- types.go
- types_api.go
- unix_privilege.go
- wait.go
- windows_adapter.go
- working_dir.go