Documentation
¶
Overview ¶
Package ssh is the OpenWatch SSH dial layer. The connectivity-check endpoint, the future scan executor, and any other operation that needs to reach a host via SSH go through this package's Dial. Plaintext credentials are decrypted by internal/credential and passed in for the duration of one dial; they never leave this layer in any log, error, or audit row.
Spec: specs/system/ssh-connectivity.spec.yaml.
Index ¶
- Constants
- Variables
- func Dial(ctx context.Context, host string, port int, cred *credential.Credential, ...) (*ssh.Client, error)
- func DialConn(ctx context.Context, conn net.Conn, host string, cred *credential.Credential, ...) (*ssh.Client, error)
- func RunSudo(ctx context.Context, sess SudoSession, cred *credential.Credential, ...) (stdout []byte, exitCode int, usedFallback bool, observed string, err error)
- func ValidateAuthKey(pem []byte, passphrase string) error
- type AuthReport
- type DialOptions
- type KnownHostsStore
- type MemoryStore
- type MethodAttempt
- type MethodResult
- type Mode
- type OutcomeKind
- type ProtectedOptions
- type ProtectedResult
- type ProtectedSudoMode
- type ProtectedSudoOptions
- type Protection
- type SudoPolicy
- type SudoResult
- type SudoSession
- type ValidatedSudoProfile
Constants ¶
const ( PreferKey = "key" PreferPassword = "password" // pragma: allowlist secret )
Auth-method preference tokens. Plain strings (not a typed enum) so the ssh package stays decoupled from connprofile — callers translate.
const ( SecretKindPassword = "password" // pragma: allowlist secret SecretKindKey = "key" // pragma: allowlist secret )
Secret kinds a credential can present.
const ( MethodPassword = "password" // pragma: allowlist secret MethodKeyboardInteractive = "keyboard-interactive" )
Methods a protected dial may submit a password with.
const ( SudoNopasswd = "nopasswd" SudoPassword = "password" )
Sudo-mode tokens for RunSudo's prefer (in) and observed (out). Plain strings — not connprofile's typed enum — so this dial-layer file stays decoupled from connprofile, exactly as PreferKey/PreferPassword do for the auth method. The values match connprofile.SudoNopasswd / connprofile.SudoPassword, so a string()/SudoMode() cast round-trips at the call site. An empty prefer/observed means "unknown — no preference".
const DefaultDialTimeout = 10 * time.Second
DefaultDialTimeout is the upper bound on connect+handshake. Callers may supply a tighter ctx deadline; can't loosen.
Spec C-01.
const DefaultReservationMargin = 15 * time.Second
DefaultReservationMargin is how long a reservation outlasts the dial's own bound, to cover the fence and settlement.
const ECDSAMinBits = sshkey.ECDSAMinBits
ECDSAMinBits is the lower bound for ECDSA curves. P-256 = 256 bits.
const RSAMinBits = sshkey.RSAMinBits
RSAMinBits is the lower bound for RSA keys per NIST SP 800-57 (good through 2030). Keys below this size are rejected.
Variables ¶
var ( ErrConnect = errors.New("ssh: tcp connect failed") ErrAuthFailed = errors.New("ssh: authentication failed") ErrDialTimeout = errors.New("ssh: dial timed out") ErrNoAuthMethod = errors.New("ssh: credential has no usable auth method") )
Dial-layer errors. Distinct sentinels per failure mode so callers (audit emitter, connectivity-check handler) can map to specific reason strings without parsing error text.
Spec C-06.
var ( ErrHostKeyUnknown = errors.New("ssh: host key not in known-hosts store") ErrHostKeyMismatch = errors.New("ssh: host key changed since first connection") )
Host-key verification errors.
var ( // ErrProtected: credential protection did not admit the submission. It // refused at reservation or at the fence, or it could not be reached. // It wraps the reason, a credprotect error where there is one. ErrProtected = errors.New("ssh: credential protection did not admit the submission") // ErrMethodNotOffered: the server does not offer a method for this // secret. ErrMethodNotOffered = errors.New("ssh: the server does not offer a method for this secret") // ErrUnsupportedExchange: the server asked for a login exchange outside // the supported profile: a keyboard-interactive round other than one // hidden prompt, or a further step after a partial success. ErrUnsupportedExchange = errors.New("ssh: the server requires an unsupported login exchange") // ErrNotRecorded: the outcome could not be recorded. The reservation // is left to expire, which records unknown and keeps the slot held. ErrNotRecorded = errors.New("ssh: the authentication outcome could not be recorded") )
Protected-dial errors. Each means nothing further was sent.
var ( ErrWeakKey = sshkey.ErrWeakKey ErrInvalidKey = sshkey.ErrInvalidKey )
Key-validation errors. The parser and strength check live in internal/sshkey, shared with the credential store; these are the same values, so errors.Is works with either name.
var ErrSudoProfile = errors.New("ssh: password sudo needs a validated single-attempt profile")
ErrSudoProfile means the invocation has no valid single-attempt profile.
Functions ¶
func Dial ¶
func Dial(ctx context.Context, host string, port int, cred *credential.Credential, opts DialOptions) (*ssh.Client, error)
Dial opens an SSH connection to host:port using cred. On success returns a live *ssh.Client; caller must Close it. On failure returns a sentinel error from the package's error set (never raw network or crypto errors that might leak credential material).
The TCP connect AND the SSH handshake are both bounded by min(ctx deadline, opts.Timeout), and canceling ctx aborts either. crypto/ssh's ClientConfig.Timeout covers only the TCP dial inside ssh.Dial, not ssh.NewClientConn, so the handshake is bounded here by closing the connection when that bound passes.
Spec AC-01, AC-02, AC-03, AC-04, AC-06, AC-07, AC-08, AC-09, AC-19, C-01, C-03.
func DialConn ¶ added in v0.8.5
func DialConn(ctx context.Context, conn net.Conn, host string, cred *credential.Credential, opts DialOptions) (*ssh.Client, error)
DialConn runs the SSH handshake for cred over an already-connected conn, with the same bounds, host-key policy and auth ordering as Dial. It takes ownership of conn: on failure conn is closed. host names the server for host-key verification. Spec AC-19.
func RunSudo ¶
func RunSudo( ctx context.Context, sess SudoSession, cred *credential.Credential, policy SudoPolicy, prefer string, cmd string, ) (stdout []byte, exitCode int, usedFallback bool, observed string, err error)
RunSudo executes `cmd` as root via sudo. The pipeline is:
- Always try `sudo -n <cmd>` first. NOPASSWD hosts return exit 0 here and the function returns immediately. The credential password is NOT touched.
- If `sudo -n` returns non-zero AND all of the following hold — - policy.AllowCredentialPassword is true, - cred is non-nil, - cred.AuthMethod is "password" or "both", - cred.Password is non-empty — re-execute as `sudo -S -k -p ” <cmd>` with the password fed via the session's stdin pipe. `-k` invalidates the remote sudo credential cache before each attempt. This does not bound PAM failures; consumers move to ProtectedSudo in OW-122 slice 6.
prefer (a Sudo* token, or "" for unknown) is the host's learned sudo mode: when it is SudoPassword AND the credential can supply a password, RunSudo leads with `sudo -S` and skips the doomed `sudo -n` round-trip. Both forms are still attempted on a miss (a hint, not a lock), so a stale preference self-heals.
Returns the final stdout, the final exit code, a bool indicating whether the password fallback was used (callers aggregate this for the per-cycle audit emission), the sudo mode OBSERVED to work this call (a Sudo* token, or "" when neither form was confirmed), and any transport error. observed is set ONLY on a confirmed exit-0 of a given form — a real command that exits non-zero for its own reasons never produces a (mis)observation, so callers can safely record it.
Source-inspection-friendly: the password is taken from cred.Password and passed as the `stdin` argument of RunWithStdin. It does NOT appear in the `cmd` string anywhere — see ssh_test.go AC-15.
Spec: system-ssh-connectivity v1.1.0 C-09 / C-10 / C-11 / C-12, AC-11..AC-17; system-connection-profile v1.2.0 C-07 (sudo-mode learning).
func ValidateAuthKey ¶
ValidateAuthKey parses an OpenSSH-format private key (PEM) and applies the NIST SP 800-57 strength check. Returns:
- ErrInvalidKey if the PEM is unparseable
- ErrWeakKey if the key is below the minimum strength for its algorithm
- nil if the key is acceptable for use with a Dial
Spec AC-05, AC-10, C-02.
Types ¶
type AuthReport ¶ added in v0.8.5
type AuthReport struct {
Attempts []MethodAttempt
// Outcomes holds an entry for every secret the credential carries,
// keyed by SecretKindPassword or SecretKindKey.
Outcomes map[string]OutcomeKind
}
AuthReport is the evidence of one dial and the outcome it supports for each secret the credential holds. Fill it by passing DialOptions.Report; Dial sets it however the dial ends.
type DialOptions ¶
type DialOptions struct {
Mode Mode
Store KnownHostsStore
Timeout time.Duration
// PreferAuth, when "key" or "password", offers that auth method
// FIRST (the other is still offered as fallback). Empty preserves the
// historical key-first order. Callers set this from the host's
// recorded connection profile to avoid a doomed publickey attempt on
// a password-only host (which counts against MaxAuthTries / trips
// fail2ban).
PreferAuth string
// ObservedAuth, when non-nil, receives the auth method that actually
// authenticated ("key" | "password") after a successful dial. Callers
// persist it so the next connection leads with it. Untouched on dial
// failure.
ObservedAuth *string
// Report, when non-nil, receives the evidence of the dial and the
// outcome it supports for each of the credential's secrets, however
// the dial ends (spec C-14). The returned error is unchanged by it.
Report *AuthReport
}
DialOptions configures one Dial. Mode + Store cover host-key verification; Timeout bounds the connect+handshake.
type KnownHostsStore ¶
type KnownHostsStore interface {
// Get returns the stored marshalled public key for hostname, or
// (nil, false) if no entry exists.
Get(hostname string) ([]byte, bool)
// Put stores the marshalled public key for hostname. Idempotent for
// the same key; should reject (or signal upward via error) if the
// caller tries to overwrite a different key — the caller decides
// whether that's allowed, not the store.
Put(hostname string, marshalled []byte) error
}
KnownHostsStore persists (hostname → public-key fingerprint). The in-memory implementation is the default; production deploys can drop in a PG-backed store later by satisfying the same interface.
type MemoryStore ¶
type MemoryStore struct {
// contains filtered or unexported fields
}
MemoryStore is an in-memory KnownHostsStore. Goroutine-safe.
func NewMemoryStore ¶
func NewMemoryStore() *MemoryStore
NewMemoryStore constructs an empty MemoryStore.
type MethodAttempt ¶ added in v0.8.5
type MethodAttempt struct {
Method string // "none", "publickey", "password" or "keyboard-interactive"
// Secret is the kind of secret the method sent, or "" if it sent none.
Secret string
// Submissions counts how many times the secret was sent in this
// method: one for publickey and password, one per hidden prompt for
// keyboard-interactive.
Submissions int
Result MethodResult
// Unsupported: keyboard-interactive asked for something outside the
// supported profile.
Unsupported bool
}
MethodAttempt is one authentication method the client ran.
type MethodResult ¶ added in v0.8.5
type MethodResult string
MethodResult is what happened to one authentication method.
const ( ResultAccepted MethodResult = "accepted" // USERAUTH_SUCCESS ResultPartial MethodResult = "partial" // USERAUTH_FAILURE with partial success // ResultEnded: the method ended without success over an intact // connection. The server answered USERAUTH_FAILURE or something else // crypto/ssh does not accept; the client cannot tell which. ResultEnded MethodResult = "ended" ResultNoAnswer MethodResult = "no_answer" // the method ended without an answer the client could see )
type Mode ¶
type Mode int
Mode controls how the dial layer treats a server's host key.
const ( // ModeStrict requires the server's host key to be in the known-hosts // store before the connection succeeds. Reject unknown. ModeStrict Mode = iota // ModeTOFU (trust-on-first-use) records the first key it sees for a // hostname; subsequent connections behave like Strict against that // stored key. A different key from the same hostname returns // ErrHostKeyMismatch. ModeTOFU )
type OutcomeKind ¶ added in v0.8.5
type OutcomeKind string
OutcomeKind is what one dial established about one secret.
const ( // OutcomeVerified: the server accepted a method that carried the // secret: USERAUTH_SUCCESS, or USERAUTH_FAILURE with partial success. // A partial success accepts the secret, not the login (RFC 4252 // section 5.1): the dial still fails, and its report keeps // ResultPartial. It is not a usable connection, and later slices must // not take it alone as grounds for recovery. OutcomeVerified OutcomeKind = "verified" // OutcomeUnsuccessful: a method sent the secret and ended without // success over a connection still intact, but what the server // answered is not established. crypto/ssh's client treats // USERAUTH_FAILURE and an unexpected reply (for example // SSH_MSG_USERAUTH_PASSWD_CHANGEREQ, RFC 4252 section 8) alike and // does not say which it saw, so this classifier never reports a // rejection for SSH. OutcomeUnsuccessful OutcomeKind = "unsuccessful" // OutcomeAmbiguous: the secret was sent and no answer to it was // observed. The connection failed, the server disconnected, or the // dial timed out during user authentication. OutcomeAmbiguous OutcomeKind = "ambiguous" // OutcomeUnsupportedProfile: a keyboard-interactive exchange left the // supported profile: across the whole exchange, at most one hidden // prompt, which the password answers, and no visible prompt. // Prompt-free rounds are information. A further hidden prompt is // outside the profile, whatever it asks: its count or wording cannot // show that the password was refused. OutcomeUnsupportedProfile OutcomeKind = "unsupported_profile" // OutcomeNotSubmitted: the secret was never sent. The server did not // offer a method for it, or the dial ended before user authentication. OutcomeNotSubmitted OutcomeKind = "not_submitted" // OutcomeLocalDecryptFailed: the private key could not be decrypted // with the stored passphrase, so nothing was sent. OutcomeLocalDecryptFailed OutcomeKind = "local_decrypt_failed" )
type ProtectedOptions ¶ added in v0.8.5
type ProtectedOptions struct {
Mode Mode
Store KnownHostsStore
Timeout time.Duration
Protection Protection
CredentialID uuid.UUID
HostID uuid.UUID
// Secret is the one secret this dial submits: SecretKindPassword or
// SecretKindKey. A key that fails never falls through to the password;
// a password attempt is a dial of its own.
Secret string
// Keyring identifies a password: the loaded fingerprint.Keyring.
// Required when Secret is a password.
Keyring credprotect.PasswordKeyring
// PasswordMethod is the host's learned password method,
// MethodPassword or MethodKeyboardInteractive. It is tried first when
// the server offers it; otherwise the other one is, if offered. Empty
// on first contact, which prefers MethodPassword.
PasswordMethod string
// Kind is the submission's kind; empty means credprotect.KindOrdinary.
Kind credprotect.Kind
// Owner holds the reservation; empty means this process.
Owner credprotect.Owner
// TTL is the reservation's lifetime; zero means Timeout plus
// DefaultReservationMargin. It never ends before the dial's bound.
TTL time.Duration
// Current reads the credential again through db, the fence's own
// transaction, for example with credential.GetByIDWith. The fence
// calls it under its lock on the credential row, and refuses unless
// the record is active, still has this username, and still holds the
// secret being sent. Reading through anything but db would take a
// second connection while the fence holds one.
Current func(ctx context.Context, db credprotect.Reader) (*credential.Credential, error)
}
ProtectedOptions configures one protected dial.
type ProtectedResult ¶ added in v0.8.5
type ProtectedResult struct {
// Reserved: a submission was reserved. If false, nothing was sent and
// nothing was recorded.
Reserved bool
Submission uuid.UUID
// Method is the method that carried the secret, or "" if none did.
Method string
// Outcome is the outcome settled, or would have been had ErrNotRecorded
// not occurred. Empty when nothing was reserved.
Outcome credprotect.Outcome
Settled credprotect.Result
Report AuthReport
}
ProtectedResult is what a protected dial reserved, sent and recorded.
func ProtectedDial ¶ added in v0.8.5
func ProtectedDial(ctx context.Context, host string, port int, cred *credential.Credential, opts ProtectedOptions) (*ssh.Client, ProtectedResult, error)
ProtectedDial dials host:port and submits one of cred's secrets under credential protection. On success it returns a live client, which the caller must close. Every reserved submission is settled before it returns; if settlement fails, the client is closed and the error wraps ErrNotRecorded.
Spec C-15.
type ProtectedSudoMode ¶ added in v0.8.5
type ProtectedSudoMode string
ProtectedSudoMode selects execution before any remote command starts.
const ( // SudoCachedOnly sends no password and never falls back. SudoCachedOnly ProtectedSudoMode = "cached" // SudoPasswordOnly reserves one password invocation, without fallback. SudoPasswordOnly ProtectedSudoMode = "password" // SudoReadOnlyFallback permits fallback only before the command has started. SudoReadOnlyFallback ProtectedSudoMode = "read_only" // SudoVerifyPassword checks a fresh password without running a command. SudoVerifyPassword ProtectedSudoMode = "verify" )
type ProtectedSudoOptions ¶ added in v0.8.5
type ProtectedSudoOptions struct {
Mode ProtectedSudoMode
Auth ProtectedOptions
Profile *ValidatedSudoProfile
Timeout time.Duration
// CaptureLimit bounds each output stream. Zero selects one MiB.
CaptureLimit int
}
ProtectedSudoOptions configures one invocation. Auth supplies the same reservation, keyring and transaction-bound Current reader as ProtectedDial. Password modes share SSH's password protection state; Stage is attribution.
type Protection ¶ added in v0.8.5
type Protection interface {
Reserve(ctx context.Context, r credprotect.Request) (credprotect.Submission, error)
// Fence calls read under its own lock on the credential, on its own
// transaction, so the credential it checks is the one as it stands at
// the fence.
Fence(ctx context.Context, id uuid.UUID, read func(context.Context, credprotect.Reader) (credprotect.Current, error)) error
Settle(ctx context.Context, id uuid.UUID, outcome credprotect.Outcome) (credprotect.Result, error)
}
Protection is the part of credential protection a protected dial uses. *credprotect.Store implements it.
type SudoPolicy ¶
type SudoPolicy struct {
AllowCredentialPassword bool
}
SudoPolicy lets the caller (collector / discovery) inject the system policy without importing the systemconfig package. Keeps this dial- layer file policy-agnostic and trivially testable.
AllowCredentialPassword corresponds to systemconfig.SecurityConfig.AllowCredentialSudoPassword. Set to false for the v1.0.0-compatible "sudo -n only" behavior.
type SudoResult ¶ added in v0.8.5
type SudoResult struct {
Stdout []byte
Stderr []byte
ExitCode int
Complete bool
CommandStarted bool
PromptSeen bool
Submitted bool
Attempt ProtectedResult
}
SudoResult separates command execution, password submission and protection. Output may be truncated; incomplete capture never permits fallback or recovery. There are no password or fingerprint fields in the result.
func ProtectedSudo ¶ added in v0.8.5
func ProtectedSudo(ctx context.Context, client *cryptossh.Client, cred *credential.Credential, command string, opts ProtectedSudoOptions) (SudoResult, error)
ProtectedSudo executes on an established SSH connection. The caller must give it exclusive use of that connection for the call: cancellation, refusal during authentication, and failed settlement close it. Ordinary command failures do not retry. No production consumer uses this adapter yet.
type SudoSession ¶
type SudoSession interface {
// Run is the no-stdin path. Used for the initial `sudo -n` attempt
// (NOPASSWD: never needs a password) and for any command that is
// not gated on sudo.
Run(ctx context.Context, cmd string) (stdout []byte, exitCode int, err error)
// RunWithStdin is the password-fallback path. The caller passes the
// credential password as the stdin payload — never as part of cmd.
// Implementations MUST send `stdin` to the remote process's stdin
// and close the pipe before returning.
RunWithStdin(ctx context.Context, cmd string, stdin []byte) (stdout []byte, exitCode int, err error)
}
SudoSession is the subset of an SSH session that RunSudo needs. The stdin pipe path is the security-critical method: it lets RunSudo deliver the credential password to sudo without putting it in the remote process argv.
Both collector.SSHSession and discovery.SSHSession satisfy this interface once their RunWithStdin methods are added.
type ValidatedSudoProfile ¶ added in v0.8.5
type ValidatedSudoProfile struct {
HostID uuid.UUID
Username string
// Command is empty for verification, otherwise the exact command string.
Command string
EvidenceID string
ExpiresAt time.Time
PasswordTries int
MaxPAMFailures int
InvokingUser bool
}
ValidatedSudoProfile is trusted configuration for this exact invocation. It must come from policy validation, never from a login or a caller's guess. Slice 6 supplies it; this adapter does not discover or change sudoers. Evidence must cover sudoers, PAM, the invoking account, and this command. A profile is invalid after any change to those inputs, even before expiry. One submission does not imply one PAM failure on an unvalidated host.