sshx

package
v0.15.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: AGPL-3.0 Imports: 39 Imported by: 0 modules, 0 packages

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

Documentation

Overview

Package sshx dials hosts from the inventory (with jump-host chains, keychain/agent/password auth and TOFU host-key checking) and runs commands.

Index

Constants

View Source
const HeldUser = "komando"

HeldUser is the user name a command logs in to a held login's socket with.

View Source
const PSTrailer = "\nif (-not $?) { if ($LASTEXITCODE) { exit $LASTEXITCODE }; exit 1 }; $global:LASTEXITCODE = 0\n"

PSTrailer ends every script: a failed last command (a cmdlet error, or a program that exited non-zero) makes the exit code non-zero, as in sh.

Variables

View Source
var AskLoginNewKey func(ctx context.Context, h *store.Host, k NewHostKey) error

AskLoginNewKey, when set, decides whether a connection may go on with a login-ask server whose host key komando has not seen before (k): the key is pinned only when it returns nil. The person's password would go to whatever answers at the address, so the cli lets a first connection through only when a person is at the terminal (who sees the key) or an app's window will warn them; an AI agent's or a script's command gets NEEDS_PERSON and nothing is pinned. Unset: only with a person at the terminal.

View Source
var Asker func() func(host, text string, hidden bool) (string, error)

Asker, when set, gives the question for the person at the terminal, or nil when nobody can be asked. The question asks what a login wants that komando cannot answer by itself: the password when none is stored, a one-time code (a two-factor login), or any other question the server asks, the way ssh does. host is the server's name in komando; text is the server's own words (the question makes them safe to show); hidden is false only when the server lets the answer show. The cli gives one only for a person at a terminal: AI agents, scripts and background processes have no one to ask, so they get NO_AUTH or AUTH_FAILED with a hint instead.

View Source
var ChainOwner func(ctx context.Context) string

ChainOwner, when set, names the command a path through jump hosts is opened for, from the context of the Dial. A path is shared only within one owner: a path one command opened (a person's, who answered a login question or approved a VPN) never serves another command in the same process (an app), which may be an AI agent's or carry other approvals.

View Source
var HostKeyPinned func(ctx context.Context, k NewHostKey)

HostKeyPinned, when set, is told about every key pinned on first use (for the output and the audit log), with the context of the Dial that pinned it. It is called after the pin is saved, while the connection waits: it must be quick.

View Source
var HostSecretEnv func(c *Client) bool

HostSecretEnv says whether the host's own env values that come from the vault go into this command's environment; nil is yes. The cli says no for an AI agent until a person has said yes: in the command's environment the agent could read the value back in a form masking does not know (printenv X | rev). extra (a command's --env) is checked where it is given.

View Source
var LoginPassword func(ctx context.Context, q LoginAsk) (pw string, refused func(), err error)

