ssh

package
v0.7.1 Latest Latest
Warning

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

Go to latest
Published: Sep 9, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Overview

Package ssh wraps golang.org/x/crypto/ssh with sshm-specific construction helpers and a small Client that owns one connection.

Index

Constants

View Source
const MaxCaptureBytes = 256 * 1024

MaxCaptureBytes caps how much stdout/stderr Exec retains per stream. Output beyond this is dropped (and Truncated is set) to avoid blowing up the caller's context window or memory on a chatty command.

Variables

This section is empty.

Functions

func Address

func Address(s *config.Server) string

Address joins host and port with default 22.

func BuildClientConfig

func BuildClientConfig(s *config.Server, opts BuildOpts) (*gssh.ClientConfig, io.Closer, error)

BuildClientConfig produces a *ssh.ClientConfig from a Server entry. It also returns an io.Closer that the caller must close when done (releases the ssh-agent unix socket when agent auth is used).

func CheckKeyPairUsable added in v0.7.1

func CheckKeyPairUsable(path string) (string, error)

CheckKeyPairUsable verifies that path and its sibling .pub file describe the same key and that sshm can obtain a working signer for it right now. It returns the exact public-key line that was checked so pairing publishes that same value instead of re-reading a possibly changed .pub file. For an encrypted private key this exercises the exact ssh-agent/keychain-backed signing path used by Dial, without exposing or persisting the passphrase.

func DialAgent added in v0.5.0

func DialAgent() (net.Conn, error)

DialAgent connects to the running ssh-agent using the platform-appropriate transport (unix socket via SSH_AUTH_SOCK, or the Windows OpenSSH agent named pipe). Callers own the returned connection and must Close it.

func ExpandHome

func ExpandHome(p string) (string, error)

ExpandHome expands a leading ~ to the current user's home directory.

func FailureCategory added in v0.7.1

func FailureCategory(err error) string

FailureCategory is safe to persist/sync: no hosts, credentials or stderr.

func ManagedAgentPath added in v0.7.1

func ManagedAgentPath() string

func PlatformFromOutput added in v0.7.1

func PlatformFromOutput(s string) string

func RecordHardware added in v0.7.1

func RecordHardware(path, alias string, expected *config.Server, h *inventory.Snapshot) error

func RecordPlatform added in v0.7.1

func RecordPlatform(path, alias string, expected *config.Server, platform string) error

func RecordSSHM added in v0.7.1

func RecordSSHM(path, alias string, expected *config.Server, status, version string, at time.Time) error

Types

type BuildOpts

type BuildOpts struct {
	// ResolveJump supplies a vault-owned jump host and its own credentials.
	// It must reject unknown or ambiguous aliases; no local fallback is used.
	ResolveJump func(string) (*config.Server, BuildOpts, error)
	// Signers are supplied by the unlocked cloud vault and are never persisted.
	Signers  []gssh.Signer
	Password string
	// Alias identifies a managed target for best-effort LastUsed tracking after
	// authentication succeeds. Empty leaves activity metadata untouched.
	Alias string
	// ProbeOnly suppresses use tracking for the target and its jump hosts.
	ProbeOnly bool
	// ActivityError receives a non-fatal error when authentication succeeded
	// but LastUsed/LastSeen could not be persisted. When nil, Dial writes a
	// concise warning to stderr so stale cleanup metadata is never silent.
	ActivityError func(error)
	// Insecure disables host-key verification (InsecureIgnoreHostKey). The
	// zero value is false: connections verify host keys via TOFU against
	// ~/.ssh/known_hosts by default.
	Insecure bool
	Timeout  time.Duration // 0 → default 10s
	// ConfigPath is the on-disk config path used to resolve a ProxyJump alias
	// to a known server. Empty falls back to config.ConfigPath(); if that
	// holds no matching alias the ProxyJump value is treated as a host spec.
	ConfigPath string
}

BuildOpts is non-persistent input gathered at connect time (e.g. password prompted from TTY). Never write the contents of BuildOpts to disk.

type Client

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

Client is one connected SSH session owner. NOT safe for concurrent use.

func Dial

func Dial(s *config.Server, opts BuildOpts) (_ *Client, dialErr error)

Dial opens a fresh connection. Caller must call Close.

The target is reached over the transport chosen by resolveTransportKind: ProxyCommand > ProxyJump > SOCKS5 (s.Proxy or env) > Direct. When a proxy or jump was selected but the connection fails, Dial retries once with a direct TCP dial — this recovers the common TUN/VPN case where the host is reachable directly but the configured SOCKS proxy is not (or vice versa is already the direct path).

func (*Client) AttachInteractive

func (c *Client) AttachInteractive() error

AttachInteractive opens an interactive shell on the connected client, wiring the local TTY to the remote PTY. Returns when the user logs out.

func (*Client) AttachInteractiveCommand added in v0.7.0

