Documentation
¶
Overview ¶
Package sshlogin is the login that Remote Work (SPEC §10.18) uses: an SSH server for the machine that is controlled (A), and an SSH client for the machine that controls (B), built on golang.org/x/crypto/ssh.
The server lets in the public keys of a list and nothing else: there is no password, no keyboard-interactive and no "none" login; the keys are compared by their wire bytes; the only thing an authenticated client may do is open one channel of the type the server was made for, and every other channel type, every request on the channel, and every global request is refused; the handshake, the wait for the channel and the number of unauthenticated connections are bounded; and failed attempts are rate-limited by address (5 a minute) before any work for a connection is done. The host key is an Ed25519 key made the first time and kept with mode 0600.
The client proves itself with a key file in OpenSSH format (a passphrase asked through a function, which is never stored) or with the keys of an ssh-agent, whose socket the caller names; it never reads ~/.ssh or the environment itself. The host key of the server is pinned on first use in a file of the caller's (remote-work-hosts.json), and a key that changed is refused.
Index ¶
- Constants
- func AddressKey(addr net.Addr) string
- func AgentKeys(ctx context.Context, socket string) ([]ssh.PublicKey, error)
- func AgentSocket(getenv func(string) string) string
- func HostOf(addr string) string
- func LoadOrCreateHostKey(path string) (ssh.Signer, error)
- func NormalizeAddress(addr string) (string, error)
- func PublicKeyOfKeyFile(path string, ask PassphraseFunc) (ssh.PublicKey, error)
- func ReadPublicKeyFile(path string) (string, error)
- func RefusalWords(r Refusal) string
- func SameKey(a, b ssh.PublicKey) bool
- type AllowedKey
- type Auth
- type Client
- type ConfirmHostFunc
- type DialOptions
- type FirstUse
- type HostKeys
- type HostStore
- type Limiter
- type LimiterOptions
- type Login
- type PassphraseFunc
- type Pinned
- type Refusal
- type Server
- type ServerOptions
- type Session
- type Throttle
- type Verdict
Constants ¶
const ( MaxKeyLine = 8 << 10 MaxCommentRunes = 128 )
MaxKeyLine is the longest authorized_keys line ParseAuthorizedKey takes, and MaxCommentRunes the longest comment it keeps.
const ( // ReasonKeyNotListed is a public key that is not in the list (or was taken out of it). ReasonKeyNotListed = "KeyNotListed" // ReasonKeyRefused is a public key attempt that failed for another reason (an algorithm the server does not take). ReasonKeyRefused = "KeyRefused" // ReasonPasswordRefused is a password login; the server has none. ReasonPasswordRefused = "PasswordRefused" // ReasonMethodRefused is any other login method (keyboard-interactive, host based, GSSAPI). ReasonMethodRefused = "MethodRefused" // ReasonHandshakeFailed is a connection that ended or timed out before it tried to authenticate, or whose signature was wrong. ReasonHandshakeFailed = "HandshakeFailed" // ReasonRateLimited is a connection from an address that had too many failures. ReasonRateLimited = "RateLimited" // ReasonChannelType is a channel of a type the server does not offer. ReasonChannelType = "ChannelType" // ReasonRequest is a request on the channel (shell, exec, pty-req, env, subsystem, forwarding); there are none to serve. ReasonRequest = "Request" // ReasonNoChannel is a logged-in client that opened no channel in time. ReasonNoChannel = "NoChannel" // ReasonTooManyPending is a connection refused because too many were still logging in. ReasonTooManyPending = "TooManyPending" )
The reasons a login attempt or a request was refused (Refusal.Reason).
const DefaultUser = "emetos"
DefaultUser is the user name a client logs in with: the server ignores it and the keys decide.
const MaxChannelData = 256
MaxChannelData is the most bytes a client may send when it opens the channel.
const MaxPassphraseTries = 3
MaxPassphraseTries is how many passphrases KeyFileAuth asks for before it gives up.
const MinRSABits = 2048
MinRSABits is the smallest RSA key a login accepts.
const NoticeThrottle = time.Minute
NoticeThrottle is how often one address may raise a notification of a refused attempt.
Variables ¶
This section is empty.
Functions ¶
func AddressKey ¶
AddressKey is the key the limiter counts an address under: the IP of a network address without its port, an IPv6 address cut to its /64, an IPv4-mapped IPv6 address as the IPv4 one. An address that is not an IP is used as it is.
func AgentKeys ¶
AgentKeys lists the public keys of the ssh-agent at the socket, for the user to choose one. It fails like AgentAuth.
func AgentSocket ¶
AgentSocket is the socket of the ssh-agent the process runs under: the value of SSH_AUTH_SOCK, which the caller reads from the environment and gives as getenv (os.Getenv in the editor, a fake in a test). It is empty when there is none.
func LoadOrCreateHostKey ¶
LoadOrCreateHostKey returns the Ed25519 host key kept at path (an OpenSSH private key). When the file does not exist a new key is made and written there with mode 0600, in a folder of mode 0700. An existing file that other users can read or change, that is not a regular file, that is too large or is not an Ed25519 key in OpenSSH format is refused and never replaced. The errors have the tags SSHLoginHostKeyInvalid, SSHLoginHostKeyCreateFailed and those of statefile.Read.
func NormalizeAddress ¶
NormalizeAddress makes host:port with the host in lower case, the key of a pin; a port is required. It fails with SSHLoginAddressInvalid.
func PublicKeyOfKeyFile ¶
func PublicKeyOfKeyFile(path string, ask PassphraseFunc) (ssh.PublicKey, error)
PublicKeyOfKeyFile reads the public half of the private key at path, for the user to show (Show My Public Key as QR Code). A key in OpenSSH format keeps its public key in the clear in front of the private part, so the public key is read from there and no passphrase is needed, whether the key has one or not; the private part of the file is not parsed. Another format (PEM) has no public part to read: the key is parsed as KeyFileAuth parses it, asking ask for the passphrase when it has one, and only the public key is kept. The file is read with the limits of KeyFileAuth (at most 64 KiB) and its bytes are overwritten when done. It fails with the tags of KeyFileAuth (SSHLoginKeyFileUnreadable, SSHLoginKeyFileInvalid, SSHLoginPassphraseRequired, SSHLoginPassphraseCancelled, SSHLoginWrongPassphrase).
func ReadPublicKeyFile ¶
ReadPublicKeyFile reads the text of a public key file (the "Choose .pub File" of Remote Work): a small regular file. The line still has to be parsed with ParseAuthorizedKey, which refuses what is not a single public key. The errors have the tags SSHLoginPubFileUnreadable (the cause is kept) and SSHLoginPubFileInvalid (not a regular file, or larger than 16 KiB).
func RefusalWords ¶
RefusalWords says a refusal to the user, for the notification "<Extension> refused a login from <ip>: <words>.".
Types ¶
type AllowedKey ¶
type AllowedKey struct {
// Key is the public key.
Key ssh.PublicKey
// Comment is the comment of the line, without control characters and cut to MaxCommentRunes; may be empty.
Comment string
}
AllowedKey is a public key that may log in: the key and the comment of its authorized_keys line.
func ParseAuthorizedKey ¶
func ParseAuthorizedKey(line string) (AllowedKey, error)
ParseAuthorizedKey reads one line of an authorized_keys file: a public key and an optional comment. A line with options (command=, from=, restrict, ...) is refused, because the options would not be applied; so are several lines, an empty or comment line, a certificate, a type that is not Ed25519, ECDSA, RSA of at least 2048 bits or a security key, and a line longer than MaxKeyLine. The errors have the tags SSHLoginKeyLineInvalid and SSHLoginKeyUnsupported.
func (AllowedKey) Equal ¶
func (k AllowedKey) Equal(other ssh.PublicKey) bool
Equal tells whether the keys are the same key (their wire encodings are equal).
func (AllowedKey) Fingerprint ¶
func (k AllowedKey) Fingerprint() string
Fingerprint is the SHA-256 fingerprint of the key in the form of ssh-keygen (SHA256:base64).
func (AllowedKey) Line ¶
func (k AllowedKey) Line() string
Line is the authorized_keys line of the key: type, base64 and the comment when there is one.
func (AllowedKey) Name ¶
func (k AllowedKey) Name() string
Name is what a banner or a notification calls the key: its comment, or its fingerprint when it has none.
func (AllowedKey) Type ¶
func (k AllowedKey) Type() string
Type is the name of the key's algorithm (ssh-ed25519).
type Auth ¶
type Auth struct {
// PublicKey is the public half of the first key, to show to the user (Show My Public Key as QR Code) or to list.
PublicKey ssh.PublicKey
// contains filtered or unexported fields
}
Auth is how a client proves who it is: the signers of a key file, or the keys of an ssh-agent. Close it after the connection is made (an agent's socket stays open until then).
func AgentAuth ¶
AgentAuth connects to the ssh-agent at the socket and returns the Auth of its keys. With a fingerprint (SHA256:...) only that key is used, so a client with many keys does not offer them all; without one every key of the agent is offered, in the agent's order. Close the Auth when the connection is made. The errors have the tags SSHLoginAgentUnavailable (no socket, or no agent behind it), SSHLoginAgentFailed (the agent did not list its keys) and SSHLoginAgentNoKey (it has no key, or not the one asked for).
func KeyFileAuth ¶
func KeyFileAuth(path string, ask PassphraseFunc) (*Auth, error)
KeyFileAuth reads the private key at path (OpenSSH or PEM format, at most 64 KiB) and returns the Auth for it. A key with a passphrase asks ask for it, up to MaxPassphraseTries times. The errors have the tags SSHLoginKeyFileUnreadable, SSHLoginKeyFileInvalid, SSHLoginPassphraseRequired (the key has a passphrase and ask is nil), SSHLoginPassphraseCancelled and SSHLoginWrongPassphrase.
func SignerAuth ¶
SignerAuth is the Auth of signers already in memory (a key made by a test).
type Client ¶
type Client struct {
// HostFingerprint is the fingerprint of the host key the connection was made to.
HostFingerprint string
// contains filtered or unexported fields
}
Client is a connection that logged in.
func Dial ¶
func Dial(ctx context.Context, o DialOptions) (*Client, error)
Dial connects to a host and logs in with the key of the Auth. The key of the host must be the one pinned for the address. On first use (nothing pinned) the connection is dropped before any login, the user is asked through ConfirmHost, the key is pinned when the answer is yes, and the connection is made again, so the user may take as long as needed and the host never waits for a person. A key that differs from the pinned one is refused with SSHLoginHostKeyChanged, whose metadata has both fingerprints; nothing is sent to such a host. The errors have the tags SSHLoginAddressInvalid, SSHLoginDialInvalid, SSHLoginHostKeyChanged, SSHLoginHostKeyRejected, SSHLoginHostKeyUnknown, SSHLoginConfirmFailed, SSHLoginAuthFailed and SSHLoginConnectFailed, and those of HostStore.
func (*Client) OpenChannel ¶
OpenChannel opens the channel of the type, with data as its open message. The server's refusal has the tag SSHLoginChannelRefused. The requests of the server on the channel are discarded.
type ConfirmHostFunc ¶
ConfirmHostFunc asks the user whether to trust a host on first use. It runs on the goroutine that dials, with no connection open, and may take as long as the user needs. true pins the key.
type DialOptions ¶
type DialOptions struct {
// Address is host:port.
Address string
// User is the user name; DefaultUser when empty.
User string
// Auth proves who the client is.
Auth *Auth
// Hosts pins the host keys.
Hosts HostKeys
// ConfirmHost is asked on first use; a nil function refuses an unknown host.
ConfirmHost ConfirmHostFunc
// HandshakeTimeout is how long the connection and the login may take, the question to the user not counted (15 s).
HandshakeTimeout time.Duration
}
DialOptions are what Dial needs.
type FirstUse ¶
type FirstUse struct {
// Address is host:port as the user typed it.
Address string
// Type is the algorithm of the host key and Fingerprint its SHA-256 fingerprint (SHA256:base64).
Type string
Fingerprint string
}
FirstUse is what the user is shown the first time a client meets a host: the fingerprint to compare with the one the host's page shows.
type HostKeys ¶
type HostKeys interface {
// Check compares the key a server showed with the one pinned for the address.
Check(addr string, key ssh.PublicKey) (Verdict, Pinned, error)
// Pin trusts the key for the address from now on.
Pin(addr string, key ssh.PublicKey) error
}
HostKeys is what a client needs of its store of pinned host keys: *HostStore, or a fake in a test.
type HostStore ¶
type HostStore struct {
// contains filtered or unexported fields
}
HostStore keeps the pinned host keys of a client in a JSON file (remote-work-hosts.json), as known_hosts does. The file is written atomically with mode 0600 and read only when nobody else can change it. Every call reads the file again, so the store never trusts a copy in memory; the calls of one store are serialized (two processes that pin at the same moment may lose one pin, which the next connection makes again). Safe for concurrent use.
func NewHostStore ¶
NewHostStore makes the store of the file at path; now is the clock of the first-seen times (time.Now when nil).
func (*HostStore) Check ¶
Check compares the key a server showed with the one pinned for the address. For HostChanged it returns the pinned entry as well, so the warning can show both fingerprints. The errors have the tags of statefile.Read, SSHLoginHostsFileInvalid and SSHLoginAddressInvalid.
func (*HostStore) Forget ¶
Forget removes the pin of the address, so that the next connection is a first use again. It is what the user chooses after a changed key was explained (a server that was installed anew); nothing calls it by itself.
type Limiter ¶
type Limiter struct {
// contains filtered or unexported fields
}
Limiter counts the failed login attempts of each address in a sliding window and says when an address has had too many (5 a minute by default). It is bounded: it keeps at most MaxAddresses addresses, each with at most Failures times, and forgets an address when its last failure is older than the window. An IPv6 address counts as its /64. Its clock is given, so a test moves time by hand. It is safe for concurrent use.
func (*Limiter) Blocked ¶
Blocked tells whether the address has had Failures failed attempts in the last Window. first is true for the first call that sees a block in a window, so that the caller logs and announces it once and not at every refused connection.
type LimiterOptions ¶
type LimiterOptions struct {
// Failures is how many failed attempts in the Window block an address (5).
Failures int
// Window is how long a failure counts (one minute).
Window time.Duration
// MaxAddresses bounds the memory: at most this many addresses are kept, and the one whose last failure is oldest is
// forgotten for a new one (4096).
MaxAddresses int
// Now is the clock; time.Now when nil.
Now func() time.Time
}
LimiterOptions are the options of NewLimiter; a zero field takes its default.
type Login ¶
type Login struct {
// Remote is the address of the client, with its port.
Remote string
// User is the user name the client gave.
User string
// Key is the key that logged in.
Key AllowedKey
// At is when it happened.
At time.Time
}
Login is a client that logged in.
type PassphraseFunc ¶
PassphraseFunc asks for the passphrase of a key file. attempt counts from 1 (so the dialog can say the last one was wrong). ok is false when the user cancelled. The function owns the bytes it returns until KeyFileAuth is done with them: KeyFileAuth overwrites them as soon as the key is parsed, and neither stores nor logs them.
type Pinned ¶
type Pinned struct {
// Address is host:port, with the host in lower case.
Address string
// Type is the algorithm of the key (ssh-ed25519) and Fingerprint its SHA-256 fingerprint (SHA256:base64).
Type string
Fingerprint string
// Key is the key.
Key ssh.PublicKey
// FirstSeen is when the user accepted it.
FirstSeen time.Time
}
Pinned is the host key that a client trusts for an address.
type Refusal ¶
type Refusal struct {
// Remote is the address of the client, with its port.
Remote string
// Address is the address the limiter counts it under (the IP).
Address string
// User is the user name the client gave; it means nothing to the server and is shown to tell attempts apart. May be empty.
User string
// Method is the login method ("publickey", "password"), or empty.
Method string
// KeyFingerprint is the fingerprint of the public key that was offered, or empty.
KeyFingerprint string
// Reason is one of the Reason constants.
Reason string
// Detail says more: the channel type or request type refused.
Detail string
// At is when it happened.
At time.Time
}
Refusal is a login attempt or a request that the server refused.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is the SSH server of the machine that is controlled. Make one with NewServer and give it a listener with Serve.
func NewServer ¶
func NewServer(opts ServerOptions) (*Server, error)
NewServer makes a server. It fails with SSHLoginServerInvalid when the host key, the channel type, the list of keys or the handler is missing.
type ServerOptions ¶
type ServerOptions struct {
// HostKey is the host key of the server (LoadOrCreateHostKey).
HostKey ssh.Signer
// ChannelType is the one channel type the server offers (emetos-remotework); every other type is refused.
ChannelType string
// Keys returns the keys that may log in, read at each attempt, so a key taken out of the list stops working at once.
Keys func() []AllowedKey
// Handler serves a session. It runs on a goroutine of its own, and when it returns the connection is closed.
Handler func(*Session)
// OnLogin and OnRefused are told of every login and every refusal; either may be nil. They run on the goroutines of the
// server and must not block.
OnLogin func(Login)
OnRefused func(Refusal)
// Logger gets a line for every login and every refusal; slog.Default() when nil.
Logger *slog.Logger
// Limiter counts the failed attempts of each address; NewLimiter(LimiterOptions{}) when nil.
Limiter *Limiter
// Now is the clock of the events; time.Now when nil. The deadlines are of the real clock.
Now func() time.Time
// HandshakeTimeout is how long a connection has to finish logging in (10 s), ChannelTimeout how long a client that logged
// in has to open the channel (10 s), and MaxPending how many connections may be logging in at once (16).
HandshakeTimeout time.Duration
ChannelTimeout time.Duration
MaxPending int
// MaxAuthTries is how many failed attempts one connection may make (5).
MaxAuthTries int
}
ServerOptions are what NewServer needs.
type Session ¶
type Session struct {
// Key is the key the client logged in with.
Key AllowedKey
// Remote is the address of the client.
Remote net.Addr
// User is the user name the client gave.
User string
// ExtraData is what the client sent when it opened the channel (at most MaxChannelData bytes).
ExtraData []byte
// Channel is the channel; the handler reads and writes it.
Channel ssh.Channel
// contains filtered or unexported fields
}
Session is a client that logged in and opened the channel the server offers.
type Throttle ¶
type Throttle struct {
// contains filtered or unexported fields
}
Throttle lets one notification through for each address a minute (SPEC §10.18 "As built (step 15.2)"): the extensions that listen use it for the notifications of refused attempts, so a scanner cannot flood the user. The block of an address is a notification of its own. It remembers at most 256 addresses. Its methods are safe for concurrent use.
func (*Throttle) Notice ¶
Notice tells whether a notification of the refusal should be raised at now, and counts it when it should. A connection that ended before it tried to log in (ReasonHandshakeFailed) is in the log and counts for the rate limit but is never a notification: it is also what a client does on its first use, while its user compares the fingerprint.