LoginPassword, when set, gives the password of a server whose login is "ask": komando never stores it, so a person types it for the command that connects (ctx is that command's Dial). It returns refused, which the login calls when the server refuses the password, so the command does not send it again. The cli asks the person at the terminal, in an app's window, or in komando's own window for an AI agent's command; a script, or an agent with no screen, gets NEEDS_PERSON. Unset: the person at the terminal (Asker) or NEEDS_PERSON.

View Source
var MayPin func(ctx context.Context) error

MayPin, when set, is asked before a new server's key is pinned on first use, with the context of the Dial. An error refuses the pin, and the connection with it: the CLI refuses a context that carries no command, since the pin would belong to no command's output and audit log.

View Source
var PSCommandLine = "powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -EncodedCommand " + encodePS(psBootstrap)

PSCommandLine is the program komando starts on a Windows server.

View Source
var PersonAtTerminal = func() bool { return false }

PersonAtTerminal reports whether a person at a terminal (not an AI agent or a script) runs komando; the cli package sets it. Only a person is told how to re-trust a changed host key.

Functions

func AskHops added in v0.15.0

func AskHops(st *store.State, h *store.Host) []*store.Host

AskHops are the servers on the way to h, h last, whose login is "ask" (a person types the password) and that no held login covers: the ones a connection to h asks a password for.

func AskLoginNeedsPerson added in v0.15.0

func AskLoginNeedsPerson(h *store.Host, agent bool) *out.Error

AskLoginNeedsPerson is NEEDS_PERSON for a login-ask server h nobody can type the password for: an AI agent (agent) with no window, or a script.

func AskLoginNewKeyNeedsPerson added in v0.15.0

func AskLoginNewKeyNeedsPerson(h *store.Host, k NewHostKey, agent bool) *out.Error

AskLoginNewKeyNeedsPerson is NEEDS_PERSON for the first connection to a login-ask server h (or one whose key is not checked) with nobody at a terminal to see the key: nothing was pinned or sent.

func AskLoginStep added in v0.15.0

func AskLoginStep(h *store.Host, agent bool) string

AskLoginStep is the one next step when nobody here can type the password of login-ask server h: a person runs `komando login NAME` in their own terminal (it keeps the login for a while); a WinRM server has no held login, so the person runs the command there.

func BuildCommand

func BuildCommand(c *Client, r RunRequest) (cmd string, sudoPass []byte, err error)

BuildCommand assembles the final remote shell line: env exports, cd, sudo wrapping. Exposed so --dry-run can show exactly what would run. sudoPass is the sudo password Run feeds on request, or nil. Values from the vault are not in it: Run sends them on the command's input. On a Windows server cmd is the PowerShell script (docs/features/windows.md).

func CertCurrent added in v0.14.0

func CertCurrent(cert *ssh.Certificate, now time.Time) bool

CertCurrent: now lies in the certificate's valid time.

func CertSigners added in v0.14.0

func CertSigners(s ssh.Signer, certPath string) []ssh.Signer

CertSigners is s, after it the same key with its OpenSSH user certificate from certPath when there is one that belongs to s and has not run out: the server picks what it trusts, as with ssh (the certificate first). A certificate that is missing, unreadable, for another key or out of date is left out.

func CleanPSError added in v0.9.0

func CleanPSError(s string) string

CleanPSError turns PowerShell's error stream back into text, without PowerShell 7's colours. Windows PowerShell writes it as CLIXML ("#< CLIXML" and XML) when its output is not a console, as over SSH or WinRM: the error and warning lines are kept, progress records are dropped.

func CountPinned added in v0.12.0

func CountPinned(addr string) (int, error)

CountPinned is how many pins addr (host:port) has, as PinHostKey with replace would remove them, keys that no longer parse included.

func EnvExports added in v0.2.0

func EnvExports(c *Client, extra map[string]string) (string, error)

EnvExports is the "export K='v'; " prefix for the host's env and extra, secret values included: for a private file only (job start), never for a command line.

func ExpandProxy added in v0.2.0

func ExpandProxy(cmd string, h *store.Host) string

ExpandProxy fills in a ProxyCommand's tokens like OpenSSH: %h address, %p port, %r user, %n the name in the inventory, %% a percent sign. Each value is quoted for sh.

func FetchHostKey added in v0.3.0

func FetchHostKey(ctx context.Context, st *store.State, h *store.Host, o Options) (ssh.PublicKey, error)

FetchHostKey fetches h's host key the way komando reaches h: directly, through a VPN, its proxy command or its --via path (those jump hosts are checked and logged in to as usual). h itself is not logged in to, and nothing is pinned for it: the caller compares and decides.

func FingerprintMismatch added in v0.15.0

func FingerprintMismatch(host, want, offered string) *out.Error

FingerprintMismatch is host trust --fingerprint's error: the server shows another key than the fingerprint given, so nothing was pinned.

func HeldFor added in v0.8.0

func HeldFor(st *store.State, h *store.Host) *store.SSHLogin

HeldFor is the held login for h that is still in time, or nil.

func HostKeyMismatch added in v0.3.0

func HostKeyMismatch(host, offered string, pinned []string) *out.Error

HostKeyMismatch is the error for a server whose key is not the pinned one: offered is the fingerprint the server shows now, pinned the ones komando knows (either may be empty). An AI agent must not re-trust the key itself: it reports it, and a person checks the new fingerprint another way first.

func HostKeyRevoked added in v0.12.0

func HostKeyRevoked(key ssh.PublicKey) (bool, error)

HostKeyRevoked reports key on the never-trust list.

func HostKeys added in v0.12.0

func HostKeys() hostKeyStore

HostKeys is where this process keeps pins: the sealed store.

func IsSecurityKey added in v0.14.0

func IsSecurityKey(pub ssh.PublicKey) bool

IsSecurityKey: pub is a FIDO2 security key's (sk-ssh-ed25519@openssh.com, sk-ecdsa-sha2-nistp256@openssh.com), which only ssh-agent can sign with.

func LocalUser added in v0.13.0

func LocalUser() string

LocalUser is the login name ssh uses when neither the server nor the settings give one: the account this process runs as, from the user database as OpenSSH takes it (on Windows without its domain). USER and USERNAME count only when the database has no answer: an agent sets them, and a login-ask server's password must go to the person's own account.

func LoginID added in v0.15.0

func LoginID(h *store.Host) string

LoginID is what login-ask server h is known by in the host keys' logins (and the password window's cool-down): its record ID, which a rename keeps, or its name.

func LoginMet added in v0.15.0

func LoginMet(h *store.Host, addr string) (bool, error)

LoginMet reports that a person logged in to login-ask server h at addr with a key pinned there now: a connection there needs nobody to see a new key first.

func MarkLoginMet added in v0.15.0