func (c *Client) AttachInteractiveCommand(command string) error

AttachInteractiveCommand runs one command under a remote PTY. It is used for terminal-owned sensitive workflows such as passwd, so secret input goes directly from the user's keyboard to the remote server.

func (*Client) CheckEnvironment added in v0.7.1

func (c *Client) CheckEnvironment(ctx context.Context) (*EnvironmentReport, error)

func (*Client) Close

func (c *Client) Close() error

Close terminates the underlying TCP connection AND all auxiliary closers.

func (*Client) DetectHardware added in v0.7.1

func (c *Client) DetectHardware(ctx context.Context, platform string) *inventory.Snapshot

func (*Client) DetectPlatform added in v0.7.1

func (c *Client) DetectPlatform(ctx context.Context) string

DetectPlatform reads an authenticated target's OS; it never uses the hostname or SSH banner to guess and never records a probe as a user connection.

func (*Client) DetectSSHM added in v0.7.1

func (c *Client) DetectSSHM(ctx context.Context, platform string) (string, string)

DetectSSHM checks PATH and documented user/system installation locations. Failure to authenticate or run the check is not evidence of an absent client.

func (*Client) Exec

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

Exec runs cmd on the remote and returns captured output. If ctx is canceled before the command completes, the session is closed and ctx.Err() is returned. Captured stdout/stderr are each capped at MaxCaptureBytes; if either stream overflows, ExecResult.Truncated is set.

func (*Client) ExecUser added in v0.7.1

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

func (*Client) NewSFTP added in v0.3.0

func (c *Client) NewSFTP() (*sftp.Client, error)

NewSFTP opens an SFTP subsystem over the existing SSH connection. The caller owns the returned *sftp.Client and must Close it. The underlying SSH connection (and any auxiliary closers) is still released by Client.Close.

func (*Client) OpenTerminal added in v0.7.1

func (c *Client) OpenTerminal(ctx context.Context, cols, rows int) (*TerminalStream, error)

func (*Client) PrepareUserCommand added in v0.7.1

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

PrepareUserCommand preserves existing PATH precedence, adding only missing conventional installation directories after loading the user login shell. Raw Exec stays available for protocol probes and callers requiring the exact sshd environment.

func (*Client) StreamExec

func (c *Client) StreamExec(ctx context.Context, cmd string, stdout, stderr io.Writer) (int, error)

StreamExec runs cmd and writes stdout/stderr to the provided writers as they arrive. Useful for `sshm exec` to show real-time output. This path is intentionally unbounded so the CLI can stream large output.

func (*Client) StreamExecUser added in v0.7.1

func (c *Client) StreamExecUser(ctx context.Context, command string, stdout, stderr io.Writer) (int, error)

func (*Client) Underlying

func (c *Client) Underlying() (*gssh.Client, error)

Underlying returns the wrapped ssh.Client. Use sparingly; tests of this package shouldn't need it.

type EnvironmentReport added in v0.7.1

type EnvironmentReport struct {
	CredentialContext string            `json:"github_credential_context,omitempty"`
	ExecutionContext  string            `json:"execution_context"`
	Scope             string            `json:"scope"`
	Platform          string            `json:"platform"`
	User              string            `json:"os_user,omitempty"`
	GHOriginalPath    string            `json:"gh_original_path,omitempty"`
	GHEffectivePath   string            `json:"gh_effective_path,omitempty"`
	Tools             map[string]string `json:"tools"`
	GitPath           string            `json:"git_path,omitempty"`
	GitHub            string            `json:"github_access"`
	Account           string            `json:"github_account,omitempty"`
	Note              string            `json:"note"`
}

EnvironmentReport describes this process/session only. Authentication failures are deliberately not classified as logout: keychains, network, SSO, scopes, credential helpers and the selected OS user can all differ from a desktop.

func CheckLocalEnvironment added in v0.7.1

func CheckLocalEnvironment(ctx context.Context) (*EnvironmentReport, error)

type ExecResult

type ExecResult struct {
	Stdout   string
	Stderr   string
	ExitCode int
	// Truncated is true when stdout or stderr exceeded MaxCaptureBytes and the
	// excess was dropped.
	Truncated bool
}

ExecResult is the captured output of one command.

type TerminalStream added in v0.7.1

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

TerminalStream owns a remote PTY and its SSH transport, independent of the agent host's OS and stdin. Closing it cancels blocked IO and the remote shell.

func (*TerminalStream) Close added in v0.7.1

func (t *TerminalStream) Close() error

func (*TerminalStream) Read added in v0.7.1

func (t *TerminalStream) Read(b []byte) (int, error)

func (*TerminalStream) Resize added in v0.7.1

func (t *TerminalStream) Resize(cols, rows int) error

func (*TerminalStream) Write added in v0.7.1

func (t *TerminalStream) Write(b []byte) (int, error)

Jump to

Keyboard shortcuts

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