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) { r := h.execute(ctx, target, command) if len(r.out) > 0 { return r.out, nil } return nil, r.err } // execResult is what a command did. started is false when it never reached // the remote shell (no connection, handshake or session), so nothing ran. A // started command that did not exit (the session dropped, the deadline // passed) may have done part or all of its work. type execResult struct { out []byte started bool exited bool status int err error } func (h *host) execute(ctx context.Context, target Target, command string) execResult { ctx, cancel := context.WithTimeout(ctx, commandTimeout) defer cancel() conn, err := dial(ctx, target.Address) if err != nil { return execResult{err: 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 execResult{err: 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 execResult{err: fmt.Errorf("ssh session on %s: %w", target.Name, err)} } defer func() { _ = session.Close() }() var out limited session.Stdout = &out err = session.Run(command) res := execResult{out: out.Bytes(), started: true, exited: err == nil} if err != nil { res.err = fmt.Errorf("on %s: %w", target.Name, err) var exit *ssh.ExitError if errors.As(err, &exit) { res.exited, res.status = true, exit.ExitStatus() } } return res } // 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")