func MarkLoginMet(h *store.Host, addr string, key ssh.PublicKey) error

MarkLoginMet pins key for addr and notes that a person logged in to login-ask server h there, as their first connection does (for tests, and for nothing an agent reaches).

func Output

func Output(ctx context.Context, c *Client, cmd string, timeout time.Duration) (string, int, error)

Output is a convenience for internal probes: run and return trimmed stdout.

func PSArray added in v0.9.0

func PSArray(items []string) string

PSArray is a PowerShell array of string literals: @('a', 'b').

func PSQ added in v0.9.0

func PSQ(s string) string

PSQ quotes s as a PowerShell string literal: in single quotes nothing is expanded, and a quote is doubled. PowerShell also reads the typographic single quotes (U+2018 to U+201B) as quotes, so they are doubled too.

func ParseAdhoc

func ParseAdhoc(s string) (*store.Host, error)

ParseAdhoc parses user@host:port into a transient host.

func ParseUserCert added in v0.14.0

func ParseUserCert(b []byte, pub ssh.PublicKey) (*ssh.Certificate, error)

ParseUserCert reads an OpenSSH user certificate (KEY-cert.pub) and checks that it is for pub.

func PinHostKey added in v0.3.0

func PinHostKey(addr string, key ssh.PublicKey, replace bool) (removed int, err error)

PinHostKey pins key for addr (host:port). A key that is pinned already is not written again. With replace, every other pin for addr goes in the same write, so a failure never leaves the server unpinned; removed is how many pins went. Whether a pin may be replaced is the caller's decision (`host trust --reset` is for a person at a terminal only).

func PinnedKeys added in v0.3.0

func PinnedKeys(addr string) ([]ssh.PublicKey, error)

PinnedKeys are the keys komando pins for addr (host:port).

func Pipe added in v0.2.0

func Pipe(ctx context.Context, c *Client, cmd string, stdin io.Reader, stdout io.Writer) (int, string, error)

Pipe runs cmd and streams stdin and stdout without buffering them, for transfers too large for Run (database dumps). stderr is kept up to 64 KiB for error messages. It returns the remote exit code.

func Q

func Q(s string) string

Q single-quotes s for POSIX sh.

func Refused added in v0.13.0

func Refused(err error) bool

Refused reports whether err is a refused connection: nothing listens on the port. Windows words it "No connection could be made because the target machine actively refused it", in the system's language, so the error number is what counts; the words are for errors that kept only their text.

func RevokeHostKeys added in v0.12.0

func RevokeHostKeys(keys []ssh.PublicKey) error

RevokeHostKeys puts keys on the never-trust list: no server is reached with them, and none can be pinned.

func Route added in v0.2.0

func Route(st *store.State, h *store.Host) (*store.Vpn, []*store.Host, error)

Route is the way to h: the VPN it starts with (or nil) and the SSH hops, ending with h itself. It reads the inventory only; nothing is dialed.

func RunPS added in v0.9.0

func RunPS(ctx context.Context, c *Client, script string, stdin io.Reader, stdout io.Writer) (int, string, error)

RunPS runs a PowerShell script on a Windows server with stdin after it and stdout streamed, for transfers too large for Run. stderr is kept up to 64 KiB. It returns the script's exit code.

func SameKey added in v0.3.0

func SameKey(a, b ssh.PublicKey) bool

SameKey reports whether a and b are the same public key.

func SaveInput added in v0.7.0

func SaveInput(n int, path string) string

SaveInput is a shell step that saves the next n bytes of the command's input in path (a shell word, such as "$d/env"), readable by the user only. dd reads one byte at a time, so what follows on the input stays for the next step: secrets go to a file without being on a command line.

func ServeHeld added in v0.8.0

func ServeHeld(ln net.Listener, up *ssh.Client, token string, key ssh.Signer, used func())

