blob: 73974d3636aa89cdd9991587b6af762129bf95c4 [file] [log] [blame]
Tim Windelschmidt6d33a432025-02-04 14:34:25 +01001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +01004package ssh
Serge Bazanskicaa12082023-02-16 14:54:04 +01005
6import (
7 "bytes"
8 "context"
9 "fmt"
10 "io"
11 "net"
12 "time"
13
14 "github.com/pkg/sftp"
15 "golang.org/x/crypto/ssh"
16)
17
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010018// Client defines a simple interface to an abstract SSH client. Usually this
19// would be DirectClient, but tests can use this interface to dependency-inject
Serge Bazanskicaa12082023-02-16 14:54:04 +010020// fake SSH connections.
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010021type Client interface {
22 // Dial returns an Connection to a given address (host:port pair) with
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020023 // a timeout for connection.
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010024 Dial(ctx context.Context, address string, connectTimeout time.Duration) (Connection, error)
Serge Bazanskicaa12082023-02-16 14:54:04 +010025}
26
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010027type Connection interface {
Serge Bazanskicaa12082023-02-16 14:54:04 +010028 // Execute a given command on a remote host synchronously, passing in stdin as
29 // input, and returning a captured stdout/stderr. The returned data might be
30 // valid even when err != nil, which might happen if the remote side returned a
31 // non-zero exit code.
32 Execute(ctx context.Context, command string, stdin []byte) (stdout []byte, stderr []byte, err error)
33 // Upload a given blob to a targetPath on the system and make executable.
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010034 Upload(ctx context.Context, targetPath string, src io.Reader) error
Serge Bazanskicaa12082023-02-16 14:54:04 +010035 // Close this connection.
36 Close() error
37}
38
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010039// DirectClient implements Client (and Connection) using
Serge Bazanskicaa12082023-02-16 14:54:04 +010040// golang.org/x/crypto/ssh.
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010041type DirectClient struct {
Tim Windelschmidtd0e39cb2024-09-16 16:14:00 +020042 AuthMethods []ssh.AuthMethod
43 Username string
Serge Bazanskicaa12082023-02-16 14:54:04 +010044}
45
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010046type directConn struct {
Serge Bazanskicaa12082023-02-16 14:54:04 +010047 cl *ssh.Client
48}
49
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010050func (p *DirectClient) Dial(ctx context.Context, address string, connectTimeout time.Duration) (Connection, error) {
Serge Bazanskicaa12082023-02-16 14:54:04 +010051 d := net.Dialer{
52 Timeout: connectTimeout,
53 }
54 conn, err := d.DialContext(ctx, "tcp", address)
55 if err != nil {
56 return nil, err
57 }
58 conf := &ssh.ClientConfig{
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020059 User: p.Username,
Tim Windelschmidtd0e39cb2024-09-16 16:14:00 +020060 Auth: p.AuthMethods,
Serge Bazanskicaa12082023-02-16 14:54:04 +010061 // Ignore the host key, since it's likely the first time anything logs into
62 // this device, and also because there's no way of knowing its fingerprint.
63 HostKeyCallback: ssh.InsecureIgnoreHostKey(),
64 // Timeout sets a bound on the time it takes to set up the connection, but
65 // not on total session time.
66 Timeout: connectTimeout,
67 }
68 conn2, chanC, reqC, err := ssh.NewClientConn(conn, address, conf)
69 if err != nil {
70 return nil, err
71 }
72 cl := ssh.NewClient(conn2, chanC, reqC)
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010073 return &directConn{
Serge Bazanskicaa12082023-02-16 14:54:04 +010074 cl: cl,
75 }, nil
76}
77
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +010078func (p *directConn) Execute(ctx context.Context, command string, stdin []byte) (stdout []byte, stderr []byte, err error) {
Serge Bazanskicaa12082023-02-16 14:54:04 +010079 sess, err := p.cl.NewSession()
80 if err != nil {
81 return nil, nil, fmt.Errorf("while creating SSH session: %w", err)
82 }
83 stdoutBuf := bytes.NewBuffer(nil)
84 stderrBuf := bytes.NewBuffer(nil)
85 sess.Stdin = bytes.NewBuffer(stdin)
86 sess.Stdout = stdoutBuf
87 sess.Stderr = stderrBuf
88 defer sess.Close()
89
90 if err := sess.Start(command); err != nil {
91 return nil, nil, err
92 }
93 doneC := make(chan error, 1)
94 go func() {
95 doneC <- sess.Wait()
96 }()
97 select {
98 case <-ctx.Done():
99 return nil, nil, ctx.Err()
100 case err := <-doneC:
101 return stdoutBuf.Bytes(), stderrBuf.Bytes(), err
102 }
103}
104
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +0100105func (p *directConn) Upload(ctx context.Context, targetPath string, src io.Reader) error {
Lorenz Brunc5d28e42024-09-17 20:38:31 +0200106 sc, err := sftp.NewClient(p.cl, sftp.UseConcurrentWrites(true), sftp.MaxConcurrentRequestsPerFile(1024))
Serge Bazanskicaa12082023-02-16 14:54:04 +0100107 if err != nil {
108 return fmt.Errorf("while building sftp client: %w", err)
109 }
110 defer sc.Close()
111
Serge Bazanskicaa12082023-02-16 14:54:04 +0100112 df, err := sc.Create(targetPath)
113 if err != nil {
114 return fmt.Errorf("while creating file on the host: %w", err)
115 }
116
117 doneC := make(chan error, 1)
118
119 go func() {
Lorenz Brunc5d28e42024-09-17 20:38:31 +0200120 _, err := df.ReadFromWithConcurrency(src, 0)
Serge Bazanskicaa12082023-02-16 14:54:04 +0100121 df.Close()
122 doneC <- err
123 }()
124
125 select {
126 case err := <-doneC:
127 if err != nil {
128 return fmt.Errorf("while copying file: %w", err)
129 }
130 case <-ctx.Done():
131 df.Close()
132 return ctx.Err()
133 }
134
135 if err := sc.Chmod(targetPath, 0755); err != nil {
136 return fmt.Errorf("while setting file permissions: %w", err)
137 }
138 return nil
139}
140
Tim Windelschmidt5f5f3302024-02-22 23:50:24 +0100141func (p *directConn) Close() error {
Serge Bazanskicaa12082023-02-16 14:54:04 +0100142 return p.cl.Close()
143}