Files
archipelago/connectors/host/ssh.go
T
2026-11-15 22:20:05 +11:00

132 lines
3.6 KiB
Go

package main
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"time"
"golang.org/x/crypto/ssh"
)
const (
dialTimeout = 10 * time.Second
commandTimeout = 30 * time.Second
maxOutput = 1 << 20
)
// run executes command on target and returns its stdout. A command that
// prints something and then exits non-zero (du meeting a directory it can't
// read) still returns what it printed.
func (h *host) run(ctx context.Context, target Target, command string) ([]byte, error) {
ctx, cancel := context.WithTimeout(ctx, commandTimeout)
defer cancel()
conn, err := dial(ctx, target.Address)
if err != nil {
return nil, fmt.Errorf("reach %s: %w", target.Name, err)
}
stop := context.AfterFunc(ctx, func() { _ = conn.Close() })
defer stop()
cc, chans, reqs, err := ssh.NewClientConn(conn, target.Address, h.clientConfig(target))
if err != nil {
_ = conn.Close()
return nil, fmt.Errorf("ssh to %s: %w", target.Name, err)
}
client := ssh.NewClient(cc, chans, reqs)
defer func() { _ = client.Close() }()
session, err := client.NewSession()
if err != nil {
return nil, fmt.Errorf("ssh session on %s: %w", target.Name, err)
}
defer func() { _ = session.Close() }()
var out limited
session.Stdout = &out
runErr := session.Run(command)
if out.Len() > 0 {
return out.Bytes(), nil
}
if runErr != nil {
return nil, fmt.Errorf("on %s: %w", target.Name, runErr)
}
return nil, nil
}
// clientConfig pins the target's host key. It asks only for that key's
// algorithm: a host holding several keys would otherwise present its
// preferred one, and a correct pin would read as a mismatch.
func (h *host) clientConfig(target Target) *ssh.ClientConfig {
algorithms := []string{target.key.Type()}
if target.key.Type() == ssh.KeyAlgoRSA {
algorithms = []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256}
}
return &ssh.ClientConfig{
User: h.username,
Auth: []ssh.AuthMethod{ssh.PublicKeys(h.signer)},
HostKeyCallback: ssh.FixedHostKey(target.key),
HostKeyAlgorithms: algorithms,
Timeout: dialTimeout,
}
}
// limited keeps the first maxOutput bytes and drops the rest.
type limited struct{ bytes.Buffer }
func (l *limited) Write(p []byte) (int, error) {
if room := maxOutput - l.Len(); room > 0 {
l.Buffer.Write(p[:min(len(p), room)])
}
return len(p), nil
}
// dial reaches addr directly, or through the egress tunnel's CONNECT proxy
// when the connector runs confined.
func dial(ctx context.Context, addr string) (net.Conn, error) {
d := net.Dialer{Timeout: dialTimeout}
proxy := os.Getenv("HTTPS_PROXY")
if proxy == "" {
return d.DialContext(ctx, "tcp", addr)
}
u, err := url.Parse(proxy)
if err != nil {
return nil, fmt.Errorf("proxy: %w", err)
}
conn, err := d.DialContext(ctx, "tcp", u.Host)
if err != nil {
return nil, err
}
req := &http.Request{Method: http.MethodConnect, URL: &url.URL{Opaque: addr}, Host: addr, Header: http.Header{}}
if err := req.Write(conn); err != nil {
_ = conn.Close()
return nil, err
}
br := bufio.NewReader(conn)
resp, err := http.ReadResponse(br, req)
if err != nil {
_ = conn.Close()
return nil, err
}
_ = resp.Body.Close()
if resp.StatusCode != http.StatusOK {
_ = conn.Close()
return nil, fmt.Errorf("egress refused %s: %s", addr, resp.Status)
}
// The SSH server speaks first, so its banner may already be buffered.
return &bufferedConn{Conn: conn, r: br}, nil
}
type bufferedConn struct {
net.Conn
r io.Reader
}
func (c *bufferedConn) Read(p []byte) (int, error) { return c.r.Read(p) }
var errNoCredential = errors.New("the ssh credential slot needs a username and a private_key")