ServeHeld serves up (the person's login) on ln until ln closes: each client that knows token gets its channels passed on to up.

func TargetOf added in v0.8.0

func TargetOf(h *store.Host) string

TargetOf is where h logs in: a held login is used only while the host still points there (a changed address or user logs in anew).

func ValidEnvKey added in v0.2.0

func ValidEnvKey(k string) bool

ValidEnvKey reports whether k can be exported as a shell variable. The key goes into the command line unquoted, so anything else could inject a command.

func WayVia added in v0.15.0

func WayVia(st *store.State, h *store.Host) string

WayVia names the steps komando dials through to reach h and h itself, as a conn reached --via h names its way.

func WithDeadlines added in v0.2.0

func WithDeadlines(c net.Conn) net.Conn

SSH channels do not support deadlines, but database and cache clients use them for timeouts. WithDeadlines emulates them: when a deadline passes the connection is closed, which ends any blocked read or write.

func WritePinsFile added in v0.12.0

func WritePinsFile(dir string, addrs []string) (string, error)

WritePinsFile writes the pins of addrs (host:port) as a known_hosts file in dir, readable by this user only, for OpenSSH (host ssh-command on a sealed home), and returns its path.

Types

type Client

type Client struct {
	*ssh.Client
	Host *store.Host

	// Win carries the commands of a Windows server reached over WinRM;
	// such a Client has no SSH connection (Client is nil)
	Win WinShell
	// contains filtered or unexported fields
}

Client wraps an ssh.Client plus the path of jump hosts it came through (shared with other servers behind the same hosts, shared.go).

func Dial

func Dial(ctx context.Context, st *store.State, h *store.Host, o Options) (*Client, error)

Dial connects to h, honouring its --via chain. A chain may start with a VPN; it is opened inside this process. The jump hosts are shared with other servers behind them (one login per jump host per command).

func (*Client) Close

func (c *Client) Close() error

func (*Client) Session added in v0.14.0

func (c *Client) Session() (*ssh.Session, error)

Session opens a session on c. For a server with forward_agent (host edit --forward-agent) it lends the session this computer's ssh-agent (SSH_AUTH_SOCK), as ssh -A does: the server's side of it lasts only as long as the connection. Without forward_agent, or without an agent here, it is a plain session.

type LoginAsk added in v0.15.0

type LoginAsk struct {
	Host *store.Host
	User string // the user komando logs in as
	Addr string // host:port, where the password goes
	// Path is the way there komando dials through ("" for straight
	// there): the VPN, each jump host with its user and address, a proxy
	// command. The password goes to Addr at its end.
	Path string
	// NewKey is the host key this connection trusted on first use (or
	// could not check: host_key_policy off); nil for a key komando knew.
	// Nothing proved a new key is the server's.
	NewKey *NewHostKey
}

LoginAsk is one connection's question for the password of a server whose login is "ask" (host add --login ask).

func LoginAskFor added in v0.15.0

func LoginAskFor(st *store.State, h *store.Host) LoginAsk

LoginAskFor is the question a connection to h asks, before it connects (NewKey unknown yet).

type NewHostKey added in v0.7.0

type NewHostKey struct {
	Host        string `json:"host"`
	Address     string `json:"address"`
	Type        string `json:"key_type"`
	Fingerprint string `json:"fingerprint"` // SHA256:...
	// Unchecked: host_key_policy off, so the key was not checked at all
	// (only a login-ask server's connection is told; nothing is pinned)
	Unchecked bool `json:"-"`
	// NotMet: the key is pinned, but no person ever logged in to this
	// login-ask server with it (a pin alone may come from an AI agent's
	// connection to another server at the same address)
	NotMet bool `json:"-"`
	// contains filtered or unexported fields
}

NewHostKey is a host key komando pinned the first time it reached a server (host_key_policy accept-new). Nothing proved that key is the server's: the person compares the fingerprint with the server's own.

type Options

type Options struct {
	ConnectTimeout time.Duration
	HostKeyPolicy  string // accept-new | strict | off
	// Fresh logs in anew, never through a held login (`komando login`
	// itself, which makes one)
	Fresh bool

	// WinRM lets Dial reach a server over WinRM: the caller only runs
	// PowerShell through Run and RunPS (no SSH sessions, no tunnels)
	WinRM bool
	// contains filtered or unexported fields
}

type RunRequest

type RunRequest struct {
	Command   string
	Sudo      bool
	SudoUser  string
	Env       map[string]string
	NoEnv     bool // leave out the exports (job start writes them to a private file instead)
	Dir       string
	Stdin     []byte
	Timeout   time.Duration
	MaxOutput int
	PTY       bool
	// Stream, when set, receives output chunks as they arrive (follow mode).
	Stream func(stream string, chunk []byte)
}

type RunResult

type RunResult struct {
	ExitCode        int    `json:"exit_code"`
	Stdout          string `json:"stdout"`
	Stderr          string `json:"stderr"`
	StdoutTruncated bool   `json:"stdout_truncated,omitempty"`
	StderrTruncated bool   `json:"stderr_truncated,omitempty"`
	TimedOut        bool   `json:"timed_out,omitempty"`
	Signal          string `json:"signal,omitempty"`
	DurationMS      int64  `json:"duration_ms"`
}

func Run

func Run(ctx context.Context, c *Client, r RunRequest) (*RunResult, error)

Run executes a command and never returns an error for a non-zero exit: that is reported in RunResult.ExitCode. err is for transport failures. On a Windows server the command is PowerShell.

type WinShell added in v0.9.0

type WinShell interface {
	Run(ctx context.Context, command string, stdin io.Reader, stdout, stderr io.Writer) (int, error)
	Close() error
}

WinShell runs one command on a Windows server over WinRM (internal/winrm).

Jump to

Keyboard shortcuts

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