Add an ssh client to Terminal, as an alternative to (or tunnel for) g2mirror

This commit is contained in:
James Babcock committed 2026-11-16 01:41:12 -08:00
1 parent ab692741f7
commit 2b75a9d66e
33 files changed
+4694 -99

No files matched your search

+43
View File
@@ -0,0 +1,43 @@
# Faceclaw SSH transport
The Terminal app's SSH client: a small Go package over
[golang.org/x/crypto/ssh](https://pkg.go.dev/golang.org/x/crypto/ssh), bound
into the apps with gomobile. It provides text-message channels over SSH:
- **exec**: run a command on the host, exchanging newline-delimited text
(used for tmux control mode and the tmux session poller; see
`app/apps/terminal/tmux-client.ts`).
- **websocket**: a WebSocket to an address as seen from the host, through a
`direct-tcpip` channel (used to tunnel g2mirror-server's protocol).
Channels to the same host and credentials share one SSH connection, with a
keepalive that fails them promptly when the peer silently disappears. Host
keys are pinned by the app (first connection reports the presented key so
the user can verify its fingerprint). Authentication uses a non-exportable
ECDSA P-256 key held by the platform keystore (Android Keystore/StrongBox,
iOS Secure Enclave; see `FaceclawSsh.kt` / `FaceclawSsh.m`) and, if the
server allows it, a password saved encrypted on the phone.
## Building
`scripts/go-ssh-build.cjs` runs `gomobile bind` (pinned in `go.mod`'s tool
block) from the NativeScript before-prepare hook and stages
`faceclaw-ssh.aar` / `Faceclawssh.xcframework` into the local
`@faceclaw/kotlin` plugin. It needs Go 1.26+ on PATH, plus the Android NDK
(Android) or Xcode (iOS); a content stamp skips rebuilds when the Go sources
haven't changed.
## Testing
`go test -race ./...` runs the transport against an in-process SSH server
(host-key pinning, password and keyboard-interactive auth, key auth through
a fake platform signer, exec framing, the websocket tunnel, connection
sharing and loss).
## Keeping it current
x/crypto/ssh is the security boundary against a malicious host or a
man in the middle; update it promptly when advisories appear
(`go get golang.org/x/crypto@latest && go mod tidy`). A Go panic in any
goroutine terminates the app: the package recovers in the goroutines it
owns, but not inside the library's own.
+254
View File
@@ -0,0 +1,254 @@
package faceclawssh
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"net"
"net/url"
"strings"
"time"
"unicode/utf8"
"github.com/gorilla/websocket"
"golang.org/x/crypto/ssh"
)
type closedPayload struct {
ExitStatus *int `json:"exitStatus,omitempty"`
Signal string `json:"signal,omitempty"`
Code *int `json:"code,omitempty"`
Reason string `json:"reason,omitempty"`
}
// runExec runs command on the host and relays newline-delimited text both
// ways until the command exits, the connection drops, or Close.
func (c *Channel) runExec(conn *pooledConn, command string) {
session, err := conn.client.NewSession()
if err != nil {
c.fail(channelOpenFailure(conn, err))
return
}
defer session.Close()
stdin, err1 := session.StdinPipe()
stdout, err2 := session.StdoutPipe()
stderr, err3 := session.StderrPipe()
if err := errors.Join(err1, err2, err3); err != nil {
c.fail(&failure{Kind: "channel", Message: err.Error()})
return
}
if err := session.Start(command); err != nil {
c.fail(&failure{Kind: "channel", Message: "could not run command: " + err.Error()})
return
}
go func() {
<-c.ctx.Done()
session.Close()
}()
c.markOpen()
go func() {
defer c.guard()
for text := range c.sendQ {
if _, err := io.WriteString(stdin, text+"\n"); err != nil {
return
}
}
// Close was called and the queue has drained: EOF tells the command
// we're done (tmux control mode detaches on it).
stdin.Close()
}()
stderrDone := make(chan struct{})
go func() {
defer close(stderrDone)
defer c.guard()
readLines(stderr, func(line string) { c.emit("stderr", line) })
}()
readErr := readLines(stdout, func(line string) { c.emit("text", line) })
// Deliver the command's last words (e.g. "tmux: command not found")
// before the close event, but don't hang on a stderr that never ends.
select {
case <-stderrDone:
case <-time.After(500 * time.Millisecond):
}
if c.ctx.Err() != nil {
return
}
waitErr := session.Wait()
var exitErr *ssh.ExitError
var missing *ssh.ExitMissingError
switch {
case waitErr == nil:
status := 0
c.finish("closed", closedPayload{ExitStatus: &status})
case errors.As(waitErr, &exitErr):
status := exitErr.ExitStatus()
c.finish("closed", closedPayload{ExitStatus: &status, Signal: exitErr.Signal()})
case errors.As(waitErr, &missing):
// The channel closed without an exit status: usually the connection
// went away under it.
c.fail(lostFailure(conn, readErr))
default:
c.fail(lostFailure(conn, waitErr))
}
}
// readLines calls emit for each line of r (without its newline) and returns
// the read error that ended it (nil at EOF). Lines may be arbitrarily long.
func readLines(r io.Reader, emit func(string)) error {
reader := bufio.NewReaderSize(r, 64*1024)
for {
line, err := reader.ReadBytes('\n')
if len(line) > 0 {
if line[len(line)-1] == '\n' {
line = line[:len(line)-1]
}
emit(escapeLine(line))
}
if err == io.EOF {
return nil
}
if err != nil {
return err
}
}
}
// escapeLine makes a line safe to hand across the gomobile boundary as a
// string (which must be valid UTF-8). Valid UTF-8 passes through. Otherwise
// every byte >= 0x80 becomes "\ooo" (backslash, three octal digits): the same
// escape tmux control mode uses for control characters and backslashes in
// %output, so a %output line split mid-character still decodes back to its
// exact bytes. (Outside %output a literal backslash is ambiguous with this
// escape; such lines are only ever displayed.)
func escapeLine(line []byte) string {
if utf8.Valid(line) {
return string(line)
}
var b strings.Builder
for _, c := range line {
if c >= 0x80 {
fmt.Fprintf(&b, "\\%03o", c)
} else {
b.WriteByte(c)
}
}
return b.String()
}
// runWebSocket opens rawURL (ws://host:port/path) through the SSH
// connection — host:port is resolved on the SSH server's side — and relays
// text frames.
func (c *Channel) runWebSocket(conn *pooledConn, rawURL string) {
parsed, err := url.Parse(rawURL)
if err != nil || parsed.Scheme != "ws" || parsed.Host == "" {
c.fail(&failure{Kind: "config", Message: fmt.Sprintf("bad websocket URL %q", rawURL)})
return
}
target := parsed.Host
if parsed.Port() == "" {
target = net.JoinHostPort(parsed.Hostname(), "80")
}
dialer := websocket.Dialer{
NetDialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
forwarded, err := conn.client.DialContext(ctx, "tcp", target)
if err != nil {
return nil, err
}
return noDeadlineConn{forwarded}, nil
},
}
// The handshake timeout rides the context: SSH channels can't do deadlines.
handshakeCtx, cancelHandshake := context.WithTimeout(c.ctx, defaultConnectTimeout)
ws, _, err := dialer.DialContext(handshakeCtx, rawURL, nil)
cancelHandshake()
if err != nil {
if c.ctx.Err() != nil {
return
}
c.fail(channelOpenFailure(conn, fmt.Errorf("could not reach %s on the host: %w", target, err)))
return
}
defer ws.Close()
go func() {
<-c.ctx.Done()
ws.Close()
}()
c.markOpen()
go func() {
defer c.guard()
for text := range c.sendQ {
if err := ws.WriteMessage(websocket.TextMessage, []byte(text)); err != nil {
return
}
}
ws.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, "bye"),
time.Now().Add(time.Second))
}()
for {
kind, data, err := ws.ReadMessage()
if err != nil {
if c.ctx.Err() != nil {
return
}
var closeErr *websocket.CloseError
if errors.As(err, &closeErr) {
code := closeErr.Code
c.finish("closed", closedPayload{Code: &code, Reason: closeErr.Text})
return
}
c.fail(lostFailure(conn, err))
return
}
if kind == websocket.TextMessage {
c.emit("text", string(data))
}
}
}
// noDeadlineConn adapts an SSH direct-tcpip channel for the websocket
// library, which sets deadlines the channel doesn't support. Timeouts come
// from contexts and the SSH keepalive instead.
type noDeadlineConn struct{ net.Conn }
func (noDeadlineConn) SetDeadline(time.Time) error { return nil }
func (noDeadlineConn) SetReadDeadline(time.Time) error { return nil }
func (noDeadlineConn) SetWriteDeadline(time.Time) error { return nil }
// channelOpenFailure classifies a failure to open a channel: if the SSH
// connection itself is gone it's a network failure (reconnect), otherwise
// the host refused this particular channel.
func channelOpenFailure(conn *pooledConn, err error) *failure {
if isConnDead(conn) {
return &failure{Kind: "network", Message: "connection lost: " + err.Error()}
}
return &failure{Kind: "channel", Message: err.Error()}
}
func lostFailure(conn *pooledConn, err error) *failure {
message := "connection lost"
if err != nil && !errors.Is(err, io.EOF) {
message += ": " + err.Error()
}
if !isConnDead(conn) {
// The connection is fine; only this channel ended abruptly.
return &failure{Kind: "channel", Message: "channel closed unexpectedly"}
}
return &failure{Kind: "network", Message: message}
}
func isConnDead(conn *pooledConn) bool {
// client.Wait's goroutine marks the connection dead slightly after the
// channels see their streams end; give it a moment to catch up.
deadline := time.Now().Add(200 * time.Millisecond)
for {
poolMu.Lock()
dead := conn.dead
poolMu.Unlock()
if dead || time.Now().After(deadline) {
return dead
}
time.Sleep(10 * time.Millisecond)
}
}
+304
View File
@@ -0,0 +1,304 @@
// Package faceclawssh is Faceclaw's SSH transport, bound into the Android and
// iOS apps with gomobile. It exposes text-message channels over SSH:
//
// - "exec": run a command on the host and exchange newline-delimited text
// with it (stdin lines in, stdout lines out). Used for tmux control mode
// and the tmux session poller.
// - "websocket": open a direct-tcpip channel to an address as seen from the
// host (normally g2mirror-server on 127.0.0.1:8737) and speak WebSocket
// text frames over it.
//
// Channels to the same host, user and credentials share one SSH connection
// (see pool.go). Host keys are pinned by the caller: a connection whose host
// presents a key that isn't in the spec's hostKeys fails with a
// "hostkey-unknown" or "hostkey-mismatch" failure carrying the presented key,
// so the app can show the fingerprint and retry once the user has trusted it.
// Authentication uses a platform-held, non-exportable ECDSA P-256 key (the
// Signer interface; Android Keystore / iOS Secure Enclave) and, if the server
// allows it, a password.
//
// Everything crossing the gomobile boundary is a string, []byte or one of the
// interfaces below; structured values are JSON strings.
package faceclawssh
import (
"context"
"encoding/json"
"fmt"
"runtime/debug"
"sync"
"time"
)
// Signer is implemented by the platform: an ECDSA P-256 key whose private
// half never leaves the device's keystore.
type Signer interface {
// PublicKey returns the key's public half, either as X.509
// SubjectPublicKeyInfo DER (Android's PublicKey.getEncoded()) or as an
// uncompressed X9.62 point, 0x04 || X || Y (iOS's
// SecKeyCopyExternalRepresentation).
PublicKey() []byte
// Sign returns the ASN.1 DER ECDSA signature of SHA-256(data).
Sign(data []byte) ([]byte, error)
}
// Listener receives a channel's events. Calls arrive on arbitrary goroutines
// (never concurrently for one channel); the platform wrapper hops them onto
// the thread that owns the channel.
//
// Event kinds and payloads:
// - "open": the channel is ready; payload empty. Sends made before this are
// queued and delivered once open.
// - "text": one message (websocket text frame, or one stdout line without
// its newline). Exec lines that aren't valid UTF-8 have every byte >= 0x80
// escaped as a backslash and three octal digits, matching tmux control
// mode's escaping of control characters (see escapeLine).
// - "stderr": one stderr line of an exec channel, escaped the same way.
// - "closed": the channel ended normally; payload is JSON
// {"exitStatus": n, "signal": "...", "code": n, "reason": "..."} with the
// fields that apply (exec exit status/signal, websocket close code/reason).
// Terminal: no events follow.
// - "failure": the channel could not be opened or was lost; payload is a
// JSON Failure. Terminal: no events follow.
type Listener interface {
OnEvent(kind string, payload string)
}
// Failure describes why a channel failed, as the JSON payload of a "failure"
// event.
type failure struct {
// "hostkey-unknown": no host key is pinned yet; HostKey is what the host
// presented. "hostkey-mismatch": the host presented a key that isn't
// pinned. "auth": the host refused every credential we have.
// "network": couldn't reach the host, or the connection dropped.
// "channel": the SSH connection is fine but the channel couldn't be
// opened (exec refused, nothing listening at the forwarded address...).
// "config": the spec was malformed. "internal": a bug.
Kind string `json:"kind"`
Message string `json:"message"`
HostKey *hostKeyInfo `json:"hostKey,omitempty"`
// For "auth": the host accepts password (or keyboard-interactive)
// authentication, whether a password was sent, and whether our key was
// offered.
PasswordAllowed bool `json:"passwordAllowed,omitempty"`
PasswordTried bool `json:"passwordTried,omitempty"`
KeyTried bool `json:"keyTried,omitempty"`
}
func (f *failure) Error() string { return f.Message }
type hostKeyInfo struct {
// SSH key type, e.g. "ssh-ed25519".
Type string `json:"type"`
// OpenSSH-style SHA-256 fingerprint, "SHA256:<base64>".
Fingerprint string `json:"fingerprint"`
// The key in SSH wire format, base64: what goes in a spec's hostKeys.
Key string `json:"key"`
}
type channelSpec struct {
// "exec" or "websocket".
Type string `json:"type"`
// exec: the command line, run by the user's login shell.
Command string `json:"command"`
// websocket: ws:// URL, resolved on the host's side of the connection.
URL string `json:"url"`
}
type openSpec struct {
Host string `json:"host"`
Port int `json:"port"`
User string `json:"user"`
Password string `json:"password"`
// Pinned host keys, SSH wire format, base64. Empty: the first connection
// fails with "hostkey-unknown".
HostKeys []string `json:"hostKeys"`
// Offer the platform key (the Signer passed to Open).
UseKey bool `json:"useKey"`
ConnectTimeoutMs int `json:"connectTimeoutMs"`
KeepaliveIntervalMs int `json:"keepaliveIntervalMs"`
Channel channelSpec `json:"channel"`
}
const (
defaultConnectTimeout = 15 * time.Second
defaultKeepaliveInterval = 20 * time.Second
// Messages queued on a channel before Send starts refusing them.
sendQueueCapacity = 4096
// How long Close waits for queued messages to flush and the far end to
// finish before tearing the channel down.
closeGracePeriod = 2 * time.Second
)
// Channel is one open (or opening) channel. Methods are safe to call from
// any thread.
type Channel struct {
listener Listener
ctx context.Context
cancel context.CancelFunc
mu sync.Mutex
closed bool // Close was called: no more sends, no more events
opened bool
sendQ chan string
finishOnce sync.Once
}
// Open starts opening a channel described by spec (a JSON openSpec) and
// returns immediately; progress arrives as listener events. signer may be
// nil (no key authentication).
func Open(spec string, signer Signer, listener Listener) *Channel {
ctx, cancel := context.WithCancel(context.Background())
c := &Channel{
listener: listener,
ctx: ctx,
cancel: cancel,
sendQ: make(chan string, sendQueueCapacity),
}
go c.run(spec, signer)
return c
}
// Send queues one message: a websocket text frame, or a line for an exec
// channel's stdin (the newline is added). Returns false if the channel is
// closed or its queue is full.
func (c *Channel) Send(text string) bool {
c.mu.Lock()
defer c.mu.Unlock()
if c.closed {
return false
}
select {
case c.sendQ <- text:
return true
default:
return false
}
}
// Close ends the channel. Messages already queued are still sent (so a
// parting "unview" reaches the host), then the channel's write side is
// closed and, after a short grace period, the channel is torn down. No
// events are delivered after Close.
func (c *Channel) Close() {
c.mu.Lock()
if c.closed {
c.mu.Unlock()
return
}
c.closed = true
opened := c.opened
close(c.sendQ)
c.mu.Unlock()
if !opened {
c.cancel()
return
}
time.AfterFunc(closeGracePeriod, c.cancel)
}
func (c *Channel) isClosed() bool {
c.mu.Lock()
defer c.mu.Unlock()
return c.closed
}
func (c *Channel) emit(kind, payload string) {
if c.isClosed() {
return
}
c.listener.OnEvent(kind, payload)
}
func (c *Channel) markOpen() {
c.mu.Lock()
c.opened = true
c.mu.Unlock()
c.emit("open", "")
}
// finish delivers the channel's one terminal event ("closed" or "failure").
func (c *Channel) finish(kind string, payload any) {
c.finishOnce.Do(func() {
encoded, err := json.Marshal(payload)
if err != nil {
encoded = []byte(`{"kind":"internal","message":"unencodable event"}`)
}
c.emit(kind, string(encoded))
c.cancel()
})
}
func (c *Channel) fail(f *failure) { c.finish("failure", f) }
// guard turns a panic in one of our goroutines into a failure event instead
// of crashing the app (an unrecovered Go panic kills the whole process).
func (c *Channel) guard() {
if r := recover(); r != nil {
c.fail(&failure{Kind: "internal", Message: fmt.Sprintf("internal error: %v\n%s", r, debug.Stack())})
}
}
func (c *Channel) run(specJSON string, signer Signer) {
defer c.guard()
var spec openSpec
if err := json.Unmarshal([]byte(specJSON), &spec); err != nil {
c.fail(&failure{Kind: "config", Message: "bad channel spec: " + err.Error()})
return
}
if spec.Host == "" || spec.User == "" {
c.fail(&failure{Kind: "config", Message: "host and user are required"})
return
}
if spec.Port == 0 {
spec.Port = 22
}
if !spec.UseKey {
signer = nil
}
conn, err := acquire(c.ctx, &spec, signer)
if err != nil {
if c.ctx.Err() != nil {
return
}
c.fail(asFailure(err))
return
}
defer conn.release()
switch spec.Channel.Type {
case "exec":
c.runExec(conn, spec.Channel.Command)
case "websocket":
c.runWebSocket(conn, spec.Channel.URL)
default:
c.fail(&failure{Kind: "config", Message: fmt.Sprintf("unknown channel type %q", spec.Channel.Type)})
}
}
func asFailure(err error) *failure {
if f, ok := err.(*failure); ok {
return f
}
return &failure{Kind: "network", Message: err.Error()}
}
// AuthorizedKey formats a platform public key (see Signer.PublicKey) as an
// authorized_keys line: "ecdsa-sha2-nistp256 AAAA... comment".
func AuthorizedKey(publicKey []byte, comment string) (string, error) {
key, err := sshPublicKey(publicKey)
if err != nil {
return "", err
}
return authorizedKeyLine(key, comment), nil
}
// Fingerprint returns the OpenSSH SHA-256 fingerprint ("SHA256:...") of a
// platform public key.
func Fingerprint(publicKey []byte) (string, error) {
key, err := sshPublicKey(publicKey)
if err != nil {
return "", err
}
return fingerprint(key), nil
}
+526
View File
@@ -0,0 +1,526 @@
package faceclawssh
import (
"bufio"
"crypto/ecdsa"
"crypto/ed25519"
"crypto/elliptic"
"crypto/rand"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/gorilla/websocket"
"golang.org/x/crypto/ssh"
)
// ---- test SSH server ----
type testServer struct {
addr string
hostKey ssh.Signer
accepts atomic.Int32
listener net.Listener
}
type serverOptions struct {
password string // "" = password auth disabled
keyboardInteractive bool // offer the password via keyboard-interactive instead
authorizedKey ssh.PublicKey
}
func newTestServer(t *testing.T, opts serverOptions) *testServer {
t.Helper()
_, priv, _ := ed25519.GenerateKey(rand.Reader)
hostKey, err := ssh.NewSignerFromKey(priv)
if err != nil {
t.Fatal(err)
}
config := &ssh.ServerConfig{}
if opts.password != "" && !opts.keyboardInteractive {
config.PasswordCallback = func(_ ssh.ConnMetadata, password []byte) (*ssh.Permissions, error) {
if string(password) == opts.password {
return nil, nil
}
return nil, fmt.Errorf("wrong password")
}
}
if opts.password != "" && opts.keyboardInteractive {
config.KeyboardInteractiveCallback = func(_ ssh.ConnMetadata, challenge ssh.KeyboardInteractiveChallenge) (*ssh.Permissions, error) {
answers, err := challenge("", "", []string{"Password: "}, []bool{false})
if err != nil {
return nil, err
}
if len(answers) == 1 && answers[0] == opts.password {
return nil, nil
}
return nil, fmt.Errorf("wrong password")
}
}
if opts.authorizedKey != nil {
config.PublicKeyCallback = func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) {
if string(key.Marshal()) == string(opts.authorizedKey.Marshal()) {
return nil, nil
}
return nil, fmt.Errorf("unknown key")
}
}
config.AddHostKey(hostKey)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
server := &testServer{addr: listener.Addr().String(), hostKey: hostKey, listener: listener}
t.Cleanup(func() { listener.Close() })
go func() {
for {
tcp, err := listener.Accept()
if err != nil {
return
}
server.accepts.Add(1)
go server.serve(tcp, config)
}
}()
return server
}
func (s *testServer) serve(tcp net.Conn, config *ssh.ServerConfig) {
conn, chans, reqs, err := ssh.NewServerConn(tcp, config)
if err != nil {
tcp.Close()
return
}
defer conn.Close()
go ssh.DiscardRequests(reqs) // replies false to keepalives, which still counts as alive
for newChannel := range chans {
switch newChannel.ChannelType() {
case "session":
go serveSession(newChannel)
case "direct-tcpip":
go serveDirectTCPIP(newChannel)
default:
newChannel.Reject(ssh.UnknownChannelType, "nope")
}
}
}
// serveSession implements a few fake commands:
// - "echo": echo stdin lines back with a "> " prefix until EOF, exit 0
// - "bytes": print an invalid-UTF-8 line and a stderr line, exit 3
func serveSession(newChannel ssh.NewChannel) {
channel, requests, err := newChannel.Accept()
if err != nil {
return
}
defer channel.Close()
for req := range requests {
if req.Type != "exec" {
req.Reply(false, nil)
continue
}
var payload struct{ Command string }
ssh.Unmarshal(req.Payload, &payload)
req.Reply(true, nil)
status := 0
switch payload.Command {
case "echo":
scanner := bufio.NewScanner(channel)
for scanner.Scan() {
fmt.Fprintf(channel, "> %s\n", scanner.Text())
}
case "bytes":
channel.Write([]byte("%output %1 caf\xc3\n%output %1 \xa9 ok\nplain ✓\n"))
channel.Stderr().Write([]byte("oops\n"))
status = 3
default:
channel.Stderr().Write([]byte("unknown command\n"))
status = 127
}
channel.SendRequest("exit-status", false, ssh.Marshal(struct{ Status uint32 }{uint32(status)}))
return
}
}
func serveDirectTCPIP(newChannel ssh.NewChannel) {
var target struct {
Host string
Port uint32
OriginHost string
OriginPort uint32
}
if err := ssh.Unmarshal(newChannel.ExtraData(), &target); err != nil {
newChannel.Reject(ssh.ConnectionFailed, "bad payload")
return
}
upstream, err := net.Dial("tcp", net.JoinHostPort(target.Host, fmt.Sprint(target.Port)))
if err != nil {
newChannel.Reject(ssh.ConnectionFailed, err.Error())
return
}
channel, requests, err := newChannel.Accept()
if err != nil {
upstream.Close()
return
}
go ssh.DiscardRequests(requests)
go func() { io.Copy(upstream, channel); upstream.Close() }()
io.Copy(channel, upstream)
channel.Close()
}
// ---- test client plumbing ----
type event struct{ kind, payload string }
type recorder struct {
events chan event
}
func newRecorder() *recorder { return &recorder{events: make(chan event, 256)} }
func (r *recorder) OnEvent(kind, payload string) { r.events <- event{kind, payload} }
func (r *recorder) next(t *testing.T) event {
t.Helper()
select {
case e := <-r.events:
return e
case <-time.After(10 * time.Second):
t.Fatal("timed out waiting for event")
return event{}
}
}
func (r *recorder) expect(t *testing.T, kind string) event {
t.Helper()
e := r.next(t)
if e.kind != kind {
t.Fatalf("got event %s(%s), want %s", e.kind, e.payload, kind)
}
return e
}
func (r *recorder) expectFailure(t *testing.T) failure {
t.Helper()
e := r.expect(t, "failure")
var f failure
if err := json.Unmarshal([]byte(e.payload), &f); err != nil {
t.Fatal(err)
}
return f
}
type softwareSigner struct{ key *ecdsa.PrivateKey }
func newSoftwareSigner(t *testing.T) *softwareSigner {
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
t.Fatal(err)
}
return &softwareSigner{key: key}
}
func (s *softwareSigner) PublicKey() []byte {
der, _ := x509.MarshalPKIXPublicKey(&s.key.PublicKey)
return der
}
func (s *softwareSigner) Sign(data []byte) ([]byte, error) {
digest := sha256.Sum256(data)
return ecdsa.SignASN1(rand.Reader, s.key, digest[:])
}
func (s *softwareSigner) sshKey(t *testing.T) ssh.PublicKey {
key, err := ssh.NewPublicKey(&s.key.PublicKey)
if err != nil {
t.Fatal(err)
}
return key
}
func specFor(server *testServer, mutate func(*openSpec)) string {
host, port, _ := net.SplitHostPort(server.addr)
var portNumber int
fmt.Sscan(port, &portNumber)
spec := openSpec{
Host: host,
Port: portNumber,
User: "jim",
HostKeys: []string{base64.StdEncoding.EncodeToString(server.hostKey.PublicKey().Marshal())},
Channel: channelSpec{Type: "exec", Command: "echo"},
}
if mutate != nil {
mutate(&spec)
}
encoded, _ := json.Marshal(spec)
return string(encoded)
}
func resetPool() {
poolMu.Lock()
defer poolMu.Unlock()
for key, conn := range pool {
conn.client.Close()
delete(pool, key)
}
}
// ---- tests ----
func TestHostKeyPinning(t *testing.T) {
defer resetPool()
server := newTestServer(t, serverOptions{password: "pw"})
wantKey := base64.StdEncoding.EncodeToString(server.hostKey.PublicKey().Marshal())
rec := newRecorder()
Open(specFor(server, func(s *openSpec) { s.HostKeys = nil; s.Password = "pw" }), nil, rec)
f := rec.expectFailure(t)
if f.Kind != "hostkey-unknown" || f.HostKey == nil || f.HostKey.Key != wantKey ||
f.HostKey.Type != ssh.KeyAlgoED25519 || !strings.HasPrefix(f.HostKey.Fingerprint, "SHA256:") {
t.Fatalf("unexpected failure %+v", f)
}
_, otherPriv, _ := ed25519.GenerateKey(rand.Reader)
other, _ := ssh.NewSignerFromKey(otherPriv)
rec = newRecorder()
Open(specFor(server, func(s *openSpec) {
s.HostKeys = []string{base64.StdEncoding.EncodeToString(other.PublicKey().Marshal())}
s.Password = "pw"
}), nil, rec)
f = rec.expectFailure(t)
if f.Kind != "hostkey-mismatch" || f.HostKey.Key != wantKey {
t.Fatalf("unexpected failure %+v", f)
}
rec = newRecorder()
ch := Open(specFor(server, func(s *openSpec) { s.Password = "pw" }), nil, rec)
rec.expect(t, "open")
ch.Close()
}
func TestPasswordAuth(t *testing.T) {
for _, interactive := range []bool{false, true} {
t.Run(fmt.Sprintf("keyboardInteractive=%v", interactive), func(t *testing.T) {
defer resetPool()
server := newTestServer(t, serverOptions{password: "secret", keyboardInteractive: interactive})
rec := newRecorder()
Open(specFor(server, nil), nil, rec)
f := rec.expectFailure(t)
if f.Kind != "auth" || !f.PasswordAllowed || f.PasswordTried {
t.Fatalf("no password: %+v", f)
}
rec = newRecorder()
Open(specFor(server, func(s *openSpec) { s.Password = "wrong" }), nil, rec)
f = rec.expectFailure(t)
if f.Kind != "auth" || !f.PasswordTried {
t.Fatalf("wrong password: %+v", f)
}
rec = newRecorder()
ch := Open(specFor(server, func(s *openSpec) { s.Password = "secret" }), nil, rec)
rec.expect(t, "open")
ch.Send("hi")
if e := rec.expect(t, "text"); e.payload != "> hi" {
t.Fatalf("got %q", e.payload)
}
ch.Close()
})
}
}
func TestKeyAuth(t *testing.T) {
defer resetPool()
signer := newSoftwareSigner(t)
server := newTestServer(t, serverOptions{authorizedKey: signer.sshKey(t)})
rec := newRecorder()
ch := Open(specFor(server, func(s *openSpec) { s.UseKey = true }), signer, rec)
rec.expect(t, "open")
ch.Close()
// A key the server doesn't know, and no password support.
resetPool()
rec = newRecorder()
Open(specFor(server, func(s *openSpec) { s.UseKey = true }), newSoftwareSigner(t), rec)
f := rec.expectFailure(t)
if f.Kind != "auth" || !f.KeyTried || f.PasswordAllowed {
t.Fatalf("unexpected failure %+v", f)
}
line, err := AuthorizedKey(signer.PublicKey(), "Faceclaw on my phone")
if err != nil || !strings.HasPrefix(line, "ecdsa-sha2-nistp256 AAAA") || !strings.HasSuffix(line, " Faceclaw-on-my-phone") {
t.Fatalf("AuthorizedKey = %q, %v", line, err)
}
parsed, _, _, _, err := ssh.ParseAuthorizedKey([]byte(line))
if err != nil || string(parsed.Marshal()) != string(signer.sshKey(t).Marshal()) {
t.Fatalf("authorized key does not round-trip: %v", err)
}
// The uncompressed-point form iOS hands us parses to the same key.
point := elliptic.Marshal(elliptic.P256(), signer.key.X, signer.key.Y) //nolint:staticcheck
fromPoint, err := Fingerprint(point)
fromDER, _ := Fingerprint(signer.PublicKey())
if err != nil || fromPoint != fromDER {
t.Fatalf("fingerprints differ: %s vs %s (%v)", fromPoint, fromDER, err)
}
}
func TestExecFraming(t *testing.T) {
defer resetPool()
server := newTestServer(t, serverOptions{password: "pw"})
rec := newRecorder()
Open(specFor(server, func(s *openSpec) { s.Password = "pw"; s.Channel.Command = "bytes" }), nil, rec)
rec.expect(t, "open")
var texts, stderr []string
var closed closedPayload
for done := false; !done; {
e := rec.next(t)
switch e.kind {
case "text":
texts = append(texts, e.payload)
case "stderr":
stderr = append(stderr, e.payload)
case "closed":
json.Unmarshal([]byte(e.payload), &closed)
done = true
default:
t.Fatalf("unexpected %s(%s)", e.kind, e.payload)
}
}
want := []string{`%output %1 caf\303`, `%output %1 \251 ok`, "plain ✓"}
if strings.Join(texts, "|") != strings.Join(want, "|") {
t.Fatalf("texts = %q, want %q", texts, want)
}
if len(stderr) != 1 || stderr[0] != "oops" {
t.Fatalf("stderr = %q", stderr)
}
if closed.ExitStatus == nil || *closed.ExitStatus != 3 {
t.Fatalf("closed = %+v", closed)
}
}
func TestWebSocketTunnelAndSharing(t *testing.T) {
defer resetPool()
upgrader := websocket.Upgrader{}
var serverConns sync.WaitGroup
wsServer := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
serverConns.Add(1)
defer serverConns.Done()
defer conn.Close()
for {
kind, data, err := conn.ReadMessage()
if err != nil {
return
}
if string(data) == "quit" {
conn.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(4000, "asked to quit"))
return
}
conn.WriteMessage(kind, append([]byte("echo:"), data...))
}
})}
wsListener, _ := net.Listen("tcp", "127.0.0.1:0")
go wsServer.Serve(wsListener)
defer wsServer.Close()
server := newTestServer(t, serverOptions{password: "pw"})
wsSpec := specFor(server, func(s *openSpec) {
s.Password = "pw"
s.Channel = channelSpec{Type: "websocket", URL: "ws://" + wsListener.Addr().String() + "/"}
})
recA, recB := newRecorder(), newRecorder()
a := Open(wsSpec, nil, recA)
b := Open(wsSpec, nil, recB)
// Sent before open: queued until the channel is up.
a.Send(`{"type":"init"}`)
recA.expect(t, "open")
recB.expect(t, "open")
if e := recA.expect(t, "text"); e.payload != `echo:{"type":"init"}` {
t.Fatalf("got %q", e.payload)
}
b.Send("quit")
e := recB.expect(t, "closed")
var closed closedPayload
json.Unmarshal([]byte(e.payload), &closed)
if closed.Code == nil || *closed.Code != 4000 || closed.Reason != "asked to quit" {
t.Fatalf("closed = %+v", closed)
}
if n := server.accepts.Load(); n != 1 {
t.Fatalf("expected both channels on one SSH connection, got %d connections", n)
}
// Close flushes queued messages before tearing down.
a.Send("last words")
a.Close()
time.Sleep(300 * time.Millisecond)
select {
case e := <-recA.events:
t.Fatalf("event after Close: %s(%s)", e.kind, e.payload)
default:
}
// Nothing listening at the forwarded address: a channel failure, not a
// network one (the SSH connection is fine).
recC := newRecorder()
Open(specFor(server, func(s *openSpec) {
s.Password = "pw"
s.Channel = channelSpec{Type: "websocket", URL: "ws://127.0.0.1:1/"}
}), nil, recC)
if f := recC.expectFailure(t); f.Kind != "channel" {
t.Fatalf("unexpected failure %+v", f)
}
}
func TestConnectionLoss(t *testing.T) {
defer resetPool()
server := newTestServer(t, serverOptions{password: "pw"})
rec := newRecorder()
Open(specFor(server, func(s *openSpec) { s.Password = "pw" }), nil, rec)
rec.expect(t, "open")
// Kill the SSH connection under the channel.
poolMu.Lock()
for _, conn := range pool {
conn.client.Close()
}
poolMu.Unlock()
if f := rec.expectFailure(t); f.Kind != "network" {
t.Fatalf("unexpected failure %+v", f)
}
// The next channel dials a fresh connection.
rec = newRecorder()
ch := Open(specFor(server, func(s *openSpec) { s.Password = "pw" }), nil, rec)
rec.expect(t, "open")
ch.Close()
if n := server.accepts.Load(); n != 2 {
t.Fatalf("expected a second connection, got %d", n)
}
}
func TestNetworkFailure(t *testing.T) {
rec := newRecorder()
Open(`{"host":"127.0.0.1","port":1,"user":"jim","channel":{"type":"exec","command":"x"}}`, nil, rec)
if f := rec.expectFailure(t); f.Kind != "network" {
t.Fatalf("unexpected failure %+v", f)
}
rec = newRecorder()
Open(`not json`, nil, rec)
if f := rec.expectFailure(t); f.Kind != "config" {
t.Fatalf("unexpected failure %+v", f)
}
}
+21
View File
@@ -0,0 +1,21 @@
module github.com/jimrandomh/faceclaw/native/ssh
go 1.26.0
require (
github.com/gorilla/websocket v1.5.3
golang.org/x/crypto v0.59.0
)
require (
golang.org/x/mobile v0.0.0-20261011034528-197770444867 // indirect
golang.org/x/mod v0.42.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.50.0 // indirect
golang.org/x/tools v0.52.0 // indirect
)
tool (
golang.org/x/mobile/cmd/gobind
golang.org/x/mobile/cmd/gomobile
)
+16
View File
@@ -0,0 +1,16 @@
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
golang.org/x/crypto v0.59.0 h1:xS2jhqYbzNrpvkWP2YTDf4TJwBy3ykR03i8vFDxEc7c=
golang.org/x/crypto v0.59.0/go.mod h1:veDyUwATGs3c+vN3VfTbzViMGXeTBk3WyhBOkn+F/4U=
golang.org/x/mobile v0.0.0-20261011034528-197770444867 h1:rav73cdd7OQUPgt1aIFbZQTiPNnjfueKXvfOiLCY0Ss=
golang.org/x/mobile v0.0.0-20261011034528-197770444867/go.mod h1:HR/iBzuQmVTl/us733QPwrqHp43a8m9ZLgyKXD3ST6U=
golang.org/x/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg=
golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs=
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
golang.org/x/sys v0.50.0 h1:dkKZEFTEKaLr1sjhs0WiKqoi8Jj5nHbS3Njmx1UoMJs=
golang.org/x/sys v0.50.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
golang.org/x/term v0.48.0 h1:G6UU1eiSB8nl3DzeUGt7Mg+2SctI8tPS6Z5/mBt6cOk=
golang.org/x/term v0.48.0/go.mod h1:BRDLHCZr2SUjIeBHHpRyQeC9xzSAVbzY2rvKgafnHf4=
golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs=
golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs=
+58
View File
@@ -0,0 +1,58 @@
package faceclawssh
import (
"encoding/json"
"net"
"os"
"strconv"
"testing"
)
// TestOpenSSHInterop checks the parts of the handshake that need no
// credentials against a real sshd: key exchange, host key reporting and
// pinning, and how an authentication refusal is classified. Opt-in:
//
// FACECLAW_SSH_INTEROP_ADDR=127.0.0.1:22 go test -run Interop -v
//
// Compare the logged fingerprint with `ssh-keygen -lf /etc/ssh/ssh_host_ed25519_key.pub`.
// It makes one failed login attempt (no password, an unknown key) as
// FACECLAW_SSH_INTEROP_USER (default: $USER).
func TestOpenSSHInterop(t *testing.T) {
addr := os.Getenv("FACECLAW_SSH_INTEROP_ADDR")
if addr == "" {
t.Skip("FACECLAW_SSH_INTEROP_ADDR not set")
}
defer resetPool()
user := os.Getenv("FACECLAW_SSH_INTEROP_USER")
if user == "" {
user = os.Getenv("USER")
}
host, portText, err := net.SplitHostPort(addr)
if err != nil {
t.Fatal(err)
}
port, _ := strconv.Atoi(portText)
spec := func(hostKeys []string) string {
encoded, _ := json.Marshal(openSpec{
Host: host, Port: port, User: user, HostKeys: hostKeys, UseKey: true,
Channel: channelSpec{Type: "exec", Command: "true"},
})
return string(encoded)
}
rec := newRecorder()
Open(spec(nil), newSoftwareSigner(t), rec)
f := rec.expectFailure(t)
if f.Kind != "hostkey-unknown" || f.HostKey == nil {
t.Fatalf("first contact: %+v", f)
}
t.Logf("host key: %s %s", f.HostKey.Type, f.HostKey.Fingerprint)
rec = newRecorder()
Open(spec([]string{f.HostKey.Key}), newSoftwareSigner(t), rec)
auth := rec.expectFailure(t)
if auth.Kind != "auth" || !auth.KeyTried {
t.Fatalf("pinned, unknown key: %+v", auth)
}
t.Logf("auth refusal: %+v", auth)
}
+91
View File
@@ -0,0 +1,91 @@
package faceclawssh
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/sha256"
"crypto/x509"
"encoding/asn1"
"encoding/base64"
"errors"
"fmt"
"io"
"math/big"
"strings"
"golang.org/x/crypto/ssh"
)
// platformSigner adapts the platform's keystore-backed Signer to ssh.Signer.
// The platform signs SHA-256(data) with ECDSA P-256 and returns ASN.1 DER;
// SSH wants the signature as two mpints (RFC 5656 §3.1.2).
type platformSigner struct {
signer Signer
pub ssh.PublicKey
}
func newPlatformSigner(signer Signer) (*platformSigner, error) {
pub, err := sshPublicKey(signer.PublicKey())
if err != nil {
return nil, err
}
return &platformSigner{signer: signer, pub: pub}, nil
}
func (p *platformSigner) PublicKey() ssh.PublicKey { return p.pub }
func (p *platformSigner) Sign(_ io.Reader, data []byte) (*ssh.Signature, error) {
der, err := p.signer.Sign(data)
if err != nil {
return nil, fmt.Errorf("platform key signing failed: %w", err)
}
var sig struct{ R, S *big.Int }
rest, err := asn1.Unmarshal(der, &sig)
if err != nil || len(rest) != 0 || sig.R == nil || sig.S == nil || sig.R.Sign() <= 0 || sig.S.Sign() <= 0 {
return nil, errors.New("platform key returned a malformed signature")
}
blob := ssh.Marshal(struct{ R, S *big.Int }{sig.R, sig.S})
return &ssh.Signature{Format: p.pub.Type(), Blob: blob}, nil
}
// sshPublicKey parses a platform public key (SubjectPublicKeyInfo DER or an
// uncompressed P-256 point) into an ecdsa-sha2-nistp256 SSH key.
func sshPublicKey(encoded []byte) (ssh.PublicKey, error) {
var pub *ecdsa.PublicKey
if len(encoded) == 65 && encoded[0] == 4 {
parsed, err := ecdsa.ParseUncompressedPublicKey(elliptic.P256(), encoded)
if err != nil {
return nil, fmt.Errorf("bad P-256 point: %v", err)
}
pub = parsed
} else {
parsed, err := x509.ParsePKIXPublicKey(encoded)
if err != nil {
return nil, fmt.Errorf("bad public key: %v", err)
}
ecdsaKey, ok := parsed.(*ecdsa.PublicKey)
if !ok {
return nil, fmt.Errorf("unsupported public key type %T", parsed)
}
pub = ecdsaKey
}
if pub.Curve != elliptic.P256() {
return nil, errors.New("only P-256 keys are supported")
}
return ssh.NewPublicKey(pub)
}
func authorizedKeyLine(key ssh.PublicKey, comment string) string {
line := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key)))
comment = strings.Join(strings.Fields(comment), "-")
if comment != "" {
line += " " + comment
}
return line
}
// fingerprint is OpenSSH's SHA256 fingerprint format (unpadded base64).
func fingerprint(key ssh.PublicKey) string {
sum := sha256.Sum256(key.Marshal())
return "SHA256:" + base64.RawStdEncoding.EncodeToString(sum[:])
}
+416
View File
@@ -0,0 +1,416 @@
package faceclawssh
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"log"
"net"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh"
)
// SSH connections are shared between channels with the same host, port,
// user, credentials and pinned keys: the Terminal app's session poller and
// each of its view windows ride one TCP connection. A connection with no
// channels left lingers briefly (a view window closing and reopening shouldn't
// pay a fresh handshake) and is then closed. A keepalive probe closes
// connections whose peer has silently gone away, which fails every channel on
// them so the app's reconnect logic takes over.
const idleLinger = 15 * time.Second
type pooledConn struct {
key string
client *ssh.Client
// Guarded by poolMu.
refs int
dead bool
linger *time.Timer
}
type dialCall struct {
done chan struct{}
err error
}
var (
poolMu sync.Mutex
pool = map[string]*pooledConn{}
dialing = map[string]*dialCall{}
)
func poolKey(spec *openSpec, signer *platformSigner) string {
h := sha256.New()
fmt.Fprintf(h, "%s\x00%d\x00%s\x00%s\x00", spec.Host, spec.Port, spec.User, spec.Password)
for _, key := range spec.HostKeys {
fmt.Fprintf(h, "%s\x00", key)
}
if signer != nil {
h.Write(signer.pub.Marshal())
}
fmt.Fprintf(h, "\x00%d", spec.KeepaliveIntervalMs)
return hex.EncodeToString(h.Sum(nil))
}
// acquire returns a live pooled connection for spec, dialing one if needed
// (concurrent callers for the same key share a single dial). The caller must
// release() it.
func acquire(ctx context.Context, spec *openSpec, signer Signer) (*pooledConn, error) {
var ps *platformSigner
if signer != nil {
var err error
if ps, err = newPlatformSigner(signer); err != nil {
return nil, &failure{Kind: "config", Message: "client key unusable: " + err.Error()}
}
}
key := poolKey(spec, ps)
for {
poolMu.Lock()
if conn := pool[key]; conn != nil && !conn.dead {
conn.refs++
if conn.linger != nil {
conn.linger.Stop()
conn.linger = nil
}
poolMu.Unlock()
return conn, nil
}
if call := dialing[key]; call != nil {
poolMu.Unlock()
select {
case <-call.done:
case <-ctx.Done():
return nil, ctx.Err()
}
if call.err != nil {
return nil, call.err
}
continue
}
call := &dialCall{done: make(chan struct{})}
dialing[key] = call
poolMu.Unlock()
conn, err := dial(spec, ps, key)
poolMu.Lock()
delete(dialing, key)
if err == nil {
pool[key] = conn
}
call.err = err
close(call.done)
poolMu.Unlock()
if err != nil {
return nil, err
}
// Loop around to take a reference like any other caller.
}
}
func (conn *pooledConn) release() {
poolMu.Lock()
defer poolMu.Unlock()
conn.refs--
if conn.refs > 0 || conn.dead {
return
}
conn.linger = time.AfterFunc(idleLinger, func() {
poolMu.Lock()
idle := conn.refs == 0 && !conn.dead
if idle {
conn.dead = true
if pool[conn.key] == conn {
delete(pool, conn.key)
}
}
poolMu.Unlock()
if idle {
conn.client.Close()
}
})
}
// markDead removes a connection from the pool once its transport has ended,
// so the next acquire dials afresh.
func (conn *pooledConn) markDead() {
poolMu.Lock()
defer poolMu.Unlock()
conn.dead = true
if conn.linger != nil {
conn.linger.Stop()
conn.linger = nil
}
if pool[conn.key] == conn {
delete(pool, conn.key)
}
}
// hostKeyChecker pins the host key: only keys listed in the spec are
// accepted, and whatever the host presented is kept for the failure report.
type hostKeyChecker struct {
known [][]byte
presented ssh.PublicKey
rejected bool
}
func newHostKeyChecker(encoded []string) (*hostKeyChecker, error) {
checker := &hostKeyChecker{}
for _, entry := range encoded {
wire, err := base64.StdEncoding.DecodeString(strings.TrimSpace(entry))
if err != nil {
return nil, fmt.Errorf("bad pinned host key: %v", err)
}
if _, err := ssh.ParsePublicKey(wire); err != nil {
return nil, fmt.Errorf("bad pinned host key: %v", err)
}
checker.known = append(checker.known, wire)
}
return checker, nil
}
func (h *hostKeyChecker) check(_ string, _ net.Addr, key ssh.PublicKey) error {
h.presented = key
wire := key.Marshal()
for _, known := range h.known {
if bytes.Equal(known, wire) {
return nil
}
}
h.rejected = true
return errors.New("host key not trusted")
}
// algorithms lists host key algorithms with the pinned keys' types first, so
// a host with several host keys presents the one we pinned rather than
// whichever the default preference order favors.
func (h *hostKeyChecker) algorithms() []string {
var preferred []string
seen := map[string]bool{}
add := func(algorithm string) {
if !seen[algorithm] {
seen[algorithm] = true
preferred = append(preferred, algorithm)
}
}
for _, wire := range h.known {
key, err := ssh.ParsePublicKey(wire)
if err != nil {
continue
}
if key.Type() == ssh.KeyAlgoRSA {
add(ssh.KeyAlgoRSASHA512)
add(ssh.KeyAlgoRSASHA256)
continue
}
add(key.Type())
}
if len(preferred) == 0 {
return nil // the library default
}
for _, algorithm := range ssh.SupportedAlgorithms().HostKeys {
add(algorithm)
}
return preferred
}
func (h *hostKeyChecker) failure() *failure {
if h.presented == nil {
return nil
}
info := &hostKeyInfo{
Type: h.presented.Type(),
Fingerprint: fingerprint(h.presented),
Key: base64.StdEncoding.EncodeToString(h.presented.Marshal()),
}
if len(h.known) == 0 {
return &failure{Kind: "hostkey-unknown", Message: "Unknown host key " + info.Fingerprint, HostKey: info}
}
return &failure{Kind: "hostkey-mismatch", Message: "Host key changed: now " + info.Fingerprint, HostKey: info}
}
// errNoPassword aborts authentication when the host would accept a password
// but we don't have one; the "auth" failure then asks the app to prompt.
var errNoPassword = errors.New("password required")
type authState struct {
mu sync.Mutex
passwordAllowed bool
passwordTried bool
keyTried bool
}
func (a *authState) set(update func(*authState)) {
a.mu.Lock()
update(a)
a.mu.Unlock()
}
func authMethods(spec *openSpec, signer *platformSigner, state *authState) []ssh.AuthMethod {
var methods []ssh.AuthMethod
if signer != nil {
methods = append(methods, ssh.PublicKeysCallback(func() ([]ssh.Signer, error) {
state.set(func(a *authState) { a.keyTried = true })
return []ssh.Signer{signer}, nil
}))
}
password := spec.Password
methods = append(methods,
ssh.PasswordCallback(func() (string, error) {
state.set(func(a *authState) { a.passwordAllowed = true })
if password == "" {
return "", errNoPassword
}
state.set(func(a *authState) { a.passwordTried = true })
return password, nil
}),
// Many hosts (PAM-backed sshd, e.g. macOS) take passwords through
// keyboard-interactive. Answer hidden prompts with the password and
// visible ones with nothing.
ssh.KeyboardInteractive(func(_, _ string, questions []string, echos []bool) ([]string, error) {
if len(questions) == 0 {
return nil, nil
}
state.set(func(a *authState) { a.passwordAllowed = true })
if password == "" {
return nil, errNoPassword
}
state.set(func(a *authState) { a.passwordTried = true })
answers := make([]string, len(questions))
for i := range questions {
if !echos[i] {
answers[i] = password
}
}
return answers, nil
}),
)
return methods
}
func dial(spec *openSpec, signer *platformSigner, key string) (*pooledConn, error) {
timeout := defaultConnectTimeout
if spec.ConnectTimeoutMs > 0 {
timeout = time.Duration(spec.ConnectTimeoutMs) * time.Millisecond
}
checker, err := newHostKeyChecker(spec.HostKeys)
if err != nil {
return nil, &failure{Kind: "config", Message: err.Error()}
}
addr := net.JoinHostPort(spec.Host, strconv.Itoa(spec.Port))
dialer := net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second}
tcp, err := dialer.Dial("tcp", addr)
if err != nil {
return nil, &failure{Kind: "network", Message: describeNetError(err)}
}
// Bound the whole handshake, not just the TCP connect.
tcp.SetDeadline(time.Now().Add(timeout))
state := &authState{}
config := &ssh.ClientConfig{
User: spec.User,
Auth: authMethods(spec, signer, state),
HostKeyCallback: checker.check,
HostKeyAlgorithms: checker.algorithms(),
ClientVersion: "SSH-2.0-Faceclaw",
Timeout: timeout,
}
sshConn, chans, reqs, err := ssh.NewClientConn(tcp, addr, config)
if err != nil {
tcp.Close()
if checker.rejected {
return nil, checker.failure()
}
state.mu.Lock()
defer state.mu.Unlock()
if errors.Is(err, errNoPassword) || strings.Contains(err.Error(), "unable to authenticate") {
message := "The host refused this device's key."
switch {
case state.passwordTried:
message = "The host refused the password."
case state.passwordAllowed:
message = "The host wants a password."
case signer == nil:
message = "The host accepts neither passwords nor keys we have."
}
return nil, &failure{
Kind: "auth",
Message: message,
PasswordAllowed: state.passwordAllowed,
PasswordTried: state.passwordTried,
KeyTried: state.keyTried,
}
}
return nil, &failure{Kind: "network", Message: "SSH handshake failed: " + describeNetError(err)}
}
tcp.SetDeadline(time.Time{})
client := ssh.NewClient(sshConn, chans, reqs)
conn := &pooledConn{key: key, client: client}
log.Printf("faceclawssh: connected to %s@%s", spec.User, addr)
go func() {
err := client.Wait()
log.Printf("faceclawssh: connection to %s ended: %v", addr, err)
conn.markDead()
}()
interval := defaultKeepaliveInterval
if spec.KeepaliveIntervalMs > 0 {
interval = time.Duration(spec.KeepaliveIntervalMs) * time.Millisecond
}
go keepalive(conn, interval)
return conn, nil
}
// keepalive probes the host every interval and closes the connection if a
// probe goes unanswered for a whole interval, so a dead peer (phone switched
// networks, laptop asleep) fails the channels promptly instead of hanging.
func keepalive(conn *pooledConn, interval time.Duration) {
defer func() {
if r := recover(); r != nil {
log.Printf("faceclawssh: keepalive panic: %v", r)
conn.client.Close()
}
}()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for range ticker.C {
poolMu.Lock()
dead := conn.dead
poolMu.Unlock()
if dead {
return
}
reply := make(chan error, 1)
go func() {
_, _, err := conn.client.SendRequest("keepalive@openssh.com", true, nil)
reply <- err
}()
select {
case err := <-reply:
if err != nil {
conn.client.Close()
return
}
case <-time.After(interval):
log.Printf("faceclawssh: keepalive timed out; closing")
conn.client.Close()
return
}
}
}
func describeNetError(err error) string {
message := err.Error()
// "dial tcp 1.2.3.4:22: connect: connection refused" → keep the tail.
if index := strings.LastIndex(message, ": "); index >= 0 && strings.HasPrefix(message, "dial ") {
return message[index+2:]
}
return message
}